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 const SFH_NO_HASH
= 1;
83 const SFH_OBJECT_ARGS
= 2;
85 # Constants needed for external link processing
86 # Everything except bracket, space, or control characters
87 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
88 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
89 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
90 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
91 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
93 # Regular expression for a non-newline space
94 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
96 # State constants for the definition list colon extraction
97 const COLON_STATE_TEXT
= 0;
98 const COLON_STATE_TAG
= 1;
99 const COLON_STATE_TAGSTART
= 2;
100 const COLON_STATE_CLOSETAG
= 3;
101 const COLON_STATE_TAGSLASH
= 4;
102 const COLON_STATE_COMMENT
= 5;
103 const COLON_STATE_COMMENTDASH
= 6;
104 const COLON_STATE_COMMENTDASHDASH
= 7;
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION
= 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
111 const OT_HTML
= 1; # like parse()
112 const OT_WIKI
= 2; # like preSaveTransform()
113 const OT_PREPROCESS
= 3; # like preprocess()
115 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
117 # Marker Suffix needs to be accessible staticly.
118 const MARKER_SUFFIX
= "-QINU\x7f";
120 # Markers used for wrapping the table of contents
121 const TOC_START
= '<mw:toc>';
122 const TOC_END
= '</mw:toc>';
125 public $mTagHooks = array();
126 public $mTransparentTagHooks = array();
127 public $mFunctionHooks = array();
128 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
129 public $mFunctionTagHooks = array();
130 public $mStripList = array();
131 public $mDefaultStripList = array();
132 public $mVarCache = array();
133 public $mImageParams = array();
134 public $mImageParamsMagicArray = array();
135 public $mMarkerIndex = 0;
136 public $mFirstCall = true;
138 # Initialised by initialiseVariables()
141 * @var MagicWordArray
146 * @var MagicWordArray
149 # Initialised in constructor
150 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols;
152 # Cleared with clearState():
157 public $mAutonumber, $mDTopen;
164 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
166 * @var LinkHolderArray
168 public $mLinkHolders;
171 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
172 public $mDefaultSort;
173 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
174 public $mExpensiveFunctionCount; # number of expensive parser function calls
175 public $mShowToc, $mForceTocPosition;
180 public $mUser; # User object; only used when doing pre-save transform
183 # These are variables reset at least once per parse regardless of $clearState
193 public $mTitle; # Title context, used for self-link rendering and similar things
194 public $mOutputType; # Output type, one of the OT_xxx constants
195 public $ot; # Shortcut alias, see setOutputType()
196 public $mRevisionObject; # The revision object of the specified revision ID
197 public $mRevisionId; # ID to display in {{REVISIONID}} tags
198 public $mRevisionTimestamp; # The timestamp of the specified revision ID
199 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
200 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
201 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
202 public $mInputSize = false; # For {{PAGESIZE}} on current page.
210 * @var array Array with the language name of each language link (i.e. the
211 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
212 * duplicate language links to the ParserOutput.
214 public $mLangLinkLanguages;
217 * @var MapCacheLRU|null
220 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
222 public $currentRevisionCache;
225 * @var bool Recursive call protection.
226 * This variable should be treated as if it were private.
228 public $mInParse = false;
230 /** @var SectionProfiler */
231 protected $mProfiler;
236 public function __construct( $conf = array() ) {
237 $this->mConf
= $conf;
238 $this->mUrlProtocols
= wfUrlProtocols();
239 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
240 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
241 if ( isset( $conf['preprocessorClass'] ) ) {
242 $this->mPreprocessorClass
= $conf['preprocessorClass'];
243 } elseif ( defined( 'HPHP_VERSION' ) ) {
244 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
245 $this->mPreprocessorClass
= 'Preprocessor_Hash';
246 } elseif ( extension_loaded( 'domxml' ) ) {
247 # PECL extension that conflicts with the core DOM extension (bug 13770)
248 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
249 $this->mPreprocessorClass
= 'Preprocessor_Hash';
250 } elseif ( extension_loaded( 'dom' ) ) {
251 $this->mPreprocessorClass
= 'Preprocessor_DOM';
253 $this->mPreprocessorClass
= 'Preprocessor_Hash';
255 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
259 * Reduce memory usage to reduce the impact of circular references
261 public function __destruct() {
262 if ( isset( $this->mLinkHolders
) ) {
263 unset( $this->mLinkHolders
);
265 foreach ( $this as $name => $value ) {
266 unset( $this->$name );
271 * Allow extensions to clean up when the parser is cloned
273 public function __clone() {
274 $this->mInParse
= false;
276 // Bug 56226: When you create a reference "to" an object field, that
277 // makes the object field itself be a reference too (until the other
278 // reference goes out of scope). When cloning, any field that's a
279 // reference is copied as a reference in the new object. Both of these
280 // are defined PHP5 behaviors, as inconvenient as it is for us when old
281 // hooks from PHP4 days are passing fields by reference.
282 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
283 // Make a non-reference copy of the field, then rebind the field to
284 // reference the new copy.
290 Hooks
::run( 'ParserCloned', array( $this ) );
294 * Do various kinds of initialisation on the first call of the parser
296 public function firstCallInit() {
297 if ( !$this->mFirstCall
) {
300 $this->mFirstCall
= false;
302 wfProfileIn( __METHOD__
);
304 CoreParserFunctions
::register( $this );
305 CoreTagHooks
::register( $this );
306 $this->initialiseVariables();
308 Hooks
::run( 'ParserFirstCallInit', array( &$this ) );
309 wfProfileOut( __METHOD__
);
317 public function clearState() {
318 wfProfileIn( __METHOD__
);
319 if ( $this->mFirstCall
) {
320 $this->firstCallInit();
322 $this->mOutput
= new ParserOutput
;
323 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
324 $this->mAutonumber
= 0;
325 $this->mLastSection
= '';
326 $this->mDTopen
= false;
327 $this->mIncludeCount
= array();
328 $this->mArgStack
= false;
329 $this->mInPre
= false;
330 $this->mLinkHolders
= new LinkHolderArray( $this );
332 $this->mRevisionObject
= $this->mRevisionTimestamp
=
333 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
334 $this->mVarCache
= array();
336 $this->mLangLinkLanguages
= array();
337 $this->currentRevisionCache
= null;
340 * Prefix for temporary replacement strings for the multipass parser.
341 * \x07 should never appear in input as it's disallowed in XML.
342 * Using it at the front also gives us a little extra robustness
343 * since it shouldn't match when butted up against identifier-like
346 * Must not consist of all title characters, or else it will change
347 * the behavior of <nowiki> in a link.
349 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
350 $this->mStripState
= new StripState( $this->mUniqPrefix
);
352 # Clear these on every parse, bug 4549
353 $this->mTplRedirCache
= $this->mTplDomCache
= array();
355 $this->mShowToc
= true;
356 $this->mForceTocPosition
= false;
357 $this->mIncludeSizes
= array(
361 $this->mPPNodeCount
= 0;
362 $this->mGeneratedPPNodeCount
= 0;
363 $this->mHighestExpansionDepth
= 0;
364 $this->mDefaultSort
= false;
365 $this->mHeadings
= array();
366 $this->mDoubleUnderscores
= array();
367 $this->mExpensiveFunctionCount
= 0;
370 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
371 $this->mPreprocessor
= null;
374 $this->mProfiler
= new SectionProfiler();
376 Hooks
::run( 'ParserClearState', array( &$this ) );
377 wfProfileOut( __METHOD__
);
381 * Convert wikitext to HTML
382 * Do not call this function recursively.
384 * @param string $text Text we want to parse
385 * @param Title $title
386 * @param ParserOptions $options
387 * @param bool $linestart
388 * @param bool $clearState
389 * @param int $revid Number to pass in {{REVISIONID}}
390 * @return ParserOutput A ParserOutput
392 public function parse( $text, Title
$title, ParserOptions
$options,
393 $linestart = true, $clearState = true, $revid = null
396 * First pass--just handle <nowiki> sections, pass the rest off
397 * to internalParse() which does all the real work.
400 global $wgShowHostnames;
401 $fname = __METHOD__
. '-' . wfGetCaller();
402 wfProfileIn( __METHOD__
);
403 wfProfileIn( $fname );
406 $magicScopeVariable = $this->lock();
409 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
411 $this->currentRevisionCache
= null;
412 $this->mInputSize
= strlen( $text );
413 if ( $this->mOptions
->getEnableLimitReport() ) {
414 $this->mOutput
->resetParseStartTime();
417 # Remove the strip marker tag prefix from the input, if present.
419 $text = str_replace( $this->mUniqPrefix
, '', $text );
422 $oldRevisionId = $this->mRevisionId
;
423 $oldRevisionObject = $this->mRevisionObject
;
424 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
425 $oldRevisionUser = $this->mRevisionUser
;
426 $oldRevisionSize = $this->mRevisionSize
;
427 if ( $revid !== null ) {
428 $this->mRevisionId
= $revid;
429 $this->mRevisionObject
= null;
430 $this->mRevisionTimestamp
= null;
431 $this->mRevisionUser
= null;
432 $this->mRevisionSize
= null;
435 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
437 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
438 $text = $this->internalParse( $text );
439 Hooks
::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
441 $text = $this->internalParseHalfParsed( $text, true, $linestart );
444 * A converted title will be provided in the output object if title and
445 * content conversion are enabled, the article text does not contain
446 * a conversion-suppressing double-underscore tag, and no
447 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
448 * automatic link conversion.
450 if ( !( $options->getDisableTitleConversion()
451 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
452 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
453 ||
$this->mOutput
->getDisplayTitle() !== false )
455 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
456 if ( $convruletitle ) {
457 $this->mOutput
->setTitleText( $convruletitle );
459 $titleText = $this->getConverterLanguage()->convertTitle( $title );
460 $this->mOutput
->setTitleText( $titleText );
464 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
465 $this->limitationWarn( 'expensive-parserfunction',
466 $this->mExpensiveFunctionCount
,
467 $this->mOptions
->getExpensiveParserFunctionLimit()
471 # Information on include size limits, for the benefit of users who try to skirt them
472 if ( $this->mOptions
->getEnableLimitReport() ) {
473 $max = $this->mOptions
->getMaxIncludeSize();
475 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
476 if ( $cpuTime !== null ) {
477 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
478 sprintf( "%.3f", $cpuTime )
482 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
483 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
484 sprintf( "%.3f", $wallTime )
487 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
488 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
490 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
491 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
493 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
494 array( $this->mIncludeSizes
['post-expand'], $max )
496 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
497 array( $this->mIncludeSizes
['arg'], $max )
499 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
500 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
502 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
503 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
505 Hooks
::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
507 $limitReport = "NewPP limit report\n";
508 if ( $wgShowHostnames ) {
509 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
511 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
512 if ( Hooks
::run( 'ParserLimitReportFormat',
513 array( $key, &$value, &$limitReport, false, false )
515 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
516 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
517 ->inLanguage( 'en' )->useDatabase( false );
518 if ( !$valueMsg->exists() ) {
519 $valueMsg = new RawMessage( '$1' );
521 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
522 $valueMsg->params( $value );
523 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
527 // Since we're not really outputting HTML, decode the entities and
528 // then re-encode the things that need hiding inside HTML comments.
529 $limitReport = htmlspecialchars_decode( $limitReport );
530 Hooks
::run( 'ParserLimitReport', array( $this, &$limitReport ) );
532 // Sanitize for comment. Note '‐' in the replacement is U+2010,
533 // which looks much like the problematic '-'.
534 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
535 $text .= "\n<!-- \n$limitReport-->\n";
537 // Add on template profiling data
538 $dataByFunc = $this->mProfiler
->getFunctionStats();
539 uasort( $dataByFunc, function ( $a, $b ) {
540 return $a['real'] < $b['real']; // descending order
542 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
543 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
544 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
545 $item['%real'], $item['real'], $item['calls'],
546 htmlspecialchars( $item['name'] ) );
548 $text .= "\n<!-- \n$profileReport-->\n";
550 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
551 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
552 $this->mTitle
->getPrefixedDBkey() );
555 $this->mOutput
->setText( $text );
557 $this->mRevisionId
= $oldRevisionId;
558 $this->mRevisionObject
= $oldRevisionObject;
559 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
560 $this->mRevisionUser
= $oldRevisionUser;
561 $this->mRevisionSize
= $oldRevisionSize;
562 $this->mInputSize
= false;
563 $this->currentRevisionCache
= null;
564 wfProfileOut( $fname );
565 wfProfileOut( __METHOD__
);
567 return $this->mOutput
;
571 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
572 * can be called from an extension tag hook.
574 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
575 * instead, which means that lists and links have not been fully parsed yet,
576 * and strip markers are still present.
578 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
580 * Use this function if you're a parser tag hook and you want to parse
581 * wikitext before or after applying additional transformations, and you
582 * intend to *return the result as hook output*, which will cause it to go
583 * through the rest of parsing process automatically.
585 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
586 * $text are not expanded
588 * @param string $text Text extension wants to have parsed
589 * @param bool|PPFrame $frame The frame to use for expanding any template variables
590 * @return string UNSAFE half-parsed HTML
592 public function recursiveTagParse( $text, $frame = false ) {
593 wfProfileIn( __METHOD__
);
594 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
595 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
596 $text = $this->internalParse( $text, false, $frame );
597 wfProfileOut( __METHOD__
);
602 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
603 * point can be called from an extension tag hook.
605 * The output of this function is fully-parsed HTML that is safe for output.
606 * If you're a parser tag hook, you might want to use recursiveTagParse()
609 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
610 * $text are not expanded
614 * @param string $text Text extension wants to have parsed
615 * @param bool|PPFrame $frame The frame to use for expanding any template variables
616 * @return string Fully parsed HTML
618 public function recursiveTagParseFully( $text, $frame = false ) {
619 wfProfileIn( __METHOD__
);
620 $text = $this->recursiveTagParse( $text, $frame );
621 $text = $this->internalParseHalfParsed( $text, false );
622 wfProfileOut( __METHOD__
);
627 * Expand templates and variables in the text, producing valid, static wikitext.
628 * Also removes comments.
629 * Do not call this function recursively.
630 * @param string $text
631 * @param Title $title
632 * @param ParserOptions $options
633 * @param int|null $revid
634 * @param bool|PPFrame $frame
635 * @return mixed|string
637 public function preprocess( $text, Title
$title = null,
638 ParserOptions
$options, $revid = null, $frame = false
640 wfProfileIn( __METHOD__
);
641 $magicScopeVariable = $this->lock();
642 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
643 if ( $revid !== null ) {
644 $this->mRevisionId
= $revid;
646 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
647 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
648 $text = $this->replaceVariables( $text, $frame );
649 $text = $this->mStripState
->unstripBoth( $text );
650 wfProfileOut( __METHOD__
);
655 * Recursive parser entry point that can be called from an extension tag
658 * @param string $text Text to be expanded
659 * @param bool|PPFrame $frame The frame to use for expanding any template variables
663 public function recursivePreprocess( $text, $frame = false ) {
664 wfProfileIn( __METHOD__
);
665 $text = $this->replaceVariables( $text, $frame );
666 $text = $this->mStripState
->unstripBoth( $text );
667 wfProfileOut( __METHOD__
);
672 * Process the wikitext for the "?preload=" feature. (bug 5210)
674 * "<noinclude>", "<includeonly>" etc. are parsed as for template
675 * transclusion, comments, templates, arguments, tags hooks and parser
676 * functions are untouched.
678 * @param string $text
679 * @param Title $title
680 * @param ParserOptions $options
681 * @param array $params
684 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
685 $msg = new RawMessage( $text );
686 $text = $msg->params( $params )->plain();
688 # Parser (re)initialisation
689 $magicScopeVariable = $this->lock();
690 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
692 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
693 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
694 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
695 $text = $this->mStripState
->unstripBoth( $text );
700 * Get a random string
704 public static function getRandomString() {
705 return wfRandomString( 16 );
709 * Set the current user.
710 * Should only be used when doing pre-save transform.
712 * @param User|null $user User object or null (to reset)
714 public function setUser( $user ) {
715 $this->mUser
= $user;
719 * Accessor for mUniqPrefix.
723 public function uniqPrefix() {
724 if ( !isset( $this->mUniqPrefix
) ) {
725 # @todo FIXME: This is probably *horribly wrong*
726 # LanguageConverter seems to want $wgParser's uniqPrefix, however
727 # if this is called for a parser cache hit, the parser may not
728 # have ever been initialized in the first place.
729 # Not really sure what the heck is supposed to be going on here.
731 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
733 return $this->mUniqPrefix
;
737 * Set the context title
741 public function setTitle( $t ) {
743 $t = Title
::newFromText( 'NO TITLE' );
746 if ( $t->hasFragment() ) {
747 # Strip the fragment to avoid various odd effects
748 $this->mTitle
= clone $t;
749 $this->mTitle
->setFragment( '' );
756 * Accessor for the Title object
760 public function getTitle() {
761 return $this->mTitle
;
765 * Accessor/mutator for the Title object
767 * @param Title $x Title object or null to just get the current one
770 public function Title( $x = null ) {
771 return wfSetVar( $this->mTitle
, $x );
775 * Set the output type
777 * @param int $ot New value
779 public function setOutputType( $ot ) {
780 $this->mOutputType
= $ot;
783 'html' => $ot == self
::OT_HTML
,
784 'wiki' => $ot == self
::OT_WIKI
,
785 'pre' => $ot == self
::OT_PREPROCESS
,
786 'plain' => $ot == self
::OT_PLAIN
,
791 * Accessor/mutator for the output type
793 * @param int|null $x New value or null to just get the current one
796 public function OutputType( $x = null ) {
797 return wfSetVar( $this->mOutputType
, $x );
801 * Get the ParserOutput object
803 * @return ParserOutput
805 public function getOutput() {
806 return $this->mOutput
;
810 * Get the ParserOptions object
812 * @return ParserOptions
814 public function getOptions() {
815 return $this->mOptions
;
819 * Accessor/mutator for the ParserOptions object
821 * @param ParserOptions $x New value or null to just get the current one
822 * @return ParserOptions Current ParserOptions object
824 public function Options( $x = null ) {
825 return wfSetVar( $this->mOptions
, $x );
831 public function nextLinkID() {
832 return $this->mLinkID++
;
838 public function setLinkID( $id ) {
839 $this->mLinkID
= $id;
843 * Get a language object for use in parser functions such as {{FORMATNUM:}}
846 public function getFunctionLang() {
847 return $this->getTargetLanguage();
851 * Get the target language for the content being parsed. This is usually the
852 * language that the content is in.
856 * @throws MWException
859 public function getTargetLanguage() {
860 $target = $this->mOptions
->getTargetLanguage();
862 if ( $target !== null ) {
864 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
865 return $this->mOptions
->getUserLangObj();
866 } elseif ( is_null( $this->mTitle
) ) {
867 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
870 return $this->mTitle
->getPageLanguage();
874 * Get the language object for language conversion
875 * @return Language|null
877 public function getConverterLanguage() {
878 return $this->getTargetLanguage();
882 * Get a User object either from $this->mUser, if set, or from the
883 * ParserOptions object otherwise
887 public function getUser() {
888 if ( !is_null( $this->mUser
) ) {
891 return $this->mOptions
->getUser();
895 * Get a preprocessor object
897 * @return Preprocessor
899 public function getPreprocessor() {
900 if ( !isset( $this->mPreprocessor
) ) {
901 $class = $this->mPreprocessorClass
;
902 $this->mPreprocessor
= new $class( $this );
904 return $this->mPreprocessor
;
908 * Replaces all occurrences of HTML-style comments and the given tags
909 * in the text with a random marker and returns the next text. The output
910 * parameter $matches will be an associative array filled with data in
914 * 'UNIQ-xxxxx' => array(
917 * array( 'param' => 'x' ),
918 * '<element param="x">tag content</element>' ) )
921 * @param array $elements List of element names. Comments are always extracted.
922 * @param string $text Source text string.
923 * @param array $matches Out parameter, Array: extracted tags
924 * @param string $uniq_prefix
925 * @return string Stripped text
927 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
932 $taglist = implode( '|', $elements );
933 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
935 while ( $text != '' ) {
936 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
938 if ( count( $p ) < 5 ) {
941 if ( count( $p ) > 5 ) {
955 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
956 $stripped .= $marker;
958 if ( $close === '/>' ) {
959 # Empty element tag, <tag />
964 if ( $element === '!--' ) {
967 $end = "/(<\\/$element\\s*>)/i";
969 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
971 if ( count( $q ) < 3 ) {
972 # No end tag -- let it run out to the end of the text.
981 $matches[$marker] = array( $element,
983 Sanitizer
::decodeTagAttributes( $attributes ),
984 "<$element$attributes$close$content$tail" );
990 * Get a list of strippable XML-like elements
994 public function getStripList() {
995 return $this->mStripList
;
999 * Add an item to the strip state
1000 * Returns the unique tag which must be inserted into the stripped text
1001 * The tag will be replaced with the original text in unstrip()
1003 * @param string $text
1007 public function insertStripItem( $text ) {
1008 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1009 $this->mMarkerIndex++
;
1010 $this->mStripState
->addGeneral( $rnd, $text );
1015 * parse the wiki syntax used to render tables
1018 * @param string $text
1021 public function doTableStuff( $text ) {
1022 wfProfileIn( __METHOD__
);
1024 $lines = StringUtils
::explode( "\n", $text );
1026 $td_history = array(); # Is currently a td tag open?
1027 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1028 $tr_history = array(); # Is currently a tr tag open?
1029 $tr_attributes = array(); # history of tr attributes
1030 $has_opened_tr = array(); # Did this table open a <tr> element?
1031 $indent_level = 0; # indent level of the table
1033 foreach ( $lines as $outLine ) {
1034 $line = trim( $outLine );
1036 if ( $line === '' ) { # empty line, go to next line
1037 $out .= $outLine . "\n";
1041 $first_character = $line[0];
1044 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1045 # First check if we are starting a new table
1046 $indent_level = strlen( $matches[1] );
1048 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1049 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1051 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1052 array_push( $td_history, false );
1053 array_push( $last_tag_history, '' );
1054 array_push( $tr_history, false );
1055 array_push( $tr_attributes, '' );
1056 array_push( $has_opened_tr, false );
1057 } elseif ( count( $td_history ) == 0 ) {
1058 # Don't do any of the following
1059 $out .= $outLine . "\n";
1061 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1062 # We are ending a table
1063 $line = '</table>' . substr( $line, 2 );
1064 $last_tag = array_pop( $last_tag_history );
1066 if ( !array_pop( $has_opened_tr ) ) {
1067 $line = "<tr><td></td></tr>{$line}";
1070 if ( array_pop( $tr_history ) ) {
1071 $line = "</tr>{$line}";
1074 if ( array_pop( $td_history ) ) {
1075 $line = "</{$last_tag}>{$line}";
1077 array_pop( $tr_attributes );
1078 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1079 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1080 # Now we have a table row
1081 $line = preg_replace( '#^\|-+#', '', $line );
1083 # Whats after the tag is now only attributes
1084 $attributes = $this->mStripState
->unstripBoth( $line );
1085 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1086 array_pop( $tr_attributes );
1087 array_push( $tr_attributes, $attributes );
1090 $last_tag = array_pop( $last_tag_history );
1091 array_pop( $has_opened_tr );
1092 array_push( $has_opened_tr, true );
1094 if ( array_pop( $tr_history ) ) {
1098 if ( array_pop( $td_history ) ) {
1099 $line = "</{$last_tag}>{$line}";
1103 array_push( $tr_history, false );
1104 array_push( $td_history, false );
1105 array_push( $last_tag_history, '' );
1106 } elseif ( $first_character === '|'
1107 ||
$first_character === '!'
1108 ||
substr( $line, 0, 2 ) === '|+'
1110 # This might be cell elements, td, th or captions
1111 if ( substr( $line, 0, 2 ) === '|+' ) {
1112 $first_character = '+';
1113 $line = substr( $line, 1 );
1116 $line = substr( $line, 1 );
1118 if ( $first_character === '!' ) {
1119 $line = str_replace( '!!', '||', $line );
1122 # Split up multiple cells on the same line.
1123 # FIXME : This can result in improper nesting of tags processed
1124 # by earlier parser steps, but should avoid splitting up eg
1125 # attribute values containing literal "||".
1126 $cells = StringUtils
::explodeMarkup( '||', $line );
1130 # Loop through each table cell
1131 foreach ( $cells as $cell ) {
1133 if ( $first_character !== '+' ) {
1134 $tr_after = array_pop( $tr_attributes );
1135 if ( !array_pop( $tr_history ) ) {
1136 $previous = "<tr{$tr_after}>\n";
1138 array_push( $tr_history, true );
1139 array_push( $tr_attributes, '' );
1140 array_pop( $has_opened_tr );
1141 array_push( $has_opened_tr, true );
1144 $last_tag = array_pop( $last_tag_history );
1146 if ( array_pop( $td_history ) ) {
1147 $previous = "</{$last_tag}>\n{$previous}";
1150 if ( $first_character === '|' ) {
1152 } elseif ( $first_character === '!' ) {
1154 } elseif ( $first_character === '+' ) {
1155 $last_tag = 'caption';
1160 array_push( $last_tag_history, $last_tag );
1162 # A cell could contain both parameters and data
1163 $cell_data = explode( '|', $cell, 2 );
1165 # Bug 553: Note that a '|' inside an invalid link should not
1166 # be mistaken as delimiting cell parameters
1167 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1168 $cell = "{$previous}<{$last_tag}>{$cell}";
1169 } elseif ( count( $cell_data ) == 1 ) {
1170 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1172 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1173 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1174 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1178 array_push( $td_history, true );
1181 $out .= $outLine . "\n";
1184 # Closing open td, tr && table
1185 while ( count( $td_history ) > 0 ) {
1186 if ( array_pop( $td_history ) ) {
1189 if ( array_pop( $tr_history ) ) {
1192 if ( !array_pop( $has_opened_tr ) ) {
1193 $out .= "<tr><td></td></tr>\n";
1196 $out .= "</table>\n";
1199 # Remove trailing line-ending (b/c)
1200 if ( substr( $out, -1 ) === "\n" ) {
1201 $out = substr( $out, 0, -1 );
1204 # special case: don't return empty table
1205 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1209 wfProfileOut( __METHOD__
);
1215 * Helper function for parse() that transforms wiki markup into half-parsed
1216 * HTML. Only called for $mOutputType == self::OT_HTML.
1220 * @param string $text
1221 * @param bool $isMain
1222 * @param bool $frame
1226 public function internalParse( $text, $isMain = true, $frame = false ) {
1227 wfProfileIn( __METHOD__
);
1231 # Hook to suspend the parser in this state
1232 if ( !Hooks
::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1233 wfProfileOut( __METHOD__
);
1237 # if $frame is provided, then use $frame for replacing any variables
1239 # use frame depth to infer how include/noinclude tags should be handled
1240 # depth=0 means this is the top-level document; otherwise it's an included document
1241 if ( !$frame->depth
) {
1244 $flag = Parser
::PTD_FOR_INCLUSION
;
1246 $dom = $this->preprocessToDom( $text, $flag );
1247 $text = $frame->expand( $dom );
1249 # if $frame is not provided, then use old-style replaceVariables
1250 $text = $this->replaceVariables( $text );
1253 Hooks
::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1254 $text = Sanitizer
::removeHTMLtags(
1256 array( &$this, 'attributeStripCallback' ),
1258 array_keys( $this->mTransparentTagHooks
)
1260 Hooks
::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1262 # Tables need to come after variable replacement for things to work
1263 # properly; putting them before other transformations should keep
1264 # exciting things like link expansions from showing up in surprising
1266 $text = $this->doTableStuff( $text );
1268 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1270 $text = $this->doDoubleUnderscore( $text );
1272 $text = $this->doHeadings( $text );
1273 $text = $this->replaceInternalLinks( $text );
1274 $text = $this->doAllQuotes( $text );
1275 $text = $this->replaceExternalLinks( $text );
1277 # replaceInternalLinks may sometimes leave behind
1278 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1279 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1281 $text = $this->doMagicLinks( $text );
1282 $text = $this->formatHeadings( $text, $origText, $isMain );
1284 wfProfileOut( __METHOD__
);
1289 * Helper function for parse() that transforms half-parsed HTML into fully
1292 * @param string $text
1293 * @param bool $isMain
1294 * @param bool $linestart
1297 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1298 global $wgUseTidy, $wgAlwaysUseTidy;
1300 $text = $this->mStripState
->unstripGeneral( $text );
1302 # Clean up special characters, only run once, next-to-last before doBlockLevels
1304 # french spaces, last one Guillemet-left
1305 # only if there is something before the space
1306 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1307 # french spaces, Guillemet-right
1308 '/(\\302\\253) /' => '\\1 ',
1309 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1311 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1313 $text = $this->doBlockLevels( $text, $linestart );
1315 $this->replaceLinkHolders( $text );
1318 * The input doesn't get language converted if
1320 * b) Content isn't converted
1321 * c) It's a conversion table
1322 * d) it is an interface message (which is in the user language)
1324 if ( !( $this->mOptions
->getDisableContentConversion()
1325 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1327 if ( !$this->mOptions
->getInterfaceMessage() ) {
1328 # The position of the convert() call should not be changed. it
1329 # assumes that the links are all replaced and the only thing left
1330 # is the <nowiki> mark.
1331 $text = $this->getConverterLanguage()->convert( $text );
1335 $text = $this->mStripState
->unstripNoWiki( $text );
1338 Hooks
::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1341 $text = $this->replaceTransparentTags( $text );
1342 $text = $this->mStripState
->unstripGeneral( $text );
1344 $text = Sanitizer
::normalizeCharReferences( $text );
1346 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
1347 $text = MWTidy
::tidy( $text );
1349 # attempt to sanitize at least some nesting problems
1350 # (bug #2702 and quite a few others)
1352 # ''Something [http://www.cool.com cool''] -->
1353 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1354 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1355 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1356 # fix up an anchor inside another anchor, only
1357 # at least for a single single nested link (bug 3695)
1358 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1359 '\\1\\2</a>\\3</a>\\1\\4</a>',
1360 # fix div inside inline elements- doBlockLevels won't wrap a line which
1361 # contains a div, so fix it up here; replace
1362 # div with escaped text
1363 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1364 '\\1\\3<div\\5>\\6</div>\\8\\9',
1365 # remove empty italic or bold tag pairs, some
1366 # introduced by rules above
1367 '/<([bi])><\/\\1>/' => '',
1370 $text = preg_replace(
1371 array_keys( $tidyregs ),
1372 array_values( $tidyregs ),
1377 Hooks
::run( 'ParserAfterTidy', array( &$this, &$text ) );
1384 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1385 * magic external links.
1390 * @param string $text
1394 public function doMagicLinks( $text ) {
1395 wfProfileIn( __METHOD__
);
1396 $prots = wfUrlProtocolsWithoutProtRel();
1397 $urlChar = self
::EXT_LINK_URL_CLASS
;
1398 $space = self
::SPACE_NOT_NL
; # non-newline space
1399 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1400 $spaces = "$space++"; # possessive match of 1 or more spaces
1401 $text = preg_replace_callback(
1403 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1404 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1405 (\b(?i:$prots)$urlChar+) | # m[3]: Free external links
1406 \b(?:RFC|PMID) $spaces # m[4]: RFC or PMID, capture number
1408 \bISBN $spaces ( # m[5]: ISBN, capture number
1409 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1410 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1411 [0-9Xx] # check digit
1413 )!xu", array( &$this, 'magicLinkCallback' ), $text );
1414 wfProfileOut( __METHOD__
);
1419 * @throws MWException
1421 * @return HTML|string
1423 public function magicLinkCallback( $m ) {
1424 if ( isset( $m[1] ) && $m[1] !== '' ) {
1427 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1430 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1431 # Free external link
1432 return $this->makeFreeExternalLink( $m[0] );
1433 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1435 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1438 $cssClass = 'mw-magiclink-rfc';
1440 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1442 $urlmsg = 'pubmedurl';
1443 $cssClass = 'mw-magiclink-pmid';
1446 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1447 substr( $m[0], 0, 20 ) . '"' );
1449 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1450 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1451 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1454 $space = self
::SPACE_NOT_NL
; # non-newline space
1455 $isbn = preg_replace( "/$space/", ' ', $isbn );
1456 $num = strtr( $isbn, array(
1461 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1462 return '<a href="' .
1463 htmlspecialchars( $titleObj->getLocalURL() ) .
1464 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1471 * Make a free external link, given a user-supplied URL
1473 * @param string $url
1475 * @return string HTML
1478 public function makeFreeExternalLink( $url ) {
1479 wfProfileIn( __METHOD__
);
1483 # The characters '<' and '>' (which were escaped by
1484 # removeHTMLtags()) should not be included in
1485 # URLs, per RFC 2396.
1487 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1488 $trail = substr( $url, $m2[0][1] ) . $trail;
1489 $url = substr( $url, 0, $m2[0][1] );
1492 # Move trailing punctuation to $trail
1494 # If there is no left bracket, then consider right brackets fair game too
1495 if ( strpos( $url, '(' ) === false ) {
1499 $urlRev = strrev( $url );
1500 $numSepChars = strspn( $urlRev, $sep );
1501 # Don't break a trailing HTML entity by moving the ; into $trail
1502 # This is in hot code, so use substr_compare to avoid having to
1503 # create a new string object for the comparison
1504 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0) {
1505 # more optimization: instead of running preg_match with a $
1506 # anchor, which can be slow, do the match on the reversed
1507 # string starting at the desired offset.
1508 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1509 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1513 if ( $numSepChars ) {
1514 $trail = substr( $url, -$numSepChars ) . $trail;
1515 $url = substr( $url, 0, -$numSepChars );
1518 $url = Sanitizer
::cleanUrl( $url );
1520 # Is this an external image?
1521 $text = $this->maybeMakeExternalImage( $url );
1522 if ( $text === false ) {
1523 # Not an image, make a link
1524 $text = Linker
::makeExternalLink( $url,
1525 $this->getConverterLanguage()->markNoConversion( $url, true ),
1527 $this->getExternalLinkAttribs( $url ) );
1528 # Register it in the output object...
1529 # Replace unnecessary URL escape codes with their equivalent characters
1530 $pasteurized = self
::normalizeLinkUrl( $url );
1531 $this->mOutput
->addExternalLink( $pasteurized );
1533 wfProfileOut( __METHOD__
);
1534 return $text . $trail;
1538 * Parse headers and return html
1542 * @param string $text
1546 public function doHeadings( $text ) {
1547 wfProfileIn( __METHOD__
);
1548 for ( $i = 6; $i >= 1; --$i ) {
1549 $h = str_repeat( '=', $i );
1550 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1552 wfProfileOut( __METHOD__
);
1557 * Replace single quotes with HTML markup
1560 * @param string $text
1562 * @return string The altered text
1564 public function doAllQuotes( $text ) {
1565 wfProfileIn( __METHOD__
);
1567 $lines = StringUtils
::explode( "\n", $text );
1568 foreach ( $lines as $line ) {
1569 $outtext .= $this->doQuotes( $line ) . "\n";
1571 $outtext = substr( $outtext, 0, -1 );
1572 wfProfileOut( __METHOD__
);
1577 * Helper function for doAllQuotes()
1579 * @param string $text
1583 public function doQuotes( $text ) {
1584 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1585 $countarr = count( $arr );
1586 if ( $countarr == 1 ) {
1590 // First, do some preliminary work. This may shift some apostrophes from
1591 // being mark-up to being text. It also counts the number of occurrences
1592 // of bold and italics mark-ups.
1595 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1596 $thislen = strlen( $arr[$i] );
1597 // If there are ever four apostrophes, assume the first is supposed to
1598 // be text, and the remaining three constitute mark-up for bold text.
1599 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1600 if ( $thislen == 4 ) {
1601 $arr[$i - 1] .= "'";
1604 } elseif ( $thislen > 5 ) {
1605 // If there are more than 5 apostrophes in a row, assume they're all
1606 // text except for the last 5.
1607 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1608 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1612 // Count the number of occurrences of bold and italics mark-ups.
1613 if ( $thislen == 2 ) {
1615 } elseif ( $thislen == 3 ) {
1617 } elseif ( $thislen == 5 ) {
1623 // If there is an odd number of both bold and italics, it is likely
1624 // that one of the bold ones was meant to be an apostrophe followed
1625 // by italics. Which one we cannot know for certain, but it is more
1626 // likely to be one that has a single-letter word before it.
1627 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1628 $firstsingleletterword = -1;
1629 $firstmultiletterword = -1;
1631 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1632 if ( strlen( $arr[$i] ) == 3 ) {
1633 $x1 = substr( $arr[$i - 1], -1 );
1634 $x2 = substr( $arr[$i - 1], -2, 1 );
1635 if ( $x1 === ' ' ) {
1636 if ( $firstspace == -1 ) {
1639 } elseif ( $x2 === ' ' ) {
1640 if ( $firstsingleletterword == -1 ) {
1641 $firstsingleletterword = $i;
1642 // if $firstsingleletterword is set, we don't
1643 // look at the other options, so we can bail early.
1647 if ( $firstmultiletterword == -1 ) {
1648 $firstmultiletterword = $i;
1654 // If there is a single-letter word, use it!
1655 if ( $firstsingleletterword > -1 ) {
1656 $arr[$firstsingleletterword] = "''";
1657 $arr[$firstsingleletterword - 1] .= "'";
1658 } elseif ( $firstmultiletterword > -1 ) {
1659 // If not, but there's a multi-letter word, use that one.
1660 $arr[$firstmultiletterword] = "''";
1661 $arr[$firstmultiletterword - 1] .= "'";
1662 } elseif ( $firstspace > -1 ) {
1663 // ... otherwise use the first one that has neither.
1664 // (notice that it is possible for all three to be -1 if, for example,
1665 // there is only one pentuple-apostrophe in the line)
1666 $arr[$firstspace] = "''";
1667 $arr[$firstspace - 1] .= "'";
1671 // Now let's actually convert our apostrophic mush to HTML!
1676 foreach ( $arr as $r ) {
1677 if ( ( $i %
2 ) == 0 ) {
1678 if ( $state === 'both' ) {
1684 $thislen = strlen( $r );
1685 if ( $thislen == 2 ) {
1686 if ( $state === 'i' ) {
1689 } elseif ( $state === 'bi' ) {
1692 } elseif ( $state === 'ib' ) {
1693 $output .= '</b></i><b>';
1695 } elseif ( $state === 'both' ) {
1696 $output .= '<b><i>' . $buffer . '</i>';
1698 } else { // $state can be 'b' or ''
1702 } elseif ( $thislen == 3 ) {
1703 if ( $state === 'b' ) {
1706 } elseif ( $state === 'bi' ) {
1707 $output .= '</i></b><i>';
1709 } elseif ( $state === 'ib' ) {
1712 } elseif ( $state === 'both' ) {
1713 $output .= '<i><b>' . $buffer . '</b>';
1715 } else { // $state can be 'i' or ''
1719 } elseif ( $thislen == 5 ) {
1720 if ( $state === 'b' ) {
1721 $output .= '</b><i>';
1723 } elseif ( $state === 'i' ) {
1724 $output .= '</i><b>';
1726 } elseif ( $state === 'bi' ) {
1727 $output .= '</i></b>';
1729 } elseif ( $state === 'ib' ) {
1730 $output .= '</b></i>';
1732 } elseif ( $state === 'both' ) {
1733 $output .= '<i><b>' . $buffer . '</b></i>';
1735 } else { // ($state == '')
1743 // Now close all remaining tags. Notice that the order is important.
1744 if ( $state === 'b' ||
$state === 'ib' ) {
1747 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1750 if ( $state === 'bi' ) {
1753 // There might be lonely ''''', so make sure we have a buffer
1754 if ( $state === 'both' && $buffer ) {
1755 $output .= '<b><i>' . $buffer . '</i></b>';
1761 * Replace external links (REL)
1763 * Note: this is all very hackish and the order of execution matters a lot.
1764 * Make sure to run tests/parserTests.php if you change this code.
1768 * @param string $text
1770 * @throws MWException
1773 public function replaceExternalLinks( $text ) {
1774 wfProfileIn( __METHOD__
);
1776 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1777 if ( $bits === false ) {
1778 wfProfileOut( __METHOD__
);
1779 throw new MWException( "PCRE needs to be compiled with "
1780 . "--enable-unicode-properties in order for MediaWiki to function" );
1782 $s = array_shift( $bits );
1785 while ( $i < count( $bits ) ) {
1788 $text = $bits[$i++
];
1789 $trail = $bits[$i++
];
1791 # The characters '<' and '>' (which were escaped by
1792 # removeHTMLtags()) should not be included in
1793 # URLs, per RFC 2396.
1795 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1796 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1797 $url = substr( $url, 0, $m2[0][1] );
1800 # If the link text is an image URL, replace it with an <img> tag
1801 # This happened by accident in the original parser, but some people used it extensively
1802 $img = $this->maybeMakeExternalImage( $text );
1803 if ( $img !== false ) {
1809 # Set linktype for CSS - if URL==text, link is essentially free
1810 $linktype = ( $text === $url ) ?
'free' : 'text';
1812 # No link text, e.g. [http://domain.tld/some.link]
1813 if ( $text == '' ) {
1815 $langObj = $this->getTargetLanguage();
1816 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1817 $linktype = 'autonumber';
1819 # Have link text, e.g. [http://domain.tld/some.link text]s
1821 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1824 $text = $this->getConverterLanguage()->markNoConversion( $text );
1826 $url = Sanitizer
::cleanUrl( $url );
1828 # Use the encoded URL
1829 # This means that users can paste URLs directly into the text
1830 # Funny characters like ö aren't valid in URLs anyway
1831 # This was changed in August 2004
1832 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1833 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1835 # Register link in the output object.
1836 # Replace unnecessary URL escape codes with the referenced character
1837 # This prevents spammers from hiding links from the filters
1838 $pasteurized = self
::normalizeLinkUrl( $url );
1839 $this->mOutput
->addExternalLink( $pasteurized );
1842 wfProfileOut( __METHOD__
);
1847 * Get the rel attribute for a particular external link.
1850 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1851 * nofollow if appropriate
1852 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1853 * @return string|null Rel attribute for $url
1855 public static function getExternalLinkRel( $url = false, $title = null ) {
1856 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1857 $ns = $title ?
$title->getNamespace() : false;
1858 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1859 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1867 * Get an associative array of additional HTML attributes appropriate for a
1868 * particular external link. This currently may include rel => nofollow
1869 * (depending on configuration, namespace, and the URL's domain) and/or a
1870 * target attribute (depending on configuration).
1872 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1873 * nofollow if appropriate
1874 * @return array Associative array of HTML attributes
1876 public function getExternalLinkAttribs( $url = false ) {
1878 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1880 if ( $this->mOptions
->getExternalLinkTarget() ) {
1881 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1887 * Replace unusual escape codes in a URL with their equivalent characters
1889 * @deprecated since 1.24, use normalizeLinkUrl
1890 * @param string $url
1893 public static function replaceUnusualEscapes( $url ) {
1894 wfDeprecated( __METHOD__
, '1.24' );
1895 return self
::normalizeLinkUrl( $url );
1899 * Replace unusual escape codes in a URL with their equivalent characters
1901 * This generally follows the syntax defined in RFC 3986, with special
1902 * consideration for HTTP query strings.
1904 * @param string $url
1907 public static function normalizeLinkUrl( $url ) {
1908 # First, make sure unsafe characters are encoded
1909 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1911 return rawurlencode( $m[0] );
1917 $end = strlen( $url );
1919 # Fragment part - 'fragment'
1920 $start = strpos( $url, '#' );
1921 if ( $start !== false && $start < $end ) {
1922 $ret = self
::normalizeUrlComponent(
1923 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1927 # Query part - 'query' minus &=+;
1928 $start = strpos( $url, '?' );
1929 if ( $start !== false && $start < $end ) {
1930 $ret = self
::normalizeUrlComponent(
1931 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1935 # Scheme and path part - 'pchar'
1936 # (we assume no userinfo or encoded colons in the host)
1937 $ret = self
::normalizeUrlComponent(
1938 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1943 private static function normalizeUrlComponent( $component, $unsafe ) {
1944 $callback = function ( $matches ) use ( $unsafe ) {
1945 $char = urldecode( $matches[0] );
1946 $ord = ord( $char );
1947 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1951 # Leave it escaped, but use uppercase for a-f
1952 return strtoupper( $matches[0] );
1955 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1959 * make an image if it's allowed, either through the global
1960 * option, through the exception, or through the on-wiki whitelist
1962 * @param string $url
1966 private function maybeMakeExternalImage( $url ) {
1967 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1968 $imagesexception = !empty( $imagesfrom );
1970 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1971 if ( $imagesexception && is_array( $imagesfrom ) ) {
1972 $imagematch = false;
1973 foreach ( $imagesfrom as $match ) {
1974 if ( strpos( $url, $match ) === 0 ) {
1979 } elseif ( $imagesexception ) {
1980 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1982 $imagematch = false;
1985 if ( $this->mOptions
->getAllowExternalImages()
1986 ||
( $imagesexception && $imagematch )
1988 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1990 $text = Linker
::makeExternalImage( $url );
1993 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1994 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1996 $whitelist = explode(
1998 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2001 foreach ( $whitelist as $entry ) {
2002 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2003 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2006 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2007 # Image matches a whitelist entry
2008 $text = Linker
::makeExternalImage( $url );
2017 * Process [[ ]] wikilinks
2021 * @return string Processed text
2025 public function replaceInternalLinks( $s ) {
2026 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2031 * Process [[ ]] wikilinks (RIL)
2033 * @throws MWException
2034 * @return LinkHolderArray
2038 public function replaceInternalLinks2( &$s ) {
2039 global $wgExtraInterlanguageLinkPrefixes;
2040 wfProfileIn( __METHOD__
);
2042 wfProfileIn( __METHOD__
. '-setup' );
2043 static $tc = false, $e1, $e1_img;
2044 # the % is needed to support urlencoded titles as well
2046 $tc = Title
::legalChars() . '#%';
2047 # Match a link having the form [[namespace:link|alternate]]trail
2048 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2049 # Match cases where there is no "]]", which might still be images
2050 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2053 $holders = new LinkHolderArray( $this );
2055 # split the entire text string on occurrences of [[
2056 $a = StringUtils
::explode( '[[', ' ' . $s );
2057 # get the first element (all text up to first [[), and remove the space we added
2060 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2061 $s = substr( $s, 1 );
2063 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2065 if ( $useLinkPrefixExtension ) {
2066 # Match the end of a line for a word that's not followed by whitespace,
2067 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2069 $charset = $wgContLang->linkPrefixCharset();
2070 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2073 if ( is_null( $this->mTitle
) ) {
2074 wfProfileOut( __METHOD__
. '-setup' );
2075 wfProfileOut( __METHOD__
);
2076 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2078 $nottalk = !$this->mTitle
->isTalkPage();
2080 if ( $useLinkPrefixExtension ) {
2082 if ( preg_match( $e2, $s, $m ) ) {
2083 $first_prefix = $m[2];
2085 $first_prefix = false;
2091 $useSubpages = $this->areSubpagesAllowed();
2092 wfProfileOut( __METHOD__
. '-setup' );
2094 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2095 # Loop for each link
2096 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2097 // @codingStandardsIgnoreStart
2099 # Check for excessive memory usage
2100 if ( $holders->isBig() ) {
2102 # Do the existence check, replace the link holders and clear the array
2103 $holders->replace( $s );
2107 if ( $useLinkPrefixExtension ) {
2108 wfProfileIn( __METHOD__
. '-prefixhandling' );
2109 if ( preg_match( $e2, $s, $m ) ) {
2116 if ( $first_prefix ) {
2117 $prefix = $first_prefix;
2118 $first_prefix = false;
2120 wfProfileOut( __METHOD__
. '-prefixhandling' );
2123 $might_be_img = false;
2125 wfProfileIn( __METHOD__
. "-e1" );
2126 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2128 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2129 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2130 # the real problem is with the $e1 regex
2133 # Still some problems for cases where the ] is meant to be outside punctuation,
2134 # and no image is in sight. See bug 2095.
2137 && substr( $m[3], 0, 1 ) === ']'
2138 && strpos( $text, '[' ) !== false
2140 $text .= ']'; # so that replaceExternalLinks($text) works later
2141 $m[3] = substr( $m[3], 1 );
2143 # fix up urlencoded title texts
2144 if ( strpos( $m[1], '%' ) !== false ) {
2145 # Should anchors '#' also be rejected?
2146 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2149 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2150 # Invalid, but might be an image with a link in its caption
2151 $might_be_img = true;
2153 if ( strpos( $m[1], '%' ) !== false ) {
2154 $m[1] = rawurldecode( $m[1] );
2157 } else { # Invalid form; output directly
2158 $s .= $prefix . '[[' . $line;
2159 wfProfileOut( __METHOD__
. "-e1" );
2162 wfProfileOut( __METHOD__
. "-e1" );
2163 wfProfileIn( __METHOD__
. "-misc" );
2167 # Don't allow internal links to pages containing
2168 # PROTO: where PROTO is a valid URL protocol; these
2169 # should be external links.
2170 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2171 $s .= $prefix . '[[' . $line;
2172 wfProfileOut( __METHOD__
. "-misc" );
2176 # Make subpage if necessary
2177 if ( $useSubpages ) {
2178 $link = $this->maybeDoSubpageLink( $origLink, $text );
2183 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2185 # Strip off leading ':'
2186 $link = substr( $link, 1 );
2189 wfProfileOut( __METHOD__
. "-misc" );
2190 wfProfileIn( __METHOD__
. "-title" );
2191 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2192 if ( $nt === null ) {
2193 $s .= $prefix . '[[' . $line;
2194 wfProfileOut( __METHOD__
. "-title" );
2198 $ns = $nt->getNamespace();
2199 $iw = $nt->getInterwiki();
2200 wfProfileOut( __METHOD__
. "-title" );
2202 if ( $might_be_img ) { # if this is actually an invalid link
2203 wfProfileIn( __METHOD__
. "-might_be_img" );
2204 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2207 # look at the next 'line' to see if we can close it there
2209 $next_line = $a->current();
2210 if ( $next_line === false ||
$next_line === null ) {
2213 $m = explode( ']]', $next_line, 3 );
2214 if ( count( $m ) == 3 ) {
2215 # the first ]] closes the inner link, the second the image
2217 $text .= "[[{$m[0]}]]{$m[1]}";
2220 } elseif ( count( $m ) == 2 ) {
2221 # if there's exactly one ]] that's fine, we'll keep looking
2222 $text .= "[[{$m[0]}]]{$m[1]}";
2224 # if $next_line is invalid too, we need look no further
2225 $text .= '[[' . $next_line;
2230 # we couldn't find the end of this imageLink, so output it raw
2231 # but don't ignore what might be perfectly normal links in the text we've examined
2232 $holders->merge( $this->replaceInternalLinks2( $text ) );
2233 $s .= "{$prefix}[[$link|$text";
2234 # note: no $trail, because without an end, there *is* no trail
2235 wfProfileOut( __METHOD__
. "-might_be_img" );
2238 } else { # it's not an image, so output it raw
2239 $s .= "{$prefix}[[$link|$text";
2240 # note: no $trail, because without an end, there *is* no trail
2241 wfProfileOut( __METHOD__
. "-might_be_img" );
2244 wfProfileOut( __METHOD__
. "-might_be_img" );
2247 $wasblank = ( $text == '' );
2251 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2252 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2253 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2254 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2255 $text = $this->doQuotes( $text );
2258 # Link not escaped by : , create the various objects
2259 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2261 wfProfileIn( __METHOD__
. "-interwiki" );
2263 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2264 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2265 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2268 # Bug 24502: filter duplicates
2269 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2270 $this->mLangLinkLanguages
[$iw] = true;
2271 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2274 $s = rtrim( $s . $prefix );
2275 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2276 wfProfileOut( __METHOD__
. "-interwiki" );
2279 wfProfileOut( __METHOD__
. "-interwiki" );
2281 if ( $ns == NS_FILE
) {
2282 wfProfileIn( __METHOD__
. "-image" );
2283 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2285 # if no parameters were passed, $text
2286 # becomes something like "File:Foo.png",
2287 # which we don't want to pass on to the
2291 # recursively parse links inside the image caption
2292 # actually, this will parse them in any other parameters, too,
2293 # but it might be hard to fix that, and it doesn't matter ATM
2294 $text = $this->replaceExternalLinks( $text );
2295 $holders->merge( $this->replaceInternalLinks2( $text ) );
2297 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2298 $s .= $prefix . $this->armorLinks(
2299 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2301 $s .= $prefix . $trail;
2303 wfProfileOut( __METHOD__
. "-image" );
2307 if ( $ns == NS_CATEGORY
) {
2308 wfProfileIn( __METHOD__
. "-category" );
2309 $s = rtrim( $s . "\n" ); # bug 87
2312 $sortkey = $this->getDefaultSort();
2316 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2317 $sortkey = str_replace( "\n", '', $sortkey );
2318 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2319 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2322 * Strip the whitespace Category links produce, see bug 87
2324 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2326 wfProfileOut( __METHOD__
. "-category" );
2331 # Self-link checking. For some languages, variants of the title are checked in
2332 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2333 # for linking to a different variant.
2334 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2335 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2339 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2340 # @todo FIXME: Should do batch file existence checks, see comment below
2341 if ( $ns == NS_MEDIA
) {
2342 wfProfileIn( __METHOD__
. "-media" );
2343 # Give extensions a chance to select the file revision for us
2346 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2347 array( $this, $nt, &$options, &$descQuery ) );
2348 # Fetch and register the file (file title may be different via hooks)
2349 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2350 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2351 $s .= $prefix . $this->armorLinks(
2352 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2353 wfProfileOut( __METHOD__
. "-media" );
2357 wfProfileIn( __METHOD__
. "-always_known" );
2358 # Some titles, such as valid special pages or files in foreign repos, should
2359 # be shown as bluelinks even though they're not included in the page table
2361 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2362 # batch file existence checks for NS_FILE and NS_MEDIA
2363 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2364 $this->mOutput
->addLink( $nt );
2365 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2367 # Links will be added to the output link list after checking
2368 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2370 wfProfileOut( __METHOD__
. "-always_known" );
2372 wfProfileOut( __METHOD__
);
2377 * Render a forced-blue link inline; protect against double expansion of
2378 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2379 * Since this little disaster has to split off the trail text to avoid
2380 * breaking URLs in the following text without breaking trails on the
2381 * wiki links, it's been made into a horrible function.
2384 * @param string $text
2385 * @param array|string $query
2386 * @param string $trail
2387 * @param string $prefix
2388 * @return string HTML-wikitext mix oh yuck
2390 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2391 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2393 if ( is_string( $query ) ) {
2394 $query = wfCgiToArray( $query );
2396 if ( $text == '' ) {
2397 $text = htmlspecialchars( $nt->getPrefixedText() );
2400 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2402 return $this->armorLinks( $link ) . $trail;
2406 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2407 * going to go through further parsing steps before inline URL expansion.
2409 * Not needed quite as much as it used to be since free links are a bit
2410 * more sensible these days. But bracketed links are still an issue.
2412 * @param string $text More-or-less HTML
2413 * @return string Less-or-more HTML with NOPARSE bits
2415 public function armorLinks( $text ) {
2416 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2417 "{$this->mUniqPrefix}NOPARSE$1", $text );
2421 * Return true if subpage links should be expanded on this page.
2424 public function areSubpagesAllowed() {
2425 # Some namespaces don't allow subpages
2426 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2430 * Handle link to subpage if necessary
2432 * @param string $target The source of the link
2433 * @param string &$text The link text, modified as necessary
2434 * @return string The full name of the link
2437 public function maybeDoSubpageLink( $target, &$text ) {
2438 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2442 * Used by doBlockLevels()
2447 public function closeParagraph() {
2449 if ( $this->mLastSection
!= '' ) {
2450 $result = '</' . $this->mLastSection
. ">\n";
2452 $this->mInPre
= false;
2453 $this->mLastSection
= '';
2458 * getCommon() returns the length of the longest common substring
2459 * of both arguments, starting at the beginning of both.
2462 * @param string $st1
2463 * @param string $st2
2467 public function getCommon( $st1, $st2 ) {
2468 $fl = strlen( $st1 );
2469 $shorter = strlen( $st2 );
2470 if ( $fl < $shorter ) {
2474 for ( $i = 0; $i < $shorter; ++
$i ) {
2475 if ( $st1[$i] != $st2[$i] ) {
2483 * These next three functions open, continue, and close the list
2484 * element appropriate to the prefix character passed into them.
2487 * @param string $char
2491 public function openList( $char ) {
2492 $result = $this->closeParagraph();
2494 if ( '*' === $char ) {
2495 $result .= "<ul><li>";
2496 } elseif ( '#' === $char ) {
2497 $result .= "<ol><li>";
2498 } elseif ( ':' === $char ) {
2499 $result .= "<dl><dd>";
2500 } elseif ( ';' === $char ) {
2501 $result .= "<dl><dt>";
2502 $this->mDTopen
= true;
2504 $result = '<!-- ERR 1 -->';
2512 * @param string $char
2517 public function nextItem( $char ) {
2518 if ( '*' === $char ||
'#' === $char ) {
2519 return "</li>\n<li>";
2520 } elseif ( ':' === $char ||
';' === $char ) {
2522 if ( $this->mDTopen
) {
2525 if ( ';' === $char ) {
2526 $this->mDTopen
= true;
2527 return $close . '<dt>';
2529 $this->mDTopen
= false;
2530 return $close . '<dd>';
2533 return '<!-- ERR 2 -->';
2538 * @param string $char
2543 public function closeList( $char ) {
2544 if ( '*' === $char ) {
2545 $text = "</li></ul>";
2546 } elseif ( '#' === $char ) {
2547 $text = "</li></ol>";
2548 } elseif ( ':' === $char ) {
2549 if ( $this->mDTopen
) {
2550 $this->mDTopen
= false;
2551 $text = "</dt></dl>";
2553 $text = "</dd></dl>";
2556 return '<!-- ERR 3 -->';
2563 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2565 * @param string $text
2566 * @param bool $linestart Whether or not this is at the start of a line.
2568 * @return string The lists rendered as HTML
2570 public function doBlockLevels( $text, $linestart ) {
2571 wfProfileIn( __METHOD__
);
2573 # Parsing through the text line by line. The main thing
2574 # happening here is handling of block-level elements p, pre,
2575 # and making lists from lines starting with * # : etc.
2577 $textLines = StringUtils
::explode( "\n", $text );
2579 $lastPrefix = $output = '';
2580 $this->mDTopen
= $inBlockElem = false;
2582 $paragraphStack = false;
2583 $inBlockquote = false;
2585 foreach ( $textLines as $oLine ) {
2587 if ( !$linestart ) {
2597 $lastPrefixLength = strlen( $lastPrefix );
2598 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2599 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2600 # If not in a <pre> element, scan for and figure out what prefixes are there.
2601 if ( !$this->mInPre
) {
2602 # Multiple prefixes may abut each other for nested lists.
2603 $prefixLength = strspn( $oLine, '*#:;' );
2604 $prefix = substr( $oLine, 0, $prefixLength );
2607 # ; and : are both from definition-lists, so they're equivalent
2608 # for the purposes of determining whether or not we need to open/close
2610 $prefix2 = str_replace( ';', ':', $prefix );
2611 $t = substr( $oLine, $prefixLength );
2612 $this->mInPre
= (bool)$preOpenMatch;
2614 # Don't interpret any other prefixes in preformatted text
2616 $prefix = $prefix2 = '';
2621 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2622 # Same as the last item, so no need to deal with nesting or opening stuff
2623 $output .= $this->nextItem( substr( $prefix, -1 ) );
2624 $paragraphStack = false;
2626 if ( substr( $prefix, -1 ) === ';' ) {
2627 # The one nasty exception: definition lists work like this:
2628 # ; title : definition text
2629 # So we check for : in the remainder text to split up the
2630 # title and definition, without b0rking links.
2632 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2634 $output .= $term . $this->nextItem( ':' );
2637 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2638 # We need to open or close prefixes, or both.
2640 # Either open or close a level...
2641 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2642 $paragraphStack = false;
2644 # Close all the prefixes which aren't shared.
2645 while ( $commonPrefixLength < $lastPrefixLength ) {
2646 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2647 --$lastPrefixLength;
2650 # Continue the current prefix if appropriate.
2651 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2652 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2655 # Open prefixes where appropriate.
2656 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2659 while ( $prefixLength > $commonPrefixLength ) {
2660 $char = substr( $prefix, $commonPrefixLength, 1 );
2661 $output .= $this->openList( $char );
2663 if ( ';' === $char ) {
2664 # @todo FIXME: This is dupe of code above
2665 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2667 $output .= $term . $this->nextItem( ':' );
2670 ++
$commonPrefixLength;
2672 if ( !$prefixLength && $lastPrefix ) {
2675 $lastPrefix = $prefix2;
2678 # If we have no prefixes, go to paragraph mode.
2679 if ( 0 == $prefixLength ) {
2680 wfProfileIn( __METHOD__
. "-paragraph" );
2681 # No prefix (not in list)--go to paragraph mode
2682 # XXX: use a stack for nestable elements like span, table and div
2683 $openmatch = preg_match(
2684 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2685 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2688 $closematch = preg_match(
2689 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2690 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2691 . $this->mUniqPrefix
2692 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2696 if ( $openmatch ||
$closematch ) {
2697 $paragraphStack = false;
2698 # @todo bug 5718: paragraph closed
2699 $output .= $this->closeParagraph();
2700 if ( $preOpenMatch && !$preCloseMatch ) {
2701 $this->mInPre
= true;
2704 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2705 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2706 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2708 $inBlockElem = !$closematch;
2709 } elseif ( !$inBlockElem && !$this->mInPre
) {
2710 if ( ' ' == substr( $t, 0, 1 )
2711 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2715 if ( $this->mLastSection
!== 'pre' ) {
2716 $paragraphStack = false;
2717 $output .= $this->closeParagraph() . '<pre>';
2718 $this->mLastSection
= 'pre';
2720 $t = substr( $t, 1 );
2723 if ( trim( $t ) === '' ) {
2724 if ( $paragraphStack ) {
2725 $output .= $paragraphStack . '<br />';
2726 $paragraphStack = false;
2727 $this->mLastSection
= 'p';
2729 if ( $this->mLastSection
!== 'p' ) {
2730 $output .= $this->closeParagraph();
2731 $this->mLastSection
= '';
2732 $paragraphStack = '<p>';
2734 $paragraphStack = '</p><p>';
2738 if ( $paragraphStack ) {
2739 $output .= $paragraphStack;
2740 $paragraphStack = false;
2741 $this->mLastSection
= 'p';
2742 } elseif ( $this->mLastSection
!== 'p' ) {
2743 $output .= $this->closeParagraph() . '<p>';
2744 $this->mLastSection
= 'p';
2749 wfProfileOut( __METHOD__
. "-paragraph" );
2751 # somewhere above we forget to get out of pre block (bug 785)
2752 if ( $preCloseMatch && $this->mInPre
) {
2753 $this->mInPre
= false;
2755 if ( $paragraphStack === false ) {
2757 if ( $prefixLength === 0 ) {
2762 while ( $prefixLength ) {
2763 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2765 if ( !$prefixLength ) {
2769 if ( $this->mLastSection
!= '' ) {
2770 $output .= '</' . $this->mLastSection
. '>';
2771 $this->mLastSection
= '';
2774 wfProfileOut( __METHOD__
);
2779 * Split up a string on ':', ignoring any occurrences inside tags
2780 * to prevent illegal overlapping.
2782 * @param string $str The string to split
2783 * @param string &$before Set to everything before the ':'
2784 * @param string &$after Set to everything after the ':'
2785 * @throws MWException
2786 * @return string The position of the ':', or false if none found
2788 public function findColonNoLinks( $str, &$before, &$after ) {
2789 wfProfileIn( __METHOD__
);
2791 $pos = strpos( $str, ':' );
2792 if ( $pos === false ) {
2794 wfProfileOut( __METHOD__
);
2798 $lt = strpos( $str, '<' );
2799 if ( $lt === false ||
$lt > $pos ) {
2800 # Easy; no tag nesting to worry about
2801 $before = substr( $str, 0, $pos );
2802 $after = substr( $str, $pos +
1 );
2803 wfProfileOut( __METHOD__
);
2807 # Ugly state machine to walk through avoiding tags.
2808 $state = self
::COLON_STATE_TEXT
;
2810 $len = strlen( $str );
2811 for ( $i = 0; $i < $len; $i++
) {
2815 # (Using the number is a performance hack for common cases)
2816 case 0: # self::COLON_STATE_TEXT:
2819 # Could be either a <start> tag or an </end> tag
2820 $state = self
::COLON_STATE_TAGSTART
;
2823 if ( $stack == 0 ) {
2825 $before = substr( $str, 0, $i );
2826 $after = substr( $str, $i +
1 );
2827 wfProfileOut( __METHOD__
);
2830 # Embedded in a tag; don't break it.
2833 # Skip ahead looking for something interesting
2834 $colon = strpos( $str, ':', $i );
2835 if ( $colon === false ) {
2836 # Nothing else interesting
2837 wfProfileOut( __METHOD__
);
2840 $lt = strpos( $str, '<', $i );
2841 if ( $stack === 0 ) {
2842 if ( $lt === false ||
$colon < $lt ) {
2844 $before = substr( $str, 0, $colon );
2845 $after = substr( $str, $colon +
1 );
2846 wfProfileOut( __METHOD__
);
2850 if ( $lt === false ) {
2851 # Nothing else interesting to find; abort!
2852 # We're nested, but there's no close tags left. Abort!
2855 # Skip ahead to next tag start
2857 $state = self
::COLON_STATE_TAGSTART
;
2860 case 1: # self::COLON_STATE_TAG:
2865 $state = self
::COLON_STATE_TEXT
;
2868 # Slash may be followed by >?
2869 $state = self
::COLON_STATE_TAGSLASH
;
2875 case 2: # self::COLON_STATE_TAGSTART:
2878 $state = self
::COLON_STATE_CLOSETAG
;
2881 $state = self
::COLON_STATE_COMMENT
;
2884 # Illegal early close? This shouldn't happen D:
2885 $state = self
::COLON_STATE_TEXT
;
2888 $state = self
::COLON_STATE_TAG
;
2891 case 3: # self::COLON_STATE_CLOSETAG:
2896 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2897 wfProfileOut( __METHOD__
);
2900 $state = self
::COLON_STATE_TEXT
;
2903 case self
::COLON_STATE_TAGSLASH
:
2905 # Yes, a self-closed tag <blah/>
2906 $state = self
::COLON_STATE_TEXT
;
2908 # Probably we're jumping the gun, and this is an attribute
2909 $state = self
::COLON_STATE_TAG
;
2912 case 5: # self::COLON_STATE_COMMENT:
2914 $state = self
::COLON_STATE_COMMENTDASH
;
2917 case self
::COLON_STATE_COMMENTDASH
:
2919 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2921 $state = self
::COLON_STATE_COMMENT
;
2924 case self
::COLON_STATE_COMMENTDASHDASH
:
2926 $state = self
::COLON_STATE_TEXT
;
2928 $state = self
::COLON_STATE_COMMENT
;
2932 wfProfileOut( __METHOD__
);
2933 throw new MWException( "State machine error in " . __METHOD__
);
2937 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2938 wfProfileOut( __METHOD__
);
2941 wfProfileOut( __METHOD__
);
2946 * Return value of a magic variable (like PAGENAME)
2951 * @param bool|PPFrame $frame
2953 * @throws MWException
2956 public function getVariableValue( $index, $frame = false ) {
2957 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2958 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2960 if ( is_null( $this->mTitle
) ) {
2961 // If no title set, bad things are going to happen
2962 // later. Title should always be set since this
2963 // should only be called in the middle of a parse
2964 // operation (but the unit-tests do funky stuff)
2965 throw new MWException( __METHOD__
. ' Should only be '
2966 . ' called while parsing (no title set)' );
2970 * Some of these require message or data lookups and can be
2971 * expensive to check many times.
2973 if ( Hooks
::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2974 if ( isset( $this->mVarCache
[$index] ) ) {
2975 return $this->mVarCache
[$index];
2979 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2980 Hooks
::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2982 $pageLang = $this->getFunctionLang();
2988 case 'currentmonth':
2989 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2991 case 'currentmonth1':
2992 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2994 case 'currentmonthname':
2995 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2997 case 'currentmonthnamegen':
2998 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
3000 case 'currentmonthabbrev':
3001 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
3004 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
3007 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
3010 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
3013 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
3015 case 'localmonthname':
3016 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
3018 case 'localmonthnamegen':
3019 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
3021 case 'localmonthabbrev':
3022 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
3025 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
3028 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
3031 $value = wfEscapeWikiText( $this->mTitle
->getText() );
3034 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
3036 case 'fullpagename':
3037 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
3039 case 'fullpagenamee':
3040 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
3043 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
3045 case 'subpagenamee':
3046 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
3048 case 'rootpagename':
3049 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
3051 case 'rootpagenamee':
3052 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3055 $this->mTitle
->getRootText()
3058 case 'basepagename':
3059 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
3061 case 'basepagenamee':
3062 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3065 $this->mTitle
->getBaseText()
3068 case 'talkpagename':
3069 if ( $this->mTitle
->canTalk() ) {
3070 $talkPage = $this->mTitle
->getTalkPage();
3071 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
3076 case 'talkpagenamee':
3077 if ( $this->mTitle
->canTalk() ) {
3078 $talkPage = $this->mTitle
->getTalkPage();
3079 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3084 case 'subjectpagename':
3085 $subjPage = $this->mTitle
->getSubjectPage();
3086 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3088 case 'subjectpagenamee':
3089 $subjPage = $this->mTitle
->getSubjectPage();
3090 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3092 case 'pageid': // requested in bug 23427
3093 $pageid = $this->getTitle()->getArticleID();
3094 if ( $pageid == 0 ) {
3095 # 0 means the page doesn't exist in the database,
3096 # which means the user is previewing a new page.
3097 # The vary-revision flag must be set, because the magic word
3098 # will have a different value once the page is saved.
3099 $this->mOutput
->setFlag( 'vary-revision' );
3100 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3102 $value = $pageid ?
$pageid : null;
3105 # Let the edit saving system know we should parse the page
3106 # *after* a revision ID has been assigned.
3107 $this->mOutput
->setFlag( 'vary-revision' );
3108 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3109 $value = $this->mRevisionId
;
3112 # Let the edit saving system know we should parse the page
3113 # *after* a revision ID has been assigned. This is for null edits.
3114 $this->mOutput
->setFlag( 'vary-revision' );
3115 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3116 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3118 case 'revisionday2':
3119 # Let the edit saving system know we should parse the page
3120 # *after* a revision ID has been assigned. This is for null edits.
3121 $this->mOutput
->setFlag( 'vary-revision' );
3122 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3123 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3125 case 'revisionmonth':
3126 # Let the edit saving system know we should parse the page
3127 # *after* a revision ID has been assigned. This is for null edits.
3128 $this->mOutput
->setFlag( 'vary-revision' );
3129 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3130 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3132 case 'revisionmonth1':
3133 # Let the edit saving system know we should parse the page
3134 # *after* a revision ID has been assigned. This is for null edits.
3135 $this->mOutput
->setFlag( 'vary-revision' );
3136 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3137 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3139 case 'revisionyear':
3140 # Let the edit saving system know we should parse the page
3141 # *after* a revision ID has been assigned. This is for null edits.
3142 $this->mOutput
->setFlag( 'vary-revision' );
3143 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3144 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3146 case 'revisiontimestamp':
3147 # Let the edit saving system know we should parse the page
3148 # *after* a revision ID has been assigned. This is for null edits.
3149 $this->mOutput
->setFlag( 'vary-revision' );
3150 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3151 $value = $this->getRevisionTimestamp();
3153 case 'revisionuser':
3154 # Let the edit saving system know we should parse the page
3155 # *after* a revision ID has been assigned. This is for null edits.
3156 $this->mOutput
->setFlag( 'vary-revision' );
3157 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3158 $value = $this->getRevisionUser();
3160 case 'revisionsize':
3161 # Let the edit saving system know we should parse the page
3162 # *after* a revision ID has been assigned. This is for null edits.
3163 $this->mOutput
->setFlag( 'vary-revision' );
3164 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3165 $value = $this->getRevisionSize();
3168 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3171 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3173 case 'namespacenumber':
3174 $value = $this->mTitle
->getNamespace();
3177 $value = $this->mTitle
->canTalk()
3178 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3182 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3184 case 'subjectspace':
3185 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3187 case 'subjectspacee':
3188 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3190 case 'currentdayname':
3191 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3194 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3197 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3200 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3203 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3204 # int to remove the padding
3205 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3208 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3210 case 'localdayname':
3211 $value = $pageLang->getWeekdayName(
3212 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3216 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3219 $value = $pageLang->time(
3220 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3226 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3229 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3230 # int to remove the padding
3231 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3234 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3236 case 'numberofarticles':
3237 $value = $pageLang->formatNum( SiteStats
::articles() );
3239 case 'numberoffiles':
3240 $value = $pageLang->formatNum( SiteStats
::images() );
3242 case 'numberofusers':
3243 $value = $pageLang->formatNum( SiteStats
::users() );
3245 case 'numberofactiveusers':
3246 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3248 case 'numberofpages':
3249 $value = $pageLang->formatNum( SiteStats
::pages() );
3251 case 'numberofadmins':
3252 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3254 case 'numberofedits':
3255 $value = $pageLang->formatNum( SiteStats
::edits() );
3257 case 'currenttimestamp':
3258 $value = wfTimestamp( TS_MW
, $ts );
3260 case 'localtimestamp':
3261 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3263 case 'currentversion':
3264 $value = SpecialVersion
::getVersion();
3267 return $wgArticlePath;
3273 return $wgServerName;
3275 return $wgScriptPath;
3277 return $wgStylePath;
3278 case 'directionmark':
3279 return $pageLang->getDirMark();
3280 case 'contentlanguage':
3281 global $wgLanguageCode;
3282 return $wgLanguageCode;
3283 case 'cascadingsources':
3284 $value = CoreParserFunctions
::cascadingsources( $this );
3289 'ParserGetVariableValueSwitch',
3290 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3297 $this->mVarCache
[$index] = $value;
3304 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3308 public function initialiseVariables() {
3309 wfProfileIn( __METHOD__
);
3310 $variableIDs = MagicWord
::getVariableIDs();
3311 $substIDs = MagicWord
::getSubstIDs();
3313 $this->mVariables
= new MagicWordArray( $variableIDs );
3314 $this->mSubstWords
= new MagicWordArray( $substIDs );
3315 wfProfileOut( __METHOD__
);
3319 * Preprocess some wikitext and return the document tree.
3320 * This is the ghost of replace_variables().
3322 * @param string $text The text to parse
3323 * @param int $flags Bitwise combination of:
3324 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3325 * included. Default is to assume a direct page view.
3327 * The generated DOM tree must depend only on the input text and the flags.
3328 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3330 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3331 * change in the DOM tree for a given text, must be passed through the section identifier
3332 * in the section edit link and thus back to extractSections().
3334 * The output of this function is currently only cached in process memory, but a persistent
3335 * cache may be implemented at a later date which takes further advantage of these strict
3336 * dependency requirements.
3340 public function preprocessToDom( $text, $flags = 0 ) {
3341 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3346 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3352 public static function splitWhitespace( $s ) {
3353 $ltrimmed = ltrim( $s );
3354 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3355 $trimmed = rtrim( $ltrimmed );
3356 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3358 $w2 = substr( $ltrimmed, -$diff );
3362 return array( $w1, $trimmed, $w2 );
3366 * Replace magic variables, templates, and template arguments
3367 * with the appropriate text. Templates are substituted recursively,
3368 * taking care to avoid infinite loops.
3370 * Note that the substitution depends on value of $mOutputType:
3371 * self::OT_WIKI: only {{subst:}} templates
3372 * self::OT_PREPROCESS: templates but not extension tags
3373 * self::OT_HTML: all templates and extension tags
3375 * @param string $text The text to transform
3376 * @param bool|PPFrame $frame Object describing the arguments passed to the
3377 * template. Arguments may also be provided as an associative array, as
3378 * was the usual case before MW1.12. Providing arguments this way may be
3379 * useful for extensions wishing to perform variable replacement
3381 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3382 * double-brace expansion.
3385 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3386 # Is there any text? Also, Prevent too big inclusions!
3387 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3390 wfProfileIn( __METHOD__
);
3392 if ( $frame === false ) {
3393 $frame = $this->getPreprocessor()->newFrame();
3394 } elseif ( !( $frame instanceof PPFrame
) ) {
3395 wfDebug( __METHOD__
. " called using plain parameters instead of "
3396 . "a PPFrame instance. Creating custom frame.\n" );
3397 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3400 $dom = $this->preprocessToDom( $text );
3401 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3402 $text = $frame->expand( $dom, $flags );
3404 wfProfileOut( __METHOD__
);
3409 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3411 * @param array $args
3415 public static function createAssocArgs( $args ) {
3416 $assocArgs = array();
3418 foreach ( $args as $arg ) {
3419 $eqpos = strpos( $arg, '=' );
3420 if ( $eqpos === false ) {
3421 $assocArgs[$index++
] = $arg;
3423 $name = trim( substr( $arg, 0, $eqpos ) );
3424 $value = trim( substr( $arg, $eqpos +
1 ) );
3425 if ( $value === false ) {
3428 if ( $name !== false ) {
3429 $assocArgs[$name] = $value;
3438 * Warn the user when a parser limitation is reached
3439 * Will warn at most once the user per limitation type
3441 * @param string $limitationType Should be one of:
3442 * 'expensive-parserfunction' (corresponding messages:
3443 * 'expensive-parserfunction-warning',
3444 * 'expensive-parserfunction-category')
3445 * 'post-expand-template-argument' (corresponding messages:
3446 * 'post-expand-template-argument-warning',
3447 * 'post-expand-template-argument-category')
3448 * 'post-expand-template-inclusion' (corresponding messages:
3449 * 'post-expand-template-inclusion-warning',
3450 * 'post-expand-template-inclusion-category')
3451 * 'node-count-exceeded' (corresponding messages:
3452 * 'node-count-exceeded-warning',
3453 * 'node-count-exceeded-category')
3454 * 'expansion-depth-exceeded' (corresponding messages:
3455 * 'expansion-depth-exceeded-warning',
3456 * 'expansion-depth-exceeded-category')
3457 * @param string|int|null $current Current value
3458 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3459 * exceeded, provide the values (optional)
3461 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3462 # does no harm if $current and $max are present but are unnecessary for the message
3463 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3464 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3465 $this->mOutput
->addWarning( $warning );
3466 $this->addTrackingCategory( "$limitationType-category" );
3470 * Return the text of a template, after recursively
3471 * replacing any variables or templates within the template.
3473 * @param array $piece The parts of the template
3474 * $piece['title']: the title, i.e. the part before the |
3475 * $piece['parts']: the parameter array
3476 * $piece['lineStart']: whether the brace was at the start of a line
3477 * @param PPFrame $frame The current frame, contains template arguments
3479 * @return string The text of the template
3481 public function braceSubstitution( $piece, $frame ) {
3482 wfProfileIn( __METHOD__
);
3483 wfProfileIn( __METHOD__
. '-setup' );
3487 // $text has been filled
3489 // wiki markup in $text should be escaped
3491 // $text is HTML, armour it against wikitext transformation
3493 // Force interwiki transclusion to be done in raw mode not rendered
3494 $forceRawInterwiki = false;
3495 // $text is a DOM node needing expansion in a child frame
3496 $isChildObj = false;
3497 // $text is a DOM node needing expansion in the current frame
3498 $isLocalObj = false;
3500 # Title object, where $text came from
3503 # $part1 is the bit before the first |, and must contain only title characters.
3504 # Various prefixes will be stripped from it later.
3505 $titleWithSpaces = $frame->expand( $piece['title'] );
3506 $part1 = trim( $titleWithSpaces );
3509 # Original title text preserved for various purposes
3510 $originalTitle = $part1;
3512 # $args is a list of argument nodes, starting from index 0, not including $part1
3513 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3514 # below won't work b/c this $args isn't an object
3515 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3516 wfProfileOut( __METHOD__
. '-setup' );
3518 $profileSection = null; // profile templates
3521 wfProfileIn( __METHOD__
. '-modifiers' );
3524 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3526 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3527 # Decide whether to expand template or keep wikitext as-is.
3528 if ( $this->ot
['wiki'] ) {
3529 if ( $substMatch === false ) {
3530 $literal = true; # literal when in PST with no prefix
3532 $literal = false; # expand when in PST with subst: or safesubst:
3535 if ( $substMatch == 'subst' ) {
3536 $literal = true; # literal when not in PST with plain subst:
3538 $literal = false; # expand when not in PST with safesubst: or no prefix
3542 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3549 if ( !$found && $args->getLength() == 0 ) {
3550 $id = $this->mVariables
->matchStartToEnd( $part1 );
3551 if ( $id !== false ) {
3552 $text = $this->getVariableValue( $id, $frame );
3553 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3554 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3560 # MSG, MSGNW and RAW
3563 $mwMsgnw = MagicWord
::get( 'msgnw' );
3564 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3567 # Remove obsolete MSG:
3568 $mwMsg = MagicWord
::get( 'msg' );
3569 $mwMsg->matchStartAndRemove( $part1 );
3573 $mwRaw = MagicWord
::get( 'raw' );
3574 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3575 $forceRawInterwiki = true;
3578 wfProfileOut( __METHOD__
. '-modifiers' );
3582 wfProfileIn( __METHOD__
. '-pfunc' );
3584 $colonPos = strpos( $part1, ':' );
3585 if ( $colonPos !== false ) {
3586 $func = substr( $part1, 0, $colonPos );
3587 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3588 for ( $i = 0; $i < $args->getLength(); $i++
) {
3589 $funcArgs[] = $args->item( $i );
3592 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3593 } catch ( Exception
$ex ) {
3594 wfProfileOut( __METHOD__
. '-pfunc' );
3595 wfProfileOut( __METHOD__
);
3599 # The interface for parser functions allows for extracting
3600 # flags into the local scope. Extract any forwarded flags
3604 wfProfileOut( __METHOD__
. '-pfunc' );
3607 # Finish mangling title and then check for loops.
3608 # Set $title to a Title object and $titleText to the PDBK
3611 # Split the title into page and subpage
3613 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3614 if ( $part1 !== $relative ) {
3616 $ns = $this->mTitle
->getNamespace();
3618 $title = Title
::newFromText( $part1, $ns );
3620 $titleText = $title->getPrefixedText();
3621 # Check for language variants if the template is not found
3622 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3623 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3625 # Do recursion depth check
3626 $limit = $this->mOptions
->getMaxTemplateDepth();
3627 if ( $frame->depth
>= $limit ) {
3629 $text = '<span class="error">'
3630 . wfMessage( 'parser-template-recursion-depth-warning' )
3631 ->numParams( $limit )->inContentLanguage()->text()
3637 # Load from database
3638 if ( !$found && $title ) {
3639 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3640 wfProfileIn( __METHOD__
. '-loadtpl' );
3641 if ( !$title->isExternal() ) {
3642 if ( $title->isSpecialPage()
3643 && $this->mOptions
->getAllowSpecialInclusion()
3644 && $this->ot
['html']
3646 // Pass the template arguments as URL parameters.
3647 // "uselang" will have no effect since the Language object
3648 // is forced to the one defined in ParserOptions.
3649 $pageArgs = array();
3650 $argsLength = $args->getLength();
3651 for ( $i = 0; $i < $argsLength; $i++
) {
3652 $bits = $args->item( $i )->splitArg();
3653 if ( strval( $bits['index'] ) === '' ) {
3654 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3655 $value = trim( $frame->expand( $bits['value'] ) );
3656 $pageArgs[$name] = $value;
3660 // Create a new context to execute the special page
3661 $context = new RequestContext
;
3662 $context->setTitle( $title );
3663 $context->setRequest( new FauxRequest( $pageArgs ) );
3664 $context->setUser( $this->getUser() );
3665 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3666 $ret = SpecialPageFactory
::capturePath( $title, $context );
3668 $text = $context->getOutput()->getHTML();
3669 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3672 $this->disableCache();
3674 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3675 $found = false; # access denied
3676 wfDebug( __METHOD__
. ": template inclusion denied for " .
3677 $title->getPrefixedDBkey() . "\n" );
3679 list( $text, $title ) = $this->getTemplateDom( $title );
3680 if ( $text !== false ) {
3686 # If the title is valid but undisplayable, make a link to it
3687 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3688 $text = "[[:$titleText]]";
3691 } elseif ( $title->isTrans() ) {
3692 # Interwiki transclusion
3693 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3694 $text = $this->interwikiTransclude( $title, 'render' );
3697 $text = $this->interwikiTransclude( $title, 'raw' );
3698 # Preprocess it like a template
3699 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3705 # Do infinite loop check
3706 # This has to be done after redirect resolution to avoid infinite loops via redirects
3707 if ( !$frame->loopCheck( $title ) ) {
3709 $text = '<span class="error">'
3710 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3712 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3714 wfProfileOut( __METHOD__
. '-loadtpl' );
3717 # If we haven't found text to substitute by now, we're done
3718 # Recover the source wikitext and return it
3720 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3721 if ( $profileSection ) {
3722 $this->mProfiler
->scopedProfileOut( $profileSection );
3724 wfProfileOut( __METHOD__
);
3725 return array( 'object' => $text );
3728 # Expand DOM-style return values in a child frame
3729 if ( $isChildObj ) {
3730 # Clean up argument array
3731 $newFrame = $frame->newChild( $args, $title );
3734 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3735 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3736 # Expansion is eligible for the empty-frame cache
3737 $text = $newFrame->cachedExpand( $titleText, $text );
3739 # Uncached expansion
3740 $text = $newFrame->expand( $text );
3743 if ( $isLocalObj && $nowiki ) {
3744 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3745 $isLocalObj = false;
3748 if ( $profileSection ) {
3749 $this->mProfiler
->scopedProfileOut( $profileSection );
3752 # Replace raw HTML by a placeholder
3754 $text = $this->insertStripItem( $text );
3755 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3756 # Escape nowiki-style return values
3757 $text = wfEscapeWikiText( $text );
3758 } elseif ( is_string( $text )
3759 && !$piece['lineStart']
3760 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3762 # Bug 529: if the template begins with a table or block-level
3763 # element, it should be treated as beginning a new line.
3764 # This behavior is somewhat controversial.
3765 $text = "\n" . $text;
3768 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3769 # Error, oversize inclusion
3770 if ( $titleText !== false ) {
3771 # Make a working, properly escaped link if possible (bug 23588)
3772 $text = "[[:$titleText]]";
3774 # This will probably not be a working link, but at least it may
3775 # provide some hint of where the problem is
3776 preg_replace( '/^:/', '', $originalTitle );
3777 $text = "[[:$originalTitle]]";
3779 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3780 . 'post-expand include size too large -->' );
3781 $this->limitationWarn( 'post-expand-template-inclusion' );
3784 if ( $isLocalObj ) {
3785 $ret = array( 'object' => $text );
3787 $ret = array( 'text' => $text );
3790 wfProfileOut( __METHOD__
);
3795 * Call a parser function and return an array with text and flags.
3797 * The returned array will always contain a boolean 'found', indicating
3798 * whether the parser function was found or not. It may also contain the
3800 * text: string|object, resulting wikitext or PP DOM object
3801 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3802 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3803 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3804 * nowiki: bool, wiki markup in $text should be escaped
3807 * @param PPFrame $frame The current frame, contains template arguments
3808 * @param string $function Function name
3809 * @param array $args Arguments to the function
3810 * @throws MWException
3813 public function callParserFunction( $frame, $function, array $args = array() ) {
3816 wfProfileIn( __METHOD__
);
3818 # Case sensitive functions
3819 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3820 $function = $this->mFunctionSynonyms
[1][$function];
3822 # Case insensitive functions
3823 $function = $wgContLang->lc( $function );
3824 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3825 $function = $this->mFunctionSynonyms
[0][$function];
3827 wfProfileOut( __METHOD__
);
3828 return array( 'found' => false );
3832 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3833 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3835 # Workaround for PHP bug 35229 and similar
3836 if ( !is_callable( $callback ) ) {
3837 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3838 wfProfileOut( __METHOD__
);
3839 throw new MWException( "Tag hook for $function is not callable\n" );
3842 $allArgs = array( &$this );
3843 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3844 # Convert arguments to PPNodes and collect for appending to $allArgs
3845 $funcArgs = array();
3846 foreach ( $args as $k => $v ) {
3847 if ( $v instanceof PPNode ||
$k === 0 ) {
3850 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3854 # Add a frame parameter, and pass the arguments as an array
3855 $allArgs[] = $frame;
3856 $allArgs[] = $funcArgs;
3858 # Convert arguments to plain text and append to $allArgs
3859 foreach ( $args as $k => $v ) {
3860 if ( $v instanceof PPNode
) {
3861 $allArgs[] = trim( $frame->expand( $v ) );
3862 } elseif ( is_int( $k ) && $k >= 0 ) {
3863 $allArgs[] = trim( $v );
3865 $allArgs[] = trim( "$k=$v" );
3870 $result = call_user_func_array( $callback, $allArgs );
3872 # The interface for function hooks allows them to return a wikitext
3873 # string or an array containing the string and any flags. This mungs
3874 # things around to match what this method should return.
3875 if ( !is_array( $result ) ) {
3881 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3882 $result['text'] = $result[0];
3884 unset( $result[0] );
3891 $preprocessFlags = 0;
3892 if ( isset( $result['noparse'] ) ) {
3893 $noparse = $result['noparse'];
3895 if ( isset( $result['preprocessFlags'] ) ) {
3896 $preprocessFlags = $result['preprocessFlags'];
3900 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3901 $result['isChildObj'] = true;
3903 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3904 wfProfileOut( __METHOD__
);
3910 * Get the semi-parsed DOM representation of a template with a given title,
3911 * and its redirect destination title. Cached.
3913 * @param Title $title
3917 public function getTemplateDom( $title ) {
3918 $cacheTitle = $title;
3919 $titleText = $title->getPrefixedDBkey();
3921 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3922 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3923 $title = Title
::makeTitle( $ns, $dbk );
3924 $titleText = $title->getPrefixedDBkey();
3926 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3927 return array( $this->mTplDomCache
[$titleText], $title );
3930 # Cache miss, go to the database
3931 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3933 if ( $text === false ) {
3934 $this->mTplDomCache
[$titleText] = false;
3935 return array( false, $title );
3938 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3939 $this->mTplDomCache
[$titleText] = $dom;
3941 if ( !$title->equals( $cacheTitle ) ) {
3942 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3943 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3946 return array( $dom, $title );
3950 * Fetch the current revision of a given title. Note that the revision
3951 * (and even the title) may not exist in the database, so everything
3952 * contributing to the output of the parser should use this method
3953 * where possible, rather than getting the revisions themselves. This
3954 * method also caches its results, so using it benefits performance.
3957 * @param Title $title
3960 public function fetchCurrentRevisionOfTitle( $title ) {
3961 $cacheKey = $title->getPrefixedDBkey();
3962 if ( !$this->currentRevisionCache
) {
3963 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3965 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3966 $this->currentRevisionCache
->set( $cacheKey,
3967 // Defaults to Parser::statelessFetchRevision()
3968 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3971 return $this->currentRevisionCache
->get( $cacheKey );
3975 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3976 * without passing them on to it.
3979 * @param Title $title
3980 * @param Parser|bool $parser
3983 public static function statelessFetchRevision( $title, $parser = false ) {
3984 return Revision
::newFromTitle( $title );
3988 * Fetch the unparsed text of a template and register a reference to it.
3989 * @param Title $title
3990 * @return array ( string or false, Title )
3992 public function fetchTemplateAndTitle( $title ) {
3993 // Defaults to Parser::statelessFetchTemplate()
3994 $templateCb = $this->mOptions
->getTemplateCallback();
3995 $stuff = call_user_func( $templateCb, $title, $this );
3996 $text = $stuff['text'];
3997 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3998 if ( isset( $stuff['deps'] ) ) {
3999 foreach ( $stuff['deps'] as $dep ) {
4000 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
4001 if ( $dep['title']->equals( $this->getTitle() ) ) {
4002 // If we transclude ourselves, the final result
4003 // will change based on the new version of the page
4004 $this->mOutput
->setFlag( 'vary-revision' );
4008 return array( $text, $finalTitle );
4012 * Fetch the unparsed text of a template and register a reference to it.
4013 * @param Title $title
4014 * @return string|bool
4016 public function fetchTemplate( $title ) {
4017 $rv = $this->fetchTemplateAndTitle( $title );
4022 * Static function to get a template
4023 * Can be overridden via ParserOptions::setTemplateCallback().
4025 * @param Title $title
4026 * @param bool|Parser $parser
4030 public static function statelessFetchTemplate( $title, $parser = false ) {
4031 $text = $skip = false;
4032 $finalTitle = $title;
4035 # Loop to fetch the article, with up to 1 redirect
4036 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
4037 # Give extensions a chance to select the revision instead
4038 $id = false; # Assume current
4039 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
4040 array( $parser, $title, &$skip, &$id ) );
4046 'page_id' => $title->getArticleID(),
4053 $rev = Revision
::newFromId( $id );
4054 } elseif ( $parser ) {
4055 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
4057 $rev = Revision
::newFromTitle( $title );
4059 $rev_id = $rev ?
$rev->getId() : 0;
4060 # If there is no current revision, there is no page
4061 if ( $id === false && !$rev ) {
4062 $linkCache = LinkCache
::singleton();
4063 $linkCache->addBadLinkObj( $title );
4068 'page_id' => $title->getArticleID(),
4069 'rev_id' => $rev_id );
4070 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
4071 # We fetched a rev from a different title; register it too...
4073 'title' => $rev->getTitle(),
4074 'page_id' => $rev->getPage(),
4075 'rev_id' => $rev_id );
4079 $content = $rev->getContent();
4080 $text = $content ?
$content->getWikitextForTransclusion() : null;
4082 if ( $text === false ||
$text === null ) {
4086 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4088 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4089 if ( !$message->exists() ) {
4093 $content = $message->content();
4094 $text = $message->plain();
4102 $finalTitle = $title;
4103 $title = $content->getRedirectTarget();
4107 'finalTitle' => $finalTitle,
4112 * Fetch a file and its title and register a reference to it.
4113 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4114 * @param Title $title
4115 * @param array $options Array of options to RepoGroup::findFile
4118 public function fetchFile( $title, $options = array() ) {
4119 $res = $this->fetchFileAndTitle( $title, $options );
4124 * Fetch a file and its title and register a reference to it.
4125 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4126 * @param Title $title
4127 * @param array $options Array of options to RepoGroup::findFile
4128 * @return array ( File or false, Title of file )
4130 public function fetchFileAndTitle( $title, $options = array() ) {
4131 $file = $this->fetchFileNoRegister( $title, $options );
4133 $time = $file ?
$file->getTimestamp() : false;
4134 $sha1 = $file ?
$file->getSha1() : false;
4135 # Register the file as a dependency...
4136 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4137 if ( $file && !$title->equals( $file->getTitle() ) ) {
4138 # Update fetched file title
4139 $title = $file->getTitle();
4140 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4142 return array( $file, $title );
4146 * Helper function for fetchFileAndTitle.
4148 * Also useful if you need to fetch a file but not use it yet,
4149 * for example to get the file's handler.
4151 * @param Title $title
4152 * @param array $options Array of options to RepoGroup::findFile
4155 protected function fetchFileNoRegister( $title, $options = array() ) {
4156 if ( isset( $options['broken'] ) ) {
4157 $file = false; // broken thumbnail forced by hook
4158 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4159 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4160 } else { // get by (name,timestamp)
4161 $file = wfFindFile( $title, $options );
4167 * Transclude an interwiki link.
4169 * @param Title $title
4170 * @param string $action
4174 public function interwikiTransclude( $title, $action ) {
4175 global $wgEnableScaryTranscluding;
4177 if ( !$wgEnableScaryTranscluding ) {
4178 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4181 $url = $title->getFullURL( array( 'action' => $action ) );
4183 if ( strlen( $url ) > 255 ) {
4184 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4186 return $this->fetchScaryTemplateMaybeFromCache( $url );
4190 * @param string $url
4191 * @return mixed|string
4193 public function fetchScaryTemplateMaybeFromCache( $url ) {
4194 global $wgTranscludeCacheExpiry;
4195 $dbr = wfGetDB( DB_SLAVE
);
4196 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4197 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4198 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4200 return $obj->tc_contents
;
4203 $req = MWHttpRequest
::factory( $url );
4204 $status = $req->execute(); // Status object
4205 if ( $status->isOK() ) {
4206 $text = $req->getContent();
4207 } elseif ( $req->getStatus() != 200 ) {
4208 // Though we failed to fetch the content, this status is useless.
4209 return wfMessage( 'scarytranscludefailed-httpstatus' )
4210 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4212 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4215 $dbw = wfGetDB( DB_MASTER
);
4216 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4218 'tc_time' => $dbw->timestamp( time() ),
4219 'tc_contents' => $text
4225 * Triple brace replacement -- used for template arguments
4228 * @param array $piece
4229 * @param PPFrame $frame
4233 public function argSubstitution( $piece, $frame ) {
4234 wfProfileIn( __METHOD__
);
4237 $parts = $piece['parts'];
4238 $nameWithSpaces = $frame->expand( $piece['title'] );
4239 $argName = trim( $nameWithSpaces );
4241 $text = $frame->getArgument( $argName );
4242 if ( $text === false && $parts->getLength() > 0
4243 && ( $this->ot
['html']
4245 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4248 # No match in frame, use the supplied default
4249 $object = $parts->item( 0 )->getChildren();
4251 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4252 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4253 $this->limitationWarn( 'post-expand-template-argument' );
4256 if ( $text === false && $object === false ) {
4258 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4260 if ( $error !== false ) {
4263 if ( $object !== false ) {
4264 $ret = array( 'object' => $object );
4266 $ret = array( 'text' => $text );
4269 wfProfileOut( __METHOD__
);
4274 * Return the text to be used for a given extension tag.
4275 * This is the ghost of strip().
4277 * @param array $params Associative array of parameters:
4278 * name PPNode for the tag name
4279 * attr PPNode for unparsed text where tag attributes are thought to be
4280 * attributes Optional associative array of parsed attributes
4281 * inner Contents of extension element
4282 * noClose Original text did not have a close tag
4283 * @param PPFrame $frame
4285 * @throws MWException
4288 public function extensionSubstitution( $params, $frame ) {
4289 $name = $frame->expand( $params['name'] );
4290 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4291 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4292 $marker = "{$this->mUniqPrefix}-$name-"
4293 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4295 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4296 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4297 if ( $isFunctionTag ) {
4298 $markerType = 'none';
4300 $markerType = 'general';
4302 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4303 $name = strtolower( $name );
4304 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4305 if ( isset( $params['attributes'] ) ) {
4306 $attributes = $attributes +
$params['attributes'];
4309 if ( isset( $this->mTagHooks
[$name] ) ) {
4310 # Workaround for PHP bug 35229 and similar
4311 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4312 throw new MWException( "Tag hook for $name is not callable\n" );
4314 $output = call_user_func_array( $this->mTagHooks
[$name],
4315 array( $content, $attributes, $this, $frame ) );
4316 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4317 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4318 if ( !is_callable( $callback ) ) {
4319 throw new MWException( "Tag hook for $name is not callable\n" );
4322 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4324 $output = '<span class="error">Invalid tag extension name: ' .
4325 htmlspecialchars( $name ) . '</span>';
4328 if ( is_array( $output ) ) {
4329 # Extract flags to local scope (to override $markerType)
4331 $output = $flags[0];
4336 if ( is_null( $attrText ) ) {
4339 if ( isset( $params['attributes'] ) ) {
4340 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4341 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4342 htmlspecialchars( $attrValue ) . '"';
4345 if ( $content === null ) {
4346 $output = "<$name$attrText/>";
4348 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4349 $output = "<$name$attrText>$content$close";
4353 if ( $markerType === 'none' ) {
4355 } elseif ( $markerType === 'nowiki' ) {
4356 $this->mStripState
->addNoWiki( $marker, $output );
4357 } elseif ( $markerType === 'general' ) {
4358 $this->mStripState
->addGeneral( $marker, $output );
4360 throw new MWException( __METHOD__
. ': invalid marker type' );
4366 * Increment an include size counter
4368 * @param string $type The type of expansion
4369 * @param int $size The size of the text
4370 * @return bool False if this inclusion would take it over the maximum, true otherwise
4372 public function incrementIncludeSize( $type, $size ) {
4373 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4376 $this->mIncludeSizes
[$type] +
= $size;
4382 * Increment the expensive function count
4384 * @return bool False if the limit has been exceeded
4386 public function incrementExpensiveFunctionCount() {
4387 $this->mExpensiveFunctionCount++
;
4388 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4392 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4393 * Fills $this->mDoubleUnderscores, returns the modified text
4395 * @param string $text
4399 public function doDoubleUnderscore( $text ) {
4400 wfProfileIn( __METHOD__
);
4402 # The position of __TOC__ needs to be recorded
4403 $mw = MagicWord
::get( 'toc' );
4404 if ( $mw->match( $text ) ) {
4405 $this->mShowToc
= true;
4406 $this->mForceTocPosition
= true;
4408 # Set a placeholder. At the end we'll fill it in with the TOC.
4409 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4411 # Only keep the first one.
4412 $text = $mw->replace( '', $text );
4415 # Now match and remove the rest of them
4416 $mwa = MagicWord
::getDoubleUnderscoreArray();
4417 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4419 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4420 $this->mOutput
->mNoGallery
= true;
4422 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4423 $this->mShowToc
= false;
4425 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4426 && $this->mTitle
->getNamespace() == NS_CATEGORY
4428 $this->addTrackingCategory( 'hidden-category-category' );
4430 # (bug 8068) Allow control over whether robots index a page.
4432 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4433 # is not desirable, the last one on the page should win.
4434 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4435 $this->mOutput
->setIndexPolicy( 'noindex' );
4436 $this->addTrackingCategory( 'noindex-category' );
4438 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4439 $this->mOutput
->setIndexPolicy( 'index' );
4440 $this->addTrackingCategory( 'index-category' );
4443 # Cache all double underscores in the database
4444 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4445 $this->mOutput
->setProperty( $key, '' );
4448 wfProfileOut( __METHOD__
);
4453 * @see ParserOutput::addTrackingCategory()
4454 * @param string $msg Message key
4455 * @return bool Whether the addition was successful
4457 public function addTrackingCategory( $msg ) {
4458 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4462 * This function accomplishes several tasks:
4463 * 1) Auto-number headings if that option is enabled
4464 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4465 * 3) Add a Table of contents on the top for users who have enabled the option
4466 * 4) Auto-anchor headings
4468 * It loops through all headlines, collects the necessary data, then splits up the
4469 * string and re-inserts the newly formatted headlines.
4471 * @param string $text
4472 * @param string $origText Original, untouched wikitext
4473 * @param bool $isMain
4474 * @return mixed|string
4477 public function formatHeadings( $text, $origText, $isMain = true ) {
4478 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4480 # Inhibit editsection links if requested in the page
4481 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4482 $maybeShowEditLink = $showEditLink = false;
4484 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4485 $showEditLink = $this->mOptions
->getEditSection();
4487 if ( $showEditLink ) {
4488 $this->mOutput
->setEditSectionTokens( true );
4491 # Get all headlines for numbering them and adding funky stuff like [edit]
4492 # links - this is for later, but we need the number of headlines right now
4494 $numMatches = preg_match_all(
4495 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4500 # if there are fewer than 4 headlines in the article, do not show TOC
4501 # unless it's been explicitly enabled.
4502 $enoughToc = $this->mShowToc
&&
4503 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4505 # Allow user to stipulate that a page should have a "new section"
4506 # link added via __NEWSECTIONLINK__
4507 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4508 $this->mOutput
->setNewSection( true );
4511 # Allow user to remove the "new section"
4512 # link via __NONEWSECTIONLINK__
4513 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4514 $this->mOutput
->hideNewSection( true );
4517 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4518 # override above conditions and always show TOC above first header
4519 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4520 $this->mShowToc
= true;
4528 # Ugh .. the TOC should have neat indentation levels which can be
4529 # passed to the skin functions. These are determined here
4533 $sublevelCount = array();
4534 $levelCount = array();
4539 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4540 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4541 $oldType = $this->mOutputType
;
4542 $this->setOutputType( self
::OT_WIKI
);
4543 $frame = $this->getPreprocessor()->newFrame();
4544 $root = $this->preprocessToDom( $origText );
4545 $node = $root->getFirstChild();
4550 foreach ( $matches[3] as $headline ) {
4551 $isTemplate = false;
4553 $sectionIndex = false;
4555 $markerMatches = array();
4556 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4557 $serial = $markerMatches[1];
4558 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4559 $isTemplate = ( $titleText != $baseTitleText );
4560 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4564 $prevlevel = $level;
4566 $level = $matches[1][$headlineCount];
4568 if ( $level > $prevlevel ) {
4569 # Increase TOC level
4571 $sublevelCount[$toclevel] = 0;
4572 if ( $toclevel < $wgMaxTocLevel ) {
4573 $prevtoclevel = $toclevel;
4574 $toc .= Linker
::tocIndent();
4577 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4578 # Decrease TOC level, find level to jump to
4580 for ( $i = $toclevel; $i > 0; $i-- ) {
4581 if ( $levelCount[$i] == $level ) {
4582 # Found last matching level
4585 } elseif ( $levelCount[$i] < $level ) {
4586 # Found first matching level below current level
4594 if ( $toclevel < $wgMaxTocLevel ) {
4595 if ( $prevtoclevel < $wgMaxTocLevel ) {
4596 # Unindent only if the previous toc level was shown :p
4597 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4598 $prevtoclevel = $toclevel;
4600 $toc .= Linker
::tocLineEnd();
4604 # No change in level, end TOC line
4605 if ( $toclevel < $wgMaxTocLevel ) {
4606 $toc .= Linker
::tocLineEnd();
4610 $levelCount[$toclevel] = $level;
4612 # count number of headlines for each level
4613 $sublevelCount[$toclevel]++
;
4615 for ( $i = 1; $i <= $toclevel; $i++
) {
4616 if ( !empty( $sublevelCount[$i] ) ) {
4620 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4625 # The safe header is a version of the header text safe to use for links
4627 # Remove link placeholders by the link text.
4628 # <!--LINK number-->
4630 # link text with suffix
4631 # Do this before unstrip since link text can contain strip markers
4632 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4634 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4635 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4637 # Strip out HTML (first regex removes any tag not allowed)
4639 # * <sup> and <sub> (bug 8393)
4642 # * <bdi> (bug 72884)
4643 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4645 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4646 # to allow setting directionality in toc items.
4647 $tocline = preg_replace(
4649 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?' . '>#',
4650 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?' . '>#'
4652 array( '', '<$1>' ),
4655 $tocline = trim( $tocline );
4657 # For the anchor, strip out HTML-y stuff period
4658 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4659 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4661 # Save headline for section edit hint before it's escaped
4662 $headlineHint = $safeHeadline;
4664 if ( $wgExperimentalHtmlIds ) {
4665 # For reverse compatibility, provide an id that's
4666 # HTML4-compatible, like we used to.
4668 # It may be worth noting, academically, that it's possible for
4669 # the legacy anchor to conflict with a non-legacy headline
4670 # anchor on the page. In this case likely the "correct" thing
4671 # would be to either drop the legacy anchors or make sure
4672 # they're numbered first. However, this would require people
4673 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4674 # manually, so let's not bother worrying about it.
4675 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4676 array( 'noninitial', 'legacy' ) );
4677 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4679 if ( $legacyHeadline == $safeHeadline ) {
4680 # No reason to have both (in fact, we can't)
4681 $legacyHeadline = false;
4684 $legacyHeadline = false;
4685 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4689 # HTML names must be case-insensitively unique (bug 10721).
4690 # This does not apply to Unicode characters per
4691 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4692 # @todo FIXME: We may be changing them depending on the current locale.
4693 $arrayKey = strtolower( $safeHeadline );
4694 if ( $legacyHeadline === false ) {
4695 $legacyArrayKey = false;
4697 $legacyArrayKey = strtolower( $legacyHeadline );
4700 # count how many in assoc. array so we can track dupes in anchors
4701 if ( isset( $refers[$arrayKey] ) ) {
4702 $refers[$arrayKey]++
;
4704 $refers[$arrayKey] = 1;
4706 if ( isset( $refers[$legacyArrayKey] ) ) {
4707 $refers[$legacyArrayKey]++
;
4709 $refers[$legacyArrayKey] = 1;
4712 # Don't number the heading if it is the only one (looks silly)
4713 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4714 # the two are different if the line contains a link
4715 $headline = Html
::element(
4717 array( 'class' => 'mw-headline-number' ),
4719 ) . ' ' . $headline;
4722 # Create the anchor for linking from the TOC to the section
4723 $anchor = $safeHeadline;
4724 $legacyAnchor = $legacyHeadline;
4725 if ( $refers[$arrayKey] > 1 ) {
4726 $anchor .= '_' . $refers[$arrayKey];
4728 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4729 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4731 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4732 $toc .= Linker
::tocLine( $anchor, $tocline,
4733 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4736 # Add the section to the section tree
4737 # Find the DOM node for this header
4738 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4739 while ( $node && !$noOffset ) {
4740 if ( $node->getName() === 'h' ) {
4741 $bits = $node->splitHeading();
4742 if ( $bits['i'] == $sectionIndex ) {
4746 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4747 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4748 $node = $node->getNextSibling();
4751 'toclevel' => $toclevel,
4754 'number' => $numbering,
4755 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4756 'fromtitle' => $titleText,
4757 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4758 'anchor' => $anchor,
4761 # give headline the correct <h#> tag
4762 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4763 // Output edit section links as markers with styles that can be customized by skins
4764 if ( $isTemplate ) {
4765 # Put a T flag in the section identifier, to indicate to extractSections()
4766 # that sections inside <includeonly> should be counted.
4767 $editsectionPage = $titleText;
4768 $editsectionSection = "T-$sectionIndex";
4769 $editsectionContent = null;
4771 $editsectionPage = $this->mTitle
->getPrefixedText();
4772 $editsectionSection = $sectionIndex;
4773 $editsectionContent = $headlineHint;
4775 // We use a bit of pesudo-xml for editsection markers. The
4776 // language converter is run later on. Using a UNIQ style marker
4777 // leads to the converter screwing up the tokens when it
4778 // converts stuff. And trying to insert strip tags fails too. At
4779 // this point all real inputted tags have already been escaped,
4780 // so we don't have to worry about a user trying to input one of
4781 // these markers directly. We use a page and section attribute
4782 // to stop the language converter from converting these
4783 // important bits of data, but put the headline hint inside a
4784 // content block because the language converter is supposed to
4785 // be able to convert that piece of data.
4786 // Gets replaced with html in ParserOutput::getText
4787 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4788 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4789 if ( $editsectionContent !== null ) {
4790 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4797 $head[$headlineCount] = Linker
::makeHeadline( $level,
4798 $matches['attrib'][$headlineCount], $anchor, $headline,
4799 $editlink, $legacyAnchor );
4804 $this->setOutputType( $oldType );
4806 # Never ever show TOC if no headers
4807 if ( $numVisible < 1 ) {
4812 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4813 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4815 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4816 $this->mOutput
->setTOCHTML( $toc );
4817 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4818 $this->mOutput
->addModules( 'mediawiki.toc' );
4822 $this->mOutput
->setSections( $tocraw );
4825 # split up and insert constructed headlines
4826 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4829 // build an array of document sections
4830 $sections = array();
4831 foreach ( $blocks as $block ) {
4832 // $head is zero-based, sections aren't.
4833 if ( empty( $head[$i - 1] ) ) {
4834 $sections[$i] = $block;
4836 $sections[$i] = $head[$i - 1] . $block;
4840 * Send a hook, one per section.
4841 * The idea here is to be able to make section-level DIVs, but to do so in a
4842 * lower-impact, more correct way than r50769
4845 * $section : the section number
4846 * &$sectionContent : ref to the content of the section
4847 * $showEditLinks : boolean describing whether this section has an edit link
4849 Hooks
::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4854 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4855 // append the TOC at the beginning
4856 // Top anchor now in skin
4857 $sections[0] = $sections[0] . $toc . "\n";
4860 $full .= join( '', $sections );
4862 if ( $this->mForceTocPosition
) {
4863 return str_replace( '<!--MWTOC-->', $toc, $full );
4870 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4871 * conversion, substituting signatures, {{subst:}} templates, etc.
4873 * @param string $text The text to transform
4874 * @param Title $title The Title object for the current article
4875 * @param User $user The User object describing the current user
4876 * @param ParserOptions $options Parsing options
4877 * @param bool $clearState Whether to clear the parser state first
4878 * @return string The altered wiki markup
4880 public function preSaveTransform( $text, Title
$title, User
$user,
4881 ParserOptions
$options, $clearState = true
4883 if ( $clearState ) {
4884 $magicScopeVariable = $this->lock();
4886 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4887 $this->setUser( $user );
4893 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4894 if ( $options->getPreSaveTransform() ) {
4895 $text = $this->pstPass2( $text, $user );
4897 $text = $this->mStripState
->unstripBoth( $text );
4899 $this->setUser( null ); #Reset
4905 * Pre-save transform helper function
4907 * @param string $text
4912 private function pstPass2( $text, $user ) {
4915 # Note: This is the timestamp saved as hardcoded wikitext to
4916 # the database, we use $wgContLang here in order to give
4917 # everyone the same signature and use the default one rather
4918 # than the one selected in each user's preferences.
4919 # (see also bug 12815)
4920 $ts = $this->mOptions
->getTimestamp();
4921 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4922 $ts = $timestamp->format( 'YmdHis' );
4923 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4925 # Allow translation of timezones through wiki. format() can return
4926 # whatever crap the system uses, localised or not, so we cannot
4927 # ship premade translations.
4928 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4929 $msg = wfMessage( $key )->inContentLanguage();
4930 if ( $msg->exists() ) {
4931 $tzMsg = $msg->text();
4934 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4936 # Variable replacement
4937 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4938 $text = $this->replaceVariables( $text );
4940 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4941 # which may corrupt this parser instance via its wfMessage()->text() call-
4944 $sigText = $this->getUserSig( $user );
4945 $text = strtr( $text, array(
4947 '~~~~' => "$sigText $d",
4951 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4952 $tc = '[' . Title
::legalChars() . ']';
4953 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4955 // [[ns:page (context)|]]
4956 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4957 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4958 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4959 // [[ns:page (context), context|]] (using either single or double-width comma)
4960 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4961 // [[|page]] (reverse pipe trick: add context from page title)
4962 $p2 = "/\[\[\\|($tc+)]]/";
4964 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4965 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4966 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4967 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4969 $t = $this->mTitle
->getText();
4971 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4972 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4973 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4974 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4976 # if there's no context, don't bother duplicating the title
4977 $text = preg_replace( $p2, '[[\\1]]', $text );
4980 # Trim trailing whitespace
4981 $text = rtrim( $text );
4987 * Fetch the user's signature text, if any, and normalize to
4988 * validated, ready-to-insert wikitext.
4989 * If you have pre-fetched the nickname or the fancySig option, you can
4990 * specify them here to save a database query.
4991 * Do not reuse this parser instance after calling getUserSig(),
4992 * as it may have changed if it's the $wgParser.
4995 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4996 * @param bool|null $fancySig whether the nicknname is the complete signature
4997 * or null to use default value
5000 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
5001 global $wgMaxSigChars;
5003 $username = $user->getName();
5005 # If not given, retrieve from the user object.
5006 if ( $nickname === false ) {
5007 $nickname = $user->getOption( 'nickname' );
5010 if ( is_null( $fancySig ) ) {
5011 $fancySig = $user->getBoolOption( 'fancysig' );
5014 $nickname = $nickname == null ?
$username : $nickname;
5016 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
5017 $nickname = $username;
5018 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
5019 } elseif ( $fancySig !== false ) {
5020 # Sig. might contain markup; validate this
5021 if ( $this->validateSig( $nickname ) !== false ) {
5022 # Validated; clean up (if needed) and return it
5023 return $this->cleanSig( $nickname, true );
5025 # Failed to validate; fall back to the default
5026 $nickname = $username;
5027 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
5031 # Make sure nickname doesnt get a sig in a sig
5032 $nickname = self
::cleanSigInSig( $nickname );
5034 # If we're still here, make it a link to the user page
5035 $userText = wfEscapeWikiText( $username );
5036 $nickText = wfEscapeWikiText( $nickname );
5037 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
5039 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
5040 ->title( $this->getTitle() )->text();
5044 * Check that the user's signature contains no bad XML
5046 * @param string $text
5047 * @return string|bool An expanded string, or false if invalid.
5049 public function validateSig( $text ) {
5050 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
5054 * Clean up signature text
5056 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
5057 * 2) Substitute all transclusions
5059 * @param string $text
5060 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
5061 * @return string Signature text
5063 public function cleanSig( $text, $parsing = false ) {
5066 $magicScopeVariable = $this->lock();
5067 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
5070 # Option to disable this feature
5071 if ( !$this->mOptions
->getCleanSignatures() ) {
5075 # @todo FIXME: Regex doesn't respect extension tags or nowiki
5076 # => Move this logic to braceSubstitution()
5077 $substWord = MagicWord
::get( 'subst' );
5078 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
5079 $substText = '{{' . $substWord->getSynonym( 0 );
5081 $text = preg_replace( $substRegex, $substText, $text );
5082 $text = self
::cleanSigInSig( $text );
5083 $dom = $this->preprocessToDom( $text );
5084 $frame = $this->getPreprocessor()->newFrame();
5085 $text = $frame->expand( $dom );
5088 $text = $this->mStripState
->unstripBoth( $text );
5095 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5097 * @param string $text
5098 * @return string Signature text with /~{3,5}/ removed
5100 public static function cleanSigInSig( $text ) {
5101 $text = preg_replace( '/~{3,5}/', '', $text );
5106 * Set up some variables which are usually set up in parse()
5107 * so that an external function can call some class members with confidence
5109 * @param Title|null $title
5110 * @param ParserOptions $options
5111 * @param int $outputType
5112 * @param bool $clearState
5114 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5115 $outputType, $clearState = true
5117 $this->startParse( $title, $options, $outputType, $clearState );
5121 * @param Title|null $title
5122 * @param ParserOptions $options
5123 * @param int $outputType
5124 * @param bool $clearState
5126 private function startParse( Title
$title = null, ParserOptions
$options,
5127 $outputType, $clearState = true
5129 $this->setTitle( $title );
5130 $this->mOptions
= $options;
5131 $this->setOutputType( $outputType );
5132 if ( $clearState ) {
5133 $this->clearState();
5138 * Wrapper for preprocess()
5140 * @param string $text The text to preprocess
5141 * @param ParserOptions $options Options
5142 * @param Title|null $title Title object or null to use $wgTitle
5145 public function transformMsg( $text, $options, $title = null ) {
5146 static $executing = false;
5148 # Guard against infinite recursion
5154 wfProfileIn( __METHOD__
);
5160 $text = $this->preprocess( $text, $title, $options );
5163 wfProfileOut( __METHOD__
);
5168 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5169 * The callback should have the following form:
5170 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5172 * Transform and return $text. Use $parser for any required context, e.g. use
5173 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5175 * Hooks may return extended information by returning an array, of which the
5176 * first numbered element (index 0) must be the return string, and all other
5177 * entries are extracted into local variables within an internal function
5178 * in the Parser class.
5180 * This interface (introduced r61913) appears to be undocumented, but
5181 * 'markerName' is used by some core tag hooks to override which strip
5182 * array their results are placed in. **Use great caution if attempting
5183 * this interface, as it is not documented and injudicious use could smash
5184 * private variables.**
5186 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5187 * @param callable $callback The callback function (and object) to use for the tag
5188 * @throws MWException
5189 * @return callable|null The old value of the mTagHooks array associated with the hook
5191 public function setHook( $tag, $callback ) {
5192 $tag = strtolower( $tag );
5193 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5194 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5196 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5197 $this->mTagHooks
[$tag] = $callback;
5198 if ( !in_array( $tag, $this->mStripList
) ) {
5199 $this->mStripList
[] = $tag;
5206 * As setHook(), but letting the contents be parsed.
5208 * Transparent tag hooks are like regular XML-style tag hooks, except they
5209 * operate late in the transformation sequence, on HTML instead of wikitext.
5211 * This is probably obsoleted by things dealing with parser frames?
5212 * The only extension currently using it is geoserver.
5215 * @todo better document or deprecate this
5217 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5218 * @param callable $callback The callback function (and object) to use for the tag
5219 * @throws MWException
5220 * @return callable|null The old value of the mTagHooks array associated with the hook
5222 public function setTransparentTagHook( $tag, $callback ) {
5223 $tag = strtolower( $tag );
5224 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5225 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5227 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5228 $this->mTransparentTagHooks
[$tag] = $callback;
5234 * Remove all tag hooks
5236 public function clearTagHooks() {
5237 $this->mTagHooks
= array();
5238 $this->mFunctionTagHooks
= array();
5239 $this->mStripList
= $this->mDefaultStripList
;
5243 * Create a function, e.g. {{sum:1|2|3}}
5244 * The callback function should have the form:
5245 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5247 * Or with Parser::SFH_OBJECT_ARGS:
5248 * function myParserFunction( $parser, $frame, $args ) { ... }
5250 * The callback may either return the text result of the function, or an array with the text
5251 * in element 0, and a number of flags in the other elements. The names of the flags are
5252 * specified in the keys. Valid flags are:
5253 * found The text returned is valid, stop processing the template. This
5255 * nowiki Wiki markup in the return value should be escaped
5256 * isHTML The returned text is HTML, armour it against wikitext transformation
5258 * @param string $id The magic word ID
5259 * @param callable $callback The callback function (and object) to use
5260 * @param int $flags A combination of the following flags:
5261 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5263 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5264 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5265 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5266 * the arguments, and to control the way they are expanded.
5268 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5269 * arguments, for instance:
5270 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5272 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5273 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5274 * working if/when this is changed.
5276 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5279 * Please read the documentation in includes/parser/Preprocessor.php for more information
5280 * about the methods available in PPFrame and PPNode.
5282 * @throws MWException
5283 * @return string|callable The old callback function for this name, if any
5285 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5288 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5289 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5291 # Add to function cache
5292 $mw = MagicWord
::get( $id );
5294 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5297 $synonyms = $mw->getSynonyms();
5298 $sensitive = intval( $mw->isCaseSensitive() );
5300 foreach ( $synonyms as $syn ) {
5302 if ( !$sensitive ) {
5303 $syn = $wgContLang->lc( $syn );
5306 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5309 # Remove trailing colon
5310 if ( substr( $syn, -1, 1 ) === ':' ) {
5311 $syn = substr( $syn, 0, -1 );
5313 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5319 * Get all registered function hook identifiers
5323 public function getFunctionHooks() {
5324 return array_keys( $this->mFunctionHooks
);
5328 * Create a tag function, e.g. "<test>some stuff</test>".
5329 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5330 * Unlike parser functions, their content is not preprocessed.
5331 * @param string $tag
5332 * @param callable $callback
5334 * @throws MWException
5337 public function setFunctionTagHook( $tag, $callback, $flags ) {
5338 $tag = strtolower( $tag );
5339 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5340 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5342 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5343 $this->mFunctionTagHooks
[$tag] : null;
5344 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5346 if ( !in_array( $tag, $this->mStripList
) ) {
5347 $this->mStripList
[] = $tag;
5354 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5355 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5356 * Placeholders created in Skin::makeLinkObj()
5358 * @param string $text
5359 * @param int $options
5361 public function replaceLinkHolders( &$text, $options = 0 ) {
5362 $this->mLinkHolders
->replace( $text );
5366 * Replace "<!--LINK-->" link placeholders with plain text of links
5367 * (not HTML-formatted).
5369 * @param string $text
5372 public function replaceLinkHoldersText( $text ) {
5373 return $this->mLinkHolders
->replaceText( $text );
5377 * Renders an image gallery from a text with one line per image.
5378 * text labels may be given by using |-style alternative text. E.g.
5379 * Image:one.jpg|The number "1"
5380 * Image:tree.jpg|A tree
5381 * given as text will return the HTML of a gallery with two images,
5382 * labeled 'The number "1"' and
5385 * @param string $text
5386 * @param array $params
5387 * @return string HTML
5389 public function renderImageGallery( $text, $params ) {
5390 wfProfileIn( __METHOD__
);
5393 if ( isset( $params['mode'] ) ) {
5394 $mode = $params['mode'];
5398 $ig = ImageGalleryBase
::factory( $mode );
5399 } catch ( MWException
$e ) {
5400 // If invalid type set, fallback to default.
5401 $ig = ImageGalleryBase
::factory( false );
5404 $ig->setContextTitle( $this->mTitle
);
5405 $ig->setShowBytes( false );
5406 $ig->setShowFilename( false );
5407 $ig->setParser( $this );
5408 $ig->setHideBadImages();
5409 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5411 if ( isset( $params['showfilename'] ) ) {
5412 $ig->setShowFilename( true );
5414 $ig->setShowFilename( false );
5416 if ( isset( $params['caption'] ) ) {
5417 $caption = $params['caption'];
5418 $caption = htmlspecialchars( $caption );
5419 $caption = $this->replaceInternalLinks( $caption );
5420 $ig->setCaptionHtml( $caption );
5422 if ( isset( $params['perrow'] ) ) {
5423 $ig->setPerRow( $params['perrow'] );
5425 if ( isset( $params['widths'] ) ) {
5426 $ig->setWidths( $params['widths'] );
5428 if ( isset( $params['heights'] ) ) {
5429 $ig->setHeights( $params['heights'] );
5431 $ig->setAdditionalOptions( $params );
5433 Hooks
::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5435 $lines = StringUtils
::explode( "\n", $text );
5436 foreach ( $lines as $line ) {
5437 # match lines like these:
5438 # Image:someimage.jpg|This is some image
5440 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5442 if ( count( $matches ) == 0 ) {
5446 if ( strpos( $matches[0], '%' ) !== false ) {
5447 $matches[1] = rawurldecode( $matches[1] );
5449 $title = Title
::newFromText( $matches[1], NS_FILE
);
5450 if ( is_null( $title ) ) {
5451 # Bogus title. Ignore these so we don't bomb out later.
5455 # We need to get what handler the file uses, to figure out parameters.
5456 # Note, a hook can overide the file name, and chose an entirely different
5457 # file (which potentially could be of a different type and have different handler).
5460 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5461 array( $this, $title, &$options, &$descQuery ) );
5462 # Don't register it now, as ImageGallery does that later.
5463 $file = $this->fetchFileNoRegister( $title, $options );
5464 $handler = $file ?
$file->getHandler() : false;
5466 wfProfileIn( __METHOD__
. '-getMagicWord' );
5468 'img_alt' => 'gallery-internal-alt',
5469 'img_link' => 'gallery-internal-link',
5472 $paramMap = $paramMap +
$handler->getParamMap();
5473 // We don't want people to specify per-image widths.
5474 // Additionally the width parameter would need special casing anyhow.
5475 unset( $paramMap['img_width'] );
5478 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5479 wfProfileOut( __METHOD__
. '-getMagicWord' );
5484 $handlerOptions = array();
5485 if ( isset( $matches[3] ) ) {
5486 // look for an |alt= definition while trying not to break existing
5487 // captions with multiple pipes (|) in it, until a more sensible grammar
5488 // is defined for images in galleries
5490 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5491 // splitting on '|' is a bit odd, and different from makeImage.
5492 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5493 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5495 foreach ( $parameterMatches as $parameterMatch ) {
5496 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5498 $paramName = $paramMap[$magicName];
5500 switch ( $paramName ) {
5501 case 'gallery-internal-alt':
5502 $alt = $this->stripAltText( $match, false );
5504 case 'gallery-internal-link':
5505 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5506 $chars = self
::EXT_LINK_URL_CLASS
;
5507 $prots = $this->mUrlProtocols
;
5508 //check to see if link matches an absolute url, if not then it must be a wiki link.
5509 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5512 $localLinkTitle = Title
::newFromText( $linkValue );
5513 if ( $localLinkTitle !== null ) {
5514 $link = $localLinkTitle->getLinkURL();
5519 // Must be a handler specific parameter.
5520 if ( $handler->validateParam( $paramName, $match ) ) {
5521 $handlerOptions[$paramName] = $match;
5523 // Guess not. Append it to the caption.
5524 wfDebug( "$parameterMatch failed parameter validation\n" );
5525 $label .= '|' . $parameterMatch;
5530 // concatenate all other pipes
5531 $label .= '|' . $parameterMatch;
5534 // remove the first pipe
5535 $label = substr( $label, 1 );
5538 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5540 $html = $ig->toHTML();
5541 Hooks
::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5542 wfProfileOut( __METHOD__
);
5547 * @param string $handler
5550 public function getImageParams( $handler ) {
5552 $handlerClass = get_class( $handler );
5556 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5557 # Initialise static lists
5558 static $internalParamNames = array(
5559 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5560 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5561 'bottom', 'text-bottom' ),
5562 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5563 'upright', 'border', 'link', 'alt', 'class' ),
5565 static $internalParamMap;
5566 if ( !$internalParamMap ) {
5567 $internalParamMap = array();
5568 foreach ( $internalParamNames as $type => $names ) {
5569 foreach ( $names as $name ) {
5570 $magicName = str_replace( '-', '_', "img_$name" );
5571 $internalParamMap[$magicName] = array( $type, $name );
5576 # Add handler params
5577 $paramMap = $internalParamMap;
5579 $handlerParamMap = $handler->getParamMap();
5580 foreach ( $handlerParamMap as $magic => $paramName ) {
5581 $paramMap[$magic] = array( 'handler', $paramName );
5584 $this->mImageParams
[$handlerClass] = $paramMap;
5585 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5587 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5591 * Parse image options text and use it to make an image
5593 * @param Title $title
5594 * @param string $options
5595 * @param LinkHolderArray|bool $holders
5596 * @return string HTML
5598 public function makeImage( $title, $options, $holders = false ) {
5599 # Check if the options text is of the form "options|alt text"
5601 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5602 # * left no resizing, just left align. label is used for alt= only
5603 # * right same, but right aligned
5604 # * none same, but not aligned
5605 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5606 # * center center the image
5607 # * frame Keep original image size, no magnify-button.
5608 # * framed Same as "frame"
5609 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5610 # * upright reduce width for upright images, rounded to full __0 px
5611 # * border draw a 1px border around the image
5612 # * alt Text for HTML alt attribute (defaults to empty)
5613 # * class Set a class for img node
5614 # * link Set the target of the image link. Can be external, interwiki, or local
5615 # vertical-align values (no % or length right now):
5625 $parts = StringUtils
::explode( "|", $options );
5627 # Give extensions a chance to select the file revision for us
5630 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5631 array( $this, $title, &$options, &$descQuery ) );
5632 # Fetch and register the file (file title may be different via hooks)
5633 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5636 $handler = $file ?
$file->getHandler() : false;
5638 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5641 $this->addTrackingCategory( 'broken-file-category' );
5644 # Process the input parameters
5646 $params = array( 'frame' => array(), 'handler' => array(),
5647 'horizAlign' => array(), 'vertAlign' => array() );
5648 $seenformat = false;
5649 foreach ( $parts as $part ) {
5650 $part = trim( $part );
5651 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5653 if ( isset( $paramMap[$magicName] ) ) {
5654 list( $type, $paramName ) = $paramMap[$magicName];
5656 # Special case; width and height come in one variable together
5657 if ( $type === 'handler' && $paramName === 'width' ) {
5658 $parsedWidthParam = $this->parseWidthParam( $value );
5659 if ( isset( $parsedWidthParam['width'] ) ) {
5660 $width = $parsedWidthParam['width'];
5661 if ( $handler->validateParam( 'width', $width ) ) {
5662 $params[$type]['width'] = $width;
5666 if ( isset( $parsedWidthParam['height'] ) ) {
5667 $height = $parsedWidthParam['height'];
5668 if ( $handler->validateParam( 'height', $height ) ) {
5669 $params[$type]['height'] = $height;
5673 # else no validation -- bug 13436
5675 if ( $type === 'handler' ) {
5676 # Validate handler parameter
5677 $validated = $handler->validateParam( $paramName, $value );
5679 # Validate internal parameters
5680 switch ( $paramName ) {
5684 # @todo FIXME: Possibly check validity here for
5685 # manualthumb? downstream behavior seems odd with
5686 # missing manual thumbs.
5688 $value = $this->stripAltText( $value, $holders );
5691 $chars = self
::EXT_LINK_URL_CLASS
;
5692 $prots = $this->mUrlProtocols
;
5693 if ( $value === '' ) {
5694 $paramName = 'no-link';
5697 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5698 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5699 $paramName = 'link-url';
5700 $this->mOutput
->addExternalLink( $value );
5701 if ( $this->mOptions
->getExternalLinkTarget() ) {
5702 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5707 $linkTitle = Title
::newFromText( $value );
5709 $paramName = 'link-title';
5710 $value = $linkTitle;
5711 $this->mOutput
->addLink( $linkTitle );
5719 // use first appearing option, discard others.
5720 $validated = ! $seenformat;
5724 # Most other things appear to be empty or numeric...
5725 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5730 $params[$type][$paramName] = $value;
5734 if ( !$validated ) {
5739 # Process alignment parameters
5740 if ( $params['horizAlign'] ) {
5741 $params['frame']['align'] = key( $params['horizAlign'] );
5743 if ( $params['vertAlign'] ) {
5744 $params['frame']['valign'] = key( $params['vertAlign'] );
5747 $params['frame']['caption'] = $caption;
5749 # Will the image be presented in a frame, with the caption below?
5750 $imageIsFramed = isset( $params['frame']['frame'] )
5751 ||
isset( $params['frame']['framed'] )
5752 ||
isset( $params['frame']['thumbnail'] )
5753 ||
isset( $params['frame']['manualthumb'] );
5755 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5756 # came to also set the caption, ordinary text after the image -- which
5757 # makes no sense, because that just repeats the text multiple times in
5758 # screen readers. It *also* came to set the title attribute.
5760 # Now that we have an alt attribute, we should not set the alt text to
5761 # equal the caption: that's worse than useless, it just repeats the
5762 # text. This is the framed/thumbnail case. If there's no caption, we
5763 # use the unnamed parameter for alt text as well, just for the time be-
5764 # ing, if the unnamed param is set and the alt param is not.
5766 # For the future, we need to figure out if we want to tweak this more,
5767 # e.g., introducing a title= parameter for the title; ignoring the un-
5768 # named parameter entirely for images without a caption; adding an ex-
5769 # plicit caption= parameter and preserving the old magic unnamed para-
5771 if ( $imageIsFramed ) { # Framed image
5772 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5773 # No caption or alt text, add the filename as the alt text so
5774 # that screen readers at least get some description of the image
5775 $params['frame']['alt'] = $title->getText();
5777 # Do not set $params['frame']['title'] because tooltips don't make sense
5779 } else { # Inline image
5780 if ( !isset( $params['frame']['alt'] ) ) {
5781 # No alt text, use the "caption" for the alt text
5782 if ( $caption !== '' ) {
5783 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5785 # No caption, fall back to using the filename for the
5787 $params['frame']['alt'] = $title->getText();
5790 # Use the "caption" for the tooltip text
5791 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5794 Hooks
::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5796 # Linker does the rest
5797 $time = isset( $options['time'] ) ?
$options['time'] : false;
5798 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5799 $time, $descQuery, $this->mOptions
->getThumbSize() );
5801 # Give the handler a chance to modify the parser object
5803 $handler->parserTransformHook( $this, $file );
5810 * @param string $caption
5811 * @param LinkHolderArray|bool $holders
5812 * @return mixed|string
5814 protected function stripAltText( $caption, $holders ) {
5815 # Strip bad stuff out of the title (tooltip). We can't just use
5816 # replaceLinkHoldersText() here, because if this function is called
5817 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5819 $tooltip = $holders->replaceText( $caption );
5821 $tooltip = $this->replaceLinkHoldersText( $caption );
5824 # make sure there are no placeholders in thumbnail attributes
5825 # that are later expanded to html- so expand them now and
5827 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5828 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5834 * Set a flag in the output object indicating that the content is dynamic and
5835 * shouldn't be cached.
5837 public function disableCache() {
5838 wfDebug( "Parser output marked as uncacheable.\n" );
5839 if ( !$this->mOutput
) {
5840 throw new MWException( __METHOD__
.
5841 " can only be called when actually parsing something" );
5843 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5844 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5848 * Callback from the Sanitizer for expanding items found in HTML attribute
5849 * values, so they can be safely tested and escaped.
5851 * @param string $text
5852 * @param bool|PPFrame $frame
5855 public function attributeStripCallback( &$text, $frame = false ) {
5856 $text = $this->replaceVariables( $text, $frame );
5857 $text = $this->mStripState
->unstripBoth( $text );
5866 public function getTags() {
5868 array_keys( $this->mTransparentTagHooks
),
5869 array_keys( $this->mTagHooks
),
5870 array_keys( $this->mFunctionTagHooks
)
5875 * Replace transparent tags in $text with the values given by the callbacks.
5877 * Transparent tag hooks are like regular XML-style tag hooks, except they
5878 * operate late in the transformation sequence, on HTML instead of wikitext.
5880 * @param string $text
5884 public function replaceTransparentTags( $text ) {
5886 $elements = array_keys( $this->mTransparentTagHooks
);
5887 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5888 $replacements = array();
5890 foreach ( $matches as $marker => $data ) {
5891 list( $element, $content, $params, $tag ) = $data;
5892 $tagName = strtolower( $element );
5893 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5894 $output = call_user_func_array(
5895 $this->mTransparentTagHooks
[$tagName],
5896 array( $content, $params, $this )
5901 $replacements[$marker] = $output;
5903 return strtr( $text, $replacements );
5907 * Break wikitext input into sections, and either pull or replace
5908 * some particular section's text.
5910 * External callers should use the getSection and replaceSection methods.
5912 * @param string $text Page wikitext
5913 * @param string|number $sectionId A section identifier string of the form:
5914 * "<flag1> - <flag2> - ... - <section number>"
5916 * Currently the only recognised flag is "T", which means the target section number
5917 * was derived during a template inclusion parse, in other words this is a template
5918 * section edit link. If no flags are given, it was an ordinary section edit link.
5919 * This flag is required to avoid a section numbering mismatch when a section is
5920 * enclosed by "<includeonly>" (bug 6563).
5922 * The section number 0 pulls the text before the first heading; other numbers will
5923 * pull the given section along with its lower-level subsections. If the section is
5924 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5926 * Section 0 is always considered to exist, even if it only contains the empty
5927 * string. If $text is the empty string and section 0 is replaced, $newText is
5930 * @param string $mode One of "get" or "replace"
5931 * @param string $newText Replacement text for section data.
5932 * @return string For "get", the extracted section text.
5933 * for "replace", the whole page with the section replaced.
5935 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5936 global $wgTitle; # not generally used but removes an ugly failure mode
5938 $magicScopeVariable = $this->lock();
5939 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5941 $frame = $this->getPreprocessor()->newFrame();
5943 # Process section extraction flags
5945 $sectionParts = explode( '-', $sectionId );
5946 $sectionIndex = array_pop( $sectionParts );
5947 foreach ( $sectionParts as $part ) {
5948 if ( $part === 'T' ) {
5949 $flags |
= self
::PTD_FOR_INCLUSION
;
5953 # Check for empty input
5954 if ( strval( $text ) === '' ) {
5955 # Only sections 0 and T-0 exist in an empty document
5956 if ( $sectionIndex == 0 ) {
5957 if ( $mode === 'get' ) {
5963 if ( $mode === 'get' ) {
5971 # Preprocess the text
5972 $root = $this->preprocessToDom( $text, $flags );
5974 # <h> nodes indicate section breaks
5975 # They can only occur at the top level, so we can find them by iterating the root's children
5976 $node = $root->getFirstChild();
5978 # Find the target section
5979 if ( $sectionIndex == 0 ) {
5980 # Section zero doesn't nest, level=big
5981 $targetLevel = 1000;
5984 if ( $node->getName() === 'h' ) {
5985 $bits = $node->splitHeading();
5986 if ( $bits['i'] == $sectionIndex ) {
5987 $targetLevel = $bits['level'];
5991 if ( $mode === 'replace' ) {
5992 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5994 $node = $node->getNextSibling();
6000 if ( $mode === 'get' ) {
6007 # Find the end of the section, including nested sections
6009 if ( $node->getName() === 'h' ) {
6010 $bits = $node->splitHeading();
6011 $curLevel = $bits['level'];
6012 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
6016 if ( $mode === 'get' ) {
6017 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
6019 $node = $node->getNextSibling();
6022 # Write out the remainder (in replace mode only)
6023 if ( $mode === 'replace' ) {
6024 # Output the replacement text
6025 # Add two newlines on -- trailing whitespace in $newText is conventionally
6026 # stripped by the editor, so we need both newlines to restore the paragraph gap
6027 # Only add trailing whitespace if there is newText
6028 if ( $newText != "" ) {
6029 $outText .= $newText . "\n\n";
6033 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
6034 $node = $node->getNextSibling();
6038 if ( is_string( $outText ) ) {
6039 # Re-insert stripped tags
6040 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
6047 * This function returns the text of a section, specified by a number ($section).
6048 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
6049 * the first section before any such heading (section 0).
6051 * If a section contains subsections, these are also returned.
6053 * @param string $text Text to look in
6054 * @param string|number $sectionId Section identifier as a number or string
6055 * (e.g. 0, 1 or 'T-1').
6056 * @param string $defaultText Default to return if section is not found
6058 * @return string Text of the requested section
6060 public function getSection( $text, $sectionId, $defaultText = '' ) {
6061 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
6065 * This function returns $oldtext after the content of the section
6066 * specified by $section has been replaced with $text. If the target
6067 * section does not exist, $oldtext is returned unchanged.
6069 * @param string $oldText Former text of the article
6070 * @param string|number $sectionId Section identifier as a number or string
6071 * (e.g. 0, 1 or 'T-1').
6072 * @param string $newText Replacing text
6074 * @return string Modified text
6076 public function replaceSection( $oldText, $sectionId, $newText ) {
6077 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
6081 * Get the ID of the revision we are parsing
6085 public function getRevisionId() {
6086 return $this->mRevisionId
;
6090 * Get the revision object for $this->mRevisionId
6092 * @return Revision|null Either a Revision object or null
6093 * @since 1.23 (public since 1.23)
6095 public function getRevisionObject() {
6096 if ( !is_null( $this->mRevisionObject
) ) {
6097 return $this->mRevisionObject
;
6099 if ( is_null( $this->mRevisionId
) ) {
6103 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
6104 return $this->mRevisionObject
;
6108 * Get the timestamp associated with the current revision, adjusted for
6109 * the default server-local timestamp
6112 public function getRevisionTimestamp() {
6113 if ( is_null( $this->mRevisionTimestamp
) ) {
6114 wfProfileIn( __METHOD__
);
6118 $revObject = $this->getRevisionObject();
6119 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6121 # The cryptic '' timezone parameter tells to use the site-default
6122 # timezone offset instead of the user settings.
6124 # Since this value will be saved into the parser cache, served
6125 # to other users, and potentially even used inside links and such,
6126 # it needs to be consistent for all visitors.
6127 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6129 wfProfileOut( __METHOD__
);
6131 return $this->mRevisionTimestamp
;
6135 * Get the name of the user that edited the last revision
6137 * @return string User name
6139 public function getRevisionUser() {
6140 if ( is_null( $this->mRevisionUser
) ) {
6141 $revObject = $this->getRevisionObject();
6143 # if this template is subst: the revision id will be blank,
6144 # so just use the current user's name
6146 $this->mRevisionUser
= $revObject->getUserText();
6147 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6148 $this->mRevisionUser
= $this->getUser()->getName();
6151 return $this->mRevisionUser
;
6155 * Get the size of the revision
6157 * @return int|null Revision size
6159 public function getRevisionSize() {
6160 if ( is_null( $this->mRevisionSize
) ) {
6161 $revObject = $this->getRevisionObject();
6163 # if this variable is subst: the revision id will be blank,
6164 # so just use the parser input size, because the own substituation
6165 # will change the size.
6167 $this->mRevisionSize
= $revObject->getSize();
6168 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6169 $this->mRevisionSize
= $this->mInputSize
;
6172 return $this->mRevisionSize
;
6176 * Mutator for $mDefaultSort
6178 * @param string $sort New value
6180 public function setDefaultSort( $sort ) {
6181 $this->mDefaultSort
= $sort;
6182 $this->mOutput
->setProperty( 'defaultsort', $sort );
6186 * Accessor for $mDefaultSort
6187 * Will use the empty string if none is set.
6189 * This value is treated as a prefix, so the
6190 * empty string is equivalent to sorting by
6195 public function getDefaultSort() {
6196 if ( $this->mDefaultSort
!== false ) {
6197 return $this->mDefaultSort
;
6204 * Accessor for $mDefaultSort
6205 * Unlike getDefaultSort(), will return false if none is set
6207 * @return string|bool
6209 public function getCustomDefaultSort() {
6210 return $this->mDefaultSort
;
6214 * Try to guess the section anchor name based on a wikitext fragment
6215 * presumably extracted from a heading, for example "Header" from
6218 * @param string $text
6222 public function guessSectionNameFromWikiText( $text ) {
6223 # Strip out wikitext links(they break the anchor)
6224 $text = $this->stripSectionName( $text );
6225 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6226 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6230 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6231 * instead. For use in redirects, since IE6 interprets Redirect: headers
6232 * as something other than UTF-8 (apparently?), resulting in breakage.
6234 * @param string $text The section name
6235 * @return string An anchor
6237 public function guessLegacySectionNameFromWikiText( $text ) {
6238 # Strip out wikitext links(they break the anchor)
6239 $text = $this->stripSectionName( $text );
6240 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6241 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6245 * Strips a text string of wikitext for use in a section anchor
6247 * Accepts a text string and then removes all wikitext from the
6248 * string and leaves only the resultant text (i.e. the result of
6249 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6250 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6251 * to create valid section anchors by mimicing the output of the
6252 * parser when headings are parsed.
6254 * @param string $text Text string to be stripped of wikitext
6255 * for use in a Section anchor
6256 * @return string Filtered text string
6258 public function stripSectionName( $text ) {
6259 # Strip internal link markup
6260 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6261 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6263 # Strip external link markup
6264 # @todo FIXME: Not tolerant to blank link text
6265 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6266 # on how many empty links there are on the page - need to figure that out.
6267 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6269 # Parse wikitext quotes (italics & bold)
6270 $text = $this->doQuotes( $text );
6273 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6278 * strip/replaceVariables/unstrip for preprocessor regression testing
6280 * @param string $text
6281 * @param Title $title
6282 * @param ParserOptions $options
6283 * @param int $outputType
6287 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6288 $magicScopeVariable = $this->lock();
6289 $this->startParse( $title, $options, $outputType, true );
6291 $text = $this->replaceVariables( $text );
6292 $text = $this->mStripState
->unstripBoth( $text );
6293 $text = Sanitizer
::removeHTMLtags( $text );
6298 * @param string $text
6299 * @param Title $title
6300 * @param ParserOptions $options
6303 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6304 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6308 * @param string $text
6309 * @param Title $title
6310 * @param ParserOptions $options
6313 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6314 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6318 * Call a callback function on all regions of the given text that are not
6319 * inside strip markers, and replace those regions with the return value
6320 * of the callback. For example, with input:
6324 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6325 * two strings will be replaced with the value returned by the callback in
6329 * @param callable $callback
6333 public function markerSkipCallback( $s, $callback ) {
6336 while ( $i < strlen( $s ) ) {
6337 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6338 if ( $markerStart === false ) {
6339 $out .= call_user_func( $callback, substr( $s, $i ) );
6342 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6343 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6344 if ( $markerEnd === false ) {
6345 $out .= substr( $s, $markerStart );
6348 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6349 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6358 * Remove any strip markers found in the given text.
6360 * @param string $text Input string
6363 public function killMarkers( $text ) {
6364 return $this->mStripState
->killMarkers( $text );
6368 * Save the parser state required to convert the given half-parsed text to
6369 * HTML. "Half-parsed" in this context means the output of
6370 * recursiveTagParse() or internalParse(). This output has strip markers
6371 * from replaceVariables (extensionSubstitution() etc.), and link
6372 * placeholders from replaceLinkHolders().
6374 * Returns an array which can be serialized and stored persistently. This
6375 * array can later be loaded into another parser instance with
6376 * unserializeHalfParsedText(). The text can then be safely incorporated into
6377 * the return value of a parser hook.
6379 * @param string $text
6383 public function serializeHalfParsedText( $text ) {
6384 wfProfileIn( __METHOD__
);
6387 'version' => self
::HALF_PARSED_VERSION
,
6388 'stripState' => $this->mStripState
->getSubState( $text ),
6389 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6391 wfProfileOut( __METHOD__
);
6396 * Load the parser state given in the $data array, which is assumed to
6397 * have been generated by serializeHalfParsedText(). The text contents is
6398 * extracted from the array, and its markers are transformed into markers
6399 * appropriate for the current Parser instance. This transformed text is
6400 * returned, and can be safely included in the return value of a parser
6403 * If the $data array has been stored persistently, the caller should first
6404 * check whether it is still valid, by calling isValidHalfParsedText().
6406 * @param array $data Serialized data
6407 * @throws MWException
6410 public function unserializeHalfParsedText( $data ) {
6411 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6412 throw new MWException( __METHOD__
. ': invalid version' );
6415 # First, extract the strip state.
6416 $texts = array( $data['text'] );
6417 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6419 # Now renumber links
6420 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6422 # Should be good to go.
6427 * Returns true if the given array, presumed to be generated by
6428 * serializeHalfParsedText(), is compatible with the current version of the
6431 * @param array $data
6435 public function isValidHalfParsedText( $data ) {
6436 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6440 * Parsed a width param of imagelink like 300px or 200x300px
6442 * @param string $value
6447 public function parseWidthParam( $value ) {
6448 $parsedWidthParam = array();
6449 if ( $value === '' ) {
6450 return $parsedWidthParam;
6453 # (bug 13500) In both cases (width/height and width only),
6454 # permit trailing "px" for backward compatibility.
6455 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6456 $width = intval( $m[1] );
6457 $height = intval( $m[2] );
6458 $parsedWidthParam['width'] = $width;
6459 $parsedWidthParam['height'] = $height;
6460 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6461 $width = intval( $value );
6462 $parsedWidthParam['width'] = $width;
6464 return $parsedWidthParam;
6468 * Lock the current instance of the parser.
6470 * This is meant to stop someone from calling the parser
6471 * recursively and messing up all the strip state.
6473 * @throws MWException If parser is in a parse
6474 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6476 protected function lock() {
6477 if ( $this->mInParse
) {
6478 throw new MWException( "Parser state cleared while parsing. "
6479 . "Did you call Parser::parse recursively?" );
6481 $this->mInParse
= true;
6484 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6485 $that->mInParse
= false;
6488 return $recursiveCheck;
6492 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6494 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6495 * or if there is more than one <p/> tag in the input HTML.
6497 * @param string $html
6501 public static function stripOuterParagraph( $html ) {
6503 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6504 if ( strpos( $m[1], '</p>' ) === false ) {
6513 * Return this parser if it is not doing anything, otherwise
6514 * get a fresh parser. You can use this method by doing
6515 * $myParser = $wgParser->getFreshParser(), or more simply
6516 * $wgParser->getFreshParser()->parse( ... );
6517 * if you're unsure if $wgParser is safe to use.
6520 * @return Parser A parser object that is not parsing anything
6522 public function getFreshParser() {
6523 global $wgParserConf;
6524 if ( $this->mInParse
) {
6525 return new $wgParserConf['class']( $wgParserConf );