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