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