Removed remaining profile calls
[lhc/web/wiklou.git] / includes / parser / Parser.php
1 <?php
2 /**
3 * PHP parser that converts wiki markup to HTML.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Parser
22 */
23
24 /**
25 * @defgroup Parser Parser
26 */
27
28 /**
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).
33 *
34 * There are seven main entry points into the Parser class:
35 *
36 * - Parser::parse()
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
50 *
51 * Globals used:
52 * object: $wgContLang
53 *
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
55 *
56 * @par Settings:
57 * $wgNamespacesWithSubpages
58 *
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
62 * $wgInterwikiMagic
63 * $wgMaxArticleSize
64 *
65 * @ingroup Parser
66 */
67 class Parser {
68 /**
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.
72 */
73 const VERSION = '1.6.4';
74
75 /**
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
78 */
79 const HALF_PARSED_VERSION = 2;
80
81 # Flags for Parser::setFunctionHook
82 const SFH_NO_HASH = 1;
83 const SFH_OBJECT_ARGS = 2;
84
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';
92
93 # Regular expression for a non-newline space
94 const SPACE_NOT_NL = '(?:\t|&nbsp;|&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
95
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;
105
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION = 1;
108
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()
114 const OT_MSG = 3;
115 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
116
117 # Marker Suffix needs to be accessible staticly.
118 const MARKER_SUFFIX = "-QINU\x7f";
119
120 # Markers used for wrapping the table of contents
121 const TOC_START = '<mw:toc>';
122 const TOC_END = '</mw:toc>';
123
124 # Persistent:
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;
137
138 # Initialised by initialiseVariables()
139
140 /**
141 * @var MagicWordArray
142 */
143 public $mVariables;
144
145 /**
146 * @var MagicWordArray
147 */
148 public $mSubstWords;
149 # Initialised in constructor
150 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols;
151
152 # Cleared with clearState():
153 /**
154 * @var ParserOutput
155 */
156 public $mOutput;
157 public $mAutonumber, $mDTopen;
158
159 /**
160 * @var StripState
161 */
162 public $mStripState;
163
164 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
165 /**
166 * @var LinkHolderArray
167 */
168 public $mLinkHolders;
169
170 public $mLinkID;
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;
176
177 /**
178 * @var User
179 */
180 public $mUser; # User object; only used when doing pre-save transform
181
182 # Temporary
183 # These are variables reset at least once per parse regardless of $clearState
184
185 /**
186 * @var ParserOptions
187 */
188 public $mOptions;
189
190 /**
191 * @var Title
192 */
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.
203
204 /**
205 * @var string
206 */
207 public $mUniqPrefix;
208
209 /**
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.
213 */
214 public $mLangLinkLanguages;
215
216 /**
217 * @var MapCacheLRU|null
218 * @since 1.24
219 *
220 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
221 */
222 public $currentRevisionCache;
223
224 /**
225 * @var bool Recursive call protection.
226 * This variable should be treated as if it were private.
227 */
228 public $mInParse = false;
229
230 /** @var SectionProfiler */
231 protected $mProfiler;
232
233 /**
234 * @param array $conf
235 */
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';
252 } else {
253 $this->mPreprocessorClass = 'Preprocessor_Hash';
254 }
255 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" );
256 }
257
258 /**
259 * Reduce memory usage to reduce the impact of circular references
260 */
261 public function __destruct() {
262 if ( isset( $this->mLinkHolders ) ) {
263 unset( $this->mLinkHolders );
264 }
265 foreach ( $this as $name => $value ) {
266 unset( $this->$name );
267 }
268 }
269
270 /**
271 * Allow extensions to clean up when the parser is cloned
272 */
273 public function __clone() {
274 $this->mInParse = false;
275
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.
285 $tmp = $this->$k;
286 $this->$k =& $tmp;
287 unset( $tmp );
288 }
289
290 Hooks::run( 'ParserCloned', array( $this ) );
291 }
292
293 /**
294 * Do various kinds of initialisation on the first call of the parser
295 */
296 public function firstCallInit() {
297 if ( !$this->mFirstCall ) {
298 return;
299 }
300 $this->mFirstCall = false;
301
302
303 CoreParserFunctions::register( $this );
304 CoreTagHooks::register( $this );
305 $this->initialiseVariables();
306
307 Hooks::run( 'ParserFirstCallInit', array( &$this ) );
308 }
309
310 /**
311 * Clear Parser state
312 *
313 * @private
314 */
315 public function clearState() {
316 if ( $this->mFirstCall ) {
317 $this->firstCallInit();
318 }
319 $this->mOutput = new ParserOutput;
320 $this->mOptions->registerWatcher( array( $this->mOutput, 'recordOption' ) );
321 $this->mAutonumber = 0;
322 $this->mLastSection = '';
323 $this->mDTopen = false;
324 $this->mIncludeCount = array();
325 $this->mArgStack = false;
326 $this->mInPre = false;
327 $this->mLinkHolders = new LinkHolderArray( $this );
328 $this->mLinkID = 0;
329 $this->mRevisionObject = $this->mRevisionTimestamp =
330 $this->mRevisionId = $this->mRevisionUser = $this->mRevisionSize = null;
331 $this->mVarCache = array();
332 $this->mUser = null;
333 $this->mLangLinkLanguages = array();
334 $this->currentRevisionCache = null;
335
336 /**
337 * Prefix for temporary replacement strings for the multipass parser.
338 * \x07 should never appear in input as it's disallowed in XML.
339 * Using it at the front also gives us a little extra robustness
340 * since it shouldn't match when butted up against identifier-like
341 * string constructs.
342 *
343 * Must not consist of all title characters, or else it will change
344 * the behavior of <nowiki> in a link.
345 */
346 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
347 $this->mStripState = new StripState( $this->mUniqPrefix );
348
349 # Clear these on every parse, bug 4549
350 $this->mTplRedirCache = $this->mTplDomCache = array();
351
352 $this->mShowToc = true;
353 $this->mForceTocPosition = false;
354 $this->mIncludeSizes = array(
355 'post-expand' => 0,
356 'arg' => 0,
357 );
358 $this->mPPNodeCount = 0;
359 $this->mGeneratedPPNodeCount = 0;
360 $this->mHighestExpansionDepth = 0;
361 $this->mDefaultSort = false;
362 $this->mHeadings = array();
363 $this->mDoubleUnderscores = array();
364 $this->mExpensiveFunctionCount = 0;
365
366 # Fix cloning
367 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
368 $this->mPreprocessor = null;
369 }
370
371 $this->mProfiler = new SectionProfiler();
372
373 Hooks::run( 'ParserClearState', array( &$this ) );
374 }
375
376 /**
377 * Convert wikitext to HTML
378 * Do not call this function recursively.
379 *
380 * @param string $text Text we want to parse
381 * @param Title $title
382 * @param ParserOptions $options
383 * @param bool $linestart
384 * @param bool $clearState
385 * @param int $revid Number to pass in {{REVISIONID}}
386 * @return ParserOutput A ParserOutput
387 */
388 public function parse( $text, Title $title, ParserOptions $options,
389 $linestart = true, $clearState = true, $revid = null
390 ) {
391 /**
392 * First pass--just handle <nowiki> sections, pass the rest off
393 * to internalParse() which does all the real work.
394 */
395
396 global $wgShowHostnames;
397 $fname = __METHOD__ . '-' . wfGetCaller();
398
399 if ( $clearState ) {
400 $magicScopeVariable = $this->lock();
401 }
402
403 $this->startParse( $title, $options, self::OT_HTML, $clearState );
404
405 $this->currentRevisionCache = null;
406 $this->mInputSize = strlen( $text );
407 if ( $this->mOptions->getEnableLimitReport() ) {
408 $this->mOutput->resetParseStartTime();
409 }
410
411 # Remove the strip marker tag prefix from the input, if present.
412 if ( $clearState ) {
413 $text = str_replace( $this->mUniqPrefix, '', $text );
414 }
415
416 $oldRevisionId = $this->mRevisionId;
417 $oldRevisionObject = $this->mRevisionObject;
418 $oldRevisionTimestamp = $this->mRevisionTimestamp;
419 $oldRevisionUser = $this->mRevisionUser;
420 $oldRevisionSize = $this->mRevisionSize;
421 if ( $revid !== null ) {
422 $this->mRevisionId = $revid;
423 $this->mRevisionObject = null;
424 $this->mRevisionTimestamp = null;
425 $this->mRevisionUser = null;
426 $this->mRevisionSize = null;
427 }
428
429 Hooks::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
430 # No more strip!
431 Hooks::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
432 $text = $this->internalParse( $text );
433 Hooks::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState ) );
434
435 $text = $this->internalParseHalfParsed( $text, true, $linestart );
436
437 /**
438 * A converted title will be provided in the output object if title and
439 * content conversion are enabled, the article text does not contain
440 * a conversion-suppressing double-underscore tag, and no
441 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
442 * automatic link conversion.
443 */
444 if ( !( $options->getDisableTitleConversion()
445 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
446 || isset( $this->mDoubleUnderscores['notitleconvert'] )
447 || $this->mOutput->getDisplayTitle() !== false )
448 ) {
449 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
450 if ( $convruletitle ) {
451 $this->mOutput->setTitleText( $convruletitle );
452 } else {
453 $titleText = $this->getConverterLanguage()->convertTitle( $title );
454 $this->mOutput->setTitleText( $titleText );
455 }
456 }
457
458 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
459 $this->limitationWarn( 'expensive-parserfunction',
460 $this->mExpensiveFunctionCount,
461 $this->mOptions->getExpensiveParserFunctionLimit()
462 );
463 }
464
465 # Information on include size limits, for the benefit of users who try to skirt them
466 if ( $this->mOptions->getEnableLimitReport() ) {
467 $max = $this->mOptions->getMaxIncludeSize();
468
469 $cpuTime = $this->mOutput->getTimeSinceStart( 'cpu' );
470 if ( $cpuTime !== null ) {
471 $this->mOutput->setLimitReportData( 'limitreport-cputime',
472 sprintf( "%.3f", $cpuTime )
473 );
474 }
475
476 $wallTime = $this->mOutput->getTimeSinceStart( 'wall' );
477 $this->mOutput->setLimitReportData( 'limitreport-walltime',
478 sprintf( "%.3f", $wallTime )
479 );
480
481 $this->mOutput->setLimitReportData( 'limitreport-ppvisitednodes',
482 array( $this->mPPNodeCount, $this->mOptions->getMaxPPNodeCount() )
483 );
484 $this->mOutput->setLimitReportData( 'limitreport-ppgeneratednodes',
485 array( $this->mGeneratedPPNodeCount, $this->mOptions->getMaxGeneratedPPNodeCount() )
486 );
487 $this->mOutput->setLimitReportData( 'limitreport-postexpandincludesize',
488 array( $this->mIncludeSizes['post-expand'], $max )
489 );
490 $this->mOutput->setLimitReportData( 'limitreport-templateargumentsize',
491 array( $this->mIncludeSizes['arg'], $max )
492 );
493 $this->mOutput->setLimitReportData( 'limitreport-expansiondepth',
494 array( $this->mHighestExpansionDepth, $this->mOptions->getMaxPPExpandDepth() )
495 );
496 $this->mOutput->setLimitReportData( 'limitreport-expensivefunctioncount',
497 array( $this->mExpensiveFunctionCount, $this->mOptions->getExpensiveParserFunctionLimit() )
498 );
499 Hooks::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput ) );
500
501 $limitReport = "NewPP limit report\n";
502 if ( $wgShowHostnames ) {
503 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
504 }
505 foreach ( $this->mOutput->getLimitReportData() as $key => $value ) {
506 if ( Hooks::run( 'ParserLimitReportFormat',
507 array( $key, &$value, &$limitReport, false, false )
508 ) ) {
509 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
510 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
511 ->inLanguage( 'en' )->useDatabase( false );
512 if ( !$valueMsg->exists() ) {
513 $valueMsg = new RawMessage( '$1' );
514 }
515 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
516 $valueMsg->params( $value );
517 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
518 }
519 }
520 }
521 // Since we're not really outputting HTML, decode the entities and
522 // then re-encode the things that need hiding inside HTML comments.
523 $limitReport = htmlspecialchars_decode( $limitReport );
524 Hooks::run( 'ParserLimitReport', array( $this, &$limitReport ) );
525
526 // Sanitize for comment. Note '‐' in the replacement is U+2010,
527 // which looks much like the problematic '-'.
528 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&amp;' ), $limitReport );
529 $text .= "\n<!-- \n$limitReport-->\n";
530
531 // Add on template profiling data
532 $dataByFunc = $this->mProfiler->getFunctionStats();
533 uasort( $dataByFunc, function ( $a, $b ) {
534 return $a['real'] < $b['real']; // descending order
535 } );
536 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
537 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
538 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
539 $item['%real'], $item['real'], $item['calls'],
540 htmlspecialchars( $item['name'] ) );
541 }
542 $text .= "\n<!-- \n$profileReport-->\n";
543
544 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
545 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' .
546 $this->mTitle->getPrefixedDBkey() );
547 }
548 }
549 $this->mOutput->setText( $text );
550
551 $this->mRevisionId = $oldRevisionId;
552 $this->mRevisionObject = $oldRevisionObject;
553 $this->mRevisionTimestamp = $oldRevisionTimestamp;
554 $this->mRevisionUser = $oldRevisionUser;
555 $this->mRevisionSize = $oldRevisionSize;
556 $this->mInputSize = false;
557 $this->currentRevisionCache = null;
558
559 return $this->mOutput;
560 }
561
562 /**
563 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
564 * can be called from an extension tag hook.
565 *
566 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
567 * instead, which means that lists and links have not been fully parsed yet,
568 * and strip markers are still present.
569 *
570 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
571 *
572 * Use this function if you're a parser tag hook and you want to parse
573 * wikitext before or after applying additional transformations, and you
574 * intend to *return the result as hook output*, which will cause it to go
575 * through the rest of parsing process automatically.
576 *
577 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
578 * $text are not expanded
579 *
580 * @param string $text Text extension wants to have parsed
581 * @param bool|PPFrame $frame The frame to use for expanding any template variables
582 * @return string UNSAFE half-parsed HTML
583 */
584 public function recursiveTagParse( $text, $frame = false ) {
585 Hooks::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
586 Hooks::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
587 $text = $this->internalParse( $text, false, $frame );
588 return $text;
589 }
590
591 /**
592 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
593 * point can be called from an extension tag hook.
594 *
595 * The output of this function is fully-parsed HTML that is safe for output.
596 * If you're a parser tag hook, you might want to use recursiveTagParse()
597 * instead.
598 *
599 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
600 * $text are not expanded
601 *
602 * @since 1.25
603 *
604 * @param string $text Text extension wants to have parsed
605 * @param bool|PPFrame $frame The frame to use for expanding any template variables
606 * @return string Fully parsed HTML
607 */
608 public function recursiveTagParseFully( $text, $frame = false ) {
609 $text = $this->recursiveTagParse( $text, $frame );
610 $text = $this->internalParseHalfParsed( $text, false );
611 return $text;
612 }
613
614 /**
615 * Expand templates and variables in the text, producing valid, static wikitext.
616 * Also removes comments.
617 * Do not call this function recursively.
618 * @param string $text
619 * @param Title $title
620 * @param ParserOptions $options
621 * @param int|null $revid
622 * @param bool|PPFrame $frame
623 * @return mixed|string
624 */
625 public function preprocess( $text, Title $title = null,
626 ParserOptions $options, $revid = null, $frame = false
627 ) {
628 $magicScopeVariable = $this->lock();
629 $this->startParse( $title, $options, self::OT_PREPROCESS, true );
630 if ( $revid !== null ) {
631 $this->mRevisionId = $revid;
632 }
633 Hooks::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
634 Hooks::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
635 $text = $this->replaceVariables( $text, $frame );
636 $text = $this->mStripState->unstripBoth( $text );
637 return $text;
638 }
639
640 /**
641 * Recursive parser entry point that can be called from an extension tag
642 * hook.
643 *
644 * @param string $text Text to be expanded
645 * @param bool|PPFrame $frame The frame to use for expanding any template variables
646 * @return string
647 * @since 1.19
648 */
649 public function recursivePreprocess( $text, $frame = false ) {
650 $text = $this->replaceVariables( $text, $frame );
651 $text = $this->mStripState->unstripBoth( $text );
652 return $text;
653 }
654
655 /**
656 * Process the wikitext for the "?preload=" feature. (bug 5210)
657 *
658 * "<noinclude>", "<includeonly>" etc. are parsed as for template
659 * transclusion, comments, templates, arguments, tags hooks and parser
660 * functions are untouched.
661 *
662 * @param string $text
663 * @param Title $title
664 * @param ParserOptions $options
665 * @param array $params
666 * @return string
667 */
668 public function getPreloadText( $text, Title $title, ParserOptions $options, $params = array() ) {
669 $msg = new RawMessage( $text );
670 $text = $msg->params( $params )->plain();
671
672 # Parser (re)initialisation
673 $magicScopeVariable = $this->lock();
674 $this->startParse( $title, $options, self::OT_PLAIN, true );
675
676 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
677 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
678 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
679 $text = $this->mStripState->unstripBoth( $text );
680 return $text;
681 }
682
683 /**
684 * Get a random string
685 *
686 * @return string
687 */
688 public static function getRandomString() {
689 return wfRandomString( 16 );
690 }
691
692 /**
693 * Set the current user.
694 * Should only be used when doing pre-save transform.
695 *
696 * @param User|null $user User object or null (to reset)
697 */
698 public function setUser( $user ) {
699 $this->mUser = $user;
700 }
701
702 /**
703 * Accessor for mUniqPrefix.
704 *
705 * @return string
706 */
707 public function uniqPrefix() {
708 if ( !isset( $this->mUniqPrefix ) ) {
709 # @todo FIXME: This is probably *horribly wrong*
710 # LanguageConverter seems to want $wgParser's uniqPrefix, however
711 # if this is called for a parser cache hit, the parser may not
712 # have ever been initialized in the first place.
713 # Not really sure what the heck is supposed to be going on here.
714 return '';
715 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
716 }
717 return $this->mUniqPrefix;
718 }
719
720 /**
721 * Set the context title
722 *
723 * @param Title $t
724 */
725 public function setTitle( $t ) {
726 if ( !$t ) {
727 $t = Title::newFromText( 'NO TITLE' );
728 }
729
730 if ( $t->hasFragment() ) {
731 # Strip the fragment to avoid various odd effects
732 $this->mTitle = clone $t;
733 $this->mTitle->setFragment( '' );
734 } else {
735 $this->mTitle = $t;
736 }
737 }
738
739 /**
740 * Accessor for the Title object
741 *
742 * @return Title
743 */
744 public function getTitle() {
745 return $this->mTitle;
746 }
747
748 /**
749 * Accessor/mutator for the Title object
750 *
751 * @param Title $x Title object or null to just get the current one
752 * @return Title
753 */
754 public function Title( $x = null ) {
755 return wfSetVar( $this->mTitle, $x );
756 }
757
758 /**
759 * Set the output type
760 *
761 * @param int $ot New value
762 */
763 public function setOutputType( $ot ) {
764 $this->mOutputType = $ot;
765 # Shortcut alias
766 $this->ot = array(
767 'html' => $ot == self::OT_HTML,
768 'wiki' => $ot == self::OT_WIKI,
769 'pre' => $ot == self::OT_PREPROCESS,
770 'plain' => $ot == self::OT_PLAIN,
771 );
772 }
773
774 /**
775 * Accessor/mutator for the output type
776 *
777 * @param int|null $x New value or null to just get the current one
778 * @return int
779 */
780 public function OutputType( $x = null ) {
781 return wfSetVar( $this->mOutputType, $x );
782 }
783
784 /**
785 * Get the ParserOutput object
786 *
787 * @return ParserOutput
788 */
789 public function getOutput() {
790 return $this->mOutput;
791 }
792
793 /**
794 * Get the ParserOptions object
795 *
796 * @return ParserOptions
797 */
798 public function getOptions() {
799 return $this->mOptions;
800 }
801
802 /**
803 * Accessor/mutator for the ParserOptions object
804 *
805 * @param ParserOptions $x New value or null to just get the current one
806 * @return ParserOptions Current ParserOptions object
807 */
808 public function Options( $x = null ) {
809 return wfSetVar( $this->mOptions, $x );
810 }
811
812 /**
813 * @return int
814 */
815 public function nextLinkID() {
816 return $this->mLinkID++;
817 }
818
819 /**
820 * @param int $id
821 */
822 public function setLinkID( $id ) {
823 $this->mLinkID = $id;
824 }
825
826 /**
827 * Get a language object for use in parser functions such as {{FORMATNUM:}}
828 * @return Language
829 */
830 public function getFunctionLang() {
831 return $this->getTargetLanguage();
832 }
833
834 /**
835 * Get the target language for the content being parsed. This is usually the
836 * language that the content is in.
837 *
838 * @since 1.19
839 *
840 * @throws MWException
841 * @return Language
842 */
843 public function getTargetLanguage() {
844 $target = $this->mOptions->getTargetLanguage();
845
846 if ( $target !== null ) {
847 return $target;
848 } elseif ( $this->mOptions->getInterfaceMessage() ) {
849 return $this->mOptions->getUserLangObj();
850 } elseif ( is_null( $this->mTitle ) ) {
851 throw new MWException( __METHOD__ . ': $this->mTitle is null' );
852 }
853
854 return $this->mTitle->getPageLanguage();
855 }
856
857 /**
858 * Get the language object for language conversion
859 * @return Language|null
860 */
861 public function getConverterLanguage() {
862 return $this->getTargetLanguage();
863 }
864
865 /**
866 * Get a User object either from $this->mUser, if set, or from the
867 * ParserOptions object otherwise
868 *
869 * @return User
870 */
871 public function getUser() {
872 if ( !is_null( $this->mUser ) ) {
873 return $this->mUser;
874 }
875 return $this->mOptions->getUser();
876 }
877
878 /**
879 * Get a preprocessor object
880 *
881 * @return Preprocessor
882 */
883 public function getPreprocessor() {
884 if ( !isset( $this->mPreprocessor ) ) {
885 $class = $this->mPreprocessorClass;
886 $this->mPreprocessor = new $class( $this );
887 }
888 return $this->mPreprocessor;
889 }
890
891 /**
892 * Replaces all occurrences of HTML-style comments and the given tags
893 * in the text with a random marker and returns the next text. The output
894 * parameter $matches will be an associative array filled with data in
895 * the form:
896 *
897 * @code
898 * 'UNIQ-xxxxx' => array(
899 * 'element',
900 * 'tag content',
901 * array( 'param' => 'x' ),
902 * '<element param="x">tag content</element>' ) )
903 * @endcode
904 *
905 * @param array $elements List of element names. Comments are always extracted.
906 * @param string $text Source text string.
907 * @param array $matches Out parameter, Array: extracted tags
908 * @param string $uniq_prefix
909 * @return string Stripped text
910 */
911 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
912 static $n = 1;
913 $stripped = '';
914 $matches = array();
915
916 $taglist = implode( '|', $elements );
917 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
918
919 while ( $text != '' ) {
920 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
921 $stripped .= $p[0];
922 if ( count( $p ) < 5 ) {
923 break;
924 }
925 if ( count( $p ) > 5 ) {
926 # comment
927 $element = $p[4];
928 $attributes = '';
929 $close = '';
930 $inside = $p[5];
931 } else {
932 # tag
933 $element = $p[1];
934 $attributes = $p[2];
935 $close = $p[3];
936 $inside = $p[4];
937 }
938
939 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
940 $stripped .= $marker;
941
942 if ( $close === '/>' ) {
943 # Empty element tag, <tag />
944 $content = null;
945 $text = $inside;
946 $tail = null;
947 } else {
948 if ( $element === '!--' ) {
949 $end = '/(-->)/';
950 } else {
951 $end = "/(<\\/$element\\s*>)/i";
952 }
953 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
954 $content = $q[0];
955 if ( count( $q ) < 3 ) {
956 # No end tag -- let it run out to the end of the text.
957 $tail = '';
958 $text = '';
959 } else {
960 $tail = $q[1];
961 $text = $q[2];
962 }
963 }
964
965 $matches[$marker] = array( $element,
966 $content,
967 Sanitizer::decodeTagAttributes( $attributes ),
968 "<$element$attributes$close$content$tail" );
969 }
970 return $stripped;
971 }
972
973 /**
974 * Get a list of strippable XML-like elements
975 *
976 * @return array
977 */
978 public function getStripList() {
979 return $this->mStripList;
980 }
981
982 /**
983 * Add an item to the strip state
984 * Returns the unique tag which must be inserted into the stripped text
985 * The tag will be replaced with the original text in unstrip()
986 *
987 * @param string $text
988 *
989 * @return string
990 */
991 public function insertStripItem( $text ) {
992 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
993 $this->mMarkerIndex++;
994 $this->mStripState->addGeneral( $rnd, $text );
995 return $rnd;
996 }
997
998 /**
999 * parse the wiki syntax used to render tables
1000 *
1001 * @private
1002 * @param string $text
1003 * @return string
1004 */
1005 public function doTableStuff( $text ) {
1006
1007 $lines = StringUtils::explode( "\n", $text );
1008 $out = '';
1009 $td_history = array(); # Is currently a td tag open?
1010 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1011 $tr_history = array(); # Is currently a tr tag open?
1012 $tr_attributes = array(); # history of tr attributes
1013 $has_opened_tr = array(); # Did this table open a <tr> element?
1014 $indent_level = 0; # indent level of the table
1015
1016 foreach ( $lines as $outLine ) {
1017 $line = trim( $outLine );
1018
1019 if ( $line === '' ) { # empty line, go to next line
1020 $out .= $outLine . "\n";
1021 continue;
1022 }
1023
1024 $first_character = $line[0];
1025 $matches = array();
1026
1027 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1028 # First check if we are starting a new table
1029 $indent_level = strlen( $matches[1] );
1030
1031 $attributes = $this->mStripState->unstripBoth( $matches[2] );
1032 $attributes = Sanitizer::fixTagAttributes( $attributes, 'table' );
1033
1034 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1035 array_push( $td_history, false );
1036 array_push( $last_tag_history, '' );
1037 array_push( $tr_history, false );
1038 array_push( $tr_attributes, '' );
1039 array_push( $has_opened_tr, false );
1040 } elseif ( count( $td_history ) == 0 ) {
1041 # Don't do any of the following
1042 $out .= $outLine . "\n";
1043 continue;
1044 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1045 # We are ending a table
1046 $line = '</table>' . substr( $line, 2 );
1047 $last_tag = array_pop( $last_tag_history );
1048
1049 if ( !array_pop( $has_opened_tr ) ) {
1050 $line = "<tr><td></td></tr>{$line}";
1051 }
1052
1053 if ( array_pop( $tr_history ) ) {
1054 $line = "</tr>{$line}";
1055 }
1056
1057 if ( array_pop( $td_history ) ) {
1058 $line = "</{$last_tag}>{$line}";
1059 }
1060 array_pop( $tr_attributes );
1061 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1062 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1063 # Now we have a table row
1064 $line = preg_replace( '#^\|-+#', '', $line );
1065
1066 # Whats after the tag is now only attributes
1067 $attributes = $this->mStripState->unstripBoth( $line );
1068 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' );
1069 array_pop( $tr_attributes );
1070 array_push( $tr_attributes, $attributes );
1071
1072 $line = '';
1073 $last_tag = array_pop( $last_tag_history );
1074 array_pop( $has_opened_tr );
1075 array_push( $has_opened_tr, true );
1076
1077 if ( array_pop( $tr_history ) ) {
1078 $line = '</tr>';
1079 }
1080
1081 if ( array_pop( $td_history ) ) {
1082 $line = "</{$last_tag}>{$line}";
1083 }
1084
1085 $outLine = $line;
1086 array_push( $tr_history, false );
1087 array_push( $td_history, false );
1088 array_push( $last_tag_history, '' );
1089 } elseif ( $first_character === '|'
1090 || $first_character === '!'
1091 || substr( $line, 0, 2 ) === '|+'
1092 ) {
1093 # This might be cell elements, td, th or captions
1094 if ( substr( $line, 0, 2 ) === '|+' ) {
1095 $first_character = '+';
1096 $line = substr( $line, 1 );
1097 }
1098
1099 $line = substr( $line, 1 );
1100
1101 if ( $first_character === '!' ) {
1102 $line = str_replace( '!!', '||', $line );
1103 }
1104
1105 # Split up multiple cells on the same line.
1106 # FIXME : This can result in improper nesting of tags processed
1107 # by earlier parser steps, but should avoid splitting up eg
1108 # attribute values containing literal "||".
1109 $cells = StringUtils::explodeMarkup( '||', $line );
1110
1111 $outLine = '';
1112
1113 # Loop through each table cell
1114 foreach ( $cells as $cell ) {
1115 $previous = '';
1116 if ( $first_character !== '+' ) {
1117 $tr_after = array_pop( $tr_attributes );
1118 if ( !array_pop( $tr_history ) ) {
1119 $previous = "<tr{$tr_after}>\n";
1120 }
1121 array_push( $tr_history, true );
1122 array_push( $tr_attributes, '' );
1123 array_pop( $has_opened_tr );
1124 array_push( $has_opened_tr, true );
1125 }
1126
1127 $last_tag = array_pop( $last_tag_history );
1128
1129 if ( array_pop( $td_history ) ) {
1130 $previous = "</{$last_tag}>\n{$previous}";
1131 }
1132
1133 if ( $first_character === '|' ) {
1134 $last_tag = 'td';
1135 } elseif ( $first_character === '!' ) {
1136 $last_tag = 'th';
1137 } elseif ( $first_character === '+' ) {
1138 $last_tag = 'caption';
1139 } else {
1140 $last_tag = '';
1141 }
1142
1143 array_push( $last_tag_history, $last_tag );
1144
1145 # A cell could contain both parameters and data
1146 $cell_data = explode( '|', $cell, 2 );
1147
1148 # Bug 553: Note that a '|' inside an invalid link should not
1149 # be mistaken as delimiting cell parameters
1150 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1151 $cell = "{$previous}<{$last_tag}>{$cell}";
1152 } elseif ( count( $cell_data ) == 1 ) {
1153 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1154 } else {
1155 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
1156 $attributes = Sanitizer::fixTagAttributes( $attributes, $last_tag );
1157 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1158 }
1159
1160 $outLine .= $cell;
1161 array_push( $td_history, true );
1162 }
1163 }
1164 $out .= $outLine . "\n";
1165 }
1166
1167 # Closing open td, tr && table
1168 while ( count( $td_history ) > 0 ) {
1169 if ( array_pop( $td_history ) ) {
1170 $out .= "</td>\n";
1171 }
1172 if ( array_pop( $tr_history ) ) {
1173 $out .= "</tr>\n";
1174 }
1175 if ( !array_pop( $has_opened_tr ) ) {
1176 $out .= "<tr><td></td></tr>\n";
1177 }
1178
1179 $out .= "</table>\n";
1180 }
1181
1182 # Remove trailing line-ending (b/c)
1183 if ( substr( $out, -1 ) === "\n" ) {
1184 $out = substr( $out, 0, -1 );
1185 }
1186
1187 # special case: don't return empty table
1188 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1189 $out = '';
1190 }
1191
1192
1193 return $out;
1194 }
1195
1196 /**
1197 * Helper function for parse() that transforms wiki markup into half-parsed
1198 * HTML. Only called for $mOutputType == self::OT_HTML.
1199 *
1200 * @private
1201 *
1202 * @param string $text
1203 * @param bool $isMain
1204 * @param bool $frame
1205 *
1206 * @return string
1207 */
1208 public function internalParse( $text, $isMain = true, $frame = false ) {
1209
1210 $origText = $text;
1211
1212 # Hook to suspend the parser in this state
1213 if ( !Hooks::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
1214 return $text;
1215 }
1216
1217 # if $frame is provided, then use $frame for replacing any variables
1218 if ( $frame ) {
1219 # use frame depth to infer how include/noinclude tags should be handled
1220 # depth=0 means this is the top-level document; otherwise it's an included document
1221 if ( !$frame->depth ) {
1222 $flag = 0;
1223 } else {
1224 $flag = Parser::PTD_FOR_INCLUSION;
1225 }
1226 $dom = $this->preprocessToDom( $text, $flag );
1227 $text = $frame->expand( $dom );
1228 } else {
1229 # if $frame is not provided, then use old-style replaceVariables
1230 $text = $this->replaceVariables( $text );
1231 }
1232
1233 Hooks::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState ) );
1234 $text = Sanitizer::removeHTMLtags(
1235 $text,
1236 array( &$this, 'attributeStripCallback' ),
1237 false,
1238 array_keys( $this->mTransparentTagHooks )
1239 );
1240 Hooks::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
1241
1242 # Tables need to come after variable replacement for things to work
1243 # properly; putting them before other transformations should keep
1244 # exciting things like link expansions from showing up in surprising
1245 # places.
1246 $text = $this->doTableStuff( $text );
1247
1248 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1249
1250 $text = $this->doDoubleUnderscore( $text );
1251
1252 $text = $this->doHeadings( $text );
1253 $text = $this->replaceInternalLinks( $text );
1254 $text = $this->doAllQuotes( $text );
1255 $text = $this->replaceExternalLinks( $text );
1256
1257 # replaceInternalLinks may sometimes leave behind
1258 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1259 $text = str_replace( $this->mUniqPrefix . 'NOPARSE', '', $text );
1260
1261 $text = $this->doMagicLinks( $text );
1262 $text = $this->formatHeadings( $text, $origText, $isMain );
1263
1264 return $text;
1265 }
1266
1267 /**
1268 * Helper function for parse() that transforms half-parsed HTML into fully
1269 * parsed HTML.
1270 *
1271 * @param string $text
1272 * @param bool $isMain
1273 * @param bool $linestart
1274 * @return string
1275 */
1276 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1277 global $wgUseTidy, $wgAlwaysUseTidy;
1278
1279 $text = $this->mStripState->unstripGeneral( $text );
1280
1281 # Clean up special characters, only run once, next-to-last before doBlockLevels
1282 $fixtags = array(
1283 # french spaces, last one Guillemet-left
1284 # only if there is something before the space
1285 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&#160;',
1286 # french spaces, Guillemet-right
1287 '/(\\302\\253) /' => '\\1&#160;',
1288 '/&#160;(!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1289 );
1290 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1291
1292 $text = $this->doBlockLevels( $text, $linestart );
1293
1294 $this->replaceLinkHolders( $text );
1295
1296 /**
1297 * The input doesn't get language converted if
1298 * a) It's disabled
1299 * b) Content isn't converted
1300 * c) It's a conversion table
1301 * d) it is an interface message (which is in the user language)
1302 */
1303 if ( !( $this->mOptions->getDisableContentConversion()
1304 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) )
1305 ) {
1306 if ( !$this->mOptions->getInterfaceMessage() ) {
1307 # The position of the convert() call should not be changed. it
1308 # assumes that the links are all replaced and the only thing left
1309 # is the <nowiki> mark.
1310 $text = $this->getConverterLanguage()->convert( $text );
1311 }
1312 }
1313
1314 $text = $this->mStripState->unstripNoWiki( $text );
1315
1316 if ( $isMain ) {
1317 Hooks::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1318 }
1319
1320 $text = $this->replaceTransparentTags( $text );
1321 $text = $this->mStripState->unstripGeneral( $text );
1322
1323 $text = Sanitizer::normalizeCharReferences( $text );
1324
1325 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) {
1326 $text = MWTidy::tidy( $text );
1327 } else {
1328 # attempt to sanitize at least some nesting problems
1329 # (bug #2702 and quite a few others)
1330 $tidyregs = array(
1331 # ''Something [http://www.cool.com cool''] -->
1332 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1333 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1334 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1335 # fix up an anchor inside another anchor, only
1336 # at least for a single single nested link (bug 3695)
1337 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1338 '\\1\\2</a>\\3</a>\\1\\4</a>',
1339 # fix div inside inline elements- doBlockLevels won't wrap a line which
1340 # contains a div, so fix it up here; replace
1341 # div with escaped text
1342 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1343 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
1344 # remove empty italic or bold tag pairs, some
1345 # introduced by rules above
1346 '/<([bi])><\/\\1>/' => '',
1347 );
1348
1349 $text = preg_replace(
1350 array_keys( $tidyregs ),
1351 array_values( $tidyregs ),
1352 $text );
1353 }
1354
1355 if ( $isMain ) {
1356 Hooks::run( 'ParserAfterTidy', array( &$this, &$text ) );
1357 }
1358
1359 return $text;
1360 }
1361
1362 /**
1363 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1364 * magic external links.
1365 *
1366 * DML
1367 * @private
1368 *
1369 * @param string $text
1370 *
1371 * @return string
1372 */
1373 public function doMagicLinks( $text ) {
1374 $prots = wfUrlProtocolsWithoutProtRel();
1375 $urlChar = self::EXT_LINK_URL_CLASS;
1376 $space = self::SPACE_NOT_NL; # non-newline space
1377 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1378 $spaces = "$space++"; # possessive match of 1 or more spaces
1379 $text = preg_replace_callback(
1380 '!(?: # Start cases
1381 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1382 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1383 (\b(?i:$prots)$urlChar+) | # m[3]: Free external links
1384 \b(?:RFC|PMID) $spaces # m[4]: RFC or PMID, capture number
1385 ([0-9]+)\b |
1386 \bISBN $spaces ( # m[5]: ISBN, capture number
1387 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1388 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1389 [0-9Xx] # check digit
1390 )\b
1391 )!xu", array( &$this, 'magicLinkCallback' ), $text );
1392 return $text;
1393 }
1394
1395 /**
1396 * @throws MWException
1397 * @param array $m
1398 * @return HTML|string
1399 */
1400 public function magicLinkCallback( $m ) {
1401 if ( isset( $m[1] ) && $m[1] !== '' ) {
1402 # Skip anchor
1403 return $m[0];
1404 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1405 # Skip HTML element
1406 return $m[0];
1407 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1408 # Free external link
1409 return $this->makeFreeExternalLink( $m[0] );
1410 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1411 # RFC or PMID
1412 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1413 $keyword = 'RFC';
1414 $urlmsg = 'rfcurl';
1415 $cssClass = 'mw-magiclink-rfc';
1416 $id = $m[4];
1417 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1418 $keyword = 'PMID';
1419 $urlmsg = 'pubmedurl';
1420 $cssClass = 'mw-magiclink-pmid';
1421 $id = $m[4];
1422 } else {
1423 throw new MWException( __METHOD__ . ': unrecognised match type "' .
1424 substr( $m[0], 0, 20 ) . '"' );
1425 }
1426 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1427 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1428 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1429 # ISBN
1430 $isbn = $m[5];
1431 $space = self::SPACE_NOT_NL; # non-newline space
1432 $isbn = preg_replace( "/$space/", ' ', $isbn );
1433 $num = strtr( $isbn, array(
1434 '-' => '',
1435 ' ' => '',
1436 'x' => 'X',
1437 ));
1438 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
1439 return '<a href="' .
1440 htmlspecialchars( $titleObj->getLocalURL() ) .
1441 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1442 } else {
1443 return $m[0];
1444 }
1445 }
1446
1447 /**
1448 * Make a free external link, given a user-supplied URL
1449 *
1450 * @param string $url
1451 *
1452 * @return string HTML
1453 * @private
1454 */
1455 public function makeFreeExternalLink( $url ) {
1456
1457 $trail = '';
1458
1459 # The characters '<' and '>' (which were escaped by
1460 # removeHTMLtags()) should not be included in
1461 # URLs, per RFC 2396.
1462 $m2 = array();
1463 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1464 $trail = substr( $url, $m2[0][1] ) . $trail;
1465 $url = substr( $url, 0, $m2[0][1] );
1466 }
1467
1468 # Move trailing punctuation to $trail
1469 $sep = ',;\.:!?';
1470 # If there is no left bracket, then consider right brackets fair game too
1471 if ( strpos( $url, '(' ) === false ) {
1472 $sep .= ')';
1473 }
1474
1475 $urlRev = strrev( $url );
1476 $numSepChars = strspn( $urlRev, $sep );
1477 # Don't break a trailing HTML entity by moving the ; into $trail
1478 # This is in hot code, so use substr_compare to avoid having to
1479 # create a new string object for the comparison
1480 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0) {
1481 # more optimization: instead of running preg_match with a $
1482 # anchor, which can be slow, do the match on the reversed
1483 # string starting at the desired offset.
1484 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1485 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1486 $numSepChars--;
1487 }
1488 }
1489 if ( $numSepChars ) {
1490 $trail = substr( $url, -$numSepChars ) . $trail;
1491 $url = substr( $url, 0, -$numSepChars );
1492 }
1493
1494 $url = Sanitizer::cleanUrl( $url );
1495
1496 # Is this an external image?
1497 $text = $this->maybeMakeExternalImage( $url );
1498 if ( $text === false ) {
1499 # Not an image, make a link
1500 $text = Linker::makeExternalLink( $url,
1501 $this->getConverterLanguage()->markNoConversion( $url, true ),
1502 true, 'free',
1503 $this->getExternalLinkAttribs( $url ) );
1504 # Register it in the output object...
1505 # Replace unnecessary URL escape codes with their equivalent characters
1506 $pasteurized = self::normalizeLinkUrl( $url );
1507 $this->mOutput->addExternalLink( $pasteurized );
1508 }
1509 return $text . $trail;
1510 }
1511
1512 /**
1513 * Parse headers and return html
1514 *
1515 * @private
1516 *
1517 * @param string $text
1518 *
1519 * @return string
1520 */
1521 public function doHeadings( $text ) {
1522 for ( $i = 6; $i >= 1; --$i ) {
1523 $h = str_repeat( '=', $i );
1524 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1525 }
1526 return $text;
1527 }
1528
1529 /**
1530 * Replace single quotes with HTML markup
1531 * @private
1532 *
1533 * @param string $text
1534 *
1535 * @return string The altered text
1536 */
1537 public function doAllQuotes( $text ) {
1538 $outtext = '';
1539 $lines = StringUtils::explode( "\n", $text );
1540 foreach ( $lines as $line ) {
1541 $outtext .= $this->doQuotes( $line ) . "\n";
1542 }
1543 $outtext = substr( $outtext, 0, -1 );
1544 return $outtext;
1545 }
1546
1547 /**
1548 * Helper function for doAllQuotes()
1549 *
1550 * @param string $text
1551 *
1552 * @return string
1553 */
1554 public function doQuotes( $text ) {
1555 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1556 $countarr = count( $arr );
1557 if ( $countarr == 1 ) {
1558 return $text;
1559 }
1560
1561 // First, do some preliminary work. This may shift some apostrophes from
1562 // being mark-up to being text. It also counts the number of occurrences
1563 // of bold and italics mark-ups.
1564 $numbold = 0;
1565 $numitalics = 0;
1566 for ( $i = 1; $i < $countarr; $i += 2 ) {
1567 $thislen = strlen( $arr[$i] );
1568 // If there are ever four apostrophes, assume the first is supposed to
1569 // be text, and the remaining three constitute mark-up for bold text.
1570 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1571 if ( $thislen == 4 ) {
1572 $arr[$i - 1] .= "'";
1573 $arr[$i] = "'''";
1574 $thislen = 3;
1575 } elseif ( $thislen > 5 ) {
1576 // If there are more than 5 apostrophes in a row, assume they're all
1577 // text except for the last 5.
1578 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1579 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1580 $arr[$i] = "'''''";
1581 $thislen = 5;
1582 }
1583 // Count the number of occurrences of bold and italics mark-ups.
1584 if ( $thislen == 2 ) {
1585 $numitalics++;
1586 } elseif ( $thislen == 3 ) {
1587 $numbold++;
1588 } elseif ( $thislen == 5 ) {
1589 $numitalics++;
1590 $numbold++;
1591 }
1592 }
1593
1594 // If there is an odd number of both bold and italics, it is likely
1595 // that one of the bold ones was meant to be an apostrophe followed
1596 // by italics. Which one we cannot know for certain, but it is more
1597 // likely to be one that has a single-letter word before it.
1598 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1599 $firstsingleletterword = -1;
1600 $firstmultiletterword = -1;
1601 $firstspace = -1;
1602 for ( $i = 1; $i < $countarr; $i += 2 ) {
1603 if ( strlen( $arr[$i] ) == 3 ) {
1604 $x1 = substr( $arr[$i - 1], -1 );
1605 $x2 = substr( $arr[$i - 1], -2, 1 );
1606 if ( $x1 === ' ' ) {
1607 if ( $firstspace == -1 ) {
1608 $firstspace = $i;
1609 }
1610 } elseif ( $x2 === ' ' ) {
1611 if ( $firstsingleletterword == -1 ) {
1612 $firstsingleletterword = $i;
1613 // if $firstsingleletterword is set, we don't
1614 // look at the other options, so we can bail early.
1615 break;
1616 }
1617 } else {
1618 if ( $firstmultiletterword == -1 ) {
1619 $firstmultiletterword = $i;
1620 }
1621 }
1622 }
1623 }
1624
1625 // If there is a single-letter word, use it!
1626 if ( $firstsingleletterword > -1 ) {
1627 $arr[$firstsingleletterword] = "''";
1628 $arr[$firstsingleletterword - 1] .= "'";
1629 } elseif ( $firstmultiletterword > -1 ) {
1630 // If not, but there's a multi-letter word, use that one.
1631 $arr[$firstmultiletterword] = "''";
1632 $arr[$firstmultiletterword - 1] .= "'";
1633 } elseif ( $firstspace > -1 ) {
1634 // ... otherwise use the first one that has neither.
1635 // (notice that it is possible for all three to be -1 if, for example,
1636 // there is only one pentuple-apostrophe in the line)
1637 $arr[$firstspace] = "''";
1638 $arr[$firstspace - 1] .= "'";
1639 }
1640 }
1641
1642 // Now let's actually convert our apostrophic mush to HTML!
1643 $output = '';
1644 $buffer = '';
1645 $state = '';
1646 $i = 0;
1647 foreach ( $arr as $r ) {
1648 if ( ( $i % 2 ) == 0 ) {
1649 if ( $state === 'both' ) {
1650 $buffer .= $r;
1651 } else {
1652 $output .= $r;
1653 }
1654 } else {
1655 $thislen = strlen( $r );
1656 if ( $thislen == 2 ) {
1657 if ( $state === 'i' ) {
1658 $output .= '</i>';
1659 $state = '';
1660 } elseif ( $state === 'bi' ) {
1661 $output .= '</i>';
1662 $state = 'b';
1663 } elseif ( $state === 'ib' ) {
1664 $output .= '</b></i><b>';
1665 $state = 'b';
1666 } elseif ( $state === 'both' ) {
1667 $output .= '<b><i>' . $buffer . '</i>';
1668 $state = 'b';
1669 } else { // $state can be 'b' or ''
1670 $output .= '<i>';
1671 $state .= 'i';
1672 }
1673 } elseif ( $thislen == 3 ) {
1674 if ( $state === 'b' ) {
1675 $output .= '</b>';
1676 $state = '';
1677 } elseif ( $state === 'bi' ) {
1678 $output .= '</i></b><i>';
1679 $state = 'i';
1680 } elseif ( $state === 'ib' ) {
1681 $output .= '</b>';
1682 $state = 'i';
1683 } elseif ( $state === 'both' ) {
1684 $output .= '<i><b>' . $buffer . '</b>';
1685 $state = 'i';
1686 } else { // $state can be 'i' or ''
1687 $output .= '<b>';
1688 $state .= 'b';
1689 }
1690 } elseif ( $thislen == 5 ) {
1691 if ( $state === 'b' ) {
1692 $output .= '</b><i>';
1693 $state = 'i';
1694 } elseif ( $state === 'i' ) {
1695 $output .= '</i><b>';
1696 $state = 'b';
1697 } elseif ( $state === 'bi' ) {
1698 $output .= '</i></b>';
1699 $state = '';
1700 } elseif ( $state === 'ib' ) {
1701 $output .= '</b></i>';
1702 $state = '';
1703 } elseif ( $state === 'both' ) {
1704 $output .= '<i><b>' . $buffer . '</b></i>';
1705 $state = '';
1706 } else { // ($state == '')
1707 $buffer = '';
1708 $state = 'both';
1709 }
1710 }
1711 }
1712 $i++;
1713 }
1714 // Now close all remaining tags. Notice that the order is important.
1715 if ( $state === 'b' || $state === 'ib' ) {
1716 $output .= '</b>';
1717 }
1718 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1719 $output .= '</i>';
1720 }
1721 if ( $state === 'bi' ) {
1722 $output .= '</b>';
1723 }
1724 // There might be lonely ''''', so make sure we have a buffer
1725 if ( $state === 'both' && $buffer ) {
1726 $output .= '<b><i>' . $buffer . '</i></b>';
1727 }
1728 return $output;
1729 }
1730
1731 /**
1732 * Replace external links (REL)
1733 *
1734 * Note: this is all very hackish and the order of execution matters a lot.
1735 * Make sure to run tests/parserTests.php if you change this code.
1736 *
1737 * @private
1738 *
1739 * @param string $text
1740 *
1741 * @throws MWException
1742 * @return string
1743 */
1744 public function replaceExternalLinks( $text ) {
1745
1746 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1747 if ( $bits === false ) {
1748 throw new MWException( "PCRE needs to be compiled with "
1749 . "--enable-unicode-properties in order for MediaWiki to function" );
1750 }
1751 $s = array_shift( $bits );
1752
1753 $i = 0;
1754 while ( $i < count( $bits ) ) {
1755 $url = $bits[$i++];
1756 $i++; // protocol
1757 $text = $bits[$i++];
1758 $trail = $bits[$i++];
1759
1760 # The characters '<' and '>' (which were escaped by
1761 # removeHTMLtags()) should not be included in
1762 # URLs, per RFC 2396.
1763 $m2 = array();
1764 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1765 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1766 $url = substr( $url, 0, $m2[0][1] );
1767 }
1768
1769 # If the link text is an image URL, replace it with an <img> tag
1770 # This happened by accident in the original parser, but some people used it extensively
1771 $img = $this->maybeMakeExternalImage( $text );
1772 if ( $img !== false ) {
1773 $text = $img;
1774 }
1775
1776 $dtrail = '';
1777
1778 # Set linktype for CSS - if URL==text, link is essentially free
1779 $linktype = ( $text === $url ) ? 'free' : 'text';
1780
1781 # No link text, e.g. [http://domain.tld/some.link]
1782 if ( $text == '' ) {
1783 # Autonumber
1784 $langObj = $this->getTargetLanguage();
1785 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1786 $linktype = 'autonumber';
1787 } else {
1788 # Have link text, e.g. [http://domain.tld/some.link text]s
1789 # Check for trail
1790 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1791 }
1792
1793 $text = $this->getConverterLanguage()->markNoConversion( $text );
1794
1795 $url = Sanitizer::cleanUrl( $url );
1796
1797 # Use the encoded URL
1798 # This means that users can paste URLs directly into the text
1799 # Funny characters like ö aren't valid in URLs anyway
1800 # This was changed in August 2004
1801 $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
1802 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1803
1804 # Register link in the output object.
1805 # Replace unnecessary URL escape codes with the referenced character
1806 # This prevents spammers from hiding links from the filters
1807 $pasteurized = self::normalizeLinkUrl( $url );
1808 $this->mOutput->addExternalLink( $pasteurized );
1809 }
1810
1811 return $s;
1812 }
1813
1814 /**
1815 * Get the rel attribute for a particular external link.
1816 *
1817 * @since 1.21
1818 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1819 * nofollow if appropriate
1820 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1821 * @return string|null Rel attribute for $url
1822 */
1823 public static function getExternalLinkRel( $url = false, $title = null ) {
1824 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1825 $ns = $title ? $title->getNamespace() : false;
1826 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1827 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1828 ) {
1829 return 'nofollow';
1830 }
1831 return null;
1832 }
1833
1834 /**
1835 * Get an associative array of additional HTML attributes appropriate for a
1836 * particular external link. This currently may include rel => nofollow
1837 * (depending on configuration, namespace, and the URL's domain) and/or a
1838 * target attribute (depending on configuration).
1839 *
1840 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1841 * nofollow if appropriate
1842 * @return array Associative array of HTML attributes
1843 */
1844 public function getExternalLinkAttribs( $url = false ) {
1845 $attribs = array();
1846 $attribs['rel'] = self::getExternalLinkRel( $url, $this->mTitle );
1847
1848 if ( $this->mOptions->getExternalLinkTarget() ) {
1849 $attribs['target'] = $this->mOptions->getExternalLinkTarget();
1850 }
1851 return $attribs;
1852 }
1853
1854 /**
1855 * Replace unusual escape codes in a URL with their equivalent characters
1856 *
1857 * @deprecated since 1.24, use normalizeLinkUrl
1858 * @param string $url
1859 * @return string
1860 */
1861 public static function replaceUnusualEscapes( $url ) {
1862 wfDeprecated( __METHOD__, '1.24' );
1863 return self::normalizeLinkUrl( $url );
1864 }
1865
1866 /**
1867 * Replace unusual escape codes in a URL with their equivalent characters
1868 *
1869 * This generally follows the syntax defined in RFC 3986, with special
1870 * consideration for HTTP query strings.
1871 *
1872 * @param string $url
1873 * @return string
1874 */
1875 public static function normalizeLinkUrl( $url ) {
1876 # First, make sure unsafe characters are encoded
1877 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1878 function ( $m ) {
1879 return rawurlencode( $m[0] );
1880 },
1881 $url
1882 );
1883
1884 $ret = '';
1885 $end = strlen( $url );
1886
1887 # Fragment part - 'fragment'
1888 $start = strpos( $url, '#' );
1889 if ( $start !== false && $start < $end ) {
1890 $ret = self::normalizeUrlComponent(
1891 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1892 $end = $start;
1893 }
1894
1895 # Query part - 'query' minus &=+;
1896 $start = strpos( $url, '?' );
1897 if ( $start !== false && $start < $end ) {
1898 $ret = self::normalizeUrlComponent(
1899 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1900 $end = $start;
1901 }
1902
1903 # Scheme and path part - 'pchar'
1904 # (we assume no userinfo or encoded colons in the host)
1905 $ret = self::normalizeUrlComponent(
1906 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1907
1908 return $ret;
1909 }
1910
1911 private static function normalizeUrlComponent( $component, $unsafe ) {
1912 $callback = function ( $matches ) use ( $unsafe ) {
1913 $char = urldecode( $matches[0] );
1914 $ord = ord( $char );
1915 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1916 # Unescape it
1917 return $char;
1918 } else {
1919 # Leave it escaped, but use uppercase for a-f
1920 return strtoupper( $matches[0] );
1921 }
1922 };
1923 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1924 }
1925
1926 /**
1927 * make an image if it's allowed, either through the global
1928 * option, through the exception, or through the on-wiki whitelist
1929 *
1930 * @param string $url
1931 *
1932 * @return string
1933 */
1934 private function maybeMakeExternalImage( $url ) {
1935 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1936 $imagesexception = !empty( $imagesfrom );
1937 $text = false;
1938 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1939 if ( $imagesexception && is_array( $imagesfrom ) ) {
1940 $imagematch = false;
1941 foreach ( $imagesfrom as $match ) {
1942 if ( strpos( $url, $match ) === 0 ) {
1943 $imagematch = true;
1944 break;
1945 }
1946 }
1947 } elseif ( $imagesexception ) {
1948 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1949 } else {
1950 $imagematch = false;
1951 }
1952
1953 if ( $this->mOptions->getAllowExternalImages()
1954 || ( $imagesexception && $imagematch )
1955 ) {
1956 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1957 # Image found
1958 $text = Linker::makeExternalImage( $url );
1959 }
1960 }
1961 if ( !$text && $this->mOptions->getEnableImageWhitelist()
1962 && preg_match( self::EXT_IMAGE_REGEX, $url )
1963 ) {
1964 $whitelist = explode(
1965 "\n",
1966 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1967 );
1968
1969 foreach ( $whitelist as $entry ) {
1970 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1971 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
1972 continue;
1973 }
1974 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1975 # Image matches a whitelist entry
1976 $text = Linker::makeExternalImage( $url );
1977 break;
1978 }
1979 }
1980 }
1981 return $text;
1982 }
1983
1984 /**
1985 * Process [[ ]] wikilinks
1986 *
1987 * @param string $s
1988 *
1989 * @return string Processed text
1990 *
1991 * @private
1992 */
1993 public function replaceInternalLinks( $s ) {
1994 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1995 return $s;
1996 }
1997
1998 /**
1999 * Process [[ ]] wikilinks (RIL)
2000 * @param string $s
2001 * @throws MWException
2002 * @return LinkHolderArray
2003 *
2004 * @private
2005 */
2006 public function replaceInternalLinks2( &$s ) {
2007 global $wgExtraInterlanguageLinkPrefixes;
2008
2009 static $tc = false, $e1, $e1_img;
2010 # the % is needed to support urlencoded titles as well
2011 if ( !$tc ) {
2012 $tc = Title::legalChars() . '#%';
2013 # Match a link having the form [[namespace:link|alternate]]trail
2014 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2015 # Match cases where there is no "]]", which might still be images
2016 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2017 }
2018
2019 $holders = new LinkHolderArray( $this );
2020
2021 # split the entire text string on occurrences of [[
2022 $a = StringUtils::explode( '[[', ' ' . $s );
2023 # get the first element (all text up to first [[), and remove the space we added
2024 $s = $a->current();
2025 $a->next();
2026 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2027 $s = substr( $s, 1 );
2028
2029 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2030 $e2 = null;
2031 if ( $useLinkPrefixExtension ) {
2032 # Match the end of a line for a word that's not followed by whitespace,
2033 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2034 global $wgContLang;
2035 $charset = $wgContLang->linkPrefixCharset();
2036 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2037 }
2038
2039 if ( is_null( $this->mTitle ) ) {
2040 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
2041 }
2042 $nottalk = !$this->mTitle->isTalkPage();
2043
2044 if ( $useLinkPrefixExtension ) {
2045 $m = array();
2046 if ( preg_match( $e2, $s, $m ) ) {
2047 $first_prefix = $m[2];
2048 } else {
2049 $first_prefix = false;
2050 }
2051 } else {
2052 $prefix = '';
2053 }
2054
2055 $useSubpages = $this->areSubpagesAllowed();
2056
2057 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2058 # Loop for each link
2059 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2060 // @codingStandardsIgnoreStart
2061
2062 # Check for excessive memory usage
2063 if ( $holders->isBig() ) {
2064 # Too big
2065 # Do the existence check, replace the link holders and clear the array
2066 $holders->replace( $s );
2067 $holders->clear();
2068 }
2069
2070 if ( $useLinkPrefixExtension ) {
2071 if ( preg_match( $e2, $s, $m ) ) {
2072 $prefix = $m[2];
2073 $s = $m[1];
2074 } else {
2075 $prefix = '';
2076 }
2077 # first link
2078 if ( $first_prefix ) {
2079 $prefix = $first_prefix;
2080 $first_prefix = false;
2081 }
2082 }
2083
2084 $might_be_img = false;
2085
2086 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2087 $text = $m[2];
2088 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2089 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2090 # the real problem is with the $e1 regex
2091 # See bug 1300.
2092 #
2093 # Still some problems for cases where the ] is meant to be outside punctuation,
2094 # and no image is in sight. See bug 2095.
2095 #
2096 if ( $text !== ''
2097 && substr( $m[3], 0, 1 ) === ']'
2098 && strpos( $text, '[' ) !== false
2099 ) {
2100 $text .= ']'; # so that replaceExternalLinks($text) works later
2101 $m[3] = substr( $m[3], 1 );
2102 }
2103 # fix up urlencoded title texts
2104 if ( strpos( $m[1], '%' ) !== false ) {
2105 # Should anchors '#' also be rejected?
2106 $m[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $m[1] ) );
2107 }
2108 $trail = $m[3];
2109 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2110 # Invalid, but might be an image with a link in its caption
2111 $might_be_img = true;
2112 $text = $m[2];
2113 if ( strpos( $m[1], '%' ) !== false ) {
2114 $m[1] = rawurldecode( $m[1] );
2115 }
2116 $trail = "";
2117 } else { # Invalid form; output directly
2118 $s .= $prefix . '[[' . $line;
2119 continue;
2120 }
2121
2122 $origLink = $m[1];
2123
2124 # Don't allow internal links to pages containing
2125 # PROTO: where PROTO is a valid URL protocol; these
2126 # should be external links.
2127 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $origLink ) ) {
2128 $s .= $prefix . '[[' . $line;
2129 continue;
2130 }
2131
2132 # Make subpage if necessary
2133 if ( $useSubpages ) {
2134 $link = $this->maybeDoSubpageLink( $origLink, $text );
2135 } else {
2136 $link = $origLink;
2137 }
2138
2139 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2140 if ( !$noforce ) {
2141 # Strip off leading ':'
2142 $link = substr( $link, 1 );
2143 }
2144
2145 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
2146 if ( $nt === null ) {
2147 $s .= $prefix . '[[' . $line;
2148 continue;
2149 }
2150
2151 $ns = $nt->getNamespace();
2152 $iw = $nt->getInterwiki();
2153
2154 if ( $might_be_img ) { # if this is actually an invalid link
2155 if ( $ns == NS_FILE && $noforce ) { # but might be an image
2156 $found = false;
2157 while ( true ) {
2158 # look at the next 'line' to see if we can close it there
2159 $a->next();
2160 $next_line = $a->current();
2161 if ( $next_line === false || $next_line === null ) {
2162 break;
2163 }
2164 $m = explode( ']]', $next_line, 3 );
2165 if ( count( $m ) == 3 ) {
2166 # the first ]] closes the inner link, the second the image
2167 $found = true;
2168 $text .= "[[{$m[0]}]]{$m[1]}";
2169 $trail = $m[2];
2170 break;
2171 } elseif ( count( $m ) == 2 ) {
2172 # if there's exactly one ]] that's fine, we'll keep looking
2173 $text .= "[[{$m[0]}]]{$m[1]}";
2174 } else {
2175 # if $next_line is invalid too, we need look no further
2176 $text .= '[[' . $next_line;
2177 break;
2178 }
2179 }
2180 if ( !$found ) {
2181 # we couldn't find the end of this imageLink, so output it raw
2182 # but don't ignore what might be perfectly normal links in the text we've examined
2183 $holders->merge( $this->replaceInternalLinks2( $text ) );
2184 $s .= "{$prefix}[[$link|$text";
2185 # note: no $trail, because without an end, there *is* no trail
2186 continue;
2187 }
2188 } else { # it's not an image, so output it raw
2189 $s .= "{$prefix}[[$link|$text";
2190 # note: no $trail, because without an end, there *is* no trail
2191 continue;
2192 }
2193 }
2194
2195 $wasblank = ( $text == '' );
2196 if ( $wasblank ) {
2197 $text = $link;
2198 } else {
2199 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2200 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2201 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2202 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2203 $text = $this->doQuotes( $text );
2204 }
2205
2206 # Link not escaped by : , create the various objects
2207 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2208 # Interwikis
2209 if (
2210 $iw && $this->mOptions->getInterwikiMagic() && $nottalk && (
2211 Language::fetchLanguageName( $iw, null, 'mw' ) ||
2212 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2213 )
2214 ) {
2215 # Bug 24502: filter duplicates
2216 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
2217 $this->mLangLinkLanguages[$iw] = true;
2218 $this->mOutput->addLanguageLink( $nt->getFullText() );
2219 }
2220
2221 $s = rtrim( $s . $prefix );
2222 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
2223 continue;
2224 }
2225
2226 if ( $ns == NS_FILE ) {
2227 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2228 if ( $wasblank ) {
2229 # if no parameters were passed, $text
2230 # becomes something like "File:Foo.png",
2231 # which we don't want to pass on to the
2232 # image generator
2233 $text = '';
2234 } else {
2235 # recursively parse links inside the image caption
2236 # actually, this will parse them in any other parameters, too,
2237 # but it might be hard to fix that, and it doesn't matter ATM
2238 $text = $this->replaceExternalLinks( $text );
2239 $holders->merge( $this->replaceInternalLinks2( $text ) );
2240 }
2241 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2242 $s .= $prefix . $this->armorLinks(
2243 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2244 } else {
2245 $s .= $prefix . $trail;
2246 }
2247 continue;
2248 }
2249
2250 if ( $ns == NS_CATEGORY ) {
2251 $s = rtrim( $s . "\n" ); # bug 87
2252
2253 if ( $wasblank ) {
2254 $sortkey = $this->getDefaultSort();
2255 } else {
2256 $sortkey = $text;
2257 }
2258 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2259 $sortkey = str_replace( "\n", '', $sortkey );
2260 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2261 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2262
2263 /**
2264 * Strip the whitespace Category links produce, see bug 87
2265 */
2266 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
2267
2268 continue;
2269 }
2270 }
2271
2272 # Self-link checking. For some languages, variants of the title are checked in
2273 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2274 # for linking to a different variant.
2275 if ( $ns != NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) {
2276 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
2277 continue;
2278 }
2279
2280 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2281 # @todo FIXME: Should do batch file existence checks, see comment below
2282 if ( $ns == NS_MEDIA ) {
2283 # Give extensions a chance to select the file revision for us
2284 $options = array();
2285 $descQuery = false;
2286 Hooks::run( 'BeforeParserFetchFileAndTitle',
2287 array( $this, $nt, &$options, &$descQuery ) );
2288 # Fetch and register the file (file title may be different via hooks)
2289 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2290 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2291 $s .= $prefix . $this->armorLinks(
2292 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2293 continue;
2294 }
2295
2296 # Some titles, such as valid special pages or files in foreign repos, should
2297 # be shown as bluelinks even though they're not included in the page table
2298 #
2299 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2300 # batch file existence checks for NS_FILE and NS_MEDIA
2301 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2302 $this->mOutput->addLink( $nt );
2303 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2304 } else {
2305 # Links will be added to the output link list after checking
2306 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2307 }
2308 }
2309 return $holders;
2310 }
2311
2312 /**
2313 * Render a forced-blue link inline; protect against double expansion of
2314 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2315 * Since this little disaster has to split off the trail text to avoid
2316 * breaking URLs in the following text without breaking trails on the
2317 * wiki links, it's been made into a horrible function.
2318 *
2319 * @param Title $nt
2320 * @param string $text
2321 * @param array|string $query
2322 * @param string $trail
2323 * @param string $prefix
2324 * @return string HTML-wikitext mix oh yuck
2325 */
2326 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2327 list( $inside, $trail ) = Linker::splitTrail( $trail );
2328
2329 if ( is_string( $query ) ) {
2330 $query = wfCgiToArray( $query );
2331 }
2332 if ( $text == '' ) {
2333 $text = htmlspecialchars( $nt->getPrefixedText() );
2334 }
2335
2336 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2337
2338 return $this->armorLinks( $link ) . $trail;
2339 }
2340
2341 /**
2342 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2343 * going to go through further parsing steps before inline URL expansion.
2344 *
2345 * Not needed quite as much as it used to be since free links are a bit
2346 * more sensible these days. But bracketed links are still an issue.
2347 *
2348 * @param string $text More-or-less HTML
2349 * @return string Less-or-more HTML with NOPARSE bits
2350 */
2351 public function armorLinks( $text ) {
2352 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
2353 "{$this->mUniqPrefix}NOPARSE$1", $text );
2354 }
2355
2356 /**
2357 * Return true if subpage links should be expanded on this page.
2358 * @return bool
2359 */
2360 public function areSubpagesAllowed() {
2361 # Some namespaces don't allow subpages
2362 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2363 }
2364
2365 /**
2366 * Handle link to subpage if necessary
2367 *
2368 * @param string $target The source of the link
2369 * @param string &$text The link text, modified as necessary
2370 * @return string The full name of the link
2371 * @private
2372 */
2373 public function maybeDoSubpageLink( $target, &$text ) {
2374 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2375 }
2376
2377 /**#@+
2378 * Used by doBlockLevels()
2379 * @private
2380 *
2381 * @return string
2382 */
2383 public function closeParagraph() {
2384 $result = '';
2385 if ( $this->mLastSection != '' ) {
2386 $result = '</' . $this->mLastSection . ">\n";
2387 }
2388 $this->mInPre = false;
2389 $this->mLastSection = '';
2390 return $result;
2391 }
2392
2393 /**
2394 * getCommon() returns the length of the longest common substring
2395 * of both arguments, starting at the beginning of both.
2396 * @private
2397 *
2398 * @param string $st1
2399 * @param string $st2
2400 *
2401 * @return int
2402 */
2403 public function getCommon( $st1, $st2 ) {
2404 $fl = strlen( $st1 );
2405 $shorter = strlen( $st2 );
2406 if ( $fl < $shorter ) {
2407 $shorter = $fl;
2408 }
2409
2410 for ( $i = 0; $i < $shorter; ++$i ) {
2411 if ( $st1[$i] != $st2[$i] ) {
2412 break;
2413 }
2414 }
2415 return $i;
2416 }
2417
2418 /**
2419 * These next three functions open, continue, and close the list
2420 * element appropriate to the prefix character passed into them.
2421 * @private
2422 *
2423 * @param string $char
2424 *
2425 * @return string
2426 */
2427 public function openList( $char ) {
2428 $result = $this->closeParagraph();
2429
2430 if ( '*' === $char ) {
2431 $result .= "<ul><li>";
2432 } elseif ( '#' === $char ) {
2433 $result .= "<ol><li>";
2434 } elseif ( ':' === $char ) {
2435 $result .= "<dl><dd>";
2436 } elseif ( ';' === $char ) {
2437 $result .= "<dl><dt>";
2438 $this->mDTopen = true;
2439 } else {
2440 $result = '<!-- ERR 1 -->';
2441 }
2442
2443 return $result;
2444 }
2445
2446 /**
2447 * TODO: document
2448 * @param string $char
2449 * @private
2450 *
2451 * @return string
2452 */
2453 public function nextItem( $char ) {
2454 if ( '*' === $char || '#' === $char ) {
2455 return "</li>\n<li>";
2456 } elseif ( ':' === $char || ';' === $char ) {
2457 $close = "</dd>\n";
2458 if ( $this->mDTopen ) {
2459 $close = "</dt>\n";
2460 }
2461 if ( ';' === $char ) {
2462 $this->mDTopen = true;
2463 return $close . '<dt>';
2464 } else {
2465 $this->mDTopen = false;
2466 return $close . '<dd>';
2467 }
2468 }
2469 return '<!-- ERR 2 -->';
2470 }
2471
2472 /**
2473 * @todo Document
2474 * @param string $char
2475 * @private
2476 *
2477 * @return string
2478 */
2479 public function closeList( $char ) {
2480 if ( '*' === $char ) {
2481 $text = "</li></ul>";
2482 } elseif ( '#' === $char ) {
2483 $text = "</li></ol>";
2484 } elseif ( ':' === $char ) {
2485 if ( $this->mDTopen ) {
2486 $this->mDTopen = false;
2487 $text = "</dt></dl>";
2488 } else {
2489 $text = "</dd></dl>";
2490 }
2491 } else {
2492 return '<!-- ERR 3 -->';
2493 }
2494 return $text;
2495 }
2496 /**#@-*/
2497
2498 /**
2499 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2500 *
2501 * @param string $text
2502 * @param bool $linestart Whether or not this is at the start of a line.
2503 * @private
2504 * @return string The lists rendered as HTML
2505 */
2506 public function doBlockLevels( $text, $linestart ) {
2507
2508 # Parsing through the text line by line. The main thing
2509 # happening here is handling of block-level elements p, pre,
2510 # and making lists from lines starting with * # : etc.
2511 #
2512 $textLines = StringUtils::explode( "\n", $text );
2513
2514 $lastPrefix = $output = '';
2515 $this->mDTopen = $inBlockElem = false;
2516 $prefixLength = 0;
2517 $paragraphStack = false;
2518 $inBlockquote = false;
2519
2520 foreach ( $textLines as $oLine ) {
2521 # Fix up $linestart
2522 if ( !$linestart ) {
2523 $output .= $oLine;
2524 $linestart = true;
2525 continue;
2526 }
2527 # * = ul
2528 # # = ol
2529 # ; = dt
2530 # : = dd
2531
2532 $lastPrefixLength = strlen( $lastPrefix );
2533 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2534 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2535 # If not in a <pre> element, scan for and figure out what prefixes are there.
2536 if ( !$this->mInPre ) {
2537 # Multiple prefixes may abut each other for nested lists.
2538 $prefixLength = strspn( $oLine, '*#:;' );
2539 $prefix = substr( $oLine, 0, $prefixLength );
2540
2541 # eh?
2542 # ; and : are both from definition-lists, so they're equivalent
2543 # for the purposes of determining whether or not we need to open/close
2544 # elements.
2545 $prefix2 = str_replace( ';', ':', $prefix );
2546 $t = substr( $oLine, $prefixLength );
2547 $this->mInPre = (bool)$preOpenMatch;
2548 } else {
2549 # Don't interpret any other prefixes in preformatted text
2550 $prefixLength = 0;
2551 $prefix = $prefix2 = '';
2552 $t = $oLine;
2553 }
2554
2555 # List generation
2556 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2557 # Same as the last item, so no need to deal with nesting or opening stuff
2558 $output .= $this->nextItem( substr( $prefix, -1 ) );
2559 $paragraphStack = false;
2560
2561 if ( substr( $prefix, -1 ) === ';' ) {
2562 # The one nasty exception: definition lists work like this:
2563 # ; title : definition text
2564 # So we check for : in the remainder text to split up the
2565 # title and definition, without b0rking links.
2566 $term = $t2 = '';
2567 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2568 $t = $t2;
2569 $output .= $term . $this->nextItem( ':' );
2570 }
2571 }
2572 } elseif ( $prefixLength || $lastPrefixLength ) {
2573 # We need to open or close prefixes, or both.
2574
2575 # Either open or close a level...
2576 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2577 $paragraphStack = false;
2578
2579 # Close all the prefixes which aren't shared.
2580 while ( $commonPrefixLength < $lastPrefixLength ) {
2581 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2582 --$lastPrefixLength;
2583 }
2584
2585 # Continue the current prefix if appropriate.
2586 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2587 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2588 }
2589
2590 # Open prefixes where appropriate.
2591 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2592 $output .= "\n";
2593 }
2594 while ( $prefixLength > $commonPrefixLength ) {
2595 $char = substr( $prefix, $commonPrefixLength, 1 );
2596 $output .= $this->openList( $char );
2597
2598 if ( ';' === $char ) {
2599 # @todo FIXME: This is dupe of code above
2600 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2601 $t = $t2;
2602 $output .= $term . $this->nextItem( ':' );
2603 }
2604 }
2605 ++$commonPrefixLength;
2606 }
2607 if ( !$prefixLength && $lastPrefix ) {
2608 $output .= "\n";
2609 }
2610 $lastPrefix = $prefix2;
2611 }
2612
2613 # If we have no prefixes, go to paragraph mode.
2614 if ( 0 == $prefixLength ) {
2615 # No prefix (not in list)--go to paragraph mode
2616 # XXX: use a stack for nestable elements like span, table and div
2617 $openmatch = preg_match(
2618 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2619 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2620 $t
2621 );
2622 $closematch = preg_match(
2623 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2624 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2625 . $this->mUniqPrefix
2626 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2627 $t
2628 );
2629
2630 if ( $openmatch || $closematch ) {
2631 $paragraphStack = false;
2632 # @todo bug 5718: paragraph closed
2633 $output .= $this->closeParagraph();
2634 if ( $preOpenMatch && !$preCloseMatch ) {
2635 $this->mInPre = true;
2636 }
2637 $bqOffset = 0;
2638 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset ) ) {
2639 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2640 $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] );
2641 }
2642 $inBlockElem = !$closematch;
2643 } elseif ( !$inBlockElem && !$this->mInPre ) {
2644 if ( ' ' == substr( $t, 0, 1 )
2645 && ( $this->mLastSection === 'pre' || trim( $t ) != '' )
2646 && !$inBlockquote
2647 ) {
2648 # pre
2649 if ( $this->mLastSection !== 'pre' ) {
2650 $paragraphStack = false;
2651 $output .= $this->closeParagraph() . '<pre>';
2652 $this->mLastSection = 'pre';
2653 }
2654 $t = substr( $t, 1 );
2655 } else {
2656 # paragraph
2657 if ( trim( $t ) === '' ) {
2658 if ( $paragraphStack ) {
2659 $output .= $paragraphStack . '<br />';
2660 $paragraphStack = false;
2661 $this->mLastSection = 'p';
2662 } else {
2663 if ( $this->mLastSection !== 'p' ) {
2664 $output .= $this->closeParagraph();
2665 $this->mLastSection = '';
2666 $paragraphStack = '<p>';
2667 } else {
2668 $paragraphStack = '</p><p>';
2669 }
2670 }
2671 } else {
2672 if ( $paragraphStack ) {
2673 $output .= $paragraphStack;
2674 $paragraphStack = false;
2675 $this->mLastSection = 'p';
2676 } elseif ( $this->mLastSection !== 'p' ) {
2677 $output .= $this->closeParagraph() . '<p>';
2678 $this->mLastSection = 'p';
2679 }
2680 }
2681 }
2682 }
2683 }
2684 # somewhere above we forget to get out of pre block (bug 785)
2685 if ( $preCloseMatch && $this->mInPre ) {
2686 $this->mInPre = false;
2687 }
2688 if ( $paragraphStack === false ) {
2689 $output .= $t;
2690 if ( $prefixLength === 0 ) {
2691 $output .= "\n";
2692 }
2693 }
2694 }
2695 while ( $prefixLength ) {
2696 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2697 --$prefixLength;
2698 if ( !$prefixLength ) {
2699 $output .= "\n";
2700 }
2701 }
2702 if ( $this->mLastSection != '' ) {
2703 $output .= '</' . $this->mLastSection . '>';
2704 $this->mLastSection = '';
2705 }
2706
2707 return $output;
2708 }
2709
2710 /**
2711 * Split up a string on ':', ignoring any occurrences inside tags
2712 * to prevent illegal overlapping.
2713 *
2714 * @param string $str The string to split
2715 * @param string &$before Set to everything before the ':'
2716 * @param string &$after Set to everything after the ':'
2717 * @throws MWException
2718 * @return string The position of the ':', or false if none found
2719 */
2720 public function findColonNoLinks( $str, &$before, &$after ) {
2721
2722 $pos = strpos( $str, ':' );
2723 if ( $pos === false ) {
2724 # Nothing to find!
2725 return false;
2726 }
2727
2728 $lt = strpos( $str, '<' );
2729 if ( $lt === false || $lt > $pos ) {
2730 # Easy; no tag nesting to worry about
2731 $before = substr( $str, 0, $pos );
2732 $after = substr( $str, $pos + 1 );
2733 return $pos;
2734 }
2735
2736 # Ugly state machine to walk through avoiding tags.
2737 $state = self::COLON_STATE_TEXT;
2738 $stack = 0;
2739 $len = strlen( $str );
2740 for ( $i = 0; $i < $len; $i++ ) {
2741 $c = $str[$i];
2742
2743 switch ( $state ) {
2744 # (Using the number is a performance hack for common cases)
2745 case 0: # self::COLON_STATE_TEXT:
2746 switch ( $c ) {
2747 case "<":
2748 # Could be either a <start> tag or an </end> tag
2749 $state = self::COLON_STATE_TAGSTART;
2750 break;
2751 case ":":
2752 if ( $stack == 0 ) {
2753 # We found it!
2754 $before = substr( $str, 0, $i );
2755 $after = substr( $str, $i + 1 );
2756 return $i;
2757 }
2758 # Embedded in a tag; don't break it.
2759 break;
2760 default:
2761 # Skip ahead looking for something interesting
2762 $colon = strpos( $str, ':', $i );
2763 if ( $colon === false ) {
2764 # Nothing else interesting
2765 return false;
2766 }
2767 $lt = strpos( $str, '<', $i );
2768 if ( $stack === 0 ) {
2769 if ( $lt === false || $colon < $lt ) {
2770 # We found it!
2771 $before = substr( $str, 0, $colon );
2772 $after = substr( $str, $colon + 1 );
2773 return $i;
2774 }
2775 }
2776 if ( $lt === false ) {
2777 # Nothing else interesting to find; abort!
2778 # We're nested, but there's no close tags left. Abort!
2779 break 2;
2780 }
2781 # Skip ahead to next tag start
2782 $i = $lt;
2783 $state = self::COLON_STATE_TAGSTART;
2784 }
2785 break;
2786 case 1: # self::COLON_STATE_TAG:
2787 # In a <tag>
2788 switch ( $c ) {
2789 case ">":
2790 $stack++;
2791 $state = self::COLON_STATE_TEXT;
2792 break;
2793 case "/":
2794 # Slash may be followed by >?
2795 $state = self::COLON_STATE_TAGSLASH;
2796 break;
2797 default:
2798 # ignore
2799 }
2800 break;
2801 case 2: # self::COLON_STATE_TAGSTART:
2802 switch ( $c ) {
2803 case "/":
2804 $state = self::COLON_STATE_CLOSETAG;
2805 break;
2806 case "!":
2807 $state = self::COLON_STATE_COMMENT;
2808 break;
2809 case ">":
2810 # Illegal early close? This shouldn't happen D:
2811 $state = self::COLON_STATE_TEXT;
2812 break;
2813 default:
2814 $state = self::COLON_STATE_TAG;
2815 }
2816 break;
2817 case 3: # self::COLON_STATE_CLOSETAG:
2818 # In a </tag>
2819 if ( $c === ">" ) {
2820 $stack--;
2821 if ( $stack < 0 ) {
2822 wfDebug( __METHOD__ . ": Invalid input; too many close tags\n" );
2823 return false;
2824 }
2825 $state = self::COLON_STATE_TEXT;
2826 }
2827 break;
2828 case self::COLON_STATE_TAGSLASH:
2829 if ( $c === ">" ) {
2830 # Yes, a self-closed tag <blah/>
2831 $state = self::COLON_STATE_TEXT;
2832 } else {
2833 # Probably we're jumping the gun, and this is an attribute
2834 $state = self::COLON_STATE_TAG;
2835 }
2836 break;
2837 case 5: # self::COLON_STATE_COMMENT:
2838 if ( $c === "-" ) {
2839 $state = self::COLON_STATE_COMMENTDASH;
2840 }
2841 break;
2842 case self::COLON_STATE_COMMENTDASH:
2843 if ( $c === "-" ) {
2844 $state = self::COLON_STATE_COMMENTDASHDASH;
2845 } else {
2846 $state = self::COLON_STATE_COMMENT;
2847 }
2848 break;
2849 case self::COLON_STATE_COMMENTDASHDASH:
2850 if ( $c === ">" ) {
2851 $state = self::COLON_STATE_TEXT;
2852 } else {
2853 $state = self::COLON_STATE_COMMENT;
2854 }
2855 break;
2856 default:
2857 throw new MWException( "State machine error in " . __METHOD__ );
2858 }
2859 }
2860 if ( $stack > 0 ) {
2861 wfDebug( __METHOD__ . ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2862 return false;
2863 }
2864 return false;
2865 }
2866
2867 /**
2868 * Return value of a magic variable (like PAGENAME)
2869 *
2870 * @private
2871 *
2872 * @param int $index
2873 * @param bool|PPFrame $frame
2874 *
2875 * @throws MWException
2876 * @return string
2877 */
2878 public function getVariableValue( $index, $frame = false ) {
2879 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2880 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2881
2882 if ( is_null( $this->mTitle ) ) {
2883 // If no title set, bad things are going to happen
2884 // later. Title should always be set since this
2885 // should only be called in the middle of a parse
2886 // operation (but the unit-tests do funky stuff)
2887 throw new MWException( __METHOD__ . ' Should only be '
2888 . ' called while parsing (no title set)' );
2889 }
2890
2891 /**
2892 * Some of these require message or data lookups and can be
2893 * expensive to check many times.
2894 */
2895 if ( Hooks::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2896 if ( isset( $this->mVarCache[$index] ) ) {
2897 return $this->mVarCache[$index];
2898 }
2899 }
2900
2901 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2902 Hooks::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2903
2904 $pageLang = $this->getFunctionLang();
2905
2906 switch ( $index ) {
2907 case '!':
2908 $value = '|';
2909 break;
2910 case 'currentmonth':
2911 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'm' ) );
2912 break;
2913 case 'currentmonth1':
2914 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2915 break;
2916 case 'currentmonthname':
2917 $value = $pageLang->getMonthName( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2918 break;
2919 case 'currentmonthnamegen':
2920 $value = $pageLang->getMonthNameGen( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2921 break;
2922 case 'currentmonthabbrev':
2923 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2924 break;
2925 case 'currentday':
2926 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'j' ) );
2927 break;
2928 case 'currentday2':
2929 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'd' ) );
2930 break;
2931 case 'localmonth':
2932 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'm' ) );
2933 break;
2934 case 'localmonth1':
2935 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2936 break;
2937 case 'localmonthname':
2938 $value = $pageLang->getMonthName( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2939 break;
2940 case 'localmonthnamegen':
2941 $value = $pageLang->getMonthNameGen( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2942 break;
2943 case 'localmonthabbrev':
2944 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2945 break;
2946 case 'localday':
2947 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'j' ) );
2948 break;
2949 case 'localday2':
2950 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'd' ) );
2951 break;
2952 case 'pagename':
2953 $value = wfEscapeWikiText( $this->mTitle->getText() );
2954 break;
2955 case 'pagenamee':
2956 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2957 break;
2958 case 'fullpagename':
2959 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2960 break;
2961 case 'fullpagenamee':
2962 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2963 break;
2964 case 'subpagename':
2965 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2966 break;
2967 case 'subpagenamee':
2968 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2969 break;
2970 case 'rootpagename':
2971 $value = wfEscapeWikiText( $this->mTitle->getRootText() );
2972 break;
2973 case 'rootpagenamee':
2974 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2975 ' ',
2976 '_',
2977 $this->mTitle->getRootText()
2978 ) ) );
2979 break;
2980 case 'basepagename':
2981 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2982 break;
2983 case 'basepagenamee':
2984 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2985 ' ',
2986 '_',
2987 $this->mTitle->getBaseText()
2988 ) ) );
2989 break;
2990 case 'talkpagename':
2991 if ( $this->mTitle->canTalk() ) {
2992 $talkPage = $this->mTitle->getTalkPage();
2993 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2994 } else {
2995 $value = '';
2996 }
2997 break;
2998 case 'talkpagenamee':
2999 if ( $this->mTitle->canTalk() ) {
3000 $talkPage = $this->mTitle->getTalkPage();
3001 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3002 } else {
3003 $value = '';
3004 }
3005 break;
3006 case 'subjectpagename':
3007 $subjPage = $this->mTitle->getSubjectPage();
3008 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3009 break;
3010 case 'subjectpagenamee':
3011 $subjPage = $this->mTitle->getSubjectPage();
3012 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3013 break;
3014 case 'pageid': // requested in bug 23427
3015 $pageid = $this->getTitle()->getArticleID();
3016 if ( $pageid == 0 ) {
3017 # 0 means the page doesn't exist in the database,
3018 # which means the user is previewing a new page.
3019 # The vary-revision flag must be set, because the magic word
3020 # will have a different value once the page is saved.
3021 $this->mOutput->setFlag( 'vary-revision' );
3022 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3023 }
3024 $value = $pageid ? $pageid : null;
3025 break;
3026 case 'revisionid':
3027 # Let the edit saving system know we should parse the page
3028 # *after* a revision ID has been assigned.
3029 $this->mOutput->setFlag( 'vary-revision' );
3030 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
3031 $value = $this->mRevisionId;
3032 break;
3033 case 'revisionday':
3034 # Let the edit saving system know we should parse the page
3035 # *after* a revision ID has been assigned. This is for null edits.
3036 $this->mOutput->setFlag( 'vary-revision' );
3037 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3038 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3039 break;
3040 case 'revisionday2':
3041 # Let the edit saving system know we should parse the page
3042 # *after* a revision ID has been assigned. This is for null edits.
3043 $this->mOutput->setFlag( 'vary-revision' );
3044 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3045 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3046 break;
3047 case 'revisionmonth':
3048 # Let the edit saving system know we should parse the page
3049 # *after* a revision ID has been assigned. This is for null edits.
3050 $this->mOutput->setFlag( 'vary-revision' );
3051 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3052 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3053 break;
3054 case 'revisionmonth1':
3055 # Let the edit saving system know we should parse the page
3056 # *after* a revision ID has been assigned. This is for null edits.
3057 $this->mOutput->setFlag( 'vary-revision' );
3058 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3059 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3060 break;
3061 case 'revisionyear':
3062 # Let the edit saving system know we should parse the page
3063 # *after* a revision ID has been assigned. This is for null edits.
3064 $this->mOutput->setFlag( 'vary-revision' );
3065 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3066 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3067 break;
3068 case 'revisiontimestamp':
3069 # Let the edit saving system know we should parse the page
3070 # *after* a revision ID has been assigned. This is for null edits.
3071 $this->mOutput->setFlag( 'vary-revision' );
3072 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3073 $value = $this->getRevisionTimestamp();
3074 break;
3075 case 'revisionuser':
3076 # Let the edit saving system know we should parse the page
3077 # *after* a revision ID has been assigned. This is for null edits.
3078 $this->mOutput->setFlag( 'vary-revision' );
3079 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3080 $value = $this->getRevisionUser();
3081 break;
3082 case 'revisionsize':
3083 # Let the edit saving system know we should parse the page
3084 # *after* a revision ID has been assigned. This is for null edits.
3085 $this->mOutput->setFlag( 'vary-revision' );
3086 wfDebug( __METHOD__ . ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3087 $value = $this->getRevisionSize();
3088 break;
3089 case 'namespace':
3090 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
3091 break;
3092 case 'namespacee':
3093 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
3094 break;
3095 case 'namespacenumber':
3096 $value = $this->mTitle->getNamespace();
3097 break;
3098 case 'talkspace':
3099 $value = $this->mTitle->canTalk()
3100 ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() )
3101 : '';
3102 break;
3103 case 'talkspacee':
3104 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
3105 break;
3106 case 'subjectspace':
3107 $value = str_replace( '_', ' ', $this->mTitle->getSubjectNsText() );
3108 break;
3109 case 'subjectspacee':
3110 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
3111 break;
3112 case 'currentdayname':
3113 $value = $pageLang->getWeekdayName( (int)MWTimestamp::getInstance( $ts )->format( 'w' ) + 1 );
3114 break;
3115 case 'currentyear':
3116 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'Y' ), true );
3117 break;
3118 case 'currenttime':
3119 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
3120 break;
3121 case 'currenthour':
3122 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'H' ), true );
3123 break;
3124 case 'currentweek':
3125 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3126 # int to remove the padding
3127 $value = $pageLang->formatNum( (int)MWTimestamp::getInstance( $ts )->format( 'W' ) );
3128 break;
3129 case 'currentdow':
3130 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) );
3131 break;
3132 case 'localdayname':
3133 $value = $pageLang->getWeekdayName(
3134 (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1
3135 );
3136 break;
3137 case 'localyear':
3138 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true );
3139 break;
3140 case 'localtime':
3141 $value = $pageLang->time(
3142 MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ),
3143 false,
3144 false
3145 );
3146 break;
3147 case 'localhour':
3148 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true );
3149 break;
3150 case 'localweek':
3151 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3152 # int to remove the padding
3153 $value = $pageLang->formatNum( (int)MWTimestamp::getLocalInstance( $ts )->format( 'W' ) );
3154 break;
3155 case 'localdow':
3156 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) );
3157 break;
3158 case 'numberofarticles':
3159 $value = $pageLang->formatNum( SiteStats::articles() );
3160 break;
3161 case 'numberoffiles':
3162 $value = $pageLang->formatNum( SiteStats::images() );
3163 break;
3164 case 'numberofusers':
3165 $value = $pageLang->formatNum( SiteStats::users() );
3166 break;
3167 case 'numberofactiveusers':
3168 $value = $pageLang->formatNum( SiteStats::activeUsers() );
3169 break;
3170 case 'numberofpages':
3171 $value = $pageLang->formatNum( SiteStats::pages() );
3172 break;
3173 case 'numberofadmins':
3174 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
3175 break;
3176 case 'numberofedits':
3177 $value = $pageLang->formatNum( SiteStats::edits() );
3178 break;
3179 case 'currenttimestamp':
3180 $value = wfTimestamp( TS_MW, $ts );
3181 break;
3182 case 'localtimestamp':
3183 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' );
3184 break;
3185 case 'currentversion':
3186 $value = SpecialVersion::getVersion();
3187 break;
3188 case 'articlepath':
3189 return $wgArticlePath;
3190 case 'sitename':
3191 return $wgSitename;
3192 case 'server':
3193 return $wgServer;
3194 case 'servername':
3195 return $wgServerName;
3196 case 'scriptpath':
3197 return $wgScriptPath;
3198 case 'stylepath':
3199 return $wgStylePath;
3200 case 'directionmark':
3201 return $pageLang->getDirMark();
3202 case 'contentlanguage':
3203 global $wgLanguageCode;
3204 return $wgLanguageCode;
3205 case 'cascadingsources':
3206 $value = CoreParserFunctions::cascadingsources( $this );
3207 break;
3208 default:
3209 $ret = null;
3210 Hooks::run(
3211 'ParserGetVariableValueSwitch',
3212 array( &$this, &$this->mVarCache, &$index, &$ret, &$frame )
3213 );
3214
3215 return $ret;
3216 }
3217
3218 if ( $index ) {
3219 $this->mVarCache[$index] = $value;
3220 }
3221
3222 return $value;
3223 }
3224
3225 /**
3226 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3227 *
3228 * @private
3229 */
3230 public function initialiseVariables() {
3231 $variableIDs = MagicWord::getVariableIDs();
3232 $substIDs = MagicWord::getSubstIDs();
3233
3234 $this->mVariables = new MagicWordArray( $variableIDs );
3235 $this->mSubstWords = new MagicWordArray( $substIDs );
3236 }
3237
3238 /**
3239 * Preprocess some wikitext and return the document tree.
3240 * This is the ghost of replace_variables().
3241 *
3242 * @param string $text The text to parse
3243 * @param int $flags Bitwise combination of:
3244 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3245 * included. Default is to assume a direct page view.
3246 *
3247 * The generated DOM tree must depend only on the input text and the flags.
3248 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3249 *
3250 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3251 * change in the DOM tree for a given text, must be passed through the section identifier
3252 * in the section edit link and thus back to extractSections().
3253 *
3254 * The output of this function is currently only cached in process memory, but a persistent
3255 * cache may be implemented at a later date which takes further advantage of these strict
3256 * dependency requirements.
3257 *
3258 * @return PPNode
3259 */
3260 public function preprocessToDom( $text, $flags = 0 ) {
3261 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3262 return $dom;
3263 }
3264
3265 /**
3266 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3267 *
3268 * @param string $s
3269 *
3270 * @return array
3271 */
3272 public static function splitWhitespace( $s ) {
3273 $ltrimmed = ltrim( $s );
3274 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3275 $trimmed = rtrim( $ltrimmed );
3276 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3277 if ( $diff > 0 ) {
3278 $w2 = substr( $ltrimmed, -$diff );
3279 } else {
3280 $w2 = '';
3281 }
3282 return array( $w1, $trimmed, $w2 );
3283 }
3284
3285 /**
3286 * Replace magic variables, templates, and template arguments
3287 * with the appropriate text. Templates are substituted recursively,
3288 * taking care to avoid infinite loops.
3289 *
3290 * Note that the substitution depends on value of $mOutputType:
3291 * self::OT_WIKI: only {{subst:}} templates
3292 * self::OT_PREPROCESS: templates but not extension tags
3293 * self::OT_HTML: all templates and extension tags
3294 *
3295 * @param string $text The text to transform
3296 * @param bool|PPFrame $frame Object describing the arguments passed to the
3297 * template. Arguments may also be provided as an associative array, as
3298 * was the usual case before MW1.12. Providing arguments this way may be
3299 * useful for extensions wishing to perform variable replacement
3300 * explicitly.
3301 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3302 * double-brace expansion.
3303 * @return string
3304 */
3305 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3306 # Is there any text? Also, Prevent too big inclusions!
3307 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
3308 return $text;
3309 }
3310
3311 if ( $frame === false ) {
3312 $frame = $this->getPreprocessor()->newFrame();
3313 } elseif ( !( $frame instanceof PPFrame ) ) {
3314 wfDebug( __METHOD__ . " called using plain parameters instead of "
3315 . "a PPFrame instance. Creating custom frame.\n" );
3316 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3317 }
3318
3319 $dom = $this->preprocessToDom( $text );
3320 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3321 $text = $frame->expand( $dom, $flags );
3322
3323 return $text;
3324 }
3325
3326 /**
3327 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3328 *
3329 * @param array $args
3330 *
3331 * @return array
3332 */
3333 public static function createAssocArgs( $args ) {
3334 $assocArgs = array();
3335 $index = 1;
3336 foreach ( $args as $arg ) {
3337 $eqpos = strpos( $arg, '=' );
3338 if ( $eqpos === false ) {
3339 $assocArgs[$index++] = $arg;
3340 } else {
3341 $name = trim( substr( $arg, 0, $eqpos ) );
3342 $value = trim( substr( $arg, $eqpos + 1 ) );
3343 if ( $value === false ) {
3344 $value = '';
3345 }
3346 if ( $name !== false ) {
3347 $assocArgs[$name] = $value;
3348 }
3349 }
3350 }
3351
3352 return $assocArgs;
3353 }
3354
3355 /**
3356 * Warn the user when a parser limitation is reached
3357 * Will warn at most once the user per limitation type
3358 *
3359 * @param string $limitationType Should be one of:
3360 * 'expensive-parserfunction' (corresponding messages:
3361 * 'expensive-parserfunction-warning',
3362 * 'expensive-parserfunction-category')
3363 * 'post-expand-template-argument' (corresponding messages:
3364 * 'post-expand-template-argument-warning',
3365 * 'post-expand-template-argument-category')
3366 * 'post-expand-template-inclusion' (corresponding messages:
3367 * 'post-expand-template-inclusion-warning',
3368 * 'post-expand-template-inclusion-category')
3369 * 'node-count-exceeded' (corresponding messages:
3370 * 'node-count-exceeded-warning',
3371 * 'node-count-exceeded-category')
3372 * 'expansion-depth-exceeded' (corresponding messages:
3373 * 'expansion-depth-exceeded-warning',
3374 * 'expansion-depth-exceeded-category')
3375 * @param string|int|null $current Current value
3376 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3377 * exceeded, provide the values (optional)
3378 */
3379 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3380 # does no harm if $current and $max are present but are unnecessary for the message
3381 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3382 ->inLanguage( $this->mOptions->getUserLangObj() )->text();
3383 $this->mOutput->addWarning( $warning );
3384 $this->addTrackingCategory( "$limitationType-category" );
3385 }
3386
3387 /**
3388 * Return the text of a template, after recursively
3389 * replacing any variables or templates within the template.
3390 *
3391 * @param array $piece The parts of the template
3392 * $piece['title']: the title, i.e. the part before the |
3393 * $piece['parts']: the parameter array
3394 * $piece['lineStart']: whether the brace was at the start of a line
3395 * @param PPFrame $frame The current frame, contains template arguments
3396 * @throws Exception
3397 * @return string The text of the template
3398 */
3399 public function braceSubstitution( $piece, $frame ) {
3400
3401 // Flags
3402
3403 // $text has been filled
3404 $found = false;
3405 // wiki markup in $text should be escaped
3406 $nowiki = false;
3407 // $text is HTML, armour it against wikitext transformation
3408 $isHTML = false;
3409 // Force interwiki transclusion to be done in raw mode not rendered
3410 $forceRawInterwiki = false;
3411 // $text is a DOM node needing expansion in a child frame
3412 $isChildObj = false;
3413 // $text is a DOM node needing expansion in the current frame
3414 $isLocalObj = false;
3415
3416 # Title object, where $text came from
3417 $title = false;
3418
3419 # $part1 is the bit before the first |, and must contain only title characters.
3420 # Various prefixes will be stripped from it later.
3421 $titleWithSpaces = $frame->expand( $piece['title'] );
3422 $part1 = trim( $titleWithSpaces );
3423 $titleText = false;
3424
3425 # Original title text preserved for various purposes
3426 $originalTitle = $part1;
3427
3428 # $args is a list of argument nodes, starting from index 0, not including $part1
3429 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3430 # below won't work b/c this $args isn't an object
3431 $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
3432
3433 $profileSection = null; // profile templates
3434
3435 # SUBST
3436 if ( !$found ) {
3437
3438 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3439
3440 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3441 # Decide whether to expand template or keep wikitext as-is.
3442 if ( $this->ot['wiki'] ) {
3443 if ( $substMatch === false ) {
3444 $literal = true; # literal when in PST with no prefix
3445 } else {
3446 $literal = false; # expand when in PST with subst: or safesubst:
3447 }
3448 } else {
3449 if ( $substMatch == 'subst' ) {
3450 $literal = true; # literal when not in PST with plain subst:
3451 } else {
3452 $literal = false; # expand when not in PST with safesubst: or no prefix
3453 }
3454 }
3455 if ( $literal ) {
3456 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3457 $isLocalObj = true;
3458 $found = true;
3459 }
3460 }
3461
3462 # Variables
3463 if ( !$found && $args->getLength() == 0 ) {
3464 $id = $this->mVariables->matchStartToEnd( $part1 );
3465 if ( $id !== false ) {
3466 $text = $this->getVariableValue( $id, $frame );
3467 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3468 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3469 }
3470 $found = true;
3471 }
3472 }
3473
3474 # MSG, MSGNW and RAW
3475 if ( !$found ) {
3476 # Check for MSGNW:
3477 $mwMsgnw = MagicWord::get( 'msgnw' );
3478 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3479 $nowiki = true;
3480 } else {
3481 # Remove obsolete MSG:
3482 $mwMsg = MagicWord::get( 'msg' );
3483 $mwMsg->matchStartAndRemove( $part1 );
3484 }
3485
3486 # Check for RAW:
3487 $mwRaw = MagicWord::get( 'raw' );
3488 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3489 $forceRawInterwiki = true;
3490 }
3491 }
3492
3493 # Parser functions
3494 if ( !$found ) {
3495
3496 $colonPos = strpos( $part1, ':' );
3497 if ( $colonPos !== false ) {
3498 $func = substr( $part1, 0, $colonPos );
3499 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3500 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3501 $funcArgs[] = $args->item( $i );
3502 }
3503 try {
3504 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3505 } catch ( Exception $ex ) {
3506 throw $ex;
3507 }
3508
3509 # The interface for parser functions allows for extracting
3510 # flags into the local scope. Extract any forwarded flags
3511 # here.
3512 extract( $result );
3513 }
3514 }
3515
3516 # Finish mangling title and then check for loops.
3517 # Set $title to a Title object and $titleText to the PDBK
3518 if ( !$found ) {
3519 $ns = NS_TEMPLATE;
3520 # Split the title into page and subpage
3521 $subpage = '';
3522 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3523 if ( $part1 !== $relative ) {
3524 $part1 = $relative;
3525 $ns = $this->mTitle->getNamespace();
3526 }
3527 $title = Title::newFromText( $part1, $ns );
3528 if ( $title ) {
3529 $titleText = $title->getPrefixedText();
3530 # Check for language variants if the template is not found
3531 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3532 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3533 }
3534 # Do recursion depth check
3535 $limit = $this->mOptions->getMaxTemplateDepth();
3536 if ( $frame->depth >= $limit ) {
3537 $found = true;
3538 $text = '<span class="error">'
3539 . wfMessage( 'parser-template-recursion-depth-warning' )
3540 ->numParams( $limit )->inContentLanguage()->text()
3541 . '</span>';
3542 }
3543 }
3544 }
3545
3546 # Load from database
3547 if ( !$found && $title ) {
3548 $profileSection = $this->mProfiler->scopedProfileIn( $title->getPrefixedDBkey() );
3549 if ( !$title->isExternal() ) {
3550 if ( $title->isSpecialPage()
3551 && $this->mOptions->getAllowSpecialInclusion()
3552 && $this->ot['html']
3553 ) {
3554 // Pass the template arguments as URL parameters.
3555 // "uselang" will have no effect since the Language object
3556 // is forced to the one defined in ParserOptions.
3557 $pageArgs = array();
3558 $argsLength = $args->getLength();
3559 for ( $i = 0; $i < $argsLength; $i++ ) {
3560 $bits = $args->item( $i )->splitArg();
3561 if ( strval( $bits['index'] ) === '' ) {
3562 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3563 $value = trim( $frame->expand( $bits['value'] ) );
3564 $pageArgs[$name] = $value;
3565 }
3566 }
3567
3568 // Create a new context to execute the special page
3569 $context = new RequestContext;
3570 $context->setTitle( $title );
3571 $context->setRequest( new FauxRequest( $pageArgs ) );
3572 $context->setUser( $this->getUser() );
3573 $context->setLanguage( $this->mOptions->getUserLangObj() );
3574 $ret = SpecialPageFactory::capturePath( $title, $context );
3575 if ( $ret ) {
3576 $text = $context->getOutput()->getHTML();
3577 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3578 $found = true;
3579 $isHTML = true;
3580 $this->disableCache();
3581 }
3582 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3583 $found = false; # access denied
3584 wfDebug( __METHOD__ . ": template inclusion denied for " .
3585 $title->getPrefixedDBkey() . "\n" );
3586 } else {
3587 list( $text, $title ) = $this->getTemplateDom( $title );
3588 if ( $text !== false ) {
3589 $found = true;
3590 $isChildObj = true;
3591 }
3592 }
3593
3594 # If the title is valid but undisplayable, make a link to it
3595 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3596 $text = "[[:$titleText]]";
3597 $found = true;
3598 }
3599 } elseif ( $title->isTrans() ) {
3600 # Interwiki transclusion
3601 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3602 $text = $this->interwikiTransclude( $title, 'render' );
3603 $isHTML = true;
3604 } else {
3605 $text = $this->interwikiTransclude( $title, 'raw' );
3606 # Preprocess it like a template
3607 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3608 $isChildObj = true;
3609 }
3610 $found = true;
3611 }
3612
3613 # Do infinite loop check
3614 # This has to be done after redirect resolution to avoid infinite loops via redirects
3615 if ( !$frame->loopCheck( $title ) ) {
3616 $found = true;
3617 $text = '<span class="error">'
3618 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3619 . '</span>';
3620 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3621 }
3622 }
3623
3624 # If we haven't found text to substitute by now, we're done
3625 # Recover the source wikitext and return it
3626 if ( !$found ) {
3627 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3628 if ( $profileSection ) {
3629 $this->mProfiler->scopedProfileOut( $profileSection );
3630 }
3631 return array( 'object' => $text );
3632 }
3633
3634 # Expand DOM-style return values in a child frame
3635 if ( $isChildObj ) {
3636 # Clean up argument array
3637 $newFrame = $frame->newChild( $args, $title );
3638
3639 if ( $nowiki ) {
3640 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3641 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3642 # Expansion is eligible for the empty-frame cache
3643 $text = $newFrame->cachedExpand( $titleText, $text );
3644 } else {
3645 # Uncached expansion
3646 $text = $newFrame->expand( $text );
3647 }
3648 }
3649 if ( $isLocalObj && $nowiki ) {
3650 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3651 $isLocalObj = false;
3652 }
3653
3654 if ( $profileSection ) {
3655 $this->mProfiler->scopedProfileOut( $profileSection );
3656 }
3657
3658 # Replace raw HTML by a placeholder
3659 if ( $isHTML ) {
3660 $text = $this->insertStripItem( $text );
3661 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3662 # Escape nowiki-style return values
3663 $text = wfEscapeWikiText( $text );
3664 } elseif ( is_string( $text )
3665 && !$piece['lineStart']
3666 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3667 ) {
3668 # Bug 529: if the template begins with a table or block-level
3669 # element, it should be treated as beginning a new line.
3670 # This behavior is somewhat controversial.
3671 $text = "\n" . $text;
3672 }
3673
3674 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3675 # Error, oversize inclusion
3676 if ( $titleText !== false ) {
3677 # Make a working, properly escaped link if possible (bug 23588)
3678 $text = "[[:$titleText]]";
3679 } else {
3680 # This will probably not be a working link, but at least it may
3681 # provide some hint of where the problem is
3682 preg_replace( '/^:/', '', $originalTitle );
3683 $text = "[[:$originalTitle]]";
3684 }
3685 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3686 . 'post-expand include size too large -->' );
3687 $this->limitationWarn( 'post-expand-template-inclusion' );
3688 }
3689
3690 if ( $isLocalObj ) {
3691 $ret = array( 'object' => $text );
3692 } else {
3693 $ret = array( 'text' => $text );
3694 }
3695
3696 return $ret;
3697 }
3698
3699 /**
3700 * Call a parser function and return an array with text and flags.
3701 *
3702 * The returned array will always contain a boolean 'found', indicating
3703 * whether the parser function was found or not. It may also contain the
3704 * following:
3705 * text: string|object, resulting wikitext or PP DOM object
3706 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3707 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3708 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3709 * nowiki: bool, wiki markup in $text should be escaped
3710 *
3711 * @since 1.21
3712 * @param PPFrame $frame The current frame, contains template arguments
3713 * @param string $function Function name
3714 * @param array $args Arguments to the function
3715 * @throws MWException
3716 * @return array
3717 */
3718 public function callParserFunction( $frame, $function, array $args = array() ) {
3719 global $wgContLang;
3720
3721
3722 # Case sensitive functions
3723 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3724 $function = $this->mFunctionSynonyms[1][$function];
3725 } else {
3726 # Case insensitive functions
3727 $function = $wgContLang->lc( $function );
3728 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3729 $function = $this->mFunctionSynonyms[0][$function];
3730 } else {
3731 return array( 'found' => false );
3732 }
3733 }
3734
3735 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3736
3737 # Workaround for PHP bug 35229 and similar
3738 if ( !is_callable( $callback ) ) {
3739 throw new MWException( "Tag hook for $function is not callable\n" );
3740 }
3741
3742 $allArgs = array( &$this );
3743 if ( $flags & self::SFH_OBJECT_ARGS ) {
3744 # Convert arguments to PPNodes and collect for appending to $allArgs
3745 $funcArgs = array();
3746 foreach ( $args as $k => $v ) {
3747 if ( $v instanceof PPNode || $k === 0 ) {
3748 $funcArgs[] = $v;
3749 } else {
3750 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( array( $k => $v ) )->item( 0 );
3751 }
3752 }
3753
3754 # Add a frame parameter, and pass the arguments as an array
3755 $allArgs[] = $frame;
3756 $allArgs[] = $funcArgs;
3757 } else {
3758 # Convert arguments to plain text and append to $allArgs
3759 foreach ( $args as $k => $v ) {
3760 if ( $v instanceof PPNode ) {
3761 $allArgs[] = trim( $frame->expand( $v ) );
3762 } elseif ( is_int( $k ) && $k >= 0 ) {
3763 $allArgs[] = trim( $v );
3764 } else {
3765 $allArgs[] = trim( "$k=$v" );
3766 }
3767 }
3768 }
3769
3770 $result = call_user_func_array( $callback, $allArgs );
3771
3772 # The interface for function hooks allows them to return a wikitext
3773 # string or an array containing the string and any flags. This mungs
3774 # things around to match what this method should return.
3775 if ( !is_array( $result ) ) {
3776 $result = array(
3777 'found' => true,
3778 'text' => $result,
3779 );
3780 } else {
3781 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3782 $result['text'] = $result[0];
3783 }
3784 unset( $result[0] );
3785 $result += array(
3786 'found' => true,
3787 );
3788 }
3789
3790 $noparse = true;
3791 $preprocessFlags = 0;
3792 if ( isset( $result['noparse'] ) ) {
3793 $noparse = $result['noparse'];
3794 }
3795 if ( isset( $result['preprocessFlags'] ) ) {
3796 $preprocessFlags = $result['preprocessFlags'];
3797 }
3798
3799 if ( !$noparse ) {
3800 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3801 $result['isChildObj'] = true;
3802 }
3803
3804 return $result;
3805 }
3806
3807 /**
3808 * Get the semi-parsed DOM representation of a template with a given title,
3809 * and its redirect destination title. Cached.
3810 *
3811 * @param Title $title
3812 *
3813 * @return array
3814 */
3815 public function getTemplateDom( $title ) {
3816 $cacheTitle = $title;
3817 $titleText = $title->getPrefixedDBkey();
3818
3819 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3820 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3821 $title = Title::makeTitle( $ns, $dbk );
3822 $titleText = $title->getPrefixedDBkey();
3823 }
3824 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3825 return array( $this->mTplDomCache[$titleText], $title );
3826 }
3827
3828 # Cache miss, go to the database
3829 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3830
3831 if ( $text === false ) {
3832 $this->mTplDomCache[$titleText] = false;
3833 return array( false, $title );
3834 }
3835
3836 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3837 $this->mTplDomCache[$titleText] = $dom;
3838
3839 if ( !$title->equals( $cacheTitle ) ) {
3840 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3841 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3842 }
3843
3844 return array( $dom, $title );
3845 }
3846
3847 /**
3848 * Fetch the current revision of a given title. Note that the revision
3849 * (and even the title) may not exist in the database, so everything
3850 * contributing to the output of the parser should use this method
3851 * where possible, rather than getting the revisions themselves. This
3852 * method also caches its results, so using it benefits performance.
3853 *
3854 * @since 1.24
3855 * @param Title $title
3856 * @return Revision
3857 */
3858 public function fetchCurrentRevisionOfTitle( $title ) {
3859 $cacheKey = $title->getPrefixedDBkey();
3860 if ( !$this->currentRevisionCache ) {
3861 $this->currentRevisionCache = new MapCacheLRU( 100 );
3862 }
3863 if ( !$this->currentRevisionCache->has( $cacheKey ) ) {
3864 $this->currentRevisionCache->set( $cacheKey,
3865 // Defaults to Parser::statelessFetchRevision()
3866 call_user_func( $this->mOptions->getCurrentRevisionCallback(), $title, $this )
3867 );
3868 }
3869 return $this->currentRevisionCache->get( $cacheKey );
3870 }
3871
3872 /**
3873 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3874 * without passing them on to it.
3875 *
3876 * @since 1.24
3877 * @param Title $title
3878 * @param Parser|bool $parser
3879 * @return Revision
3880 */
3881 public static function statelessFetchRevision( $title, $parser = false ) {
3882 return Revision::newFromTitle( $title );
3883 }
3884
3885 /**
3886 * Fetch the unparsed text of a template and register a reference to it.
3887 * @param Title $title
3888 * @return array ( string or false, Title )
3889 */
3890 public function fetchTemplateAndTitle( $title ) {
3891 // Defaults to Parser::statelessFetchTemplate()
3892 $templateCb = $this->mOptions->getTemplateCallback();
3893 $stuff = call_user_func( $templateCb, $title, $this );
3894 $text = $stuff['text'];
3895 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3896 if ( isset( $stuff['deps'] ) ) {
3897 foreach ( $stuff['deps'] as $dep ) {
3898 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3899 if ( $dep['title']->equals( $this->getTitle() ) ) {
3900 // If we transclude ourselves, the final result
3901 // will change based on the new version of the page
3902 $this->mOutput->setFlag( 'vary-revision' );
3903 }
3904 }
3905 }
3906 return array( $text, $finalTitle );
3907 }
3908
3909 /**
3910 * Fetch the unparsed text of a template and register a reference to it.
3911 * @param Title $title
3912 * @return string|bool
3913 */
3914 public function fetchTemplate( $title ) {
3915 $rv = $this->fetchTemplateAndTitle( $title );
3916 return $rv[0];
3917 }
3918
3919 /**
3920 * Static function to get a template
3921 * Can be overridden via ParserOptions::setTemplateCallback().
3922 *
3923 * @param Title $title
3924 * @param bool|Parser $parser
3925 *
3926 * @return array
3927 */
3928 public static function statelessFetchTemplate( $title, $parser = false ) {
3929 $text = $skip = false;
3930 $finalTitle = $title;
3931 $deps = array();
3932
3933 # Loop to fetch the article, with up to 1 redirect
3934 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3935 # Give extensions a chance to select the revision instead
3936 $id = false; # Assume current
3937 Hooks::run( 'BeforeParserFetchTemplateAndtitle',
3938 array( $parser, $title, &$skip, &$id ) );
3939
3940 if ( $skip ) {
3941 $text = false;
3942 $deps[] = array(
3943 'title' => $title,
3944 'page_id' => $title->getArticleID(),
3945 'rev_id' => null
3946 );
3947 break;
3948 }
3949 # Get the revision
3950 if ( $id ) {
3951 $rev = Revision::newFromId( $id );
3952 } elseif ( $parser ) {
3953 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3954 } else {
3955 $rev = Revision::newFromTitle( $title );
3956 }
3957 $rev_id = $rev ? $rev->getId() : 0;
3958 # If there is no current revision, there is no page
3959 if ( $id === false && !$rev ) {
3960 $linkCache = LinkCache::singleton();
3961 $linkCache->addBadLinkObj( $title );
3962 }
3963
3964 $deps[] = array(
3965 'title' => $title,
3966 'page_id' => $title->getArticleID(),
3967 'rev_id' => $rev_id );
3968 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3969 # We fetched a rev from a different title; register it too...
3970 $deps[] = array(
3971 'title' => $rev->getTitle(),
3972 'page_id' => $rev->getPage(),
3973 'rev_id' => $rev_id );
3974 }
3975
3976 if ( $rev ) {
3977 $content = $rev->getContent();
3978 $text = $content ? $content->getWikitextForTransclusion() : null;
3979
3980 if ( $text === false || $text === null ) {
3981 $text = false;
3982 break;
3983 }
3984 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3985 global $wgContLang;
3986 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3987 if ( !$message->exists() ) {
3988 $text = false;
3989 break;
3990 }
3991 $content = $message->content();
3992 $text = $message->plain();
3993 } else {
3994 break;
3995 }
3996 if ( !$content ) {
3997 break;
3998 }
3999 # Redirect?
4000 $finalTitle = $title;
4001 $title = $content->getRedirectTarget();
4002 }
4003 return array(
4004 'text' => $text,
4005 'finalTitle' => $finalTitle,
4006 'deps' => $deps );
4007 }
4008
4009 /**
4010 * Fetch a file and its title and register a reference to it.
4011 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4012 * @param Title $title
4013 * @param array $options Array of options to RepoGroup::findFile
4014 * @return File|bool
4015 */
4016 public function fetchFile( $title, $options = array() ) {
4017 $res = $this->fetchFileAndTitle( $title, $options );
4018 return $res[0];
4019 }
4020
4021 /**
4022 * Fetch a file and its title and register a reference to it.
4023 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4024 * @param Title $title
4025 * @param array $options Array of options to RepoGroup::findFile
4026 * @return array ( File or false, Title of file )
4027 */
4028 public function fetchFileAndTitle( $title, $options = array() ) {
4029 $file = $this->fetchFileNoRegister( $title, $options );
4030
4031 $time = $file ? $file->getTimestamp() : false;
4032 $sha1 = $file ? $file->getSha1() : false;
4033 # Register the file as a dependency...
4034 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
4035 if ( $file && !$title->equals( $file->getTitle() ) ) {
4036 # Update fetched file title
4037 $title = $file->getTitle();
4038 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
4039 }
4040 return array( $file, $title );
4041 }
4042
4043 /**
4044 * Helper function for fetchFileAndTitle.
4045 *
4046 * Also useful if you need to fetch a file but not use it yet,
4047 * for example to get the file's handler.
4048 *
4049 * @param Title $title
4050 * @param array $options Array of options to RepoGroup::findFile
4051 * @return File|bool
4052 */
4053 protected function fetchFileNoRegister( $title, $options = array() ) {
4054 if ( isset( $options['broken'] ) ) {
4055 $file = false; // broken thumbnail forced by hook
4056 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4057 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
4058 } else { // get by (name,timestamp)
4059 $file = wfFindFile( $title, $options );
4060 }
4061 return $file;
4062 }
4063
4064 /**
4065 * Transclude an interwiki link.
4066 *
4067 * @param Title $title
4068 * @param string $action
4069 *
4070 * @return string
4071 */
4072 public function interwikiTransclude( $title, $action ) {
4073 global $wgEnableScaryTranscluding;
4074
4075 if ( !$wgEnableScaryTranscluding ) {
4076 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4077 }
4078
4079 $url = $title->getFullURL( array( 'action' => $action ) );
4080
4081 if ( strlen( $url ) > 255 ) {
4082 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4083 }
4084 return $this->fetchScaryTemplateMaybeFromCache( $url );
4085 }
4086
4087 /**
4088 * @param string $url
4089 * @return mixed|string
4090 */
4091 public function fetchScaryTemplateMaybeFromCache( $url ) {
4092 global $wgTranscludeCacheExpiry;
4093 $dbr = wfGetDB( DB_SLAVE );
4094 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4095 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4096 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4097 if ( $obj ) {
4098 return $obj->tc_contents;
4099 }
4100
4101 $req = MWHttpRequest::factory( $url );
4102 $status = $req->execute(); // Status object
4103 if ( $status->isOK() ) {
4104 $text = $req->getContent();
4105 } elseif ( $req->getStatus() != 200 ) {
4106 // Though we failed to fetch the content, this status is useless.
4107 return wfMessage( 'scarytranscludefailed-httpstatus' )
4108 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4109 } else {
4110 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4111 }
4112
4113 $dbw = wfGetDB( DB_MASTER );
4114 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4115 'tc_url' => $url,
4116 'tc_time' => $dbw->timestamp( time() ),
4117 'tc_contents' => $text
4118 ) );
4119 return $text;
4120 }
4121
4122 /**
4123 * Triple brace replacement -- used for template arguments
4124 * @private
4125 *
4126 * @param array $piece
4127 * @param PPFrame $frame
4128 *
4129 * @return array
4130 */
4131 public function argSubstitution( $piece, $frame ) {
4132
4133 $error = false;
4134 $parts = $piece['parts'];
4135 $nameWithSpaces = $frame->expand( $piece['title'] );
4136 $argName = trim( $nameWithSpaces );
4137 $object = false;
4138 $text = $frame->getArgument( $argName );
4139 if ( $text === false && $parts->getLength() > 0
4140 && ( $this->ot['html']
4141 || $this->ot['pre']
4142 || ( $this->ot['wiki'] && $frame->isTemplate() )
4143 )
4144 ) {
4145 # No match in frame, use the supplied default
4146 $object = $parts->item( 0 )->getChildren();
4147 }
4148 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4149 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4150 $this->limitationWarn( 'post-expand-template-argument' );
4151 }
4152
4153 if ( $text === false && $object === false ) {
4154 # No match anywhere
4155 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4156 }
4157 if ( $error !== false ) {
4158 $text .= $error;
4159 }
4160 if ( $object !== false ) {
4161 $ret = array( 'object' => $object );
4162 } else {
4163 $ret = array( 'text' => $text );
4164 }
4165
4166 return $ret;
4167 }
4168
4169 /**
4170 * Return the text to be used for a given extension tag.
4171 * This is the ghost of strip().
4172 *
4173 * @param array $params Associative array of parameters:
4174 * name PPNode for the tag name
4175 * attr PPNode for unparsed text where tag attributes are thought to be
4176 * attributes Optional associative array of parsed attributes
4177 * inner Contents of extension element
4178 * noClose Original text did not have a close tag
4179 * @param PPFrame $frame
4180 *
4181 * @throws MWException
4182 * @return string
4183 */
4184 public function extensionSubstitution( $params, $frame ) {
4185 $name = $frame->expand( $params['name'] );
4186 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
4187 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
4188 $marker = "{$this->mUniqPrefix}-$name-"
4189 . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
4190
4191 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
4192 ( $this->ot['html'] || $this->ot['pre'] );
4193 if ( $isFunctionTag ) {
4194 $markerType = 'none';
4195 } else {
4196 $markerType = 'general';
4197 }
4198 if ( $this->ot['html'] || $isFunctionTag ) {
4199 $name = strtolower( $name );
4200 $attributes = Sanitizer::decodeTagAttributes( $attrText );
4201 if ( isset( $params['attributes'] ) ) {
4202 $attributes = $attributes + $params['attributes'];
4203 }
4204
4205 if ( isset( $this->mTagHooks[$name] ) ) {
4206 # Workaround for PHP bug 35229 and similar
4207 if ( !is_callable( $this->mTagHooks[$name] ) ) {
4208 throw new MWException( "Tag hook for $name is not callable\n" );
4209 }
4210 $output = call_user_func_array( $this->mTagHooks[$name],
4211 array( $content, $attributes, $this, $frame ) );
4212 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
4213 list( $callback, ) = $this->mFunctionTagHooks[$name];
4214 if ( !is_callable( $callback ) ) {
4215 throw new MWException( "Tag hook for $name is not callable\n" );
4216 }
4217
4218 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4219 } else {
4220 $output = '<span class="error">Invalid tag extension name: ' .
4221 htmlspecialchars( $name ) . '</span>';
4222 }
4223
4224 if ( is_array( $output ) ) {
4225 # Extract flags to local scope (to override $markerType)
4226 $flags = $output;
4227 $output = $flags[0];
4228 unset( $flags[0] );
4229 extract( $flags );
4230 }
4231 } else {
4232 if ( is_null( $attrText ) ) {
4233 $attrText = '';
4234 }
4235 if ( isset( $params['attributes'] ) ) {
4236 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4237 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4238 htmlspecialchars( $attrValue ) . '"';
4239 }
4240 }
4241 if ( $content === null ) {
4242 $output = "<$name$attrText/>";
4243 } else {
4244 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
4245 $output = "<$name$attrText>$content$close";
4246 }
4247 }
4248
4249 if ( $markerType === 'none' ) {
4250 return $output;
4251 } elseif ( $markerType === 'nowiki' ) {
4252 $this->mStripState->addNoWiki( $marker, $output );
4253 } elseif ( $markerType === 'general' ) {
4254 $this->mStripState->addGeneral( $marker, $output );
4255 } else {
4256 throw new MWException( __METHOD__ . ': invalid marker type' );
4257 }
4258 return $marker;
4259 }
4260
4261 /**
4262 * Increment an include size counter
4263 *
4264 * @param string $type The type of expansion
4265 * @param int $size The size of the text
4266 * @return bool False if this inclusion would take it over the maximum, true otherwise
4267 */
4268 public function incrementIncludeSize( $type, $size ) {
4269 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
4270 return false;
4271 } else {
4272 $this->mIncludeSizes[$type] += $size;
4273 return true;
4274 }
4275 }
4276
4277 /**
4278 * Increment the expensive function count
4279 *
4280 * @return bool False if the limit has been exceeded
4281 */
4282 public function incrementExpensiveFunctionCount() {
4283 $this->mExpensiveFunctionCount++;
4284 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
4285 }
4286
4287 /**
4288 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4289 * Fills $this->mDoubleUnderscores, returns the modified text
4290 *
4291 * @param string $text
4292 *
4293 * @return string
4294 */
4295 public function doDoubleUnderscore( $text ) {
4296
4297 # The position of __TOC__ needs to be recorded
4298 $mw = MagicWord::get( 'toc' );
4299 if ( $mw->match( $text ) ) {
4300 $this->mShowToc = true;
4301 $this->mForceTocPosition = true;
4302
4303 # Set a placeholder. At the end we'll fill it in with the TOC.
4304 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4305
4306 # Only keep the first one.
4307 $text = $mw->replace( '', $text );
4308 }
4309
4310 # Now match and remove the rest of them
4311 $mwa = MagicWord::getDoubleUnderscoreArray();
4312 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
4313
4314 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
4315 $this->mOutput->mNoGallery = true;
4316 }
4317 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
4318 $this->mShowToc = false;
4319 }
4320 if ( isset( $this->mDoubleUnderscores['hiddencat'] )
4321 && $this->mTitle->getNamespace() == NS_CATEGORY
4322 ) {
4323 $this->addTrackingCategory( 'hidden-category-category' );
4324 }
4325 # (bug 8068) Allow control over whether robots index a page.
4326 #
4327 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4328 # is not desirable, the last one on the page should win.
4329 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
4330 $this->mOutput->setIndexPolicy( 'noindex' );
4331 $this->addTrackingCategory( 'noindex-category' );
4332 }
4333 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4334 $this->mOutput->setIndexPolicy( 'index' );
4335 $this->addTrackingCategory( 'index-category' );
4336 }
4337
4338 # Cache all double underscores in the database
4339 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4340 $this->mOutput->setProperty( $key, '' );
4341 }
4342
4343 return $text;
4344 }
4345
4346 /**
4347 * @see ParserOutput::addTrackingCategory()
4348 * @param string $msg Message key
4349 * @return bool Whether the addition was successful
4350 */
4351 public function addTrackingCategory( $msg ) {
4352 return $this->mOutput->addTrackingCategory( $msg, $this->mTitle );
4353 }
4354
4355 /**
4356 * This function accomplishes several tasks:
4357 * 1) Auto-number headings if that option is enabled
4358 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4359 * 3) Add a Table of contents on the top for users who have enabled the option
4360 * 4) Auto-anchor headings
4361 *
4362 * It loops through all headlines, collects the necessary data, then splits up the
4363 * string and re-inserts the newly formatted headlines.
4364 *
4365 * @param string $text
4366 * @param string $origText Original, untouched wikitext
4367 * @param bool $isMain
4368 * @return mixed|string
4369 * @private
4370 */
4371 public function formatHeadings( $text, $origText, $isMain = true ) {
4372 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4373
4374 # Inhibit editsection links if requested in the page
4375 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4376 $maybeShowEditLink = $showEditLink = false;
4377 } else {
4378 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4379 $showEditLink = $this->mOptions->getEditSection();
4380 }
4381 if ( $showEditLink ) {
4382 $this->mOutput->setEditSectionTokens( true );
4383 }
4384
4385 # Get all headlines for numbering them and adding funky stuff like [edit]
4386 # links - this is for later, but we need the number of headlines right now
4387 $matches = array();
4388 $numMatches = preg_match_all(
4389 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4390 $text,
4391 $matches
4392 );
4393
4394 # if there are fewer than 4 headlines in the article, do not show TOC
4395 # unless it's been explicitly enabled.
4396 $enoughToc = $this->mShowToc &&
4397 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4398
4399 # Allow user to stipulate that a page should have a "new section"
4400 # link added via __NEWSECTIONLINK__
4401 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4402 $this->mOutput->setNewSection( true );
4403 }
4404
4405 # Allow user to remove the "new section"
4406 # link via __NONEWSECTIONLINK__
4407 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4408 $this->mOutput->hideNewSection( true );
4409 }
4410
4411 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4412 # override above conditions and always show TOC above first header
4413 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4414 $this->mShowToc = true;
4415 $enoughToc = true;
4416 }
4417
4418 # headline counter
4419 $headlineCount = 0;
4420 $numVisible = 0;
4421
4422 # Ugh .. the TOC should have neat indentation levels which can be
4423 # passed to the skin functions. These are determined here
4424 $toc = '';
4425 $full = '';
4426 $head = array();
4427 $sublevelCount = array();
4428 $levelCount = array();
4429 $level = 0;
4430 $prevlevel = 0;
4431 $toclevel = 0;
4432 $prevtoclevel = 0;
4433 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
4434 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4435 $oldType = $this->mOutputType;
4436 $this->setOutputType( self::OT_WIKI );
4437 $frame = $this->getPreprocessor()->newFrame();
4438 $root = $this->preprocessToDom( $origText );
4439 $node = $root->getFirstChild();
4440 $byteOffset = 0;
4441 $tocraw = array();
4442 $refers = array();
4443
4444 foreach ( $matches[3] as $headline ) {
4445 $isTemplate = false;
4446 $titleText = false;
4447 $sectionIndex = false;
4448 $numbering = '';
4449 $markerMatches = array();
4450 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4451 $serial = $markerMatches[1];
4452 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4453 $isTemplate = ( $titleText != $baseTitleText );
4454 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4455 }
4456
4457 if ( $toclevel ) {
4458 $prevlevel = $level;
4459 }
4460 $level = $matches[1][$headlineCount];
4461
4462 if ( $level > $prevlevel ) {
4463 # Increase TOC level
4464 $toclevel++;
4465 $sublevelCount[$toclevel] = 0;
4466 if ( $toclevel < $wgMaxTocLevel ) {
4467 $prevtoclevel = $toclevel;
4468 $toc .= Linker::tocIndent();
4469 $numVisible++;
4470 }
4471 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4472 # Decrease TOC level, find level to jump to
4473
4474 for ( $i = $toclevel; $i > 0; $i-- ) {
4475 if ( $levelCount[$i] == $level ) {
4476 # Found last matching level
4477 $toclevel = $i;
4478 break;
4479 } elseif ( $levelCount[$i] < $level ) {
4480 # Found first matching level below current level
4481 $toclevel = $i + 1;
4482 break;
4483 }
4484 }
4485 if ( $i == 0 ) {
4486 $toclevel = 1;
4487 }
4488 if ( $toclevel < $wgMaxTocLevel ) {
4489 if ( $prevtoclevel < $wgMaxTocLevel ) {
4490 # Unindent only if the previous toc level was shown :p
4491 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4492 $prevtoclevel = $toclevel;
4493 } else {
4494 $toc .= Linker::tocLineEnd();
4495 }
4496 }
4497 } else {
4498 # No change in level, end TOC line
4499 if ( $toclevel < $wgMaxTocLevel ) {
4500 $toc .= Linker::tocLineEnd();
4501 }
4502 }
4503
4504 $levelCount[$toclevel] = $level;
4505
4506 # count number of headlines for each level
4507 $sublevelCount[$toclevel]++;
4508 $dot = 0;
4509 for ( $i = 1; $i <= $toclevel; $i++ ) {
4510 if ( !empty( $sublevelCount[$i] ) ) {
4511 if ( $dot ) {
4512 $numbering .= '.';
4513 }
4514 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4515 $dot = 1;
4516 }
4517 }
4518
4519 # The safe header is a version of the header text safe to use for links
4520
4521 # Remove link placeholders by the link text.
4522 # <!--LINK number-->
4523 # turns into
4524 # link text with suffix
4525 # Do this before unstrip since link text can contain strip markers
4526 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4527
4528 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4529 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4530
4531 # Strip out HTML (first regex removes any tag not allowed)
4532 # Allowed tags are:
4533 # * <sup> and <sub> (bug 8393)
4534 # * <i> (bug 26375)
4535 # * <b> (r105284)
4536 # * <bdi> (bug 72884)
4537 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4538 #
4539 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4540 # to allow setting directionality in toc items.
4541 $tocline = preg_replace(
4542 array(
4543 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?' . '>#',
4544 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?' . '>#'
4545 ),
4546 array( '', '<$1>' ),
4547 $safeHeadline
4548 );
4549 $tocline = trim( $tocline );
4550
4551 # For the anchor, strip out HTML-y stuff period
4552 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4553 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4554
4555 # Save headline for section edit hint before it's escaped
4556 $headlineHint = $safeHeadline;
4557
4558 if ( $wgExperimentalHtmlIds ) {
4559 # For reverse compatibility, provide an id that's
4560 # HTML4-compatible, like we used to.
4561 #
4562 # It may be worth noting, academically, that it's possible for
4563 # the legacy anchor to conflict with a non-legacy headline
4564 # anchor on the page. In this case likely the "correct" thing
4565 # would be to either drop the legacy anchors or make sure
4566 # they're numbered first. However, this would require people
4567 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4568 # manually, so let's not bother worrying about it.
4569 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4570 array( 'noninitial', 'legacy' ) );
4571 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4572
4573 if ( $legacyHeadline == $safeHeadline ) {
4574 # No reason to have both (in fact, we can't)
4575 $legacyHeadline = false;
4576 }
4577 } else {
4578 $legacyHeadline = false;
4579 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4580 'noninitial' );
4581 }
4582
4583 # HTML names must be case-insensitively unique (bug 10721).
4584 # This does not apply to Unicode characters per
4585 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4586 # @todo FIXME: We may be changing them depending on the current locale.
4587 $arrayKey = strtolower( $safeHeadline );
4588 if ( $legacyHeadline === false ) {
4589 $legacyArrayKey = false;
4590 } else {
4591 $legacyArrayKey = strtolower( $legacyHeadline );
4592 }
4593
4594 # count how many in assoc. array so we can track dupes in anchors
4595 if ( isset( $refers[$arrayKey] ) ) {
4596 $refers[$arrayKey]++;
4597 } else {
4598 $refers[$arrayKey] = 1;
4599 }
4600 if ( isset( $refers[$legacyArrayKey] ) ) {
4601 $refers[$legacyArrayKey]++;
4602 } else {
4603 $refers[$legacyArrayKey] = 1;
4604 }
4605
4606 # Don't number the heading if it is the only one (looks silly)
4607 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4608 # the two are different if the line contains a link
4609 $headline = Html::element(
4610 'span',
4611 array( 'class' => 'mw-headline-number' ),
4612 $numbering
4613 ) . ' ' . $headline;
4614 }
4615
4616 # Create the anchor for linking from the TOC to the section
4617 $anchor = $safeHeadline;
4618 $legacyAnchor = $legacyHeadline;
4619 if ( $refers[$arrayKey] > 1 ) {
4620 $anchor .= '_' . $refers[$arrayKey];
4621 }
4622 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4623 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4624 }
4625 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4626 $toc .= Linker::tocLine( $anchor, $tocline,
4627 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4628 }
4629
4630 # Add the section to the section tree
4631 # Find the DOM node for this header
4632 $noOffset = ( $isTemplate || $sectionIndex === false );
4633 while ( $node && !$noOffset ) {
4634 if ( $node->getName() === 'h' ) {
4635 $bits = $node->splitHeading();
4636 if ( $bits['i'] == $sectionIndex ) {
4637 break;
4638 }
4639 }
4640 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4641 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4642 $node = $node->getNextSibling();
4643 }
4644 $tocraw[] = array(
4645 'toclevel' => $toclevel,
4646 'level' => $level,
4647 'line' => $tocline,
4648 'number' => $numbering,
4649 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4650 'fromtitle' => $titleText,
4651 'byteoffset' => ( $noOffset ? null : $byteOffset ),
4652 'anchor' => $anchor,
4653 );
4654
4655 # give headline the correct <h#> tag
4656 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4657 // Output edit section links as markers with styles that can be customized by skins
4658 if ( $isTemplate ) {
4659 # Put a T flag in the section identifier, to indicate to extractSections()
4660 # that sections inside <includeonly> should be counted.
4661 $editsectionPage = $titleText;
4662 $editsectionSection = "T-$sectionIndex";
4663 $editsectionContent = null;
4664 } else {
4665 $editsectionPage = $this->mTitle->getPrefixedText();
4666 $editsectionSection = $sectionIndex;
4667 $editsectionContent = $headlineHint;
4668 }
4669 // We use a bit of pesudo-xml for editsection markers. The
4670 // language converter is run later on. Using a UNIQ style marker
4671 // leads to the converter screwing up the tokens when it
4672 // converts stuff. And trying to insert strip tags fails too. At
4673 // this point all real inputted tags have already been escaped,
4674 // so we don't have to worry about a user trying to input one of
4675 // these markers directly. We use a page and section attribute
4676 // to stop the language converter from converting these
4677 // important bits of data, but put the headline hint inside a
4678 // content block because the language converter is supposed to
4679 // be able to convert that piece of data.
4680 // Gets replaced with html in ParserOutput::getText
4681 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4682 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4683 if ( $editsectionContent !== null ) {
4684 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4685 } else {
4686 $editlink .= '/>';
4687 }
4688 } else {
4689 $editlink = '';
4690 }
4691 $head[$headlineCount] = Linker::makeHeadline( $level,
4692 $matches['attrib'][$headlineCount], $anchor, $headline,
4693 $editlink, $legacyAnchor );
4694
4695 $headlineCount++;
4696 }
4697
4698 $this->setOutputType( $oldType );
4699
4700 # Never ever show TOC if no headers
4701 if ( $numVisible < 1 ) {
4702 $enoughToc = false;
4703 }
4704
4705 if ( $enoughToc ) {
4706 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4707 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4708 }
4709 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4710 $this->mOutput->setTOCHTML( $toc );
4711 $toc = self::TOC_START . $toc . self::TOC_END;
4712 $this->mOutput->addModules( 'mediawiki.toc' );
4713 }
4714
4715 if ( $isMain ) {
4716 $this->mOutput->setSections( $tocraw );
4717 }
4718
4719 # split up and insert constructed headlines
4720 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4721 $i = 0;
4722
4723 // build an array of document sections
4724 $sections = array();
4725 foreach ( $blocks as $block ) {
4726 // $head is zero-based, sections aren't.
4727 if ( empty( $head[$i - 1] ) ) {
4728 $sections[$i] = $block;
4729 } else {
4730 $sections[$i] = $head[$i - 1] . $block;
4731 }
4732
4733 /**
4734 * Send a hook, one per section.
4735 * The idea here is to be able to make section-level DIVs, but to do so in a
4736 * lower-impact, more correct way than r50769
4737 *
4738 * $this : caller
4739 * $section : the section number
4740 * &$sectionContent : ref to the content of the section
4741 * $showEditLinks : boolean describing whether this section has an edit link
4742 */
4743 Hooks::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4744
4745 $i++;
4746 }
4747
4748 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4749 // append the TOC at the beginning
4750 // Top anchor now in skin
4751 $sections[0] = $sections[0] . $toc . "\n";
4752 }
4753
4754 $full .= join( '', $sections );
4755
4756 if ( $this->mForceTocPosition ) {
4757 return str_replace( '<!--MWTOC-->', $toc, $full );
4758 } else {
4759 return $full;
4760 }
4761 }
4762
4763 /**
4764 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4765 * conversion, substituting signatures, {{subst:}} templates, etc.
4766 *
4767 * @param string $text The text to transform
4768 * @param Title $title The Title object for the current article
4769 * @param User $user The User object describing the current user
4770 * @param ParserOptions $options Parsing options
4771 * @param bool $clearState Whether to clear the parser state first
4772 * @return string The altered wiki markup
4773 */
4774 public function preSaveTransform( $text, Title $title, User $user,
4775 ParserOptions $options, $clearState = true
4776 ) {
4777 if ( $clearState ) {
4778 $magicScopeVariable = $this->lock();
4779 }
4780 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4781 $this->setUser( $user );
4782
4783 $pairs = array(
4784 "\r\n" => "\n",
4785 "\r" => "\n",
4786 );
4787 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4788 if ( $options->getPreSaveTransform() ) {
4789 $text = $this->pstPass2( $text, $user );
4790 }
4791 $text = $this->mStripState->unstripBoth( $text );
4792
4793 $this->setUser( null ); #Reset
4794
4795 return $text;
4796 }
4797
4798 /**
4799 * Pre-save transform helper function
4800 *
4801 * @param string $text
4802 * @param User $user
4803 *
4804 * @return string
4805 */
4806 private function pstPass2( $text, $user ) {
4807 global $wgContLang;
4808
4809 # Note: This is the timestamp saved as hardcoded wikitext to
4810 # the database, we use $wgContLang here in order to give
4811 # everyone the same signature and use the default one rather
4812 # than the one selected in each user's preferences.
4813 # (see also bug 12815)
4814 $ts = $this->mOptions->getTimestamp();
4815 $timestamp = MWTimestamp::getLocalInstance( $ts );
4816 $ts = $timestamp->format( 'YmdHis' );
4817 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4818
4819 # Allow translation of timezones through wiki. format() can return
4820 # whatever crap the system uses, localised or not, so we cannot
4821 # ship premade translations.
4822 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4823 $msg = wfMessage( $key )->inContentLanguage();
4824 if ( $msg->exists() ) {
4825 $tzMsg = $msg->text();
4826 }
4827
4828 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4829
4830 # Variable replacement
4831 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4832 $text = $this->replaceVariables( $text );
4833
4834 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4835 # which may corrupt this parser instance via its wfMessage()->text() call-
4836
4837 # Signatures
4838 $sigText = $this->getUserSig( $user );
4839 $text = strtr( $text, array(
4840 '~~~~~' => $d,
4841 '~~~~' => "$sigText $d",
4842 '~~~' => $sigText
4843 ) );
4844
4845 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4846 $tc = '[' . Title::legalChars() . ']';
4847 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4848
4849 // [[ns:page (context)|]]
4850 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4851 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4852 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4853 // [[ns:page (context), context|]] (using either single or double-width comma)
4854 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4855 // [[|page]] (reverse pipe trick: add context from page title)
4856 $p2 = "/\[\[\\|($tc+)]]/";
4857
4858 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4859 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4860 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4861 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4862
4863 $t = $this->mTitle->getText();
4864 $m = array();
4865 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4866 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4867 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4868 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4869 } else {
4870 # if there's no context, don't bother duplicating the title
4871 $text = preg_replace( $p2, '[[\\1]]', $text );
4872 }
4873
4874 # Trim trailing whitespace
4875 $text = rtrim( $text );
4876
4877 return $text;
4878 }
4879
4880 /**
4881 * Fetch the user's signature text, if any, and normalize to
4882 * validated, ready-to-insert wikitext.
4883 * If you have pre-fetched the nickname or the fancySig option, you can
4884 * specify them here to save a database query.
4885 * Do not reuse this parser instance after calling getUserSig(),
4886 * as it may have changed if it's the $wgParser.
4887 *
4888 * @param User $user
4889 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4890 * @param bool|null $fancySig whether the nicknname is the complete signature
4891 * or null to use default value
4892 * @return string
4893 */
4894 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4895 global $wgMaxSigChars;
4896
4897 $username = $user->getName();
4898
4899 # If not given, retrieve from the user object.
4900 if ( $nickname === false ) {
4901 $nickname = $user->getOption( 'nickname' );
4902 }
4903
4904 if ( is_null( $fancySig ) ) {
4905 $fancySig = $user->getBoolOption( 'fancysig' );
4906 }
4907
4908 $nickname = $nickname == null ? $username : $nickname;
4909
4910 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4911 $nickname = $username;
4912 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4913 } elseif ( $fancySig !== false ) {
4914 # Sig. might contain markup; validate this
4915 if ( $this->validateSig( $nickname ) !== false ) {
4916 # Validated; clean up (if needed) and return it
4917 return $this->cleanSig( $nickname, true );
4918 } else {
4919 # Failed to validate; fall back to the default
4920 $nickname = $username;
4921 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4922 }
4923 }
4924
4925 # Make sure nickname doesnt get a sig in a sig
4926 $nickname = self::cleanSigInSig( $nickname );
4927
4928 # If we're still here, make it a link to the user page
4929 $userText = wfEscapeWikiText( $username );
4930 $nickText = wfEscapeWikiText( $nickname );
4931 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4932
4933 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4934 ->title( $this->getTitle() )->text();
4935 }
4936
4937 /**
4938 * Check that the user's signature contains no bad XML
4939 *
4940 * @param string $text
4941 * @return string|bool An expanded string, or false if invalid.
4942 */
4943 public function validateSig( $text ) {
4944 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4945 }
4946
4947 /**
4948 * Clean up signature text
4949 *
4950 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4951 * 2) Substitute all transclusions
4952 *
4953 * @param string $text
4954 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4955 * @return string Signature text
4956 */
4957 public function cleanSig( $text, $parsing = false ) {
4958 if ( !$parsing ) {
4959 global $wgTitle;
4960 $magicScopeVariable = $this->lock();
4961 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4962 }
4963
4964 # Option to disable this feature
4965 if ( !$this->mOptions->getCleanSignatures() ) {
4966 return $text;
4967 }
4968
4969 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4970 # => Move this logic to braceSubstitution()
4971 $substWord = MagicWord::get( 'subst' );
4972 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4973 $substText = '{{' . $substWord->getSynonym( 0 );
4974
4975 $text = preg_replace( $substRegex, $substText, $text );
4976 $text = self::cleanSigInSig( $text );
4977 $dom = $this->preprocessToDom( $text );
4978 $frame = $this->getPreprocessor()->newFrame();
4979 $text = $frame->expand( $dom );
4980
4981 if ( !$parsing ) {
4982 $text = $this->mStripState->unstripBoth( $text );
4983 }
4984
4985 return $text;
4986 }
4987
4988 /**
4989 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4990 *
4991 * @param string $text
4992 * @return string Signature text with /~{3,5}/ removed
4993 */
4994 public static function cleanSigInSig( $text ) {
4995 $text = preg_replace( '/~{3,5}/', '', $text );
4996 return $text;
4997 }
4998
4999 /**
5000 * Set up some variables which are usually set up in parse()
5001 * so that an external function can call some class members with confidence
5002 *
5003 * @param Title|null $title
5004 * @param ParserOptions $options
5005 * @param int $outputType
5006 * @param bool $clearState
5007 */
5008 public function startExternalParse( Title $title = null, ParserOptions $options,
5009 $outputType, $clearState = true
5010 ) {
5011 $this->startParse( $title, $options, $outputType, $clearState );
5012 }
5013
5014 /**
5015 * @param Title|null $title
5016 * @param ParserOptions $options
5017 * @param int $outputType
5018 * @param bool $clearState
5019 */
5020 private function startParse( Title $title = null, ParserOptions $options,
5021 $outputType, $clearState = true
5022 ) {
5023 $this->setTitle( $title );
5024 $this->mOptions = $options;
5025 $this->setOutputType( $outputType );
5026 if ( $clearState ) {
5027 $this->clearState();
5028 }
5029 }
5030
5031 /**
5032 * Wrapper for preprocess()
5033 *
5034 * @param string $text The text to preprocess
5035 * @param ParserOptions $options Options
5036 * @param Title|null $title Title object or null to use $wgTitle
5037 * @return string
5038 */
5039 public function transformMsg( $text, $options, $title = null ) {
5040 static $executing = false;
5041
5042 # Guard against infinite recursion
5043 if ( $executing ) {
5044 return $text;
5045 }
5046 $executing = true;
5047
5048 if ( !$title ) {
5049 global $wgTitle;
5050 $title = $wgTitle;
5051 }
5052
5053 $text = $this->preprocess( $text, $title, $options );
5054
5055 $executing = false;
5056 return $text;
5057 }
5058
5059 /**
5060 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5061 * The callback should have the following form:
5062 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5063 *
5064 * Transform and return $text. Use $parser for any required context, e.g. use
5065 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5066 *
5067 * Hooks may return extended information by returning an array, of which the
5068 * first numbered element (index 0) must be the return string, and all other
5069 * entries are extracted into local variables within an internal function
5070 * in the Parser class.
5071 *
5072 * This interface (introduced r61913) appears to be undocumented, but
5073 * 'markerName' is used by some core tag hooks to override which strip
5074 * array their results are placed in. **Use great caution if attempting
5075 * this interface, as it is not documented and injudicious use could smash
5076 * private variables.**
5077 *
5078 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5079 * @param callable $callback The callback function (and object) to use for the tag
5080 * @throws MWException
5081 * @return callable|null The old value of the mTagHooks array associated with the hook
5082 */
5083 public function setHook( $tag, $callback ) {
5084 $tag = strtolower( $tag );
5085 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5086 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5087 }
5088 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
5089 $this->mTagHooks[$tag] = $callback;
5090 if ( !in_array( $tag, $this->mStripList ) ) {
5091 $this->mStripList[] = $tag;
5092 }
5093
5094 return $oldVal;
5095 }
5096
5097 /**
5098 * As setHook(), but letting the contents be parsed.
5099 *
5100 * Transparent tag hooks are like regular XML-style tag hooks, except they
5101 * operate late in the transformation sequence, on HTML instead of wikitext.
5102 *
5103 * This is probably obsoleted by things dealing with parser frames?
5104 * The only extension currently using it is geoserver.
5105 *
5106 * @since 1.10
5107 * @todo better document or deprecate this
5108 *
5109 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5110 * @param callable $callback The callback function (and object) to use for the tag
5111 * @throws MWException
5112 * @return callable|null The old value of the mTagHooks array associated with the hook
5113 */
5114 public function setTransparentTagHook( $tag, $callback ) {
5115 $tag = strtolower( $tag );
5116 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5117 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5118 }
5119 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
5120 $this->mTransparentTagHooks[$tag] = $callback;
5121
5122 return $oldVal;
5123 }
5124
5125 /**
5126 * Remove all tag hooks
5127 */
5128 public function clearTagHooks() {
5129 $this->mTagHooks = array();
5130 $this->mFunctionTagHooks = array();
5131 $this->mStripList = $this->mDefaultStripList;
5132 }
5133
5134 /**
5135 * Create a function, e.g. {{sum:1|2|3}}
5136 * The callback function should have the form:
5137 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5138 *
5139 * Or with Parser::SFH_OBJECT_ARGS:
5140 * function myParserFunction( $parser, $frame, $args ) { ... }
5141 *
5142 * The callback may either return the text result of the function, or an array with the text
5143 * in element 0, and a number of flags in the other elements. The names of the flags are
5144 * specified in the keys. Valid flags are:
5145 * found The text returned is valid, stop processing the template. This
5146 * is on by default.
5147 * nowiki Wiki markup in the return value should be escaped
5148 * isHTML The returned text is HTML, armour it against wikitext transformation
5149 *
5150 * @param string $id The magic word ID
5151 * @param callable $callback The callback function (and object) to use
5152 * @param int $flags A combination of the following flags:
5153 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5154 *
5155 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5156 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5157 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5158 * the arguments, and to control the way they are expanded.
5159 *
5160 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5161 * arguments, for instance:
5162 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5163 *
5164 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5165 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5166 * working if/when this is changed.
5167 *
5168 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5169 * expansion.
5170 *
5171 * Please read the documentation in includes/parser/Preprocessor.php for more information
5172 * about the methods available in PPFrame and PPNode.
5173 *
5174 * @throws MWException
5175 * @return string|callable The old callback function for this name, if any
5176 */
5177 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5178 global $wgContLang;
5179
5180 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
5181 $this->mFunctionHooks[$id] = array( $callback, $flags );
5182
5183 # Add to function cache
5184 $mw = MagicWord::get( $id );
5185 if ( !$mw ) {
5186 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
5187 }
5188
5189 $synonyms = $mw->getSynonyms();
5190 $sensitive = intval( $mw->isCaseSensitive() );
5191
5192 foreach ( $synonyms as $syn ) {
5193 # Case
5194 if ( !$sensitive ) {
5195 $syn = $wgContLang->lc( $syn );
5196 }
5197 # Add leading hash
5198 if ( !( $flags & self::SFH_NO_HASH ) ) {
5199 $syn = '#' . $syn;
5200 }
5201 # Remove trailing colon
5202 if ( substr( $syn, -1, 1 ) === ':' ) {
5203 $syn = substr( $syn, 0, -1 );
5204 }
5205 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
5206 }
5207 return $oldVal;
5208 }
5209
5210 /**
5211 * Get all registered function hook identifiers
5212 *
5213 * @return array
5214 */
5215 public function getFunctionHooks() {
5216 return array_keys( $this->mFunctionHooks );
5217 }
5218
5219 /**
5220 * Create a tag function, e.g. "<test>some stuff</test>".
5221 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5222 * Unlike parser functions, their content is not preprocessed.
5223 * @param string $tag
5224 * @param callable $callback
5225 * @param int $flags
5226 * @throws MWException
5227 * @return null
5228 */
5229 public function setFunctionTagHook( $tag, $callback, $flags ) {
5230 $tag = strtolower( $tag );
5231 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5232 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5233 }
5234 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
5235 $this->mFunctionTagHooks[$tag] : null;
5236 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
5237
5238 if ( !in_array( $tag, $this->mStripList ) ) {
5239 $this->mStripList[] = $tag;
5240 }
5241
5242 return $old;
5243 }
5244
5245 /**
5246 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5247 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5248 * Placeholders created in Skin::makeLinkObj()
5249 *
5250 * @param string $text
5251 * @param int $options
5252 */
5253 public function replaceLinkHolders( &$text, $options = 0 ) {
5254 $this->mLinkHolders->replace( $text );
5255 }
5256
5257 /**
5258 * Replace "<!--LINK-->" link placeholders with plain text of links
5259 * (not HTML-formatted).
5260 *
5261 * @param string $text
5262 * @return string
5263 */
5264 public function replaceLinkHoldersText( $text ) {
5265 return $this->mLinkHolders->replaceText( $text );
5266 }
5267
5268 /**
5269 * Renders an image gallery from a text with one line per image.
5270 * text labels may be given by using |-style alternative text. E.g.
5271 * Image:one.jpg|The number "1"
5272 * Image:tree.jpg|A tree
5273 * given as text will return the HTML of a gallery with two images,
5274 * labeled 'The number "1"' and
5275 * 'A tree'.
5276 *
5277 * @param string $text
5278 * @param array $params
5279 * @return string HTML
5280 */
5281 public function renderImageGallery( $text, $params ) {
5282
5283 $mode = false;
5284 if ( isset( $params['mode'] ) ) {
5285 $mode = $params['mode'];
5286 }
5287
5288 try {
5289 $ig = ImageGalleryBase::factory( $mode );
5290 } catch ( MWException $e ) {
5291 // If invalid type set, fallback to default.
5292 $ig = ImageGalleryBase::factory( false );
5293 }
5294
5295 $ig->setContextTitle( $this->mTitle );
5296 $ig->setShowBytes( false );
5297 $ig->setShowFilename( false );
5298 $ig->setParser( $this );
5299 $ig->setHideBadImages();
5300 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
5301
5302 if ( isset( $params['showfilename'] ) ) {
5303 $ig->setShowFilename( true );
5304 } else {
5305 $ig->setShowFilename( false );
5306 }
5307 if ( isset( $params['caption'] ) ) {
5308 $caption = $params['caption'];
5309 $caption = htmlspecialchars( $caption );
5310 $caption = $this->replaceInternalLinks( $caption );
5311 $ig->setCaptionHtml( $caption );
5312 }
5313 if ( isset( $params['perrow'] ) ) {
5314 $ig->setPerRow( $params['perrow'] );
5315 }
5316 if ( isset( $params['widths'] ) ) {
5317 $ig->setWidths( $params['widths'] );
5318 }
5319 if ( isset( $params['heights'] ) ) {
5320 $ig->setHeights( $params['heights'] );
5321 }
5322 $ig->setAdditionalOptions( $params );
5323
5324 Hooks::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5325
5326 $lines = StringUtils::explode( "\n", $text );
5327 foreach ( $lines as $line ) {
5328 # match lines like these:
5329 # Image:someimage.jpg|This is some image
5330 $matches = array();
5331 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5332 # Skip empty lines
5333 if ( count( $matches ) == 0 ) {
5334 continue;
5335 }
5336
5337 if ( strpos( $matches[0], '%' ) !== false ) {
5338 $matches[1] = rawurldecode( $matches[1] );
5339 }
5340 $title = Title::newFromText( $matches[1], NS_FILE );
5341 if ( is_null( $title ) ) {
5342 # Bogus title. Ignore these so we don't bomb out later.
5343 continue;
5344 }
5345
5346 # We need to get what handler the file uses, to figure out parameters.
5347 # Note, a hook can overide the file name, and chose an entirely different
5348 # file (which potentially could be of a different type and have different handler).
5349 $options = array();
5350 $descQuery = false;
5351 Hooks::run( 'BeforeParserFetchFileAndTitle',
5352 array( $this, $title, &$options, &$descQuery ) );
5353 # Don't register it now, as ImageGallery does that later.
5354 $file = $this->fetchFileNoRegister( $title, $options );
5355 $handler = $file ? $file->getHandler() : false;
5356
5357 $paramMap = array(
5358 'img_alt' => 'gallery-internal-alt',
5359 'img_link' => 'gallery-internal-link',
5360 );
5361 if ( $handler ) {
5362 $paramMap = $paramMap + $handler->getParamMap();
5363 // We don't want people to specify per-image widths.
5364 // Additionally the width parameter would need special casing anyhow.
5365 unset( $paramMap['img_width'] );
5366 }
5367
5368 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5369
5370 $label = '';
5371 $alt = '';
5372 $link = '';
5373 $handlerOptions = array();
5374 if ( isset( $matches[3] ) ) {
5375 // look for an |alt= definition while trying not to break existing
5376 // captions with multiple pipes (|) in it, until a more sensible grammar
5377 // is defined for images in galleries
5378
5379 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5380 // splitting on '|' is a bit odd, and different from makeImage.
5381 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5382 $parameterMatches = StringUtils::explode( '|', $matches[3] );
5383
5384 foreach ( $parameterMatches as $parameterMatch ) {
5385 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5386 if ( $magicName ) {
5387 $paramName = $paramMap[$magicName];
5388
5389 switch ( $paramName ) {
5390 case 'gallery-internal-alt':
5391 $alt = $this->stripAltText( $match, false );
5392 break;
5393 case 'gallery-internal-link':
5394 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5395 $chars = self::EXT_LINK_URL_CLASS;
5396 $prots = $this->mUrlProtocols;
5397 //check to see if link matches an absolute url, if not then it must be a wiki link.
5398 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5399 $link = $linkValue;
5400 } else {
5401 $localLinkTitle = Title::newFromText( $linkValue );
5402 if ( $localLinkTitle !== null ) {
5403 $link = $localLinkTitle->getLinkURL();
5404 }
5405 }
5406 break;
5407 default:
5408 // Must be a handler specific parameter.
5409 if ( $handler->validateParam( $paramName, $match ) ) {
5410 $handlerOptions[$paramName] = $match;
5411 } else {
5412 // Guess not. Append it to the caption.
5413 wfDebug( "$parameterMatch failed parameter validation\n" );
5414 $label .= '|' . $parameterMatch;
5415 }
5416 }
5417
5418 } else {
5419 // concatenate all other pipes
5420 $label .= '|' . $parameterMatch;
5421 }
5422 }
5423 // remove the first pipe
5424 $label = substr( $label, 1 );
5425 }
5426
5427 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5428 }
5429 $html = $ig->toHTML();
5430 Hooks::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5431 return $html;
5432 }
5433
5434 /**
5435 * @param string $handler
5436 * @return array
5437 */
5438 public function getImageParams( $handler ) {
5439 if ( $handler ) {
5440 $handlerClass = get_class( $handler );
5441 } else {
5442 $handlerClass = '';
5443 }
5444 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5445 # Initialise static lists
5446 static $internalParamNames = array(
5447 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5448 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5449 'bottom', 'text-bottom' ),
5450 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5451 'upright', 'border', 'link', 'alt', 'class' ),
5452 );
5453 static $internalParamMap;
5454 if ( !$internalParamMap ) {
5455 $internalParamMap = array();
5456 foreach ( $internalParamNames as $type => $names ) {
5457 foreach ( $names as $name ) {
5458 $magicName = str_replace( '-', '_', "img_$name" );
5459 $internalParamMap[$magicName] = array( $type, $name );
5460 }
5461 }
5462 }
5463
5464 # Add handler params
5465 $paramMap = $internalParamMap;
5466 if ( $handler ) {
5467 $handlerParamMap = $handler->getParamMap();
5468 foreach ( $handlerParamMap as $magic => $paramName ) {
5469 $paramMap[$magic] = array( 'handler', $paramName );
5470 }
5471 }
5472 $this->mImageParams[$handlerClass] = $paramMap;
5473 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5474 }
5475 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
5476 }
5477
5478 /**
5479 * Parse image options text and use it to make an image
5480 *
5481 * @param Title $title
5482 * @param string $options
5483 * @param LinkHolderArray|bool $holders
5484 * @return string HTML
5485 */
5486 public function makeImage( $title, $options, $holders = false ) {
5487 # Check if the options text is of the form "options|alt text"
5488 # Options are:
5489 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5490 # * left no resizing, just left align. label is used for alt= only
5491 # * right same, but right aligned
5492 # * none same, but not aligned
5493 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5494 # * center center the image
5495 # * frame Keep original image size, no magnify-button.
5496 # * framed Same as "frame"
5497 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5498 # * upright reduce width for upright images, rounded to full __0 px
5499 # * border draw a 1px border around the image
5500 # * alt Text for HTML alt attribute (defaults to empty)
5501 # * class Set a class for img node
5502 # * link Set the target of the image link. Can be external, interwiki, or local
5503 # vertical-align values (no % or length right now):
5504 # * baseline
5505 # * sub
5506 # * super
5507 # * top
5508 # * text-top
5509 # * middle
5510 # * bottom
5511 # * text-bottom
5512
5513 $parts = StringUtils::explode( "|", $options );
5514
5515 # Give extensions a chance to select the file revision for us
5516 $options = array();
5517 $descQuery = false;
5518 Hooks::run( 'BeforeParserFetchFileAndTitle',
5519 array( $this, $title, &$options, &$descQuery ) );
5520 # Fetch and register the file (file title may be different via hooks)
5521 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5522
5523 # Get parameter map
5524 $handler = $file ? $file->getHandler() : false;
5525
5526 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5527
5528 if ( !$file ) {
5529 $this->addTrackingCategory( 'broken-file-category' );
5530 }
5531
5532 # Process the input parameters
5533 $caption = '';
5534 $params = array( 'frame' => array(), 'handler' => array(),
5535 'horizAlign' => array(), 'vertAlign' => array() );
5536 $seenformat = false;
5537 foreach ( $parts as $part ) {
5538 $part = trim( $part );
5539 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5540 $validated = false;
5541 if ( isset( $paramMap[$magicName] ) ) {
5542 list( $type, $paramName ) = $paramMap[$magicName];
5543
5544 # Special case; width and height come in one variable together
5545 if ( $type === 'handler' && $paramName === 'width' ) {
5546 $parsedWidthParam = $this->parseWidthParam( $value );
5547 if ( isset( $parsedWidthParam['width'] ) ) {
5548 $width = $parsedWidthParam['width'];
5549 if ( $handler->validateParam( 'width', $width ) ) {
5550 $params[$type]['width'] = $width;
5551 $validated = true;
5552 }
5553 }
5554 if ( isset( $parsedWidthParam['height'] ) ) {
5555 $height = $parsedWidthParam['height'];
5556 if ( $handler->validateParam( 'height', $height ) ) {
5557 $params[$type]['height'] = $height;
5558 $validated = true;
5559 }
5560 }
5561 # else no validation -- bug 13436
5562 } else {
5563 if ( $type === 'handler' ) {
5564 # Validate handler parameter
5565 $validated = $handler->validateParam( $paramName, $value );
5566 } else {
5567 # Validate internal parameters
5568 switch ( $paramName ) {
5569 case 'manualthumb':
5570 case 'alt':
5571 case 'class':
5572 # @todo FIXME: Possibly check validity here for
5573 # manualthumb? downstream behavior seems odd with
5574 # missing manual thumbs.
5575 $validated = true;
5576 $value = $this->stripAltText( $value, $holders );
5577 break;
5578 case 'link':
5579 $chars = self::EXT_LINK_URL_CLASS;
5580 $prots = $this->mUrlProtocols;
5581 if ( $value === '' ) {
5582 $paramName = 'no-link';
5583 $value = true;
5584 $validated = true;
5585 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5586 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5587 $paramName = 'link-url';
5588 $this->mOutput->addExternalLink( $value );
5589 if ( $this->mOptions->getExternalLinkTarget() ) {
5590 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5591 }
5592 $validated = true;
5593 }
5594 } else {
5595 $linkTitle = Title::newFromText( $value );
5596 if ( $linkTitle ) {
5597 $paramName = 'link-title';
5598 $value = $linkTitle;
5599 $this->mOutput->addLink( $linkTitle );
5600 $validated = true;
5601 }
5602 }
5603 break;
5604 case 'frameless':
5605 case 'framed':
5606 case 'thumbnail':
5607 // use first appearing option, discard others.
5608 $validated = ! $seenformat;
5609 $seenformat = true;
5610 break;
5611 default:
5612 # Most other things appear to be empty or numeric...
5613 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5614 }
5615 }
5616
5617 if ( $validated ) {
5618 $params[$type][$paramName] = $value;
5619 }
5620 }
5621 }
5622 if ( !$validated ) {
5623 $caption = $part;
5624 }
5625 }
5626
5627 # Process alignment parameters
5628 if ( $params['horizAlign'] ) {
5629 $params['frame']['align'] = key( $params['horizAlign'] );
5630 }
5631 if ( $params['vertAlign'] ) {
5632 $params['frame']['valign'] = key( $params['vertAlign'] );
5633 }
5634
5635 $params['frame']['caption'] = $caption;
5636
5637 # Will the image be presented in a frame, with the caption below?
5638 $imageIsFramed = isset( $params['frame']['frame'] )
5639 || isset( $params['frame']['framed'] )
5640 || isset( $params['frame']['thumbnail'] )
5641 || isset( $params['frame']['manualthumb'] );
5642
5643 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5644 # came to also set the caption, ordinary text after the image -- which
5645 # makes no sense, because that just repeats the text multiple times in
5646 # screen readers. It *also* came to set the title attribute.
5647 #
5648 # Now that we have an alt attribute, we should not set the alt text to
5649 # equal the caption: that's worse than useless, it just repeats the
5650 # text. This is the framed/thumbnail case. If there's no caption, we
5651 # use the unnamed parameter for alt text as well, just for the time be-
5652 # ing, if the unnamed param is set and the alt param is not.
5653 #
5654 # For the future, we need to figure out if we want to tweak this more,
5655 # e.g., introducing a title= parameter for the title; ignoring the un-
5656 # named parameter entirely for images without a caption; adding an ex-
5657 # plicit caption= parameter and preserving the old magic unnamed para-
5658 # meter for BC; ...
5659 if ( $imageIsFramed ) { # Framed image
5660 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5661 # No caption or alt text, add the filename as the alt text so
5662 # that screen readers at least get some description of the image
5663 $params['frame']['alt'] = $title->getText();
5664 }
5665 # Do not set $params['frame']['title'] because tooltips don't make sense
5666 # for framed images
5667 } else { # Inline image
5668 if ( !isset( $params['frame']['alt'] ) ) {
5669 # No alt text, use the "caption" for the alt text
5670 if ( $caption !== '' ) {
5671 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5672 } else {
5673 # No caption, fall back to using the filename for the
5674 # alt text
5675 $params['frame']['alt'] = $title->getText();
5676 }
5677 }
5678 # Use the "caption" for the tooltip text
5679 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5680 }
5681
5682 Hooks::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5683
5684 # Linker does the rest
5685 $time = isset( $options['time'] ) ? $options['time'] : false;
5686 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5687 $time, $descQuery, $this->mOptions->getThumbSize() );
5688
5689 # Give the handler a chance to modify the parser object
5690 if ( $handler ) {
5691 $handler->parserTransformHook( $this, $file );
5692 }
5693
5694 return $ret;
5695 }
5696
5697 /**
5698 * @param string $caption
5699 * @param LinkHolderArray|bool $holders
5700 * @return mixed|string
5701 */
5702 protected function stripAltText( $caption, $holders ) {
5703 # Strip bad stuff out of the title (tooltip). We can't just use
5704 # replaceLinkHoldersText() here, because if this function is called
5705 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5706 if ( $holders ) {
5707 $tooltip = $holders->replaceText( $caption );
5708 } else {
5709 $tooltip = $this->replaceLinkHoldersText( $caption );
5710 }
5711
5712 # make sure there are no placeholders in thumbnail attributes
5713 # that are later expanded to html- so expand them now and
5714 # remove the tags
5715 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5716 $tooltip = Sanitizer::stripAllTags( $tooltip );
5717
5718 return $tooltip;
5719 }
5720
5721 /**
5722 * Set a flag in the output object indicating that the content is dynamic and
5723 * shouldn't be cached.
5724 */
5725 public function disableCache() {
5726 wfDebug( "Parser output marked as uncacheable.\n" );
5727 if ( !$this->mOutput ) {
5728 throw new MWException( __METHOD__ .
5729 " can only be called when actually parsing something" );
5730 }
5731 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
5732 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5733 }
5734
5735 /**
5736 * Callback from the Sanitizer for expanding items found in HTML attribute
5737 * values, so they can be safely tested and escaped.
5738 *
5739 * @param string $text
5740 * @param bool|PPFrame $frame
5741 * @return string
5742 */
5743 public function attributeStripCallback( &$text, $frame = false ) {
5744 $text = $this->replaceVariables( $text, $frame );
5745 $text = $this->mStripState->unstripBoth( $text );
5746 return $text;
5747 }
5748
5749 /**
5750 * Accessor
5751 *
5752 * @return array
5753 */
5754 public function getTags() {
5755 return array_merge(
5756 array_keys( $this->mTransparentTagHooks ),
5757 array_keys( $this->mTagHooks ),
5758 array_keys( $this->mFunctionTagHooks )
5759 );
5760 }
5761
5762 /**
5763 * Replace transparent tags in $text with the values given by the callbacks.
5764 *
5765 * Transparent tag hooks are like regular XML-style tag hooks, except they
5766 * operate late in the transformation sequence, on HTML instead of wikitext.
5767 *
5768 * @param string $text
5769 *
5770 * @return string
5771 */
5772 public function replaceTransparentTags( $text ) {
5773 $matches = array();
5774 $elements = array_keys( $this->mTransparentTagHooks );
5775 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
5776 $replacements = array();
5777
5778 foreach ( $matches as $marker => $data ) {
5779 list( $element, $content, $params, $tag ) = $data;
5780 $tagName = strtolower( $element );
5781 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5782 $output = call_user_func_array(
5783 $this->mTransparentTagHooks[$tagName],
5784 array( $content, $params, $this )
5785 );
5786 } else {
5787 $output = $tag;
5788 }
5789 $replacements[$marker] = $output;
5790 }
5791 return strtr( $text, $replacements );
5792 }
5793
5794 /**
5795 * Break wikitext input into sections, and either pull or replace
5796 * some particular section's text.
5797 *
5798 * External callers should use the getSection and replaceSection methods.
5799 *
5800 * @param string $text Page wikitext
5801 * @param string|number $sectionId A section identifier string of the form:
5802 * "<flag1> - <flag2> - ... - <section number>"
5803 *
5804 * Currently the only recognised flag is "T", which means the target section number
5805 * was derived during a template inclusion parse, in other words this is a template
5806 * section edit link. If no flags are given, it was an ordinary section edit link.
5807 * This flag is required to avoid a section numbering mismatch when a section is
5808 * enclosed by "<includeonly>" (bug 6563).
5809 *
5810 * The section number 0 pulls the text before the first heading; other numbers will
5811 * pull the given section along with its lower-level subsections. If the section is
5812 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5813 *
5814 * Section 0 is always considered to exist, even if it only contains the empty
5815 * string. If $text is the empty string and section 0 is replaced, $newText is
5816 * returned.
5817 *
5818 * @param string $mode One of "get" or "replace"
5819 * @param string $newText Replacement text for section data.
5820 * @return string For "get", the extracted section text.
5821 * for "replace", the whole page with the section replaced.
5822 */
5823 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5824 global $wgTitle; # not generally used but removes an ugly failure mode
5825
5826 $magicScopeVariable = $this->lock();
5827 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5828 $outText = '';
5829 $frame = $this->getPreprocessor()->newFrame();
5830
5831 # Process section extraction flags
5832 $flags = 0;
5833 $sectionParts = explode( '-', $sectionId );
5834 $sectionIndex = array_pop( $sectionParts );
5835 foreach ( $sectionParts as $part ) {
5836 if ( $part === 'T' ) {
5837 $flags |= self::PTD_FOR_INCLUSION;
5838 }
5839 }
5840
5841 # Check for empty input
5842 if ( strval( $text ) === '' ) {
5843 # Only sections 0 and T-0 exist in an empty document
5844 if ( $sectionIndex == 0 ) {
5845 if ( $mode === 'get' ) {
5846 return '';
5847 } else {
5848 return $newText;
5849 }
5850 } else {
5851 if ( $mode === 'get' ) {
5852 return $newText;
5853 } else {
5854 return $text;
5855 }
5856 }
5857 }
5858
5859 # Preprocess the text
5860 $root = $this->preprocessToDom( $text, $flags );
5861
5862 # <h> nodes indicate section breaks
5863 # They can only occur at the top level, so we can find them by iterating the root's children
5864 $node = $root->getFirstChild();
5865
5866 # Find the target section
5867 if ( $sectionIndex == 0 ) {
5868 # Section zero doesn't nest, level=big
5869 $targetLevel = 1000;
5870 } else {
5871 while ( $node ) {
5872 if ( $node->getName() === 'h' ) {
5873 $bits = $node->splitHeading();
5874 if ( $bits['i'] == $sectionIndex ) {
5875 $targetLevel = $bits['level'];
5876 break;
5877 }
5878 }
5879 if ( $mode === 'replace' ) {
5880 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5881 }
5882 $node = $node->getNextSibling();
5883 }
5884 }
5885
5886 if ( !$node ) {
5887 # Not found
5888 if ( $mode === 'get' ) {
5889 return $newText;
5890 } else {
5891 return $text;
5892 }
5893 }
5894
5895 # Find the end of the section, including nested sections
5896 do {
5897 if ( $node->getName() === 'h' ) {
5898 $bits = $node->splitHeading();
5899 $curLevel = $bits['level'];
5900 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5901 break;
5902 }
5903 }
5904 if ( $mode === 'get' ) {
5905 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5906 }
5907 $node = $node->getNextSibling();
5908 } while ( $node );
5909
5910 # Write out the remainder (in replace mode only)
5911 if ( $mode === 'replace' ) {
5912 # Output the replacement text
5913 # Add two newlines on -- trailing whitespace in $newText is conventionally
5914 # stripped by the editor, so we need both newlines to restore the paragraph gap
5915 # Only add trailing whitespace if there is newText
5916 if ( $newText != "" ) {
5917 $outText .= $newText . "\n\n";
5918 }
5919
5920 while ( $node ) {
5921 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5922 $node = $node->getNextSibling();
5923 }
5924 }
5925
5926 if ( is_string( $outText ) ) {
5927 # Re-insert stripped tags
5928 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5929 }
5930
5931 return $outText;
5932 }
5933
5934 /**
5935 * This function returns the text of a section, specified by a number ($section).
5936 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5937 * the first section before any such heading (section 0).
5938 *
5939 * If a section contains subsections, these are also returned.
5940 *
5941 * @param string $text Text to look in
5942 * @param string|number $sectionId Section identifier as a number or string
5943 * (e.g. 0, 1 or 'T-1').
5944 * @param string $defaultText Default to return if section is not found
5945 *
5946 * @return string Text of the requested section
5947 */
5948 public function getSection( $text, $sectionId, $defaultText = '' ) {
5949 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5950 }
5951
5952 /**
5953 * This function returns $oldtext after the content of the section
5954 * specified by $section has been replaced with $text. If the target
5955 * section does not exist, $oldtext is returned unchanged.
5956 *
5957 * @param string $oldText Former text of the article
5958 * @param string|number $sectionId Section identifier as a number or string
5959 * (e.g. 0, 1 or 'T-1').
5960 * @param string $newText Replacing text
5961 *
5962 * @return string Modified text
5963 */
5964 public function replaceSection( $oldText, $sectionId, $newText ) {
5965 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5966 }
5967
5968 /**
5969 * Get the ID of the revision we are parsing
5970 *
5971 * @return int|null
5972 */
5973 public function getRevisionId() {
5974 return $this->mRevisionId;
5975 }
5976
5977 /**
5978 * Get the revision object for $this->mRevisionId
5979 *
5980 * @return Revision|null Either a Revision object or null
5981 * @since 1.23 (public since 1.23)
5982 */
5983 public function getRevisionObject() {
5984 if ( !is_null( $this->mRevisionObject ) ) {
5985 return $this->mRevisionObject;
5986 }
5987 if ( is_null( $this->mRevisionId ) ) {
5988 return null;
5989 }
5990
5991 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
5992 return $this->mRevisionObject;
5993 }
5994
5995 /**
5996 * Get the timestamp associated with the current revision, adjusted for
5997 * the default server-local timestamp
5998 * @return string
5999 */
6000 public function getRevisionTimestamp() {
6001 if ( is_null( $this->mRevisionTimestamp ) ) {
6002
6003 global $wgContLang;
6004
6005 $revObject = $this->getRevisionObject();
6006 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
6007
6008 # The cryptic '' timezone parameter tells to use the site-default
6009 # timezone offset instead of the user settings.
6010 #
6011 # Since this value will be saved into the parser cache, served
6012 # to other users, and potentially even used inside links and such,
6013 # it needs to be consistent for all visitors.
6014 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
6015
6016 }
6017 return $this->mRevisionTimestamp;
6018 }
6019
6020 /**
6021 * Get the name of the user that edited the last revision
6022 *
6023 * @return string User name
6024 */
6025 public function getRevisionUser() {
6026 if ( is_null( $this->mRevisionUser ) ) {
6027 $revObject = $this->getRevisionObject();
6028
6029 # if this template is subst: the revision id will be blank,
6030 # so just use the current user's name
6031 if ( $revObject ) {
6032 $this->mRevisionUser = $revObject->getUserText();
6033 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
6034 $this->mRevisionUser = $this->getUser()->getName();
6035 }
6036 }
6037 return $this->mRevisionUser;
6038 }
6039
6040 /**
6041 * Get the size of the revision
6042 *
6043 * @return int|null Revision size
6044 */
6045 public function getRevisionSize() {
6046 if ( is_null( $this->mRevisionSize ) ) {
6047 $revObject = $this->getRevisionObject();
6048
6049 # if this variable is subst: the revision id will be blank,
6050 # so just use the parser input size, because the own substituation
6051 # will change the size.
6052 if ( $revObject ) {
6053 $this->mRevisionSize = $revObject->getSize();
6054 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
6055 $this->mRevisionSize = $this->mInputSize;
6056 }
6057 }
6058 return $this->mRevisionSize;
6059 }
6060
6061 /**
6062 * Mutator for $mDefaultSort
6063 *
6064 * @param string $sort New value
6065 */
6066 public function setDefaultSort( $sort ) {
6067 $this->mDefaultSort = $sort;
6068 $this->mOutput->setProperty( 'defaultsort', $sort );
6069 }
6070
6071 /**
6072 * Accessor for $mDefaultSort
6073 * Will use the empty string if none is set.
6074 *
6075 * This value is treated as a prefix, so the
6076 * empty string is equivalent to sorting by
6077 * page name.
6078 *
6079 * @return string
6080 */
6081 public function getDefaultSort() {
6082 if ( $this->mDefaultSort !== false ) {
6083 return $this->mDefaultSort;
6084 } else {
6085 return '';
6086 }
6087 }
6088
6089 /**
6090 * Accessor for $mDefaultSort
6091 * Unlike getDefaultSort(), will return false if none is set
6092 *
6093 * @return string|bool
6094 */
6095 public function getCustomDefaultSort() {
6096 return $this->mDefaultSort;
6097 }
6098
6099 /**
6100 * Try to guess the section anchor name based on a wikitext fragment
6101 * presumably extracted from a heading, for example "Header" from
6102 * "== Header ==".
6103 *
6104 * @param string $text
6105 *
6106 * @return string
6107 */
6108 public function guessSectionNameFromWikiText( $text ) {
6109 # Strip out wikitext links(they break the anchor)
6110 $text = $this->stripSectionName( $text );
6111 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
6112 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
6113 }
6114
6115 /**
6116 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6117 * instead. For use in redirects, since IE6 interprets Redirect: headers
6118 * as something other than UTF-8 (apparently?), resulting in breakage.
6119 *
6120 * @param string $text The section name
6121 * @return string An anchor
6122 */
6123 public function guessLegacySectionNameFromWikiText( $text ) {
6124 # Strip out wikitext links(they break the anchor)
6125 $text = $this->stripSectionName( $text );
6126 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
6127 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
6128 }
6129
6130 /**
6131 * Strips a text string of wikitext for use in a section anchor
6132 *
6133 * Accepts a text string and then removes all wikitext from the
6134 * string and leaves only the resultant text (i.e. the result of
6135 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6136 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6137 * to create valid section anchors by mimicing the output of the
6138 * parser when headings are parsed.
6139 *
6140 * @param string $text Text string to be stripped of wikitext
6141 * for use in a Section anchor
6142 * @return string Filtered text string
6143 */
6144 public function stripSectionName( $text ) {
6145 # Strip internal link markup
6146 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6147 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6148
6149 # Strip external link markup
6150 # @todo FIXME: Not tolerant to blank link text
6151 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6152 # on how many empty links there are on the page - need to figure that out.
6153 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6154
6155 # Parse wikitext quotes (italics & bold)
6156 $text = $this->doQuotes( $text );
6157
6158 # Strip HTML tags
6159 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
6160 return $text;
6161 }
6162
6163 /**
6164 * strip/replaceVariables/unstrip for preprocessor regression testing
6165 *
6166 * @param string $text
6167 * @param Title $title
6168 * @param ParserOptions $options
6169 * @param int $outputType
6170 *
6171 * @return string
6172 */
6173 public function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
6174 $magicScopeVariable = $this->lock();
6175 $this->startParse( $title, $options, $outputType, true );
6176
6177 $text = $this->replaceVariables( $text );
6178 $text = $this->mStripState->unstripBoth( $text );
6179 $text = Sanitizer::removeHTMLtags( $text );
6180 return $text;
6181 }
6182
6183 /**
6184 * @param string $text
6185 * @param Title $title
6186 * @param ParserOptions $options
6187 * @return string
6188 */
6189 public function testPst( $text, Title $title, ParserOptions $options ) {
6190 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6191 }
6192
6193 /**
6194 * @param string $text
6195 * @param Title $title
6196 * @param ParserOptions $options
6197 * @return string
6198 */
6199 public function testPreprocess( $text, Title $title, ParserOptions $options ) {
6200 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
6201 }
6202
6203 /**
6204 * Call a callback function on all regions of the given text that are not
6205 * inside strip markers, and replace those regions with the return value
6206 * of the callback. For example, with input:
6207 *
6208 * aaa<MARKER>bbb
6209 *
6210 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6211 * two strings will be replaced with the value returned by the callback in
6212 * each case.
6213 *
6214 * @param string $s
6215 * @param callable $callback
6216 *
6217 * @return string
6218 */
6219 public function markerSkipCallback( $s, $callback ) {
6220 $i = 0;
6221 $out = '';
6222 while ( $i < strlen( $s ) ) {
6223 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
6224 if ( $markerStart === false ) {
6225 $out .= call_user_func( $callback, substr( $s, $i ) );
6226 break;
6227 } else {
6228 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6229 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
6230 if ( $markerEnd === false ) {
6231 $out .= substr( $s, $markerStart );
6232 break;
6233 } else {
6234 $markerEnd += strlen( self::MARKER_SUFFIX );
6235 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6236 $i = $markerEnd;
6237 }
6238 }
6239 }
6240 return $out;
6241 }
6242
6243 /**
6244 * Remove any strip markers found in the given text.
6245 *
6246 * @param string $text Input string
6247 * @return string
6248 */
6249 public function killMarkers( $text ) {
6250 return $this->mStripState->killMarkers( $text );
6251 }
6252
6253 /**
6254 * Save the parser state required to convert the given half-parsed text to
6255 * HTML. "Half-parsed" in this context means the output of
6256 * recursiveTagParse() or internalParse(). This output has strip markers
6257 * from replaceVariables (extensionSubstitution() etc.), and link
6258 * placeholders from replaceLinkHolders().
6259 *
6260 * Returns an array which can be serialized and stored persistently. This
6261 * array can later be loaded into another parser instance with
6262 * unserializeHalfParsedText(). The text can then be safely incorporated into
6263 * the return value of a parser hook.
6264 *
6265 * @param string $text
6266 *
6267 * @return array
6268 */
6269 public function serializeHalfParsedText( $text ) {
6270 $data = array(
6271 'text' => $text,
6272 'version' => self::HALF_PARSED_VERSION,
6273 'stripState' => $this->mStripState->getSubState( $text ),
6274 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
6275 );
6276 return $data;
6277 }
6278
6279 /**
6280 * Load the parser state given in the $data array, which is assumed to
6281 * have been generated by serializeHalfParsedText(). The text contents is
6282 * extracted from the array, and its markers are transformed into markers
6283 * appropriate for the current Parser instance. This transformed text is
6284 * returned, and can be safely included in the return value of a parser
6285 * hook.
6286 *
6287 * If the $data array has been stored persistently, the caller should first
6288 * check whether it is still valid, by calling isValidHalfParsedText().
6289 *
6290 * @param array $data Serialized data
6291 * @throws MWException
6292 * @return string
6293 */
6294 public function unserializeHalfParsedText( $data ) {
6295 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
6296 throw new MWException( __METHOD__ . ': invalid version' );
6297 }
6298
6299 # First, extract the strip state.
6300 $texts = array( $data['text'] );
6301 $texts = $this->mStripState->merge( $data['stripState'], $texts );
6302
6303 # Now renumber links
6304 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
6305
6306 # Should be good to go.
6307 return $texts[0];
6308 }
6309
6310 /**
6311 * Returns true if the given array, presumed to be generated by
6312 * serializeHalfParsedText(), is compatible with the current version of the
6313 * parser.
6314 *
6315 * @param array $data
6316 *
6317 * @return bool
6318 */
6319 public function isValidHalfParsedText( $data ) {
6320 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
6321 }
6322
6323 /**
6324 * Parsed a width param of imagelink like 300px or 200x300px
6325 *
6326 * @param string $value
6327 *
6328 * @return array
6329 * @since 1.20
6330 */
6331 public function parseWidthParam( $value ) {
6332 $parsedWidthParam = array();
6333 if ( $value === '' ) {
6334 return $parsedWidthParam;
6335 }
6336 $m = array();
6337 # (bug 13500) In both cases (width/height and width only),
6338 # permit trailing "px" for backward compatibility.
6339 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6340 $width = intval( $m[1] );
6341 $height = intval( $m[2] );
6342 $parsedWidthParam['width'] = $width;
6343 $parsedWidthParam['height'] = $height;
6344 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6345 $width = intval( $value );
6346 $parsedWidthParam['width'] = $width;
6347 }
6348 return $parsedWidthParam;
6349 }
6350
6351 /**
6352 * Lock the current instance of the parser.
6353 *
6354 * This is meant to stop someone from calling the parser
6355 * recursively and messing up all the strip state.
6356 *
6357 * @throws MWException If parser is in a parse
6358 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6359 */
6360 protected function lock() {
6361 if ( $this->mInParse ) {
6362 throw new MWException( "Parser state cleared while parsing. "
6363 . "Did you call Parser::parse recursively?" );
6364 }
6365 $this->mInParse = true;
6366
6367 $that = $this;
6368 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6369 $that->mInParse = false;
6370 } );
6371
6372 return $recursiveCheck;
6373 }
6374
6375 /**
6376 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6377 *
6378 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6379 * or if there is more than one <p/> tag in the input HTML.
6380 *
6381 * @param string $html
6382 * @return string
6383 * @since 1.24
6384 */
6385 public static function stripOuterParagraph( $html ) {
6386 $m = array();
6387 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6388 if ( strpos( $m[1], '</p>' ) === false ) {
6389 $html = $m[1];
6390 }
6391 }
6392
6393 return $html;
6394 }
6395
6396 /**
6397 * Return this parser if it is not doing anything, otherwise
6398 * get a fresh parser. You can use this method by doing
6399 * $myParser = $wgParser->getFreshParser(), or more simply
6400 * $wgParser->getFreshParser()->parse( ... );
6401 * if you're unsure if $wgParser is safe to use.
6402 *
6403 * @since 1.24
6404 * @return Parser A parser object that is not parsing anything
6405 */
6406 public function getFreshParser() {
6407 global $wgParserConf;
6408 if ( $this->mInParse ) {
6409 return new $wgParserConf['class']( $wgParserConf );
6410 } else {
6411 return $this;
6412 }
6413 }
6414 }