* Fixed "Morwen/13" from http://meta.wikimedia.org/w/index.php?title=Migration_to_the...
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2
3 /**
4 *
5 * File for Parser and related classes
6 *
7 * @addtogroup Parser
8 */
9
10
11 /**
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
16 *
17 * <pre>
18 * There are four main entry points into the Parser class:
19 * parse()
20 * produces HTML output
21 * preSaveTransform().
22 * produces altered wiki markup.
23 * transformMsg()
24 * performs brace substitution on MediaWiki messages
25 * preprocess()
26 * removes HTML comments and expands templates
27 *
28 * Globals used:
29 * objects: $wgLang, $wgContLang
30 *
31 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
32 *
33 * settings:
34 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
35 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
36 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
37 * $wgMaxArticleSize*
38 *
39 * * only within ParserOptions
40 * </pre>
41 *
42 * @addtogroup Parser
43 */
44 class Parser
45 {
46 /**
47 * Update this version number when the ParserOutput format
48 * changes in an incompatible way, so the parser cache
49 * can automatically discard old data.
50 */
51 const VERSION = '1.6.4';
52
53 # Flags for Parser::setFunctionHook
54 # Also available as global constants from Defines.php
55 const SFH_NO_HASH = 1;
56 const SFH_OBJECT_ARGS = 2;
57
58 # Constants needed for external link processing
59 # Everything except bracket, space, or control characters
60 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F]';
61 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
62 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
63
64 // State constants for the definition list colon extraction
65 const COLON_STATE_TEXT = 0;
66 const COLON_STATE_TAG = 1;
67 const COLON_STATE_TAGSTART = 2;
68 const COLON_STATE_CLOSETAG = 3;
69 const COLON_STATE_TAGSLASH = 4;
70 const COLON_STATE_COMMENT = 5;
71 const COLON_STATE_COMMENTDASH = 6;
72 const COLON_STATE_COMMENTDASHDASH = 7;
73
74 // Flags for preprocessToDom
75 const PTD_FOR_INCLUSION = 1;
76
77 /**#@+
78 * @private
79 */
80 # Persistent:
81 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
82 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerSuffix,
83 $mExtLinkBracketedRegex;
84
85 # Cleared with clearState():
86 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
87 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
88 var $mInterwikiLinkHolders, $mLinkHolders;
89 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
90 var $mTplExpandCache; // empty-frame expansion cache
91 var $mTplRedirCache, $mTplDomCache, $mHeadings;
92
93 # Temporary
94 # These are variables reset at least once per parse regardless of $clearState
95 var $mOptions, // ParserOptions object
96 $mTitle, // Title context, used for self-link rendering and similar things
97 $mOutputType, // Output type, one of the OT_xxx constants
98 $ot, // Shortcut alias, see setOutputType()
99 $mRevisionId, // ID to display in {{REVISIONID}} tags
100 $mRevisionTimestamp, // The timestamp of the specified revision ID
101 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
102
103 /**#@-*/
104
105 /**
106 * Constructor
107 *
108 * @public
109 */
110 function __construct( $conf = array() ) {
111 $this->mTagHooks = array();
112 $this->mTransparentTagHooks = array();
113 $this->mFunctionHooks = array();
114 $this->mFunctionSynonyms = array( 0 => array(), 1 => array() );
115 $this->mStripList = array( 'nowiki', 'gallery' );
116 $this->mMarkerSuffix = "-QINU\x7f";
117 $this->mExtLinkBracketedRegex = '/\[(\b(' . wfUrlProtocols() . ')'.
118 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
119 $this->mFirstCall = true;
120 }
121
122 /**
123 * Do various kinds of initialisation on the first call of the parser
124 */
125 function firstCallInit() {
126 if ( !$this->mFirstCall ) {
127 return;
128 }
129
130 wfProfileIn( __METHOD__ );
131 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
132
133 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
134
135 # Syntax for arguments (see self::setFunctionHook):
136 # "name for lookup in localized magic words array",
137 # function callback,
138 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}
139 # instead of {{#int:...}})
140 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH );
141 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH );
142 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH );
143 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH );
144 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH );
145 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH );
146 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH );
147 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH );
148 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH );
149 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH );
150 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH );
151 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH );
152 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH );
153 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH );
154 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH );
155 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH );
156 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH );
157 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH );
158 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH );
159 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH );
160 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH );
161 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH );
162 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH );
163 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH );
164 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
165 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH );
166 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH );
167 $this->setFunctionHook( 'tag', array( 'CoreParserFunctions', 'tagObj' ), SFH_OBJECT_ARGS );
168
169 if ( $wgAllowDisplayTitle ) {
170 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH );
171 }
172 if ( $wgAllowSlowParserFunctions ) {
173 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH );
174 }
175
176 $this->initialiseVariables();
177 $this->mFirstCall = false;
178 wfProfileOut( __METHOD__ );
179 }
180
181 /**
182 * Clear Parser state
183 *
184 * @private
185 */
186 function clearState() {
187 wfProfileIn( __METHOD__ );
188 if ( $this->mFirstCall ) {
189 $this->firstCallInit();
190 }
191 $this->mOutput = new ParserOutput;
192 $this->mAutonumber = 0;
193 $this->mLastSection = '';
194 $this->mDTopen = false;
195 $this->mIncludeCount = array();
196 $this->mStripState = new StripState;
197 $this->mArgStack = false;
198 $this->mInPre = false;
199 $this->mInterwikiLinkHolders = array(
200 'texts' => array(),
201 'titles' => array()
202 );
203 $this->mLinkHolders = array(
204 'namespaces' => array(),
205 'dbkeys' => array(),
206 'queries' => array(),
207 'texts' => array(),
208 'titles' => array()
209 );
210 $this->mRevisionTimestamp = $this->mRevisionId = null;
211
212 /**
213 * Prefix for temporary replacement strings for the multipass parser.
214 * \x07 should never appear in input as it's disallowed in XML.
215 * Using it at the front also gives us a little extra robustness
216 * since it shouldn't match when butted up against identifier-like
217 * string constructs.
218 *
219 * Must not consist of all title characters, or else it will change
220 * the behaviour of <nowiki> in a link.
221 */
222 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
223 $this->mUniqPrefix = "\x7fUNIQ" . Parser::getRandomString();
224
225 # Clear these on every parse, bug 4549
226 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
227
228 $this->mShowToc = true;
229 $this->mForceTocPosition = false;
230 $this->mIncludeSizes = array(
231 'post-expand' => 0,
232 'arg' => 0,
233 );
234 $this->mPPNodeCount = 0;
235 $this->mDefaultSort = false;
236 $this->mHeadings = array();
237
238 wfRunHooks( 'ParserClearState', array( &$this ) );
239 wfProfileOut( __METHOD__ );
240 }
241
242 function setOutputType( $ot ) {
243 $this->mOutputType = $ot;
244 // Shortcut alias
245 $this->ot = array(
246 'html' => $ot == OT_HTML,
247 'wiki' => $ot == OT_WIKI,
248 'msg' => $ot == OT_MSG,
249 'pre' => $ot == OT_PREPROCESS,
250 );
251 }
252
253 /**
254 * Set the context title
255 */
256 function setTitle( $t ) {
257 if ( strval( $t->getFragment() ) !== '' ) {
258 # Strip the fragment to avoid various odd effects
259 $this->mTitle = clone $t;
260 $this->mTitle->setFragment( '' );
261 } else {
262 $this->mTitle = $t;
263 }
264 }
265
266 /**
267 * Accessor for mUniqPrefix.
268 *
269 * @public
270 */
271 function uniqPrefix() {
272 if( !isset( $this->mUniqPrefix ) ) {
273 // @fixme this is probably *horribly wrong*
274 // LanguageConverter seems to want $wgParser's uniqPrefix, however
275 // if this is called for a parser cache hit, the parser may not
276 // have ever been initialized in the first place.
277 // Not really sure what the heck is supposed to be going on here.
278 return '';
279 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
280 }
281 return $this->mUniqPrefix;
282 }
283
284 /**
285 * Convert wikitext to HTML
286 * Do not call this function recursively.
287 *
288 * @param string $text Text we want to parse
289 * @param Title &$title A title object
290 * @param array $options
291 * @param boolean $linestart
292 * @param boolean $clearState
293 * @param int $revid number to pass in {{REVISIONID}}
294 * @return ParserOutput a ParserOutput
295 */
296 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
297 /**
298 * First pass--just handle <nowiki> sections, pass the rest off
299 * to internalParse() which does all the real work.
300 */
301
302 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
303 $fname = 'Parser::parse-' . wfGetCaller();
304 wfProfileIn( __METHOD__ );
305 wfProfileIn( $fname );
306
307 if ( $clearState ) {
308 $this->clearState();
309 }
310
311 $this->mOptions = $options;
312 $this->setTitle( $title );
313 $oldRevisionId = $this->mRevisionId;
314 $oldRevisionTimestamp = $this->mRevisionTimestamp;
315 if( $revid !== null ) {
316 $this->mRevisionId = $revid;
317 $this->mRevisionTimestamp = null;
318 }
319 $this->setOutputType( OT_HTML );
320 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
321 # No more strip!
322 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
323 $text = $this->internalParse( $text );
324 $text = $this->mStripState->unstripGeneral( $text );
325
326 # Clean up special characters, only run once, next-to-last before doBlockLevels
327 $fixtags = array(
328 # french spaces, last one Guillemet-left
329 # only if there is something before the space
330 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&nbsp;\\2',
331 # french spaces, Guillemet-right
332 '/(\\302\\253) /' => '\\1&nbsp;',
333 );
334 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
335
336 # only once and last
337 $text = $this->doBlockLevels( $text, $linestart );
338
339 $this->replaceLinkHolders( $text );
340
341 # the position of the parserConvert() call should not be changed. it
342 # assumes that the links are all replaced and the only thing left
343 # is the <nowiki> mark.
344 # Side-effects: this calls $this->mOutput->setTitleText()
345 $text = $wgContLang->parserConvert( $text, $this );
346
347 $text = $this->mStripState->unstripNoWiki( $text );
348
349 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
350
351 //!JF Move to its own function
352
353 $uniq_prefix = $this->mUniqPrefix;
354 $matches = array();
355 $elements = array_keys( $this->mTransparentTagHooks );
356 $text = Parser::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
357
358 foreach( $matches as $marker => $data ) {
359 list( $element, $content, $params, $tag ) = $data;
360 $tagName = strtolower( $element );
361 if( isset( $this->mTransparentTagHooks[$tagName] ) ) {
362 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName],
363 array( $content, $params, $this ) );
364 } else {
365 $output = $tag;
366 }
367 $this->mStripState->general->setPair( $marker, $output );
368 }
369 $text = $this->mStripState->unstripGeneral( $text );
370
371 $text = Sanitizer::normalizeCharReferences( $text );
372
373 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
374 $text = Parser::tidy($text);
375 } else {
376 # attempt to sanitize at least some nesting problems
377 # (bug #2702 and quite a few others)
378 $tidyregs = array(
379 # ''Something [http://www.cool.com cool''] -->
380 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
381 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
382 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
383 # fix up an anchor inside another anchor, only
384 # at least for a single single nested link (bug 3695)
385 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
386 '\\1\\2</a>\\3</a>\\1\\4</a>',
387 # fix div inside inline elements- doBlockLevels won't wrap a line which
388 # contains a div, so fix it up here; replace
389 # div with escaped text
390 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
391 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
392 # remove empty italic or bold tag pairs, some
393 # introduced by rules above
394 '/<([bi])><\/\\1>/' => '',
395 );
396
397 $text = preg_replace(
398 array_keys( $tidyregs ),
399 array_values( $tidyregs ),
400 $text );
401 }
402
403 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
404
405 # Information on include size limits, for the benefit of users who try to skirt them
406 if ( $this->mOptions->getEnableLimitReport() ) {
407 $max = $this->mOptions->getMaxIncludeSize();
408 $limitReport =
409 "NewPP limit report\n" .
410 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
411 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
412 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
413 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
414 $text .= "\n<!-- \n$limitReport-->\n";
415 }
416 $this->mOutput->setText( $text );
417 $this->mRevisionId = $oldRevisionId;
418 $this->mRevisionTimestamp = $oldRevisionTimestamp;
419 wfProfileOut( $fname );
420 wfProfileOut( __METHOD__ );
421
422 return $this->mOutput;
423 }
424
425 /**
426 * Recursive parser entry point that can be called from an extension tag
427 * hook.
428 */
429 function recursiveTagParse( $text ) {
430 wfProfileIn( __METHOD__ );
431 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
432 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
433 $text = $this->internalParse( $text );
434 wfProfileOut( __METHOD__ );
435 return $text;
436 }
437
438 /**
439 * Expand templates and variables in the text, producing valid, static wikitext.
440 * Also removes comments.
441 */
442 function preprocess( $text, $title, $options, $revid = null ) {
443 wfProfileIn( __METHOD__ );
444 $this->clearState();
445 $this->setOutputType( OT_PREPROCESS );
446 $this->mOptions = $options;
447 $this->setTitle( $title );
448 if( $revid !== null ) {
449 $this->mRevisionId = $revid;
450 }
451 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
452 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
453 $text = $this->replaceVariables( $text );
454 if ( $this->mOptions->getRemoveComments() ) {
455 $text = Sanitizer::removeHTMLcomments( $text );
456 }
457 $text = $this->mStripState->unstripBoth( $text );
458 wfProfileOut( __METHOD__ );
459 return $text;
460 }
461
462 /**
463 * Get a random string
464 *
465 * @private
466 * @static
467 */
468 function getRandomString() {
469 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
470 }
471
472 function &getTitle() { return $this->mTitle; }
473 function getOptions() { return $this->mOptions; }
474
475 function getFunctionLang() {
476 global $wgLang, $wgContLang;
477 return $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
478 }
479
480 /**
481 * Replaces all occurrences of HTML-style comments and the given tags
482 * in the text with a random marker and returns teh next text. The output
483 * parameter $matches will be an associative array filled with data in
484 * the form:
485 * 'UNIQ-xxxxx' => array(
486 * 'element',
487 * 'tag content',
488 * array( 'param' => 'x' ),
489 * '<element param="x">tag content</element>' ) )
490 *
491 * @param $elements list of element names. Comments are always extracted.
492 * @param $text Source text string.
493 * @param $uniq_prefix
494 *
495 * @public
496 * @static
497 */
498 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
499 static $n = 1;
500 $stripped = '';
501 $matches = array();
502
503 $taglist = implode( '|', $elements );
504 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
505
506 while ( '' != $text ) {
507 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
508 $stripped .= $p[0];
509 if( count( $p ) < 5 ) {
510 break;
511 }
512 if( count( $p ) > 5 ) {
513 // comment
514 $element = $p[4];
515 $attributes = '';
516 $close = '';
517 $inside = $p[5];
518 } else {
519 // tag
520 $element = $p[1];
521 $attributes = $p[2];
522 $close = $p[3];
523 $inside = $p[4];
524 }
525
526 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++) . $this->mMarkerSuffix;
527 $stripped .= $marker;
528
529 if ( $close === '/>' ) {
530 // Empty element tag, <tag />
531 $content = null;
532 $text = $inside;
533 $tail = null;
534 } else {
535 if( $element == '!--' ) {
536 $end = '/(-->)/';
537 } else {
538 $end = "/(<\\/$element\\s*>)/i";
539 }
540 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
541 $content = $q[0];
542 if( count( $q ) < 3 ) {
543 # No end tag -- let it run out to the end of the text.
544 $tail = '';
545 $text = '';
546 } else {
547 $tail = $q[1];
548 $text = $q[2];
549 }
550 }
551
552 $matches[$marker] = array( $element,
553 $content,
554 Sanitizer::decodeTagAttributes( $attributes ),
555 "<$element$attributes$close$content$tail" );
556 }
557 return $stripped;
558 }
559
560 /**
561 * Get a list of strippable XML-like elements
562 */
563 function getStripList() {
564 global $wgRawHtml;
565 $elements = $this->mStripList;
566 if( $wgRawHtml ) {
567 $elements[] = 'html';
568 }
569 if( $this->mOptions->getUseTeX() ) {
570 $elements[] = 'math';
571 }
572 return $elements;
573 }
574
575 /**
576 * @deprecated use replaceVariables
577 */
578 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
579 return $text;
580 }
581
582 /**
583 * Restores pre, math, and other extensions removed by strip()
584 *
585 * always call unstripNoWiki() after this one
586 * @private
587 * @deprecated use $this->mStripState->unstrip()
588 */
589 function unstrip( $text, $state ) {
590 return $state->unstripGeneral( $text );
591 }
592
593 /**
594 * Always call this after unstrip() to preserve the order
595 *
596 * @private
597 * @deprecated use $this->mStripState->unstrip()
598 */
599 function unstripNoWiki( $text, $state ) {
600 return $state->unstripNoWiki( $text );
601 }
602
603 /**
604 * @deprecated use $this->mStripState->unstripBoth()
605 */
606 function unstripForHTML( $text ) {
607 return $this->mStripState->unstripBoth( $text );
608 }
609
610 /**
611 * Add an item to the strip state
612 * Returns the unique tag which must be inserted into the stripped text
613 * The tag will be replaced with the original text in unstrip()
614 *
615 * @private
616 */
617 function insertStripItem( $text ) {
618 static $n = 0;
619 $rnd = "{$this->mUniqPrefix}-item-$n-{$this->mMarkerSuffix}";
620 ++$n;
621 $this->mStripState->general->setPair( $rnd, $text );
622 return $rnd;
623 }
624
625 /**
626 * Interface with html tidy, used if $wgUseTidy = true.
627 * If tidy isn't able to correct the markup, the original will be
628 * returned in all its glory with a warning comment appended.
629 *
630 * Either the external tidy program or the in-process tidy extension
631 * will be used depending on availability. Override the default
632 * $wgTidyInternal setting to disable the internal if it's not working.
633 *
634 * @param string $text Hideous HTML input
635 * @return string Corrected HTML output
636 * @public
637 * @static
638 */
639 function tidy( $text ) {
640 global $wgTidyInternal;
641 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
642 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
643 '<head><title>test</title></head><body>'.$text.'</body></html>';
644 if( $wgTidyInternal ) {
645 $correctedtext = Parser::internalTidy( $wrappedtext );
646 } else {
647 $correctedtext = Parser::externalTidy( $wrappedtext );
648 }
649 if( is_null( $correctedtext ) ) {
650 wfDebug( "Tidy error detected!\n" );
651 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
652 }
653 return $correctedtext;
654 }
655
656 /**
657 * Spawn an external HTML tidy process and get corrected markup back from it.
658 *
659 * @private
660 * @static
661 */
662 function externalTidy( $text ) {
663 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
664 $fname = 'Parser::externalTidy';
665 wfProfileIn( $fname );
666
667 $cleansource = '';
668 $opts = ' -utf8';
669
670 $descriptorspec = array(
671 0 => array('pipe', 'r'),
672 1 => array('pipe', 'w'),
673 2 => array('file', wfGetNull(), 'a')
674 );
675 $pipes = array();
676 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
677 if (is_resource($process)) {
678 // Theoretically, this style of communication could cause a deadlock
679 // here. If the stdout buffer fills up, then writes to stdin could
680 // block. This doesn't appear to happen with tidy, because tidy only
681 // writes to stdout after it's finished reading from stdin. Search
682 // for tidyParseStdin and tidySaveStdout in console/tidy.c
683 fwrite($pipes[0], $text);
684 fclose($pipes[0]);
685 while (!feof($pipes[1])) {
686 $cleansource .= fgets($pipes[1], 1024);
687 }
688 fclose($pipes[1]);
689 proc_close($process);
690 }
691
692 wfProfileOut( $fname );
693
694 if( $cleansource == '' && $text != '') {
695 // Some kind of error happened, so we couldn't get the corrected text.
696 // Just give up; we'll use the source text and append a warning.
697 return null;
698 } else {
699 return $cleansource;
700 }
701 }
702
703 /**
704 * Use the HTML tidy PECL extension to use the tidy library in-process,
705 * saving the overhead of spawning a new process.
706 *
707 * 'pear install tidy' should be able to compile the extension module.
708 *
709 * @private
710 * @static
711 */
712 function internalTidy( $text ) {
713 global $wgTidyConf, $IP, $wgDebugTidy;
714 $fname = 'Parser::internalTidy';
715 wfProfileIn( $fname );
716
717 $tidy = new tidy;
718 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
719 $tidy->cleanRepair();
720 if( $tidy->getStatus() == 2 ) {
721 // 2 is magic number for fatal error
722 // http://www.php.net/manual/en/function.tidy-get-status.php
723 $cleansource = null;
724 } else {
725 $cleansource = tidy_get_output( $tidy );
726 }
727 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
728 $cleansource .= "<!--\nTidy reports:\n" .
729 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
730 "\n-->";
731 }
732
733 wfProfileOut( $fname );
734 return $cleansource;
735 }
736
737 /**
738 * parse the wiki syntax used to render tables
739 *
740 * @private
741 */
742 function doTableStuff ( $text ) {
743 $fname = 'Parser::doTableStuff';
744 wfProfileIn( $fname );
745
746 $lines = explode ( "\n" , $text );
747 $td_history = array (); // Is currently a td tag open?
748 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
749 $tr_history = array (); // Is currently a tr tag open?
750 $tr_attributes = array (); // history of tr attributes
751 $has_opened_tr = array(); // Did this table open a <tr> element?
752 $indent_level = 0; // indent level of the table
753 foreach ( $lines as $key => $line )
754 {
755 $line = trim ( $line );
756
757 if( $line == '' ) { // empty line, go to next line
758 continue;
759 }
760 $first_character = $line{0};
761 $matches = array();
762
763 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
764 // First check if we are starting a new table
765 $indent_level = strlen( $matches[1] );
766
767 $attributes = $this->mStripState->unstripBoth( $matches[2] );
768 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'table' );
769
770 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
771 array_push ( $td_history , false );
772 array_push ( $last_tag_history , '' );
773 array_push ( $tr_history , false );
774 array_push ( $tr_attributes , '' );
775 array_push ( $has_opened_tr , false );
776 } else if ( count ( $td_history ) == 0 ) {
777 // Don't do any of the following
778 continue;
779 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
780 // We are ending a table
781 $line = '</table>' . substr ( $line , 2 );
782 $last_tag = array_pop ( $last_tag_history );
783
784 if ( !array_pop ( $has_opened_tr ) ) {
785 $line = "<tr><td></td></tr>{$line}";
786 }
787
788 if ( array_pop ( $tr_history ) ) {
789 $line = "</tr>{$line}";
790 }
791
792 if ( array_pop ( $td_history ) ) {
793 $line = "</{$last_tag}>{$line}";
794 }
795 array_pop ( $tr_attributes );
796 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
797 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
798 // Now we have a table row
799 $line = preg_replace( '#^\|-+#', '', $line );
800
801 // Whats after the tag is now only attributes
802 $attributes = $this->mStripState->unstripBoth( $line );
803 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'tr' );
804 array_pop ( $tr_attributes );
805 array_push ( $tr_attributes , $attributes );
806
807 $line = '';
808 $last_tag = array_pop ( $last_tag_history );
809 array_pop ( $has_opened_tr );
810 array_push ( $has_opened_tr , true );
811
812 if ( array_pop ( $tr_history ) ) {
813 $line = '</tr>';
814 }
815
816 if ( array_pop ( $td_history ) ) {
817 $line = "</{$last_tag}>{$line}";
818 }
819
820 $lines[$key] = $line;
821 array_push ( $tr_history , false );
822 array_push ( $td_history , false );
823 array_push ( $last_tag_history , '' );
824 }
825 else if ( $first_character == '|' || $first_character == '!' || substr ( $line , 0 , 2 ) == '|+' ) {
826 // This might be cell elements, td, th or captions
827 if ( substr ( $line , 0 , 2 ) == '|+' ) {
828 $first_character = '+';
829 $line = substr ( $line , 1 );
830 }
831
832 $line = substr ( $line , 1 );
833
834 if ( $first_character == '!' ) {
835 $line = str_replace ( '!!' , '||' , $line );
836 }
837
838 // Split up multiple cells on the same line.
839 // FIXME : This can result in improper nesting of tags processed
840 // by earlier parser steps, but should avoid splitting up eg
841 // attribute values containing literal "||".
842 $cells = StringUtils::explodeMarkup( '||' , $line );
843
844 $lines[$key] = '';
845
846 // Loop through each table cell
847 foreach ( $cells as $cell )
848 {
849 $previous = '';
850 if ( $first_character != '+' )
851 {
852 $tr_after = array_pop ( $tr_attributes );
853 if ( !array_pop ( $tr_history ) ) {
854 $previous = "<tr{$tr_after}>\n";
855 }
856 array_push ( $tr_history , true );
857 array_push ( $tr_attributes , '' );
858 array_pop ( $has_opened_tr );
859 array_push ( $has_opened_tr , true );
860 }
861
862 $last_tag = array_pop ( $last_tag_history );
863
864 if ( array_pop ( $td_history ) ) {
865 $previous = "</{$last_tag}>{$previous}";
866 }
867
868 if ( $first_character == '|' ) {
869 $last_tag = 'td';
870 } else if ( $first_character == '!' ) {
871 $last_tag = 'th';
872 } else if ( $first_character == '+' ) {
873 $last_tag = 'caption';
874 } else {
875 $last_tag = '';
876 }
877
878 array_push ( $last_tag_history , $last_tag );
879
880 // A cell could contain both parameters and data
881 $cell_data = explode ( '|' , $cell , 2 );
882
883 // Bug 553: Note that a '|' inside an invalid link should not
884 // be mistaken as delimiting cell parameters
885 if ( strpos( $cell_data[0], '[[' ) !== false ) {
886 $cell = "{$previous}<{$last_tag}>{$cell}";
887 } else if ( count ( $cell_data ) == 1 )
888 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
889 else {
890 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
891 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag );
892 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
893 }
894
895 $lines[$key] .= $cell;
896 array_push ( $td_history , true );
897 }
898 }
899 }
900
901 // Closing open td, tr && table
902 while ( count ( $td_history ) > 0 )
903 {
904 if ( array_pop ( $td_history ) ) {
905 $lines[] = '</td>' ;
906 }
907 if ( array_pop ( $tr_history ) ) {
908 $lines[] = '</tr>' ;
909 }
910 if ( !array_pop ( $has_opened_tr ) ) {
911 $lines[] = "<tr><td></td></tr>" ;
912 }
913
914 $lines[] = '</table>' ;
915 }
916
917 $output = implode ( "\n" , $lines ) ;
918
919 // special case: don't return empty table
920 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
921 $output = '';
922 }
923
924 wfProfileOut( $fname );
925
926 return $output;
927 }
928
929 /**
930 * Helper function for parse() that transforms wiki markup into
931 * HTML. Only called for $mOutputType == OT_HTML.
932 *
933 * @private
934 */
935 function internalParse( $text ) {
936 $isMain = true;
937 $fname = 'Parser::internalParse';
938 wfProfileIn( $fname );
939
940 # Hook to suspend the parser in this state
941 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
942 wfProfileOut( $fname );
943 return $text ;
944 }
945
946 $text = $this->replaceVariables( $text );
947 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
948 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
949
950 // Tables need to come after variable replacement for things to work
951 // properly; putting them before other transformations should keep
952 // exciting things like link expansions from showing up in surprising
953 // places.
954 $text = $this->doTableStuff( $text );
955
956 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
957
958 $text = $this->stripToc( $text );
959 $this->stripNoGallery( $text );
960 $text = $this->doHeadings( $text );
961 if($this->mOptions->getUseDynamicDates()) {
962 $df =& DateFormatter::getInstance();
963 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
964 }
965 $text = $this->doAllQuotes( $text );
966 $text = $this->replaceInternalLinks( $text );
967 $text = $this->replaceExternalLinks( $text );
968
969 # replaceInternalLinks may sometimes leave behind
970 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
971 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
972
973 $text = $this->doMagicLinks( $text );
974 $text = $this->formatHeadings( $text, $isMain );
975
976 wfProfileOut( $fname );
977 return $text;
978 }
979
980 /**
981 * Replace special strings like "ISBN xxx" and "RFC xxx" with
982 * magic external links.
983 *
984 * @private
985 */
986 function doMagicLinks( $text ) {
987 wfProfileIn( __METHOD__ );
988 $text = preg_replace_callback(
989 '!(?: # Start cases
990 <a.*?</a> | # Skip link text
991 <.*?> | # Skip stuff inside HTML elements
992 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
993 ISBN\s+(\b # ISBN, capture number as m[2]
994 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
995 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
996 [0-9Xx] # check digit
997 \b)
998 )!x', array( &$this, 'magicLinkCallback' ), $text );
999 wfProfileOut( __METHOD__ );
1000 return $text;
1001 }
1002
1003 function magicLinkCallback( $m ) {
1004 if ( substr( $m[0], 0, 1 ) == '<' ) {
1005 # Skip HTML element
1006 return $m[0];
1007 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1008 $isbn = $m[2];
1009 $num = strtr( $isbn, array(
1010 '-' => '',
1011 ' ' => '',
1012 'x' => 'X',
1013 ));
1014 $titleObj = SpecialPage::getTitleFor( 'Booksources' );
1015 $text = '<a href="' .
1016 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1017 "\" class=\"internal\">ISBN $isbn</a>";
1018 } else {
1019 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1020 $keyword = 'RFC';
1021 $urlmsg = 'rfcurl';
1022 $id = $m[1];
1023 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1024 $keyword = 'PMID';
1025 $urlmsg = 'pubmedurl';
1026 $id = $m[1];
1027 } else {
1028 throw new MWException( __METHOD__.': unrecognised match type "' .
1029 substr($m[0], 0, 20 ) . '"' );
1030 }
1031
1032 $url = wfMsg( $urlmsg, $id);
1033 $sk = $this->mOptions->getSkin();
1034 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1035 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1036 }
1037 return $text;
1038 }
1039
1040 /**
1041 * Parse headers and return html
1042 *
1043 * @private
1044 */
1045 function doHeadings( $text ) {
1046 $fname = 'Parser::doHeadings';
1047 wfProfileIn( $fname );
1048 for ( $i = 6; $i >= 1; --$i ) {
1049 $h = str_repeat( '=', $i );
1050 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1051 "<h$i>\\1</h$i>", $text );
1052 }
1053 wfProfileOut( $fname );
1054 return $text;
1055 }
1056
1057 /**
1058 * Replace single quotes with HTML markup
1059 * @private
1060 * @return string the altered text
1061 */
1062 function doAllQuotes( $text ) {
1063 $fname = 'Parser::doAllQuotes';
1064 wfProfileIn( $fname );
1065 $outtext = '';
1066 $lines = explode( "\n", $text );
1067 foreach ( $lines as $line ) {
1068 $outtext .= $this->doQuotes ( $line ) . "\n";
1069 }
1070 $outtext = substr($outtext, 0,-1);
1071 wfProfileOut( $fname );
1072 return $outtext;
1073 }
1074
1075 /**
1076 * Helper function for doAllQuotes()
1077 */
1078 public function doQuotes( $text ) {
1079 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1080 if ( count( $arr ) == 1 )
1081 return $text;
1082 else
1083 {
1084 # First, do some preliminary work. This may shift some apostrophes from
1085 # being mark-up to being text. It also counts the number of occurrences
1086 # of bold and italics mark-ups.
1087 $i = 0;
1088 $numbold = 0;
1089 $numitalics = 0;
1090 foreach ( $arr as $r )
1091 {
1092 if ( ( $i % 2 ) == 1 )
1093 {
1094 # If there are ever four apostrophes, assume the first is supposed to
1095 # be text, and the remaining three constitute mark-up for bold text.
1096 if ( strlen( $arr[$i] ) == 4 )
1097 {
1098 $arr[$i-1] .= "'";
1099 $arr[$i] = "'''";
1100 }
1101 # If there are more than 5 apostrophes in a row, assume they're all
1102 # text except for the last 5.
1103 else if ( strlen( $arr[$i] ) > 5 )
1104 {
1105 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1106 $arr[$i] = "'''''";
1107 }
1108 # Count the number of occurrences of bold and italics mark-ups.
1109 # We are not counting sequences of five apostrophes.
1110 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++; }
1111 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++; }
1112 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
1113 }
1114 $i++;
1115 }
1116
1117 # If there is an odd number of both bold and italics, it is likely
1118 # that one of the bold ones was meant to be an apostrophe followed
1119 # by italics. Which one we cannot know for certain, but it is more
1120 # likely to be one that has a single-letter word before it.
1121 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
1122 {
1123 $i = 0;
1124 $firstsingleletterword = -1;
1125 $firstmultiletterword = -1;
1126 $firstspace = -1;
1127 foreach ( $arr as $r )
1128 {
1129 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
1130 {
1131 $x1 = substr ($arr[$i-1], -1);
1132 $x2 = substr ($arr[$i-1], -2, 1);
1133 if ($x1 == ' ') {
1134 if ($firstspace == -1) $firstspace = $i;
1135 } else if ($x2 == ' ') {
1136 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1137 } else {
1138 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1139 }
1140 }
1141 $i++;
1142 }
1143
1144 # If there is a single-letter word, use it!
1145 if ($firstsingleletterword > -1)
1146 {
1147 $arr [ $firstsingleletterword ] = "''";
1148 $arr [ $firstsingleletterword-1 ] .= "'";
1149 }
1150 # If not, but there's a multi-letter word, use that one.
1151 else if ($firstmultiletterword > -1)
1152 {
1153 $arr [ $firstmultiletterword ] = "''";
1154 $arr [ $firstmultiletterword-1 ] .= "'";
1155 }
1156 # ... otherwise use the first one that has neither.
1157 # (notice that it is possible for all three to be -1 if, for example,
1158 # there is only one pentuple-apostrophe in the line)
1159 else if ($firstspace > -1)
1160 {
1161 $arr [ $firstspace ] = "''";
1162 $arr [ $firstspace-1 ] .= "'";
1163 }
1164 }
1165
1166 # Now let's actually convert our apostrophic mush to HTML!
1167 $output = '';
1168 $buffer = '';
1169 $state = '';
1170 $i = 0;
1171 foreach ($arr as $r)
1172 {
1173 if (($i % 2) == 0)
1174 {
1175 if ($state == 'both')
1176 $buffer .= $r;
1177 else
1178 $output .= $r;
1179 }
1180 else
1181 {
1182 if (strlen ($r) == 2)
1183 {
1184 if ($state == 'i')
1185 { $output .= '</i>'; $state = ''; }
1186 else if ($state == 'bi')
1187 { $output .= '</i>'; $state = 'b'; }
1188 else if ($state == 'ib')
1189 { $output .= '</b></i><b>'; $state = 'b'; }
1190 else if ($state == 'both')
1191 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1192 else # $state can be 'b' or ''
1193 { $output .= '<i>'; $state .= 'i'; }
1194 }
1195 else if (strlen ($r) == 3)
1196 {
1197 if ($state == 'b')
1198 { $output .= '</b>'; $state = ''; }
1199 else if ($state == 'bi')
1200 { $output .= '</i></b><i>'; $state = 'i'; }
1201 else if ($state == 'ib')
1202 { $output .= '</b>'; $state = 'i'; }
1203 else if ($state == 'both')
1204 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1205 else # $state can be 'i' or ''
1206 { $output .= '<b>'; $state .= 'b'; }
1207 }
1208 else if (strlen ($r) == 5)
1209 {
1210 if ($state == 'b')
1211 { $output .= '</b><i>'; $state = 'i'; }
1212 else if ($state == 'i')
1213 { $output .= '</i><b>'; $state = 'b'; }
1214 else if ($state == 'bi')
1215 { $output .= '</i></b>'; $state = ''; }
1216 else if ($state == 'ib')
1217 { $output .= '</b></i>'; $state = ''; }
1218 else if ($state == 'both')
1219 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1220 else # ($state == '')
1221 { $buffer = ''; $state = 'both'; }
1222 }
1223 }
1224 $i++;
1225 }
1226 # Now close all remaining tags. Notice that the order is important.
1227 if ($state == 'b' || $state == 'ib')
1228 $output .= '</b>';
1229 if ($state == 'i' || $state == 'bi' || $state == 'ib')
1230 $output .= '</i>';
1231 if ($state == 'bi')
1232 $output .= '</b>';
1233 # There might be lonely ''''', so make sure we have a buffer
1234 if ($state == 'both' && $buffer)
1235 $output .= '<b><i>'.$buffer.'</i></b>';
1236 return $output;
1237 }
1238 }
1239
1240 /**
1241 * Replace external links
1242 *
1243 * Note: this is all very hackish and the order of execution matters a lot.
1244 * Make sure to run maintenance/parserTests.php if you change this code.
1245 *
1246 * @private
1247 */
1248 function replaceExternalLinks( $text ) {
1249 global $wgContLang;
1250 $fname = 'Parser::replaceExternalLinks';
1251 wfProfileIn( $fname );
1252
1253 $sk = $this->mOptions->getSkin();
1254
1255 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1256
1257 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1258
1259 $i = 0;
1260 while ( $i<count( $bits ) ) {
1261 $url = $bits[$i++];
1262 $protocol = $bits[$i++];
1263 $text = $bits[$i++];
1264 $trail = $bits[$i++];
1265
1266 # The characters '<' and '>' (which were escaped by
1267 # removeHTMLtags()) should not be included in
1268 # URLs, per RFC 2396.
1269 $m2 = array();
1270 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1271 $text = substr($url, $m2[0][1]) . ' ' . $text;
1272 $url = substr($url, 0, $m2[0][1]);
1273 }
1274
1275 # If the link text is an image URL, replace it with an <img> tag
1276 # This happened by accident in the original parser, but some people used it extensively
1277 $img = $this->maybeMakeExternalImage( $text );
1278 if ( $img !== false ) {
1279 $text = $img;
1280 }
1281
1282 $dtrail = '';
1283
1284 # Set linktype for CSS - if URL==text, link is essentially free
1285 $linktype = ($text == $url) ? 'free' : 'text';
1286
1287 # No link text, e.g. [http://domain.tld/some.link]
1288 if ( $text == '' ) {
1289 # Autonumber if allowed. See bug #5918
1290 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1291 $text = '[' . ++$this->mAutonumber . ']';
1292 $linktype = 'autonumber';
1293 } else {
1294 # Otherwise just use the URL
1295 $text = htmlspecialchars( $url );
1296 $linktype = 'free';
1297 }
1298 } else {
1299 # Have link text, e.g. [http://domain.tld/some.link text]s
1300 # Check for trail
1301 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1302 }
1303
1304 $text = $wgContLang->markNoConversion($text);
1305
1306 $url = Sanitizer::cleanUrl( $url );
1307
1308 # Process the trail (i.e. everything after this link up until start of the next link),
1309 # replacing any non-bracketed links
1310 $trail = $this->replaceFreeExternalLinks( $trail );
1311
1312 # Use the encoded URL
1313 # This means that users can paste URLs directly into the text
1314 # Funny characters like &ouml; aren't valid in URLs anyway
1315 # This was changed in August 2004
1316 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle->getNamespace() ) . $dtrail . $trail;
1317
1318 # Register link in the output object.
1319 # Replace unnecessary URL escape codes with the referenced character
1320 # This prevents spammers from hiding links from the filters
1321 $pasteurized = Parser::replaceUnusualEscapes( $url );
1322 $this->mOutput->addExternalLink( $pasteurized );
1323 }
1324
1325 wfProfileOut( $fname );
1326 return $s;
1327 }
1328
1329 /**
1330 * Replace anything that looks like a URL with a link
1331 * @private
1332 */
1333 function replaceFreeExternalLinks( $text ) {
1334 global $wgContLang;
1335 $fname = 'Parser::replaceFreeExternalLinks';
1336 wfProfileIn( $fname );
1337
1338 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1339 $s = array_shift( $bits );
1340 $i = 0;
1341
1342 $sk = $this->mOptions->getSkin();
1343
1344 while ( $i < count( $bits ) ){
1345 $protocol = $bits[$i++];
1346 $remainder = $bits[$i++];
1347
1348 $m = array();
1349 if ( preg_match( '/^('.self::EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1350 # Found some characters after the protocol that look promising
1351 $url = $protocol . $m[1];
1352 $trail = $m[2];
1353
1354 # special case: handle urls as url args:
1355 # http://www.example.com/foo?=http://www.example.com/bar
1356 if(strlen($trail) == 0 &&
1357 isset($bits[$i]) &&
1358 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1359 preg_match( '/^('.self::EXT_LINK_URL_CLASS.'+)(.*)$/s', $bits[$i + 1], $m ))
1360 {
1361 # add protocol, arg
1362 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1363 $i += 2;
1364 $trail = $m[2];
1365 }
1366
1367 # The characters '<' and '>' (which were escaped by
1368 # removeHTMLtags()) should not be included in
1369 # URLs, per RFC 2396.
1370 $m2 = array();
1371 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1372 $trail = substr($url, $m2[0][1]) . $trail;
1373 $url = substr($url, 0, $m2[0][1]);
1374 }
1375
1376 # Move trailing punctuation to $trail
1377 $sep = ',;\.:!?';
1378 # If there is no left bracket, then consider right brackets fair game too
1379 if ( strpos( $url, '(' ) === false ) {
1380 $sep .= ')';
1381 }
1382
1383 $numSepChars = strspn( strrev( $url ), $sep );
1384 if ( $numSepChars ) {
1385 $trail = substr( $url, -$numSepChars ) . $trail;
1386 $url = substr( $url, 0, -$numSepChars );
1387 }
1388
1389 $url = Sanitizer::cleanUrl( $url );
1390
1391 # Is this an external image?
1392 $text = $this->maybeMakeExternalImage( $url );
1393 if ( $text === false ) {
1394 # Not an image, make a link
1395 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle->getNamespace() );
1396 # Register it in the output object...
1397 # Replace unnecessary URL escape codes with their equivalent characters
1398 $pasteurized = Parser::replaceUnusualEscapes( $url );
1399 $this->mOutput->addExternalLink( $pasteurized );
1400 }
1401 $s .= $text . $trail;
1402 } else {
1403 $s .= $protocol . $remainder;
1404 }
1405 }
1406 wfProfileOut( $fname );
1407 return $s;
1408 }
1409
1410 /**
1411 * Replace unusual URL escape codes with their equivalent characters
1412 * @param string
1413 * @return string
1414 * @static
1415 * @todo This can merge genuinely required bits in the path or query string,
1416 * breaking legit URLs. A proper fix would treat the various parts of
1417 * the URL differently; as a workaround, just use the output for
1418 * statistical records, not for actual linking/output.
1419 */
1420 static function replaceUnusualEscapes( $url ) {
1421 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1422 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1423 }
1424
1425 /**
1426 * Callback function used in replaceUnusualEscapes().
1427 * Replaces unusual URL escape codes with their equivalent character
1428 * @static
1429 * @private
1430 */
1431 private static function replaceUnusualEscapesCallback( $matches ) {
1432 $char = urldecode( $matches[0] );
1433 $ord = ord( $char );
1434 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1435 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1436 // No, shouldn't be escaped
1437 return $char;
1438 } else {
1439 // Yes, leave it escaped
1440 return $matches[0];
1441 }
1442 }
1443
1444 /**
1445 * make an image if it's allowed, either through the global
1446 * option or through the exception
1447 * @private
1448 */
1449 function maybeMakeExternalImage( $url ) {
1450 $sk = $this->mOptions->getSkin();
1451 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1452 $imagesexception = !empty($imagesfrom);
1453 $text = false;
1454 if ( $this->mOptions->getAllowExternalImages()
1455 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1456 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1457 # Image found
1458 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1459 }
1460 }
1461 return $text;
1462 }
1463
1464 /**
1465 * Process [[ ]] wikilinks
1466 *
1467 * @private
1468 */
1469 function replaceInternalLinks( $s ) {
1470 global $wgContLang;
1471 static $fname = 'Parser::replaceInternalLinks' ;
1472
1473 wfProfileIn( $fname );
1474
1475 wfProfileIn( $fname.'-setup' );
1476 static $tc = FALSE;
1477 # the % is needed to support urlencoded titles as well
1478 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1479
1480 $sk = $this->mOptions->getSkin();
1481
1482 #split the entire text string on occurences of [[
1483 $a = explode( '[[', ' ' . $s );
1484 #get the first element (all text up to first [[), and remove the space we added
1485 $s = array_shift( $a );
1486 $s = substr( $s, 1 );
1487
1488 # Match a link having the form [[namespace:link|alternate]]trail
1489 static $e1 = FALSE;
1490 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1491 # Match cases where there is no "]]", which might still be images
1492 static $e1_img = FALSE;
1493 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1494
1495 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1496 $e2 = null;
1497 if ( $useLinkPrefixExtension ) {
1498 # Match the end of a line for a word that's not followed by whitespace,
1499 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1500 $e2 = wfMsgForContent( 'linkprefix' );
1501 }
1502
1503 if( is_null( $this->mTitle ) ) {
1504 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1505 }
1506 $nottalk = !$this->mTitle->isTalkPage();
1507
1508 if ( $useLinkPrefixExtension ) {
1509 $m = array();
1510 if ( preg_match( $e2, $s, $m ) ) {
1511 $first_prefix = $m[2];
1512 } else {
1513 $first_prefix = false;
1514 }
1515 } else {
1516 $prefix = '';
1517 }
1518
1519 if($wgContLang->hasVariants()) {
1520 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle->getPrefixedText());
1521 } else {
1522 $selflink = array($this->mTitle->getPrefixedText());
1523 }
1524 $useSubpages = $this->areSubpagesAllowed();
1525 wfProfileOut( $fname.'-setup' );
1526
1527 # Loop for each link
1528 for ($k = 0; isset( $a[$k] ); $k++) {
1529 $line = $a[$k];
1530 if ( $useLinkPrefixExtension ) {
1531 wfProfileIn( $fname.'-prefixhandling' );
1532 if ( preg_match( $e2, $s, $m ) ) {
1533 $prefix = $m[2];
1534 $s = $m[1];
1535 } else {
1536 $prefix='';
1537 }
1538 # first link
1539 if($first_prefix) {
1540 $prefix = $first_prefix;
1541 $first_prefix = false;
1542 }
1543 wfProfileOut( $fname.'-prefixhandling' );
1544 }
1545
1546 $might_be_img = false;
1547
1548 wfProfileIn( "$fname-e1" );
1549 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1550 $text = $m[2];
1551 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1552 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1553 # the real problem is with the $e1 regex
1554 # See bug 1300.
1555 #
1556 # Still some problems for cases where the ] is meant to be outside punctuation,
1557 # and no image is in sight. See bug 2095.
1558 #
1559 if( $text !== '' &&
1560 substr( $m[3], 0, 1 ) === ']' &&
1561 strpos($text, '[') !== false
1562 )
1563 {
1564 $text .= ']'; # so that replaceExternalLinks($text) works later
1565 $m[3] = substr( $m[3], 1 );
1566 }
1567 # fix up urlencoded title texts
1568 if( strpos( $m[1], '%' ) !== false ) {
1569 # Should anchors '#' also be rejected?
1570 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1571 }
1572 $trail = $m[3];
1573 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1574 $might_be_img = true;
1575 $text = $m[2];
1576 if ( strpos( $m[1], '%' ) !== false ) {
1577 $m[1] = urldecode($m[1]);
1578 }
1579 $trail = "";
1580 } else { # Invalid form; output directly
1581 $s .= $prefix . '[[' . $line ;
1582 wfProfileOut( "$fname-e1" );
1583 continue;
1584 }
1585 wfProfileOut( "$fname-e1" );
1586 wfProfileIn( "$fname-misc" );
1587
1588 # Don't allow internal links to pages containing
1589 # PROTO: where PROTO is a valid URL protocol; these
1590 # should be external links.
1591 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1592 $s .= $prefix . '[[' . $line ;
1593 continue;
1594 }
1595
1596 # Make subpage if necessary
1597 if( $useSubpages ) {
1598 $link = $this->maybeDoSubpageLink( $m[1], $text );
1599 } else {
1600 $link = $m[1];
1601 }
1602
1603 $noforce = (substr($m[1], 0, 1) != ':');
1604 if (!$noforce) {
1605 # Strip off leading ':'
1606 $link = substr($link, 1);
1607 }
1608
1609 wfProfileOut( "$fname-misc" );
1610 wfProfileIn( "$fname-title" );
1611 $nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) );
1612 if( !$nt ) {
1613 $s .= $prefix . '[[' . $line;
1614 wfProfileOut( "$fname-title" );
1615 continue;
1616 }
1617
1618 $ns = $nt->getNamespace();
1619 $iw = $nt->getInterWiki();
1620 wfProfileOut( "$fname-title" );
1621
1622 if ($might_be_img) { # if this is actually an invalid link
1623 wfProfileIn( "$fname-might_be_img" );
1624 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1625 $found = false;
1626 while (isset ($a[$k+1]) ) {
1627 #look at the next 'line' to see if we can close it there
1628 $spliced = array_splice( $a, $k + 1, 1 );
1629 $next_line = array_shift( $spliced );
1630 $m = explode( ']]', $next_line, 3 );
1631 if ( count( $m ) == 3 ) {
1632 # the first ]] closes the inner link, the second the image
1633 $found = true;
1634 $text .= "[[{$m[0]}]]{$m[1]}";
1635 $trail = $m[2];
1636 break;
1637 } elseif ( count( $m ) == 2 ) {
1638 #if there's exactly one ]] that's fine, we'll keep looking
1639 $text .= "[[{$m[0]}]]{$m[1]}";
1640 } else {
1641 #if $next_line is invalid too, we need look no further
1642 $text .= '[[' . $next_line;
1643 break;
1644 }
1645 }
1646 if ( !$found ) {
1647 # we couldn't find the end of this imageLink, so output it raw
1648 #but don't ignore what might be perfectly normal links in the text we've examined
1649 $text = $this->replaceInternalLinks($text);
1650 $s .= "{$prefix}[[$link|$text";
1651 # note: no $trail, because without an end, there *is* no trail
1652 wfProfileOut( "$fname-might_be_img" );
1653 continue;
1654 }
1655 } else { #it's not an image, so output it raw
1656 $s .= "{$prefix}[[$link|$text";
1657 # note: no $trail, because without an end, there *is* no trail
1658 wfProfileOut( "$fname-might_be_img" );
1659 continue;
1660 }
1661 wfProfileOut( "$fname-might_be_img" );
1662 }
1663
1664 $wasblank = ( '' == $text );
1665 if( $wasblank ) $text = $link;
1666
1667 # Link not escaped by : , create the various objects
1668 if( $noforce ) {
1669
1670 # Interwikis
1671 wfProfileIn( "$fname-interwiki" );
1672 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1673 $this->mOutput->addLanguageLink( $nt->getFullText() );
1674 $s = rtrim($s . $prefix);
1675 $s .= trim($trail, "\n") == '' ? '': $prefix . $trail;
1676 wfProfileOut( "$fname-interwiki" );
1677 continue;
1678 }
1679 wfProfileOut( "$fname-interwiki" );
1680
1681 if ( $ns == NS_IMAGE ) {
1682 wfProfileIn( "$fname-image" );
1683 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1684 # recursively parse links inside the image caption
1685 # actually, this will parse them in any other parameters, too,
1686 # but it might be hard to fix that, and it doesn't matter ATM
1687 $text = $this->replaceExternalLinks($text);
1688 $text = $this->replaceInternalLinks($text);
1689
1690 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1691 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1692 $this->mOutput->addImage( $nt->getDBkey() );
1693
1694 wfProfileOut( "$fname-image" );
1695 continue;
1696 } else {
1697 # We still need to record the image's presence on the page
1698 $this->mOutput->addImage( $nt->getDBkey() );
1699 }
1700 wfProfileOut( "$fname-image" );
1701
1702 }
1703
1704 if ( $ns == NS_CATEGORY ) {
1705 wfProfileIn( "$fname-category" );
1706 $s = rtrim($s . "\n"); # bug 87
1707
1708 if ( $wasblank ) {
1709 $sortkey = $this->getDefaultSort();
1710 } else {
1711 $sortkey = $text;
1712 }
1713 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1714 $sortkey = str_replace( "\n", '', $sortkey );
1715 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1716 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1717
1718 /**
1719 * Strip the whitespace Category links produce, see bug 87
1720 * @todo We might want to use trim($tmp, "\n") here.
1721 */
1722 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1723
1724 wfProfileOut( "$fname-category" );
1725 continue;
1726 }
1727 }
1728
1729 # Self-link checking
1730 if( $nt->getFragment() === '' ) {
1731 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1732 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1733 continue;
1734 }
1735 }
1736
1737 # Special and Media are pseudo-namespaces; no pages actually exist in them
1738 if( $ns == NS_MEDIA ) {
1739 $link = $sk->makeMediaLinkObj( $nt, $text );
1740 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1741 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1742 $this->mOutput->addImage( $nt->getDBkey() );
1743 continue;
1744 } elseif( $ns == NS_SPECIAL ) {
1745 if( SpecialPage::exists( $nt->getDBkey() ) ) {
1746 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1747 } else {
1748 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1749 }
1750 continue;
1751 } elseif( $ns == NS_IMAGE ) {
1752 $img = wfFindFile( $nt );
1753 if( $img ) {
1754 // Force a blue link if the file exists; may be a remote
1755 // upload on the shared repository, and we want to see its
1756 // auto-generated page.
1757 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1758 $this->mOutput->addLink( $nt );
1759 continue;
1760 }
1761 }
1762 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1763 }
1764 wfProfileOut( $fname );
1765 return $s;
1766 }
1767
1768 /**
1769 * Make a link placeholder. The text returned can be later resolved to a real link with
1770 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1771 * parsing of interwiki links, and secondly to allow all existence checks and
1772 * article length checks (for stub links) to be bundled into a single query.
1773 *
1774 */
1775 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1776 wfProfileIn( __METHOD__ );
1777 if ( ! is_object($nt) ) {
1778 # Fail gracefully
1779 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1780 } else {
1781 # Separate the link trail from the rest of the link
1782 list( $inside, $trail ) = Linker::splitTrail( $trail );
1783
1784 if ( $nt->isExternal() ) {
1785 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1786 $this->mInterwikiLinkHolders['titles'][] = $nt;
1787 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1788 } else {
1789 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1790 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1791 $this->mLinkHolders['queries'][] = $query;
1792 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1793 $this->mLinkHolders['titles'][] = $nt;
1794
1795 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1796 }
1797 }
1798 wfProfileOut( __METHOD__ );
1799 return $retVal;
1800 }
1801
1802 /**
1803 * Render a forced-blue link inline; protect against double expansion of
1804 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1805 * Since this little disaster has to split off the trail text to avoid
1806 * breaking URLs in the following text without breaking trails on the
1807 * wiki links, it's been made into a horrible function.
1808 *
1809 * @param Title $nt
1810 * @param string $text
1811 * @param string $query
1812 * @param string $trail
1813 * @param string $prefix
1814 * @return string HTML-wikitext mix oh yuck
1815 */
1816 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1817 list( $inside, $trail ) = Linker::splitTrail( $trail );
1818 $sk = $this->mOptions->getSkin();
1819 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1820 return $this->armorLinks( $link ) . $trail;
1821 }
1822
1823 /**
1824 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1825 * going to go through further parsing steps before inline URL expansion.
1826 *
1827 * In particular this is important when using action=render, which causes
1828 * full URLs to be included.
1829 *
1830 * Oh man I hate our multi-layer parser!
1831 *
1832 * @param string more-or-less HTML
1833 * @return string less-or-more HTML with NOPARSE bits
1834 */
1835 function armorLinks( $text ) {
1836 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1837 "{$this->mUniqPrefix}NOPARSE$1", $text );
1838 }
1839
1840 /**
1841 * Return true if subpage links should be expanded on this page.
1842 * @return bool
1843 */
1844 function areSubpagesAllowed() {
1845 # Some namespaces don't allow subpages
1846 global $wgNamespacesWithSubpages;
1847 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1848 }
1849
1850 /**
1851 * Handle link to subpage if necessary
1852 * @param string $target the source of the link
1853 * @param string &$text the link text, modified as necessary
1854 * @return string the full name of the link
1855 * @private
1856 */
1857 function maybeDoSubpageLink($target, &$text) {
1858 # Valid link forms:
1859 # Foobar -- normal
1860 # :Foobar -- override special treatment of prefix (images, language links)
1861 # /Foobar -- convert to CurrentPage/Foobar
1862 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1863 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1864 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1865
1866 $fname = 'Parser::maybeDoSubpageLink';
1867 wfProfileIn( $fname );
1868 $ret = $target; # default return value is no change
1869
1870 # Some namespaces don't allow subpages,
1871 # so only perform processing if subpages are allowed
1872 if( $this->areSubpagesAllowed() ) {
1873 $hash = strpos( $target, '#' );
1874 if( $hash !== false ) {
1875 $suffix = substr( $target, $hash );
1876 $target = substr( $target, 0, $hash );
1877 } else {
1878 $suffix = '';
1879 }
1880 # bug 7425
1881 $target = trim( $target );
1882 # Look at the first character
1883 if( $target != '' && $target{0} == '/' ) {
1884 # / at end means we don't want the slash to be shown
1885 $m = array();
1886 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1887 if( $trailingSlashes ) {
1888 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1889 } else {
1890 $noslash = substr( $target, 1 );
1891 }
1892
1893 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash) . $suffix;
1894 if( '' === $text ) {
1895 $text = $target . $suffix;
1896 } # this might be changed for ugliness reasons
1897 } else {
1898 # check for .. subpage backlinks
1899 $dotdotcount = 0;
1900 $nodotdot = $target;
1901 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1902 ++$dotdotcount;
1903 $nodotdot = substr( $nodotdot, 3 );
1904 }
1905 if($dotdotcount > 0) {
1906 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1907 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1908 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1909 # / at the end means don't show full path
1910 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1911 $nodotdot = substr( $nodotdot, 0, -1 );
1912 if( '' === $text ) {
1913 $text = $nodotdot . $suffix;
1914 }
1915 }
1916 $nodotdot = trim( $nodotdot );
1917 if( $nodotdot != '' ) {
1918 $ret .= '/' . $nodotdot;
1919 }
1920 $ret .= $suffix;
1921 }
1922 }
1923 }
1924 }
1925
1926 wfProfileOut( $fname );
1927 return $ret;
1928 }
1929
1930 /**#@+
1931 * Used by doBlockLevels()
1932 * @private
1933 */
1934 /* private */ function closeParagraph() {
1935 $result = '';
1936 if ( '' != $this->mLastSection ) {
1937 $result = '</' . $this->mLastSection . ">\n";
1938 }
1939 $this->mInPre = false;
1940 $this->mLastSection = '';
1941 return $result;
1942 }
1943 # getCommon() returns the length of the longest common substring
1944 # of both arguments, starting at the beginning of both.
1945 #
1946 /* private */ function getCommon( $st1, $st2 ) {
1947 $fl = strlen( $st1 );
1948 $shorter = strlen( $st2 );
1949 if ( $fl < $shorter ) { $shorter = $fl; }
1950
1951 for ( $i = 0; $i < $shorter; ++$i ) {
1952 if ( $st1{$i} != $st2{$i} ) { break; }
1953 }
1954 return $i;
1955 }
1956 # These next three functions open, continue, and close the list
1957 # element appropriate to the prefix character passed into them.
1958 #
1959 /* private */ function openList( $char ) {
1960 $result = $this->closeParagraph();
1961
1962 if ( '*' == $char ) { $result .= '<ul><li>'; }
1963 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1964 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1965 else if ( ';' == $char ) {
1966 $result .= '<dl><dt>';
1967 $this->mDTopen = true;
1968 }
1969 else { $result = '<!-- ERR 1 -->'; }
1970
1971 return $result;
1972 }
1973
1974 /* private */ function nextItem( $char ) {
1975 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1976 else if ( ':' == $char || ';' == $char ) {
1977 $close = '</dd>';
1978 if ( $this->mDTopen ) { $close = '</dt>'; }
1979 if ( ';' == $char ) {
1980 $this->mDTopen = true;
1981 return $close . '<dt>';
1982 } else {
1983 $this->mDTopen = false;
1984 return $close . '<dd>';
1985 }
1986 }
1987 return '<!-- ERR 2 -->';
1988 }
1989
1990 /* private */ function closeList( $char ) {
1991 if ( '*' == $char ) { $text = '</li></ul>'; }
1992 else if ( '#' == $char ) { $text = '</li></ol>'; }
1993 else if ( ':' == $char ) {
1994 if ( $this->mDTopen ) {
1995 $this->mDTopen = false;
1996 $text = '</dt></dl>';
1997 } else {
1998 $text = '</dd></dl>';
1999 }
2000 }
2001 else { return '<!-- ERR 3 -->'; }
2002 return $text."\n";
2003 }
2004 /**#@-*/
2005
2006 /**
2007 * Make lists from lines starting with ':', '*', '#', etc.
2008 *
2009 * @private
2010 * @return string the lists rendered as HTML
2011 */
2012 function doBlockLevels( $text, $linestart ) {
2013 $fname = 'Parser::doBlockLevels';
2014 wfProfileIn( $fname );
2015
2016 # Parsing through the text line by line. The main thing
2017 # happening here is handling of block-level elements p, pre,
2018 # and making lists from lines starting with * # : etc.
2019 #
2020 $textLines = explode( "\n", $text );
2021
2022 $lastPrefix = $output = '';
2023 $this->mDTopen = $inBlockElem = false;
2024 $prefixLength = 0;
2025 $paragraphStack = false;
2026
2027 if ( !$linestart ) {
2028 $output .= array_shift( $textLines );
2029 }
2030 foreach ( $textLines as $oLine ) {
2031 $lastPrefixLength = strlen( $lastPrefix );
2032 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2033 $preOpenMatch = preg_match('/<pre/i', $oLine );
2034 if ( !$this->mInPre ) {
2035 # Multiple prefixes may abut each other for nested lists.
2036 $prefixLength = strspn( $oLine, '*#:;' );
2037 $pref = substr( $oLine, 0, $prefixLength );
2038
2039 # eh?
2040 $pref2 = str_replace( ';', ':', $pref );
2041 $t = substr( $oLine, $prefixLength );
2042 $this->mInPre = !empty($preOpenMatch);
2043 } else {
2044 # Don't interpret any other prefixes in preformatted text
2045 $prefixLength = 0;
2046 $pref = $pref2 = '';
2047 $t = $oLine;
2048 }
2049
2050 # List generation
2051 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2052 # Same as the last item, so no need to deal with nesting or opening stuff
2053 $output .= $this->nextItem( substr( $pref, -1 ) );
2054 $paragraphStack = false;
2055
2056 if ( substr( $pref, -1 ) == ';') {
2057 # The one nasty exception: definition lists work like this:
2058 # ; title : definition text
2059 # So we check for : in the remainder text to split up the
2060 # title and definition, without b0rking links.
2061 $term = $t2 = '';
2062 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2063 $t = $t2;
2064 $output .= $term . $this->nextItem( ':' );
2065 }
2066 }
2067 } elseif( $prefixLength || $lastPrefixLength ) {
2068 # Either open or close a level...
2069 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2070 $paragraphStack = false;
2071
2072 while( $commonPrefixLength < $lastPrefixLength ) {
2073 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2074 --$lastPrefixLength;
2075 }
2076 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2077 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2078 }
2079 while ( $prefixLength > $commonPrefixLength ) {
2080 $char = substr( $pref, $commonPrefixLength, 1 );
2081 $output .= $this->openList( $char );
2082
2083 if ( ';' == $char ) {
2084 # FIXME: This is dupe of code above
2085 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2086 $t = $t2;
2087 $output .= $term . $this->nextItem( ':' );
2088 }
2089 }
2090 ++$commonPrefixLength;
2091 }
2092 $lastPrefix = $pref2;
2093 }
2094 if( 0 == $prefixLength ) {
2095 wfProfileIn( "$fname-paragraph" );
2096 # No prefix (not in list)--go to paragraph mode
2097 // XXX: use a stack for nestable elements like span, table and div
2098 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2099 $closematch = preg_match(
2100 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2101 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2102 if ( $openmatch or $closematch ) {
2103 $paragraphStack = false;
2104 # TODO bug 5718: paragraph closed
2105 $output .= $this->closeParagraph();
2106 if ( $preOpenMatch and !$preCloseMatch ) {
2107 $this->mInPre = true;
2108 }
2109 if ( $closematch ) {
2110 $inBlockElem = false;
2111 } else {
2112 $inBlockElem = true;
2113 }
2114 } else if ( !$inBlockElem && !$this->mInPre ) {
2115 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
2116 // pre
2117 if ($this->mLastSection != 'pre') {
2118 $paragraphStack = false;
2119 $output .= $this->closeParagraph().'<pre>';
2120 $this->mLastSection = 'pre';
2121 }
2122 $t = substr( $t, 1 );
2123 } else {
2124 // paragraph
2125 if ( '' == trim($t) ) {
2126 if ( $paragraphStack ) {
2127 $output .= $paragraphStack.'<br />';
2128 $paragraphStack = false;
2129 $this->mLastSection = 'p';
2130 } else {
2131 if ($this->mLastSection != 'p' ) {
2132 $output .= $this->closeParagraph();
2133 $this->mLastSection = '';
2134 $paragraphStack = '<p>';
2135 } else {
2136 $paragraphStack = '</p><p>';
2137 }
2138 }
2139 } else {
2140 if ( $paragraphStack ) {
2141 $output .= $paragraphStack;
2142 $paragraphStack = false;
2143 $this->mLastSection = 'p';
2144 } else if ($this->mLastSection != 'p') {
2145 $output .= $this->closeParagraph().'<p>';
2146 $this->mLastSection = 'p';
2147 }
2148 }
2149 }
2150 }
2151 wfProfileOut( "$fname-paragraph" );
2152 }
2153 // somewhere above we forget to get out of pre block (bug 785)
2154 if($preCloseMatch && $this->mInPre) {
2155 $this->mInPre = false;
2156 }
2157 if ($paragraphStack === false) {
2158 $output .= $t."\n";
2159 }
2160 }
2161 while ( $prefixLength ) {
2162 $output .= $this->closeList( $pref2{$prefixLength-1} );
2163 --$prefixLength;
2164 }
2165 if ( '' != $this->mLastSection ) {
2166 $output .= '</' . $this->mLastSection . '>';
2167 $this->mLastSection = '';
2168 }
2169
2170 wfProfileOut( $fname );
2171 return $output;
2172 }
2173
2174 /**
2175 * Split up a string on ':', ignoring any occurences inside tags
2176 * to prevent illegal overlapping.
2177 * @param string $str the string to split
2178 * @param string &$before set to everything before the ':'
2179 * @param string &$after set to everything after the ':'
2180 * return string the position of the ':', or false if none found
2181 */
2182 function findColonNoLinks($str, &$before, &$after) {
2183 $fname = 'Parser::findColonNoLinks';
2184 wfProfileIn( $fname );
2185
2186 $pos = strpos( $str, ':' );
2187 if( $pos === false ) {
2188 // Nothing to find!
2189 wfProfileOut( $fname );
2190 return false;
2191 }
2192
2193 $lt = strpos( $str, '<' );
2194 if( $lt === false || $lt > $pos ) {
2195 // Easy; no tag nesting to worry about
2196 $before = substr( $str, 0, $pos );
2197 $after = substr( $str, $pos+1 );
2198 wfProfileOut( $fname );
2199 return $pos;
2200 }
2201
2202 // Ugly state machine to walk through avoiding tags.
2203 $state = self::COLON_STATE_TEXT;
2204 $stack = 0;
2205 $len = strlen( $str );
2206 for( $i = 0; $i < $len; $i++ ) {
2207 $c = $str{$i};
2208
2209 switch( $state ) {
2210 // (Using the number is a performance hack for common cases)
2211 case 0: // self::COLON_STATE_TEXT:
2212 switch( $c ) {
2213 case "<":
2214 // Could be either a <start> tag or an </end> tag
2215 $state = self::COLON_STATE_TAGSTART;
2216 break;
2217 case ":":
2218 if( $stack == 0 ) {
2219 // We found it!
2220 $before = substr( $str, 0, $i );
2221 $after = substr( $str, $i + 1 );
2222 wfProfileOut( $fname );
2223 return $i;
2224 }
2225 // Embedded in a tag; don't break it.
2226 break;
2227 default:
2228 // Skip ahead looking for something interesting
2229 $colon = strpos( $str, ':', $i );
2230 if( $colon === false ) {
2231 // Nothing else interesting
2232 wfProfileOut( $fname );
2233 return false;
2234 }
2235 $lt = strpos( $str, '<', $i );
2236 if( $stack === 0 ) {
2237 if( $lt === false || $colon < $lt ) {
2238 // We found it!
2239 $before = substr( $str, 0, $colon );
2240 $after = substr( $str, $colon + 1 );
2241 wfProfileOut( $fname );
2242 return $i;
2243 }
2244 }
2245 if( $lt === false ) {
2246 // Nothing else interesting to find; abort!
2247 // We're nested, but there's no close tags left. Abort!
2248 break 2;
2249 }
2250 // Skip ahead to next tag start
2251 $i = $lt;
2252 $state = self::COLON_STATE_TAGSTART;
2253 }
2254 break;
2255 case 1: // self::COLON_STATE_TAG:
2256 // In a <tag>
2257 switch( $c ) {
2258 case ">":
2259 $stack++;
2260 $state = self::COLON_STATE_TEXT;
2261 break;
2262 case "/":
2263 // Slash may be followed by >?
2264 $state = self::COLON_STATE_TAGSLASH;
2265 break;
2266 default:
2267 // ignore
2268 }
2269 break;
2270 case 2: // self::COLON_STATE_TAGSTART:
2271 switch( $c ) {
2272 case "/":
2273 $state = self::COLON_STATE_CLOSETAG;
2274 break;
2275 case "!":
2276 $state = self::COLON_STATE_COMMENT;
2277 break;
2278 case ">":
2279 // Illegal early close? This shouldn't happen D:
2280 $state = self::COLON_STATE_TEXT;
2281 break;
2282 default:
2283 $state = self::COLON_STATE_TAG;
2284 }
2285 break;
2286 case 3: // self::COLON_STATE_CLOSETAG:
2287 // In a </tag>
2288 if( $c == ">" ) {
2289 $stack--;
2290 if( $stack < 0 ) {
2291 wfDebug( "Invalid input in $fname; too many close tags\n" );
2292 wfProfileOut( $fname );
2293 return false;
2294 }
2295 $state = self::COLON_STATE_TEXT;
2296 }
2297 break;
2298 case self::COLON_STATE_TAGSLASH:
2299 if( $c == ">" ) {
2300 // Yes, a self-closed tag <blah/>
2301 $state = self::COLON_STATE_TEXT;
2302 } else {
2303 // Probably we're jumping the gun, and this is an attribute
2304 $state = self::COLON_STATE_TAG;
2305 }
2306 break;
2307 case 5: // self::COLON_STATE_COMMENT:
2308 if( $c == "-" ) {
2309 $state = self::COLON_STATE_COMMENTDASH;
2310 }
2311 break;
2312 case self::COLON_STATE_COMMENTDASH:
2313 if( $c == "-" ) {
2314 $state = self::COLON_STATE_COMMENTDASHDASH;
2315 } else {
2316 $state = self::COLON_STATE_COMMENT;
2317 }
2318 break;
2319 case self::COLON_STATE_COMMENTDASHDASH:
2320 if( $c == ">" ) {
2321 $state = self::COLON_STATE_TEXT;
2322 } else {
2323 $state = self::COLON_STATE_COMMENT;
2324 }
2325 break;
2326 default:
2327 throw new MWException( "State machine error in $fname" );
2328 }
2329 }
2330 if( $stack > 0 ) {
2331 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2332 return false;
2333 }
2334 wfProfileOut( $fname );
2335 return false;
2336 }
2337
2338 /**
2339 * Return value of a magic variable (like PAGENAME)
2340 *
2341 * @private
2342 */
2343 function getVariableValue( $index ) {
2344 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2345
2346 /**
2347 * Some of these require message or data lookups and can be
2348 * expensive to check many times.
2349 */
2350 static $varCache = array();
2351 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2352 if ( isset( $varCache[$index] ) ) {
2353 return $varCache[$index];
2354 }
2355 }
2356
2357 $ts = time();
2358 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2359
2360 # Use the time zone
2361 global $wgLocaltimezone;
2362 if ( isset( $wgLocaltimezone ) ) {
2363 $oldtz = getenv( 'TZ' );
2364 putenv( 'TZ='.$wgLocaltimezone );
2365 }
2366
2367 wfSuppressWarnings(); // E_STRICT system time bitching
2368 $localTimestamp = date( 'YmdHis', $ts );
2369 $localMonth = date( 'm', $ts );
2370 $localMonthName = date( 'n', $ts );
2371 $localDay = date( 'j', $ts );
2372 $localDay2 = date( 'd', $ts );
2373 $localDayOfWeek = date( 'w', $ts );
2374 $localWeek = date( 'W', $ts );
2375 $localYear = date( 'Y', $ts );
2376 $localHour = date( 'H', $ts );
2377 if ( isset( $wgLocaltimezone ) ) {
2378 putenv( 'TZ='.$oldtz );
2379 }
2380 wfRestoreWarnings();
2381
2382 switch ( $index ) {
2383 case 'currentmonth':
2384 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2385 case 'currentmonthname':
2386 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2387 case 'currentmonthnamegen':
2388 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2389 case 'currentmonthabbrev':
2390 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2391 case 'currentday':
2392 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2393 case 'currentday2':
2394 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2395 case 'localmonth':
2396 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2397 case 'localmonthname':
2398 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2399 case 'localmonthnamegen':
2400 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2401 case 'localmonthabbrev':
2402 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2403 case 'localday':
2404 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2405 case 'localday2':
2406 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2407 case 'pagename':
2408 return wfEscapeWikiText( $this->mTitle->getText() );
2409 case 'pagenamee':
2410 return $this->mTitle->getPartialURL();
2411 case 'fullpagename':
2412 return wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2413 case 'fullpagenamee':
2414 return $this->mTitle->getPrefixedURL();
2415 case 'subpagename':
2416 return wfEscapeWikiText( $this->mTitle->getSubpageText() );
2417 case 'subpagenamee':
2418 return $this->mTitle->getSubpageUrlForm();
2419 case 'basepagename':
2420 return wfEscapeWikiText( $this->mTitle->getBaseText() );
2421 case 'basepagenamee':
2422 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2423 case 'talkpagename':
2424 if( $this->mTitle->canTalk() ) {
2425 $talkPage = $this->mTitle->getTalkPage();
2426 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2427 } else {
2428 return '';
2429 }
2430 case 'talkpagenamee':
2431 if( $this->mTitle->canTalk() ) {
2432 $talkPage = $this->mTitle->getTalkPage();
2433 return $talkPage->getPrefixedUrl();
2434 } else {
2435 return '';
2436 }
2437 case 'subjectpagename':
2438 $subjPage = $this->mTitle->getSubjectPage();
2439 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2440 case 'subjectpagenamee':
2441 $subjPage = $this->mTitle->getSubjectPage();
2442 return $subjPage->getPrefixedUrl();
2443 case 'revisionid':
2444 // Let the edit saving system know we should parse the page
2445 // *after* a revision ID has been assigned.
2446 $this->mOutput->setFlag( 'vary-revision' );
2447 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2448 return $this->mRevisionId;
2449 case 'revisionday':
2450 // Let the edit saving system know we should parse the page
2451 // *after* a revision ID has been assigned. This is for null edits.
2452 $this->mOutput->setFlag( 'vary-revision' );
2453 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2454 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2455 case 'revisionday2':
2456 // Let the edit saving system know we should parse the page
2457 // *after* a revision ID has been assigned. This is for null edits.
2458 $this->mOutput->setFlag( 'vary-revision' );
2459 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2460 return substr( $this->getRevisionTimestamp(), 6, 2 );
2461 case 'revisionmonth':
2462 // Let the edit saving system know we should parse the page
2463 // *after* a revision ID has been assigned. This is for null edits.
2464 $this->mOutput->setFlag( 'vary-revision' );
2465 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2466 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2467 case 'revisionyear':
2468 // Let the edit saving system know we should parse the page
2469 // *after* a revision ID has been assigned. This is for null edits.
2470 $this->mOutput->setFlag( 'vary-revision' );
2471 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2472 return substr( $this->getRevisionTimestamp(), 0, 4 );
2473 case 'revisiontimestamp':
2474 // Let the edit saving system know we should parse the page
2475 // *after* a revision ID has been assigned. This is for null edits.
2476 $this->mOutput->setFlag( 'vary-revision' );
2477 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2478 return $this->getRevisionTimestamp();
2479 case 'namespace':
2480 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2481 case 'namespacee':
2482 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2483 case 'talkspace':
2484 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2485 case 'talkspacee':
2486 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2487 case 'subjectspace':
2488 return $this->mTitle->getSubjectNsText();
2489 case 'subjectspacee':
2490 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2491 case 'currentdayname':
2492 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2493 case 'currentyear':
2494 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2495 case 'currenttime':
2496 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2497 case 'currenthour':
2498 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2499 case 'currentweek':
2500 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2501 // int to remove the padding
2502 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2503 case 'currentdow':
2504 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2505 case 'localdayname':
2506 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2507 case 'localyear':
2508 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2509 case 'localtime':
2510 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2511 case 'localhour':
2512 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2513 case 'localweek':
2514 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2515 // int to remove the padding
2516 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2517 case 'localdow':
2518 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2519 case 'numberofarticles':
2520 return $varCache[$index] = $wgContLang->formatNum( SiteStats::articles() );
2521 case 'numberoffiles':
2522 return $varCache[$index] = $wgContLang->formatNum( SiteStats::images() );
2523 case 'numberofusers':
2524 return $varCache[$index] = $wgContLang->formatNum( SiteStats::users() );
2525 case 'numberofpages':
2526 return $varCache[$index] = $wgContLang->formatNum( SiteStats::pages() );
2527 case 'numberofadmins':
2528 return $varCache[$index] = $wgContLang->formatNum( SiteStats::admins() );
2529 case 'numberofedits':
2530 return $varCache[$index] = $wgContLang->formatNum( SiteStats::edits() );
2531 case 'currenttimestamp':
2532 return $varCache[$index] = wfTimestampNow();
2533 case 'localtimestamp':
2534 return $varCache[$index] = $localTimestamp;
2535 case 'currentversion':
2536 return $varCache[$index] = SpecialVersion::getVersion();
2537 case 'sitename':
2538 return $wgSitename;
2539 case 'server':
2540 return $wgServer;
2541 case 'servername':
2542 return $wgServerName;
2543 case 'scriptpath':
2544 return $wgScriptPath;
2545 case 'directionmark':
2546 return $wgContLang->getDirMark();
2547 case 'contentlanguage':
2548 global $wgContLanguageCode;
2549 return $wgContLanguageCode;
2550 default:
2551 $ret = null;
2552 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2553 return $ret;
2554 else
2555 return null;
2556 }
2557 }
2558
2559 /**
2560 * initialise the magic variables (like CURRENTMONTHNAME)
2561 *
2562 * @private
2563 */
2564 function initialiseVariables() {
2565 $fname = 'Parser::initialiseVariables';
2566 wfProfileIn( $fname );
2567 $variableIDs = MagicWord::getVariableIDs();
2568
2569 $this->mVariables = new MagicWordArray( $variableIDs );
2570 wfProfileOut( $fname );
2571 }
2572
2573 /**
2574 * Preprocess some wikitext and return the document tree.
2575 * This is the ghost of replace_variables().
2576 *
2577 * @param string $text The text to parse
2578 * @param integer flags Bitwise combination of:
2579 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2580 * included. Default is to assume a direct page view.
2581 *
2582 * The generated DOM tree must depend only on the input text, the flags, and $this->ot['msg'].
2583 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2584 *
2585 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2586 * change in the DOM tree for a given text, must be passed through the section identifier
2587 * in the section edit link and thus back to extractSections().
2588 *
2589 * The output of this function is currently only cached in process memory, but a persistent
2590 * cache may be implemented at a later date which takes further advantage of these strict
2591 * dependency requirements.
2592 *
2593 * @private
2594 */
2595 function preprocessToDom ( $text, $flags = 0 ) {
2596 wfProfileIn( __METHOD__ );
2597 wfProfileIn( __METHOD__.'-makexml' );
2598
2599 static $msgRules, $normalRules, $inclusionSupertags, $nonInclusionSupertags;
2600 if ( !$msgRules ) {
2601 $msgRules = array(
2602 '{' => array(
2603 'end' => '}',
2604 'names' => array(
2605 2 => 'template',
2606 ),
2607 'min' => 2,
2608 'max' => 2,
2609 ),
2610 '[' => array(
2611 'end' => ']',
2612 'names' => array( 2 => null ),
2613 'min' => 2,
2614 'max' => 2,
2615 )
2616 );
2617 $normalRules = array(
2618 '{' => array(
2619 'end' => '}',
2620 'names' => array(
2621 2 => 'template',
2622 3 => 'tplarg',
2623 ),
2624 'min' => 2,
2625 'max' => 3,
2626 ),
2627 '[' => array(
2628 'end' => ']',
2629 'names' => array( 2 => null ),
2630 'min' => 2,
2631 'max' => 2,
2632 )
2633 );
2634 }
2635 if ( $this->ot['msg'] ) {
2636 $rules = $msgRules;
2637 } else {
2638 $rules = $normalRules;
2639 }
2640 $forInclusion = $flags & self::PTD_FOR_INCLUSION;
2641
2642 $xmlishElements = $this->getStripList();
2643 $enableOnlyinclude = false;
2644 if ( $forInclusion ) {
2645 $ignoredTags = array( 'includeonly', '/includeonly' );
2646 $ignoredElements = array( 'noinclude' );
2647 $xmlishElements[] = 'noinclude';
2648 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
2649 $enableOnlyinclude = true;
2650 }
2651 } else {
2652 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
2653 $ignoredElements = array( 'includeonly' );
2654 $xmlishElements[] = 'includeonly';
2655 }
2656 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
2657
2658 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
2659 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
2660
2661 $stack = new PPDStack;
2662
2663 $searchBase = implode( '', array_keys( $rules ) ) . '<';
2664 $revText = strrev( $text ); // For fast reverse searches
2665
2666 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
2667 $accum =& $stack->getAccum(); # Current text accumulator
2668 $accum = '<root>';
2669 $findEquals = false; # True to find equals signs in arguments
2670 $findPipe = false; # True to take notice of pipe characters
2671 $headingIndex = 1;
2672 $inHeading = false; # True if $i is inside a possible heading
2673 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
2674 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
2675 $fakeLineStart = true; # Do a line-start run without outputting an LF character
2676
2677 while ( true ) {
2678 if ( $findOnlyinclude ) {
2679 // Ignore all input up to the next <onlyinclude>
2680 $startPos = strpos( $text, '<onlyinclude>', $i );
2681 if ( $startPos === false ) {
2682 // Ignored section runs to the end
2683 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
2684 break;
2685 }
2686 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
2687 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
2688 $i = $tagEndPos;
2689 $findOnlyinclude = false;
2690 }
2691
2692 if ( $fakeLineStart ) {
2693 $found = 'line-start';
2694 $curChar = '';
2695 } else {
2696 # Find next opening brace, closing brace or pipe
2697 $search = $searchBase;
2698 if ( $stack->top === false ) {
2699 $currentClosing = '';
2700 } else {
2701 $currentClosing = $stack->top->close;
2702 $search .= $currentClosing;
2703 }
2704 if ( $findPipe ) {
2705 $search .= '|';
2706 }
2707 if ( $findEquals ) {
2708 // First equals will be for the template
2709 $search .= '=';
2710 } else {
2711 // Look for headings
2712 // We can't look for headings when $findEquals is true, because the ambiguity
2713 // between template name/value separators and heading starts would be unresolved
2714 // until the closing double-brace is found. This would mean either infinite
2715 // backtrack, or creating and updating two separate tree structures until the
2716 // end of the ambiguity -- one tree structure assuming a heading, and the other
2717 // assuming a template argument.
2718 //
2719 // Easier to just break some section edit links.
2720 $search .= "\n";
2721 }
2722 $rule = null;
2723 # Output literal section, advance input counter
2724 $literalLength = strcspn( $text, $search, $i );
2725 if ( $literalLength > 0 ) {
2726 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
2727 $i += $literalLength;
2728 }
2729 if ( $i >= strlen( $text ) ) {
2730 if ( $currentClosing == "\n" ) {
2731 // Do a past-the-end run to finish off the heading
2732 $curChar = '';
2733 $found = 'line-end';
2734 } else {
2735 # All done
2736 break;
2737 }
2738 } else {
2739 $curChar = $text[$i];
2740 if ( $curChar == '|' ) {
2741 $found = 'pipe';
2742 } elseif ( $curChar == '=' ) {
2743 $found = 'equals';
2744 } elseif ( $curChar == '<' ) {
2745 $found = 'angle';
2746 } elseif ( $curChar == "\n" ) {
2747 if ( $inHeading ) {
2748 $found = 'line-end';
2749 } else {
2750 $found = 'line-start';
2751 }
2752 } elseif ( $curChar == $currentClosing ) {
2753 $found = 'close';
2754 } elseif ( isset( $rules[$curChar] ) ) {
2755 $found = 'open';
2756 $rule = $rules[$curChar];
2757 } else {
2758 # Some versions of PHP have a strcspn which stops on null characters
2759 # Ignore and continue
2760 ++$i;
2761 continue;
2762 }
2763 }
2764 }
2765
2766 if ( $found == 'angle' ) {
2767 $matches = false;
2768 // Handle </onlyinclude>
2769 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
2770 $findOnlyinclude = true;
2771 continue;
2772 }
2773
2774 // Determine element name
2775 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
2776 // Element name missing or not listed
2777 $accum .= '&lt;';
2778 ++$i;
2779 continue;
2780 }
2781 // Handle comments
2782 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
2783 // To avoid leaving blank lines, when a comment is both preceded
2784 // and followed by a newline (ignoring spaces), trim leading and
2785 // trailing spaces and one of the newlines.
2786
2787 // Find the end
2788 $endPos = strpos( $text, '-->', $i + 4 );
2789 if ( $endPos === false ) {
2790 // Unclosed comment in input, runs to end
2791 $inner = substr( $text, $i );
2792 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
2793 $i = strlen( $text );
2794 } else {
2795 // Search backwards for leading whitespace
2796 $wsStart = $i ? ( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
2797 // Search forwards for trailing whitespace
2798 // $wsEnd will be the position of the last space
2799 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
2800 // Eat the line if possible
2801 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
2802 // the overall start. That's not how Sanitizer::removeHTMLcomments() does it, but
2803 // it's a possible beneficial b/c break.
2804 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
2805 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
2806 {
2807 $startPos = $wsStart;
2808 $endPos = $wsEnd + 1;
2809 // Remove leading whitespace from the end of the accumulator
2810 // Sanity check first though
2811 $wsLength = $i - $wsStart;
2812 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
2813 $accum = substr( $accum, 0, -$wsLength );
2814 }
2815 // Do a line-start run next time to look for headings after the comment,
2816 // but only if stack->top===false, because headings don't exist at deeper levels.
2817 if ( $stack->top === false ) {
2818 $fakeLineStart = true;
2819 }
2820 } else {
2821 // No line to eat, just take the comment itself
2822 $startPos = $i;
2823 $endPos += 2;
2824 }
2825
2826 $i = $endPos + 1;
2827 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
2828 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
2829 }
2830 continue;
2831 }
2832 $name = $matches[1];
2833 $attrStart = $i + strlen( $name ) + 1;
2834
2835 // Find end of tag
2836 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
2837 if ( $tagEndPos === false ) {
2838 // Infinite backtrack
2839 // Disable tag search to prevent worst-case O(N^2) performance
2840 $noMoreGT = true;
2841 $accum .= '&lt;';
2842 ++$i;
2843 continue;
2844 }
2845
2846 // Handle ignored tags
2847 if ( in_array( $name, $ignoredTags ) ) {
2848 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
2849 $i = $tagEndPos + 1;
2850 continue;
2851 }
2852
2853 $tagStartPos = $i;
2854 if ( $text[$tagEndPos-1] == '/' ) {
2855 $attrEnd = $tagEndPos - 1;
2856 $inner = null;
2857 $i = $tagEndPos + 1;
2858 $close = '';
2859 } else {
2860 $attrEnd = $tagEndPos;
2861 // Find closing tag
2862 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) ) {
2863 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
2864 $i = $matches[0][1] + strlen( $matches[0][0] );
2865 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
2866 } else {
2867 // No end tag -- let it run out to the end of the text.
2868 $inner = substr( $text, $tagEndPos + 1 );
2869 $i = strlen( $text );
2870 $close = '';
2871 }
2872 }
2873 // <includeonly> and <noinclude> just become <ignore> tags
2874 if ( in_array( $name, $ignoredElements ) ) {
2875 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
2876 . '</ignore>';
2877 continue;
2878 }
2879
2880 $accum .= '<ext>';
2881 if ( $attrEnd <= $attrStart ) {
2882 $attr = '';
2883 } else {
2884 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
2885 }
2886 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
2887 // Note that the attr element contains the whitespace between name and attribute,
2888 // this is necessary for precise reconstruction during pre-save transform.
2889 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
2890 if ( $inner !== null ) {
2891 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
2892 }
2893 $accum .= $close . '</ext>';
2894 }
2895
2896 elseif ( $found == 'line-start' ) {
2897 // Is this the start of a heading?
2898 // Line break belongs before the heading element in any case
2899 if ( $fakeLineStart ) {
2900 $fakeLineStart = false;
2901 } else {
2902 $accum .= $curChar;
2903 $i++;
2904 }
2905
2906 $count = strspn( $text, '=', $i, 6 );
2907 if ( $count > 0 ) {
2908 $piece = array(
2909 'open' => "\n",
2910 'close' => "\n",
2911 'parts' => array( str_repeat( '=', $count ) ),
2912 'startPos' => $i,
2913 'count' => $count );
2914 $stack->push( $piece );
2915 $accum =& $stack->getAccum();
2916 extract( $stack->getFlags() );
2917 $i += $count;
2918 }
2919 }
2920
2921 elseif ( $found == 'line-end' ) {
2922 $piece = $stack->top;
2923 // A heading must be open, otherwise \n wouldn't have been in the search list
2924 assert( $piece->open == "\n" );
2925 // Search back through the input to see if it has a proper close
2926 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
2927 $m = false;
2928 $count = $piece->count;
2929 if ( preg_match( "/\s*(={{$count}})/A", $revText, $m, 0, strlen( $text ) - $i ) ) {
2930 if ( $i - strlen( $m[0] ) == $piece->startPos ) {
2931 // This is just a single string of equals signs on its own line
2932 // Divide by two and round down to create start and end delimiters
2933 $count = intval( $count / 2 );
2934 } else {
2935 $count = min( strlen( $m[1] ), $count );
2936 }
2937 if ( $count > 0 ) {
2938 // Normal match, output <h>
2939 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
2940 $headingIndex++;
2941 } else {
2942 // Single equals sign on its own line, count=0
2943 $element = $accum;
2944 }
2945 } else {
2946 // No match, no <h>, just pass down the inner text
2947 $element = $accum;
2948 }
2949 // Unwind the stack
2950 $stack->pop();
2951 $accum =& $stack->getAccum();
2952 extract( $stack->getFlags() );
2953
2954 // Append the result to the enclosing accumulator
2955 $accum .= $element;
2956 // Note that we do NOT increment the input pointer.
2957 // This is because the closing linebreak could be the opening linebreak of
2958 // another heading. Infinite loops are avoided because the next iteration MUST
2959 // hit the heading open case above, which unconditionally increments the
2960 // input pointer.
2961 }
2962
2963 elseif ( $found == 'open' ) {
2964 # count opening brace characters
2965 $count = strspn( $text, $curChar, $i );
2966
2967 # we need to add to stack only if opening brace count is enough for one of the rules
2968 if ( $count >= $rule['min'] ) {
2969 # Add it to the stack
2970 $piece = array(
2971 'open' => $curChar,
2972 'close' => $rule['end'],
2973 'count' => $count,
2974 'parts' => array( '' ),
2975 'eqpos' => array(),
2976 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
2977 );
2978
2979 $stack->push( $piece );
2980 $accum =& $stack->getAccum();
2981 extract( $stack->getFlags() );
2982 } else {
2983 # Add literal brace(s)
2984 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
2985 }
2986 $i += $count;
2987 }
2988
2989 elseif ( $found == 'close' ) {
2990 $piece = $stack->top;
2991 # lets check if there are enough characters for closing brace
2992 $maxCount = $piece->count;
2993 $count = strspn( $text, $curChar, $i, $maxCount );
2994
2995 # check for maximum matching characters (if there are 5 closing
2996 # characters, we will probably need only 3 - depending on the rules)
2997 $matchingCount = 0;
2998 $rule = $rules[$piece->open];
2999 if ( $count > $rule['max'] ) {
3000 # The specified maximum exists in the callback array, unless the caller
3001 # has made an error
3002 $matchingCount = $rule['max'];
3003 } else {
3004 # Count is less than the maximum
3005 # Skip any gaps in the callback array to find the true largest match
3006 # Need to use array_key_exists not isset because the callback can be null
3007 $matchingCount = $count;
3008 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
3009 --$matchingCount;
3010 }
3011 }
3012
3013 if ($matchingCount <= 0) {
3014 # No matching element found in callback array
3015 # Output a literal closing brace and continue
3016 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
3017 $i += $count;
3018 continue;
3019 }
3020 $name = $rule['names'][$matchingCount];
3021 if ( $name === null ) {
3022 // No element, just literal text
3023 $element = str_repeat( $piece->open, $matchingCount ) .
3024 implode( '|', $piece->parts ) .
3025 str_repeat( $rule['end'], $matchingCount );
3026 } else {
3027 # Create XML element
3028 # Note: $parts is already XML, does not need to be encoded further
3029 $parts = $piece->parts;
3030 $title = $parts[0];
3031 unset( $parts[0] );
3032
3033 # The invocation is at the start of the line if lineStart is set in
3034 # the stack, and all opening brackets are used up.
3035 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
3036 $attr = ' lineStart="1"';
3037 } else {
3038 $attr = '';
3039 }
3040
3041 $element = "<$name$attr>";
3042 $element .= "<title>$title</title>";
3043 $argIndex = 1;
3044 foreach ( $parts as $partIndex => $part ) {
3045 if ( isset( $piece->eqpos[$partIndex] ) ) {
3046 $eqpos = $piece->eqpos[$partIndex];
3047 $argName = substr( $part, 0, $eqpos );
3048 $argValue = substr( $part, $eqpos + 1 );
3049 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
3050 } else {
3051 $element .= "<part><name index=\"$argIndex\" /><value>$part</value></part>";
3052 $argIndex++;
3053 }
3054 }
3055 $element .= "</$name>";
3056 }
3057
3058 # Advance input pointer
3059 $i += $matchingCount;
3060
3061 # Unwind the stack
3062 $stack->pop();
3063 $accum =& $stack->getAccum();
3064
3065 # Re-add the old stack element if it still has unmatched opening characters remaining
3066 if ($matchingCount < $piece->count) {
3067 $piece->parts = array( '' );
3068 $piece->count -= $matchingCount;
3069 $piece->eqpos = array();
3070 # do we still qualify for any callback with remaining count?
3071 $names = $rules[$piece->open]['names'];
3072 $skippedBraces = 0;
3073 $enclosingAccum =& $accum;
3074 while ( $piece->count ) {
3075 if ( array_key_exists( $piece->count, $names ) ) {
3076 $stack->push( $piece );
3077 $accum =& $stack->getAccum();
3078 break;
3079 }
3080 --$piece->count;
3081 $skippedBraces ++;
3082 }
3083 $enclosingAccum .= str_repeat( $piece->open, $skippedBraces );
3084 }
3085
3086 extract( $stack->getFlags() );
3087
3088 # Add XML element to the enclosing accumulator
3089 $accum .= $element;
3090 }
3091
3092 elseif ( $found == 'pipe' ) {
3093 $findEquals = true; // shortcut for getFlags()
3094 $stack->top->addPart();
3095 $accum =& $stack->getAccum();
3096 ++$i;
3097 }
3098
3099 elseif ( $found == 'equals' ) {
3100 $findEquals = false; // shortcut for getFlags()
3101 $partsCount = count( $stack->top->parts );
3102 $stack->top->eqpos[$partsCount - 1] = strlen( $accum );
3103 $accum .= '=';
3104 ++$i;
3105 }
3106 }
3107
3108 # Output any remaining unclosed brackets
3109 foreach ( $stack->stack as $piece ) {
3110 if ( $piece->open == "\n" ) {
3111 $stack->topAccum .= $piece->parts[0];
3112 } else {
3113 $stack->topAccum .= str_repeat( $piece->open, $piece->count ) . implode( '|', $piece->parts );
3114 }
3115 }
3116 $stack->topAccum .= '</root>';
3117 $xml = $stack->topAccum;
3118
3119 wfProfileOut( __METHOD__.'-makexml' );
3120 wfProfileIn( __METHOD__.'-loadXML' );
3121 $dom = new DOMDocument;
3122 wfSuppressWarnings();
3123 $result = $dom->loadXML( $xml );
3124 wfRestoreWarnings();
3125 if ( !$result ) {
3126 // Try running the XML through UtfNormal to get rid of invalid characters
3127 $xml = UtfNormal::cleanUp( $xml );
3128 $result = $dom->loadXML( $xml );
3129 if ( !$result ) {
3130 throw new MWException( __METHOD__.' generated invalid XML' );
3131 }
3132 }
3133 wfProfileOut( __METHOD__.'-loadXML' );
3134 wfProfileOut( __METHOD__ );
3135 return $dom;
3136 }
3137
3138 /*
3139 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3140 */
3141 public static function splitWhitespace( $s ) {
3142 $ltrimmed = ltrim( $s );
3143 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3144 $trimmed = rtrim( $ltrimmed );
3145 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3146 if ( $diff > 0 ) {
3147 $w2 = substr( $ltrimmed, -$diff );
3148 } else {
3149 $w2 = '';
3150 }
3151 return array( $w1, $trimmed, $w2 );
3152 }
3153
3154 /**
3155 * Replace magic variables, templates, and template arguments
3156 * with the appropriate text. Templates are substituted recursively,
3157 * taking care to avoid infinite loops.
3158 *
3159 * Note that the substitution depends on value of $mOutputType:
3160 * OT_WIKI: only {{subst:}} templates
3161 * OT_MSG: only magic variables
3162 * OT_HTML: all templates and magic variables
3163 *
3164 * @param string $tex The text to transform
3165 * @param PPFrame $frame Object describing the arguments passed to the template
3166 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
3167 * @private
3168 */
3169 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3170 # Prevent too big inclusions
3171 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
3172 return $text;
3173 }
3174
3175 $fname = __METHOD__;
3176 wfProfileIn( $fname );
3177
3178 if ( $frame === false ) {
3179 $frame = new PPFrame( $this );
3180 } elseif ( !( $frame instanceof PPFrame ) ) {
3181 throw new MWException( __METHOD__ . ' called using the old argument format' );
3182 }
3183
3184 $dom = $this->preprocessToDom( $text );
3185 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3186 $text = $frame->expand( $dom, $flags );
3187
3188 wfProfileOut( $fname );
3189 return $text;
3190 }
3191
3192 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3193 static function createAssocArgs( $args ) {
3194 $assocArgs = array();
3195 $index = 1;
3196 foreach( $args as $arg ) {
3197 $eqpos = strpos( $arg, '=' );
3198 if ( $eqpos === false ) {
3199 $assocArgs[$index++] = $arg;
3200 } else {
3201 $name = trim( substr( $arg, 0, $eqpos ) );
3202 $value = trim( substr( $arg, $eqpos+1 ) );
3203 if ( $value === false ) {
3204 $value = '';
3205 }
3206 if ( $name !== false ) {
3207 $assocArgs[$name] = $value;
3208 }
3209 }
3210 }
3211
3212 return $assocArgs;
3213 }
3214
3215 /**
3216 * Return the text of a template, after recursively
3217 * replacing any variables or templates within the template.
3218 *
3219 * @param array $piece The parts of the template
3220 * $piece['text']: matched text
3221 * $piece['title']: the title, i.e. the part before the |
3222 * $piece['parts']: the parameter array
3223 * @param PPFrame The current frame, contains template arguments
3224 * @return string the text of the template
3225 * @private
3226 */
3227 function braceSubstitution( $piece, $frame ) {
3228 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
3229 $fname = __METHOD__;
3230 wfProfileIn( $fname );
3231 wfProfileIn( __METHOD__.'-setup' );
3232
3233 # Flags
3234 $found = false; # $text has been filled
3235 $nowiki = false; # wiki markup in $text should be escaped
3236 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3237 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3238 $isDOM = false; # $text is a DOM node needing expansion
3239
3240 # Title object, where $text came from
3241 $title = NULL;
3242
3243 # $part1 is the bit before the first |, and must contain only title characters.
3244 # Various prefixes will be stripped from it later.
3245 $titleWithSpaces = $frame->expand( $piece['title'] );
3246 $part1 = trim( $titleWithSpaces );
3247 $titleText = false;
3248
3249 # Original title text preserved for various purposes
3250 $originalTitle = $part1;
3251
3252 # $args is a list of argument nodes, starting from index 0, not including $part1
3253 $args = (null == $piece['parts']) ? array() : $piece['parts'];
3254 wfProfileOut( __METHOD__.'-setup' );
3255
3256 # SUBST
3257 wfProfileIn( __METHOD__.'-modifiers' );
3258 if ( !$found ) {
3259 $mwSubst =& MagicWord::get( 'subst' );
3260 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
3261 # One of two possibilities is true:
3262 # 1) Found SUBST but not in the PST phase
3263 # 2) Didn't find SUBST and in the PST phase
3264 # In either case, return without further processing
3265 $text = '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3266 $found = true;
3267 }
3268 }
3269
3270 # Variables
3271 if ( !$found && $args->length == 0 ) {
3272 $id = $this->mVariables->matchStartToEnd( $part1 );
3273 if ( $id !== false ) {
3274 $text = $this->getVariableValue( $id );
3275 if (MagicWord::getCacheTTL($id)>-1)
3276 $this->mOutput->mContainsOldMagic = true;
3277 $found = true;
3278 }
3279 }
3280
3281 # MSG, MSGNW and RAW
3282 if ( !$found ) {
3283 # Check for MSGNW:
3284 $mwMsgnw =& MagicWord::get( 'msgnw' );
3285 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3286 $nowiki = true;
3287 } else {
3288 # Remove obsolete MSG:
3289 $mwMsg =& MagicWord::get( 'msg' );
3290 $mwMsg->matchStartAndRemove( $part1 );
3291 }
3292
3293 # Check for RAW:
3294 $mwRaw =& MagicWord::get( 'raw' );
3295 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3296 $forceRawInterwiki = true;
3297 }
3298 }
3299 wfProfileOut( __METHOD__.'-modifiers' );
3300
3301 # Parser functions
3302 if ( !$found ) {
3303 wfProfileIn( __METHOD__ . '-pfunc' );
3304
3305 $colonPos = strpos( $part1, ':' );
3306 if ( $colonPos !== false ) {
3307 # Case sensitive functions
3308 $function = substr( $part1, 0, $colonPos );
3309 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3310 $function = $this->mFunctionSynonyms[1][$function];
3311 } else {
3312 # Case insensitive functions
3313 $function = strtolower( $function );
3314 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3315 $function = $this->mFunctionSynonyms[0][$function];
3316 } else {
3317 $function = false;
3318 }
3319 }
3320 if ( $function ) {
3321 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3322 $initialArgs = array( &$this );
3323 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3324 if ( $flags & SFH_OBJECT_ARGS ) {
3325 # Add a frame parameter, and pass the arguments as an array
3326 $allArgs = $initialArgs;
3327 $allArgs[] = $frame;
3328 foreach ( $args as $arg ) {
3329 $funcArgs[] = $arg;
3330 }
3331 $allArgs[] = $funcArgs;
3332 } else {
3333 # Convert arguments to plain text
3334 foreach ( $args as $arg ) {
3335 $funcArgs[] = trim( $frame->expand( $arg ) );
3336 }
3337 $allArgs = array_merge( $initialArgs, $funcArgs );
3338 }
3339
3340 $result = call_user_func_array( $callback, $allArgs );
3341 $found = true;
3342
3343 if ( is_array( $result ) ) {
3344 if ( isset( $result[0] ) ) {
3345 $text = $result[0];
3346 unset( $result[0] );
3347 }
3348
3349 // Extract flags into the local scope
3350 // This allows callers to set flags such as nowiki, found, etc.
3351 extract( $result );
3352 } else {
3353 $text = $result;
3354 }
3355 }
3356 }
3357 wfProfileOut( __METHOD__ . '-pfunc' );
3358 }
3359
3360 # Finish mangling title and then check for loops.
3361 # Set $title to a Title object and $titleText to the PDBK
3362 if ( !$found ) {
3363 $ns = NS_TEMPLATE;
3364 # Split the title into page and subpage
3365 $subpage = '';
3366 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3367 if ($subpage !== '') {
3368 $ns = $this->mTitle->getNamespace();
3369 }
3370 $title = Title::newFromText( $part1, $ns );
3371 if ( $title ) {
3372 $titleText = $title->getPrefixedText();
3373 # Check for language variants if the template is not found
3374 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3375 $wgContLang->findVariantLink($part1, $title);
3376 }
3377 # Do infinite loop check
3378 if ( !$frame->loopCheck( $title ) ) {
3379 $found = true;
3380 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
3381 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
3382 }
3383 # Do recursion depth check
3384 $limit = $this->mOptions->getMaxTemplateDepth();
3385 if ( $frame->depth >= $limit ) {
3386 $found = true;
3387 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
3388 }
3389 }
3390 }
3391
3392 # Load from database
3393 if ( !$found && $title ) {
3394 wfProfileIn( __METHOD__ . '-loadtpl' );
3395 if ( !$title->isExternal() ) {
3396 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
3397 $text = SpecialPage::capturePath( $title );
3398 if ( is_string( $text ) ) {
3399 $found = true;
3400 $isHTML = true;
3401 $this->disableCache();
3402 }
3403 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3404 $found = false; //access denied
3405 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3406 } else {
3407 list( $text, $title ) = $this->getTemplateDom( $title );
3408 if ( $text !== false ) {
3409 $found = true;
3410 $isDOM = true;
3411 }
3412 }
3413
3414 # If the title is valid but undisplayable, make a link to it
3415 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3416 $text = "[[:$titleText]]";
3417 $found = true;
3418 }
3419 } elseif ( $title->isTrans() ) {
3420 // Interwiki transclusion
3421 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3422 $text = $this->interwikiTransclude( $title, 'render' );
3423 $isHTML = true;
3424 } else {
3425 $text = $this->interwikiTransclude( $title, 'raw' );
3426 // Preprocess it like a template
3427 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3428 $isDOM = true;
3429 }
3430 $found = true;
3431 }
3432 wfProfileOut( __METHOD__ . '-loadtpl' );
3433 }
3434
3435 # If we haven't found text to substitute by now, we're done
3436 # Recover the source wikitext and return it
3437 if ( !$found ) {
3438 $text = '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3439 wfProfileOut( $fname );
3440 return $text;
3441 }
3442
3443 # Expand DOM-style return values in a child frame
3444 if ( $isDOM ) {
3445 # Clean up argument array
3446 $newFrame = $frame->newChild( $args, $title );
3447
3448 if ( $titleText !== false && $newFrame->isEmpty() ) {
3449 # Expansion is eligible for the empty-frame cache
3450 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3451 $text = $this->mTplExpandCache[$titleText];
3452 } else {
3453 $text = $newFrame->expand( $text );
3454 $this->mTplExpandCache[$titleText] = $text;
3455 }
3456 } else {
3457 # Uncached expansion
3458 $text = $newFrame->expand( $text );
3459 }
3460 }
3461
3462 # Replace raw HTML by a placeholder
3463 # Add a blank line preceding, to prevent it from mucking up
3464 # immediately preceding headings
3465 if ( $isHTML ) {
3466 $text = "\n\n" . $this->insertStripItem( $text );
3467 }
3468 # Escape nowiki-style return values
3469 elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3470 $text = wfEscapeWikiText( $text );
3471 }
3472 # Bug 529: if the template begins with a table or block-level
3473 # element, it should be treated as beginning a new line.
3474 # This behaviour is somewhat controversial.
3475 elseif ( !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3476 $text = "\n" . $text;
3477 }
3478
3479 if ( !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3480 # Error, oversize inclusion
3481 $text = "[[$originalTitle]]" .
3482 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3483 }
3484
3485 wfProfileOut( $fname );
3486 return $text;
3487 }
3488
3489 /**
3490 * Get the semi-parsed DOM representation of a template with a given title,
3491 * and its redirect destination title. Cached.
3492 */
3493 function getTemplateDom( $title ) {
3494 $cacheTitle = $title;
3495 $titleText = $title->getPrefixedDBkey();
3496
3497 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3498 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3499 $title = Title::makeTitle( $ns, $dbk );
3500 $titleText = $title->getPrefixedDBkey();
3501 }
3502 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3503 return array( $this->mTplDomCache[$titleText], $title );
3504 }
3505
3506 // Cache miss, go to the database
3507 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3508
3509 if ( $text === false ) {
3510 $this->mTplDomCache[$titleText] = false;
3511 return array( false, $title );
3512 }
3513
3514 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3515 $this->mTplDomCache[ $titleText ] = $dom;
3516
3517 if (! $title->equals($cacheTitle)) {
3518 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3519 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3520 }
3521
3522 return array( $dom, $title );
3523 }
3524
3525 /**
3526 * Fetch the unparsed text of a template and register a reference to it.
3527 */
3528 function fetchTemplateAndTitle( $title ) {
3529 $templateCb = $this->mOptions->getTemplateCallback();
3530 $stuff = call_user_func( $templateCb, $title );
3531 $text = $stuff['text'];
3532 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3533 if ( isset( $stuff['deps'] ) ) {
3534 foreach ( $stuff['deps'] as $dep ) {
3535 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3536 }
3537 }
3538 return array($text,$finalTitle);
3539 }
3540
3541 function fetchTemplate( $title ) {
3542 $rv = $this->fetchTemplateAndTitle($title);
3543 return $rv[0];
3544 }
3545
3546 /**
3547 * Static function to get a template
3548 * Can be overridden via ParserOptions::setTemplateCallback().
3549 */
3550 static function statelessFetchTemplate( $title ) {
3551 $text = $skip = false;
3552 $finalTitle = $title;
3553 $deps = array();
3554
3555 // Loop to fetch the article, with up to 1 redirect
3556 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3557 # Give extensions a chance to select the revision instead
3558 $id = false; // Assume current
3559 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3560
3561 if( $skip ) {
3562 $text = false;
3563 $deps[] = array(
3564 'title' => $title,
3565 'page_id' => $title->getArticleID(),
3566 'rev_id' => null );
3567 break;
3568 }
3569 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3570 $rev_id = $rev ? $rev->getId() : 0;
3571
3572 $deps[] = array(
3573 'title' => $title,
3574 'page_id' => $title->getArticleID(),
3575 'rev_id' => $rev_id );
3576
3577 if( $rev ) {
3578 $text = $rev->getText();
3579 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3580 global $wgLang;
3581 $message = $wgLang->lcfirst( $title->getText() );
3582 $text = wfMsgForContentNoTrans( $message );
3583 if( wfEmptyMsg( $message, $text ) ) {
3584 $text = false;
3585 break;
3586 }
3587 } else {
3588 break;
3589 }
3590 if ( $text === false ) {
3591 break;
3592 }
3593 // Redirect?
3594 $finalTitle = $title;
3595 $title = Title::newFromRedirect( $text );
3596 }
3597 return array(
3598 'text' => $text,
3599 'finalTitle' => $finalTitle,
3600 'deps' => $deps );
3601 }
3602
3603 /**
3604 * Transclude an interwiki link.
3605 */
3606 function interwikiTransclude( $title, $action ) {
3607 global $wgEnableScaryTranscluding;
3608
3609 if (!$wgEnableScaryTranscluding)
3610 return wfMsg('scarytranscludedisabled');
3611
3612 $url = $title->getFullUrl( "action=$action" );
3613
3614 if (strlen($url) > 255)
3615 return wfMsg('scarytranscludetoolong');
3616 return $this->fetchScaryTemplateMaybeFromCache($url);
3617 }
3618
3619 function fetchScaryTemplateMaybeFromCache($url) {
3620 global $wgTranscludeCacheExpiry;
3621 $dbr = wfGetDB(DB_SLAVE);
3622 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3623 array('tc_url' => $url));
3624 if ($obj) {
3625 $time = $obj->tc_time;
3626 $text = $obj->tc_contents;
3627 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3628 return $text;
3629 }
3630 }
3631
3632 $text = Http::get($url);
3633 if (!$text)
3634 return wfMsg('scarytranscludefailed', $url);
3635
3636 $dbw = wfGetDB(DB_MASTER);
3637 $dbw->replace('transcache', array('tc_url'), array(
3638 'tc_url' => $url,
3639 'tc_time' => time(),
3640 'tc_contents' => $text));
3641 return $text;
3642 }
3643
3644
3645 /**
3646 * Triple brace replacement -- used for template arguments
3647 * @private
3648 */
3649 function argSubstitution( $piece, $frame ) {
3650 wfProfileIn( __METHOD__ );
3651
3652 $error = false;
3653 $parts = $piece['parts'];
3654 $nameWithSpaces = $frame->expand( $piece['title'] );
3655 $argName = trim( $nameWithSpaces );
3656
3657 $text = $frame->getArgument( $argName );
3658 if ( $text === false && ( $this->ot['html'] || $this->ot['pre'] ) && $parts->length > 0 ) {
3659 # No match in frame, use the supplied default
3660 $text = $frame->expand( $parts->item( 0 ) );
3661 }
3662 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3663 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3664 }
3665
3666 if ( $text === false ) {
3667 # No match anywhere
3668 $text = '{{{' . $frame->implode( '|', $nameWithSpaces, $parts ) . '}}}';
3669 }
3670 if ( $error !== false ) {
3671 $text .= $error;
3672 }
3673
3674 wfProfileOut( __METHOD__ );
3675 return $text;
3676 }
3677
3678 /**
3679 * Return the text to be used for a given extension tag.
3680 * This is the ghost of strip().
3681 *
3682 * @param array $params Associative array of parameters:
3683 * name DOMNode for the tag name
3684 * attr DOMNode for unparsed text where tag attributes are thought to be
3685 * attributes Optional associative array of parsed attributes
3686 * inner Contents of extension element
3687 * noClose Original text did not have a close tag
3688 * @param PPFrame $frame
3689 */
3690 function extensionSubstitution( $params, $frame ) {
3691 global $wgRawHtml, $wgContLang;
3692 static $n = 1;
3693
3694 $name = $frame->expand( $params['name'] );
3695 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3696 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3697
3698 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $n++) . $this->mMarkerSuffix;
3699
3700 if ( $this->ot['html'] ) {
3701 $name = strtolower( $name );
3702
3703 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3704 if ( isset( $params['attributes'] ) ) {
3705 $attributes = $attributes + $params['attributes'];
3706 }
3707 switch ( $name ) {
3708 case 'html':
3709 if( $wgRawHtml ) {
3710 $output = $content;
3711 break;
3712 } else {
3713 throw new MWException( '<html> extension tag encountered unexpectedly' );
3714 }
3715 case 'nowiki':
3716 $output = Xml::escapeTagsOnly( $content );
3717 break;
3718 case 'math':
3719 $output = $wgContLang->armourMath(
3720 MathRenderer::renderMath( $content, $attributes ) );
3721 break;
3722 case 'gallery':
3723 $output = $this->renderImageGallery( $content, $attributes );
3724 break;
3725 default:
3726 if( isset( $this->mTagHooks[$name] ) ) {
3727 $output = call_user_func_array( $this->mTagHooks[$name],
3728 array( $content, $attributes, $this ) );
3729 } else {
3730 throw new MWException( "Invalid call hook $name" );
3731 }
3732 }
3733 } else {
3734 if ( $content === null ) {
3735 $output = "<$name$attrText/>";
3736 } else {
3737 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3738 $output = "<$name$attrText>$content$close";
3739 }
3740 }
3741
3742 if ( $name == 'html' || $name == 'nowiki' ) {
3743 $this->mStripState->nowiki->setPair( $marker, $output );
3744 } else {
3745 $this->mStripState->general->setPair( $marker, $output );
3746 }
3747 return $marker;
3748 }
3749
3750 /**
3751 * Increment an include size counter
3752 *
3753 * @param string $type The type of expansion
3754 * @param integer $size The size of the text
3755 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3756 */
3757 function incrementIncludeSize( $type, $size ) {
3758 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3759 return false;
3760 } else {
3761 $this->mIncludeSizes[$type] += $size;
3762 return true;
3763 }
3764 }
3765
3766 /**
3767 * Detect __NOGALLERY__ magic word and set a placeholder
3768 */
3769 function stripNoGallery( &$text ) {
3770 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3771 # do not add TOC
3772 $mw = MagicWord::get( 'nogallery' );
3773 $this->mOutput->mNoGallery = $mw->matchAndRemove( $text ) ;
3774 }
3775
3776 /**
3777 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3778 * placeholder that will then be replaced by the real TOC in
3779 * ->formatHeadings, this works because at this points real
3780 * comments will have already been discarded by the sanitizer.
3781 *
3782 * Any additional __TOC__ magic words left over will be discarded
3783 * as there can only be one TOC on the page.
3784 */
3785 function stripToc( $text ) {
3786 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3787 # do not add TOC
3788 $mw = MagicWord::get( 'notoc' );
3789 if( $mw->matchAndRemove( $text ) ) {
3790 $this->mShowToc = false;
3791 }
3792
3793 $mw = MagicWord::get( 'toc' );
3794 if( $mw->match( $text ) ) {
3795 $this->mShowToc = true;
3796 $this->mForceTocPosition = true;
3797
3798 // Set a placeholder. At the end we'll fill it in with the TOC.
3799 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3800
3801 // Only keep the first one.
3802 $text = $mw->replace( '', $text );
3803 }
3804 return $text;
3805 }
3806
3807 /**
3808 * This function accomplishes several tasks:
3809 * 1) Auto-number headings if that option is enabled
3810 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3811 * 3) Add a Table of contents on the top for users who have enabled the option
3812 * 4) Auto-anchor headings
3813 *
3814 * It loops through all headlines, collects the necessary data, then splits up the
3815 * string and re-inserts the newly formatted headlines.
3816 *
3817 * @param string $text
3818 * @param boolean $isMain
3819 * @private
3820 */
3821 function formatHeadings( $text, $isMain=true ) {
3822 global $wgMaxTocLevel, $wgContLang;
3823
3824 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3825 if( !$this->mTitle->quickUserCan( 'edit' ) ) {
3826 $showEditLink = 0;
3827 } else {
3828 $showEditLink = $this->mOptions->getEditSection();
3829 }
3830
3831 # Inhibit editsection links if requested in the page
3832 $esw =& MagicWord::get( 'noeditsection' );
3833 if( $esw->matchAndRemove( $text ) ) {
3834 $showEditLink = 0;
3835 }
3836
3837 # Get all headlines for numbering them and adding funky stuff like [edit]
3838 # links - this is for later, but we need the number of headlines right now
3839 $matches = array();
3840 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3841
3842 # if there are fewer than 4 headlines in the article, do not show TOC
3843 # unless it's been explicitly enabled.
3844 $enoughToc = $this->mShowToc &&
3845 (($numMatches >= 4) || $this->mForceTocPosition);
3846
3847 # Allow user to stipulate that a page should have a "new section"
3848 # link added via __NEWSECTIONLINK__
3849 $mw =& MagicWord::get( 'newsectionlink' );
3850 if( $mw->matchAndRemove( $text ) )
3851 $this->mOutput->setNewSection( true );
3852
3853 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3854 # override above conditions and always show TOC above first header
3855 $mw =& MagicWord::get( 'forcetoc' );
3856 if ($mw->matchAndRemove( $text ) ) {
3857 $this->mShowToc = true;
3858 $enoughToc = true;
3859 }
3860
3861 # We need this to perform operations on the HTML
3862 $sk = $this->mOptions->getSkin();
3863
3864 # headline counter
3865 $headlineCount = 0;
3866 $numVisible = 0;
3867
3868 # Ugh .. the TOC should have neat indentation levels which can be
3869 # passed to the skin functions. These are determined here
3870 $toc = '';
3871 $full = '';
3872 $head = array();
3873 $sublevelCount = array();
3874 $levelCount = array();
3875 $toclevel = 0;
3876 $level = 0;
3877 $prevlevel = 0;
3878 $toclevel = 0;
3879 $prevtoclevel = 0;
3880 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-{$this->mMarkerSuffix}";
3881 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3882 $tocraw = array();
3883
3884 foreach( $matches[3] as $headline ) {
3885 $isTemplate = false;
3886 $titleText = false;
3887 $sectionIndex = false;
3888 $numbering = '';
3889 $markerMatches = array();
3890 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3891 $serial = $markerMatches[1];
3892 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3893 $isTemplate = ($titleText != $baseTitleText);
3894 $headline = preg_replace("/^$markerRegex/", "", $headline);
3895 }
3896
3897 if( $toclevel ) {
3898 $prevlevel = $level;
3899 $prevtoclevel = $toclevel;
3900 }
3901 $level = $matches[1][$headlineCount];
3902
3903 if( $doNumberHeadings || $enoughToc ) {
3904
3905 if ( $level > $prevlevel ) {
3906 # Increase TOC level
3907 $toclevel++;
3908 $sublevelCount[$toclevel] = 0;
3909 if( $toclevel<$wgMaxTocLevel ) {
3910 $prevtoclevel = $toclevel;
3911 $toc .= $sk->tocIndent();
3912 $numVisible++;
3913 }
3914 }
3915 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3916 # Decrease TOC level, find level to jump to
3917
3918 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3919 # Can only go down to level 1
3920 $toclevel = 1;
3921 } else {
3922 for ($i = $toclevel; $i > 0; $i--) {
3923 if ( $levelCount[$i] == $level ) {
3924 # Found last matching level
3925 $toclevel = $i;
3926 break;
3927 }
3928 elseif ( $levelCount[$i] < $level ) {
3929 # Found first matching level below current level
3930 $toclevel = $i + 1;
3931 break;
3932 }
3933 }
3934 }
3935 if( $toclevel<$wgMaxTocLevel ) {
3936 if($prevtoclevel < $wgMaxTocLevel) {
3937 # Unindent only if the previous toc level was shown :p
3938 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3939 } else {
3940 $toc .= $sk->tocLineEnd();
3941 }
3942 }
3943 }
3944 else {
3945 # No change in level, end TOC line
3946 if( $toclevel<$wgMaxTocLevel ) {
3947 $toc .= $sk->tocLineEnd();
3948 }
3949 }
3950
3951 $levelCount[$toclevel] = $level;
3952
3953 # count number of headlines for each level
3954 @$sublevelCount[$toclevel]++;
3955 $dot = 0;
3956 for( $i = 1; $i <= $toclevel; $i++ ) {
3957 if( !empty( $sublevelCount[$i] ) ) {
3958 if( $dot ) {
3959 $numbering .= '.';
3960 }
3961 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3962 $dot = 1;
3963 }
3964 }
3965 }
3966
3967 # The safe header is a version of the header text safe to use for links
3968 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3969 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3970
3971 # Remove link placeholders by the link text.
3972 # <!--LINK number-->
3973 # turns into
3974 # link text with suffix
3975 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3976 "\$this->mLinkHolders['texts'][\$1]",
3977 $safeHeadline );
3978 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3979 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3980 $safeHeadline );
3981
3982 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3983 $tocline = preg_replace(
3984 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3985 array( '', '<$1>'),
3986 $safeHeadline
3987 );
3988 $tocline = trim( $tocline );
3989
3990 # For the anchor, strip out HTML-y stuff period
3991 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3992 $safeHeadline = trim( $safeHeadline );
3993
3994 # Save headline for section edit hint before it's escaped
3995 $headlineHint = $safeHeadline;
3996 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
3997 $refers[$headlineCount] = $safeHeadline;
3998
3999 # count how many in assoc. array so we can track dupes in anchors
4000 isset( $refers[$safeHeadline] ) ? $refers[$safeHeadline]++ : $refers[$safeHeadline] = 1;
4001 $refcount[$headlineCount] = $refers[$safeHeadline];
4002
4003 # Don't number the heading if it is the only one (looks silly)
4004 if( $doNumberHeadings && count( $matches[3] ) > 1) {
4005 # the two are different if the line contains a link
4006 $headline=$numbering . ' ' . $headline;
4007 }
4008
4009 # Create the anchor for linking from the TOC to the section
4010 $anchor = $safeHeadline;
4011 if($refcount[$headlineCount] > 1 ) {
4012 $anchor .= '_' . $refcount[$headlineCount];
4013 }
4014 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
4015 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
4016 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
4017 }
4018 # give headline the correct <h#> tag
4019 if( $showEditLink && $sectionIndex !== false ) {
4020 if( $isTemplate ) {
4021 # Put a T flag in the section identifier, to indicate to extractSections()
4022 # that sections inside <includeonly> should be counted.
4023 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
4024 } else {
4025 $editlink = $sk->editSectionLink($this->mTitle, $sectionIndex, $headlineHint);
4026 }
4027 } else {
4028 $editlink = '';
4029 }
4030 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
4031
4032 $headlineCount++;
4033 }
4034
4035 $this->mOutput->setSections( $tocraw );
4036
4037 # Never ever show TOC if no headers
4038 if( $numVisible < 1 ) {
4039 $enoughToc = false;
4040 }
4041
4042 if( $enoughToc ) {
4043 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4044 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
4045 }
4046 $toc = $sk->tocList( $toc );
4047 }
4048
4049 # split up and insert constructed headlines
4050
4051 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4052 $i = 0;
4053
4054 foreach( $blocks as $block ) {
4055 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
4056 # This is the [edit] link that appears for the top block of text when
4057 # section editing is enabled
4058
4059 # Disabled because it broke block formatting
4060 # For example, a bullet point in the top line
4061 # $full .= $sk->editSectionLink(0);
4062 }
4063 $full .= $block;
4064 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
4065 # Top anchor now in skin
4066 $full = $full.$toc;
4067 }
4068
4069 if( !empty( $head[$i] ) ) {
4070 $full .= $head[$i];
4071 }
4072 $i++;
4073 }
4074 if( $this->mForceTocPosition ) {
4075 return str_replace( '<!--MWTOC-->', $toc, $full );
4076 } else {
4077 return $full;
4078 }
4079 }
4080
4081 /**
4082 * Transform wiki markup when saving a page by doing \r\n -> \n
4083 * conversion, substitting signatures, {{subst:}} templates, etc.
4084 *
4085 * @param string $text the text to transform
4086 * @param Title &$title the Title object for the current article
4087 * @param User &$user the User object describing the current user
4088 * @param ParserOptions $options parsing options
4089 * @param bool $clearState whether to clear the parser state first
4090 * @return string the altered wiki markup
4091 * @public
4092 */
4093 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
4094 $this->mOptions = $options;
4095 $this->setTitle( $title );
4096 $this->setOutputType( OT_WIKI );
4097
4098 if ( $clearState ) {
4099 $this->clearState();
4100 }
4101
4102 $pairs = array(
4103 "\r\n" => "\n",
4104 );
4105 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4106 $text = $this->pstPass2( $text, $user );
4107 $text = $this->mStripState->unstripBoth( $text );
4108 return $text;
4109 }
4110
4111 /**
4112 * Pre-save transform helper function
4113 * @private
4114 */
4115 function pstPass2( $text, $user ) {
4116 global $wgContLang, $wgLocaltimezone;
4117
4118 /* Note: This is the timestamp saved as hardcoded wikitext to
4119 * the database, we use $wgContLang here in order to give
4120 * everyone the same signature and use the default one rather
4121 * than the one selected in each user's preferences.
4122 */
4123 if ( isset( $wgLocaltimezone ) ) {
4124 $oldtz = getenv( 'TZ' );
4125 putenv( 'TZ='.$wgLocaltimezone );
4126 }
4127 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
4128 ' (' . date( 'T' ) . ')';
4129 if ( isset( $wgLocaltimezone ) ) {
4130 putenv( 'TZ='.$oldtz );
4131 }
4132
4133 # Variable replacement
4134 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4135 $text = $this->replaceVariables( $text );
4136
4137 # Strip out <nowiki> etc. added via replaceVariables
4138 #$text = $this->strip( $text, $this->mStripState, false, array( 'gallery' ) );
4139
4140 # Signatures
4141 $sigText = $this->getUserSig( $user );
4142 $text = strtr( $text, array(
4143 '~~~~~' => $d,
4144 '~~~~' => "$sigText $d",
4145 '~~~' => $sigText
4146 ) );
4147
4148 # Context links: [[|name]] and [[name (context)|]]
4149 #
4150 global $wgLegalTitleChars;
4151 $tc = "[$wgLegalTitleChars]";
4152 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
4153
4154 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4155 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4156 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4157
4158 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4159 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4160 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4161
4162 $t = $this->mTitle->getText();
4163 $m = array();
4164 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4165 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4166 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
4167 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4168 } else {
4169 # if there's no context, don't bother duplicating the title
4170 $text = preg_replace( $p2, '[[\\1]]', $text );
4171 }
4172
4173 # Trim trailing whitespace
4174 $text = rtrim( $text );
4175
4176 return $text;
4177 }
4178
4179 /**
4180 * Fetch the user's signature text, if any, and normalize to
4181 * validated, ready-to-insert wikitext.
4182 *
4183 * @param User $user
4184 * @return string
4185 * @private
4186 */
4187 function getUserSig( &$user ) {
4188 global $wgMaxSigChars;
4189
4190 $username = $user->getName();
4191 $nickname = $user->getOption( 'nickname' );
4192 $nickname = $nickname === '' ? $username : $nickname;
4193
4194 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4195 $nickname = $username;
4196 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4197 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
4198 # Sig. might contain markup; validate this
4199 if( $this->validateSig( $nickname ) !== false ) {
4200 # Validated; clean up (if needed) and return it
4201 return $this->cleanSig( $nickname, true );
4202 } else {
4203 # Failed to validate; fall back to the default
4204 $nickname = $username;
4205 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
4206 }
4207 }
4208
4209 // Make sure nickname doesnt get a sig in a sig
4210 $nickname = $this->cleanSigInSig( $nickname );
4211
4212 # If we're still here, make it a link to the user page
4213 $userText = wfEscapeWikiText( $username );
4214 $nickText = wfEscapeWikiText( $nickname );
4215 if ( $user->isAnon() ) {
4216 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4217 } else {
4218 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4219 }
4220 }
4221
4222 /**
4223 * Check that the user's signature contains no bad XML
4224 *
4225 * @param string $text
4226 * @return mixed An expanded string, or false if invalid.
4227 */
4228 function validateSig( $text ) {
4229 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
4230 }
4231
4232 /**
4233 * Clean up signature text
4234 *
4235 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4236 * 2) Substitute all transclusions
4237 *
4238 * @param string $text
4239 * @param $parsing Whether we're cleaning (preferences save) or parsing
4240 * @return string Signature text
4241 */
4242 function cleanSig( $text, $parsing = false ) {
4243 if ( !$parsing ) {
4244 global $wgTitle;
4245 $this->startExternalParse( $wgTitle, new ParserOptions(), OT_MSG );
4246 }
4247
4248 # FIXME: regex doesn't respect extension tags or nowiki
4249 # => Move this logic to braceSubstitution()
4250 $substWord = MagicWord::get( 'subst' );
4251 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4252 $substText = '{{' . $substWord->getSynonym( 0 );
4253
4254 $text = preg_replace( $substRegex, $substText, $text );
4255 $text = $this->cleanSigInSig( $text );
4256 $dom = $this->preprocessToDom( $text );
4257 $frame = new PPFrame( $this );
4258 $text = $frame->expand( $dom->documentElement );
4259
4260 if ( !$parsing ) {
4261 $text = $this->mStripState->unstripBoth( $text );
4262 }
4263
4264 return $text;
4265 }
4266
4267 /**
4268 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4269 * @param string $text
4270 * @return string Signature text with /~{3,5}/ removed
4271 */
4272 function cleanSigInSig( $text ) {
4273 $text = preg_replace( '/~{3,5}/', '', $text );
4274 return $text;
4275 }
4276
4277 /**
4278 * Set up some variables which are usually set up in parse()
4279 * so that an external function can call some class members with confidence
4280 * @public
4281 */
4282 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4283 $this->setTitle( $title );
4284 $this->mOptions = $options;
4285 $this->setOutputType( $outputType );
4286 if ( $clearState ) {
4287 $this->clearState();
4288 }
4289 }
4290
4291 /**
4292 * Transform a MediaWiki message by replacing magic variables.
4293 *
4294 * For some unknown reason, it also expands templates, but only to the
4295 * first recursion level. This is wrong and broken, probably introduced
4296 * accidentally during refactoring, but probably relied upon by thousands
4297 * of users.
4298 *
4299 * @param string $text the text to transform
4300 * @param ParserOptions $options options
4301 * @return string the text with variables substituted
4302 * @public
4303 */
4304 function transformMsg( $text, $options ) {
4305 global $wgTitle;
4306 static $executing = false;
4307
4308 $fname = "Parser::transformMsg";
4309
4310 # Guard against infinite recursion
4311 if ( $executing ) {
4312 return $text;
4313 }
4314 $executing = true;
4315
4316 wfProfileIn($fname);
4317
4318 if ( $wgTitle && !( $wgTitle instanceof FakeTitle ) ) {
4319 $this->setTitle( $wgTitle );
4320 } else {
4321 $this->setTitle( Title::newFromText('msg') );
4322 }
4323 $this->mOptions = $options;
4324 $this->setOutputType( OT_MSG );
4325 $this->clearState();
4326 $text = $this->replaceVariables( $text );
4327 $text = $this->mStripState->unstripBoth( $text );
4328
4329 $executing = false;
4330 wfProfileOut($fname);
4331 return $text;
4332 }
4333
4334 /**
4335 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4336 * The callback should have the following form:
4337 * function myParserHook( $text, $params, &$parser ) { ... }
4338 *
4339 * Transform and return $text. Use $parser for any required context, e.g. use
4340 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4341 *
4342 * @public
4343 *
4344 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4345 * @param mixed $callback The callback function (and object) to use for the tag
4346 *
4347 * @return The old value of the mTagHooks array associated with the hook
4348 */
4349 function setHook( $tag, $callback ) {
4350 $tag = strtolower( $tag );
4351 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4352 $this->mTagHooks[$tag] = $callback;
4353 $this->mStripList[] = $tag;
4354
4355 return $oldVal;
4356 }
4357
4358 function setTransparentTagHook( $tag, $callback ) {
4359 $tag = strtolower( $tag );
4360 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4361 $this->mTransparentTagHooks[$tag] = $callback;
4362
4363 return $oldVal;
4364 }
4365
4366 /**
4367 * Create a function, e.g. {{sum:1|2|3}}
4368 * The callback function should have the form:
4369 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4370 *
4371 * The callback may either return the text result of the function, or an array with the text
4372 * in element 0, and a number of flags in the other elements. The names of the flags are
4373 * specified in the keys. Valid flags are:
4374 * found The text returned is valid, stop processing the template. This
4375 * is on by default.
4376 * nowiki Wiki markup in the return value should be escaped
4377 * isHTML The returned text is HTML, armour it against wikitext transformation
4378 *
4379 * @public
4380 *
4381 * @param string $id The magic word ID
4382 * @param mixed $callback The callback function (and object) to use
4383 * @param integer $flags a combination of the following flags:
4384 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4385 *
4386 * @return The old callback function for this name, if any
4387 */
4388 function setFunctionHook( $id, $callback, $flags = 0 ) {
4389 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4390 $this->mFunctionHooks[$id] = array( $callback, $flags );
4391
4392 # Add to function cache
4393 $mw = MagicWord::get( $id );
4394 if( !$mw )
4395 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4396
4397 $synonyms = $mw->getSynonyms();
4398 $sensitive = intval( $mw->isCaseSensitive() );
4399
4400 foreach ( $synonyms as $syn ) {
4401 # Case
4402 if ( !$sensitive ) {
4403 $syn = strtolower( $syn );
4404 }
4405 # Add leading hash
4406 if ( !( $flags & SFH_NO_HASH ) ) {
4407 $syn = '#' . $syn;
4408 }
4409 # Remove trailing colon
4410 if ( substr( $syn, -1, 1 ) == ':' ) {
4411 $syn = substr( $syn, 0, -1 );
4412 }
4413 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4414 }
4415 return $oldVal;
4416 }
4417
4418 /**
4419 * Get all registered function hook identifiers
4420 *
4421 * @return array
4422 */
4423 function getFunctionHooks() {
4424 return array_keys( $this->mFunctionHooks );
4425 }
4426
4427 /**
4428 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4429 * Placeholders created in Skin::makeLinkObj()
4430 * Returns an array of link CSS classes, indexed by PDBK.
4431 * $options is a bit field, RLH_FOR_UPDATE to select for update
4432 */
4433 function replaceLinkHolders( &$text, $options = 0 ) {
4434 global $wgUser;
4435 global $wgContLang;
4436
4437 $fname = 'Parser::replaceLinkHolders';
4438 wfProfileIn( $fname );
4439
4440 $pdbks = array();
4441 $colours = array();
4442 $linkcolour_ids = array();
4443 $sk = $this->mOptions->getSkin();
4444 $linkCache =& LinkCache::singleton();
4445
4446 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
4447 wfProfileIn( $fname.'-check' );
4448 $dbr = wfGetDB( DB_SLAVE );
4449 $page = $dbr->tableName( 'page' );
4450 $threshold = $wgUser->getOption('stubthreshold');
4451
4452 # Sort by namespace
4453 asort( $this->mLinkHolders['namespaces'] );
4454
4455 # Generate query
4456 $query = false;
4457 $current = null;
4458 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4459 # Make title object
4460 $title = $this->mLinkHolders['titles'][$key];
4461
4462 # Skip invalid entries.
4463 # Result will be ugly, but prevents crash.
4464 if ( is_null( $title ) ) {
4465 continue;
4466 }
4467 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4468
4469 # Check if it's a static known link, e.g. interwiki
4470 if ( $title->isAlwaysKnown() ) {
4471 $colours[$pdbk] = '';
4472 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4473 $colours[$pdbk] = '';
4474 $this->mOutput->addLink( $title, $id );
4475 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4476 $colours[$pdbk] = 'new';
4477 } elseif ( $title->getNamespace() == NS_SPECIAL && !SpecialPage::exists( $pdbk ) ) {
4478 $colours[$pdbk] = 'new';
4479 } else {
4480 # Not in the link cache, add it to the query
4481 if ( !isset( $current ) ) {
4482 $current = $ns;
4483 $query = "SELECT page_id, page_namespace, page_title";
4484 if ( $threshold > 0 ) {
4485 $query .= ', page_len, page_is_redirect';
4486 }
4487 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4488 } elseif ( $current != $ns ) {
4489 $current = $ns;
4490 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4491 } else {
4492 $query .= ', ';
4493 }
4494
4495 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
4496 }
4497 }
4498 if ( $query ) {
4499 $query .= '))';
4500 if ( $options & RLH_FOR_UPDATE ) {
4501 $query .= ' FOR UPDATE';
4502 }
4503
4504 $res = $dbr->query( $query, $fname );
4505
4506 # Fetch data and form into an associative array
4507 # non-existent = broken
4508 while ( $s = $dbr->fetchObject($res) ) {
4509 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
4510 $pdbk = $title->getPrefixedDBkey();
4511 $linkCache->addGoodLinkObj( $s->page_id, $title );
4512 $this->mOutput->addLink( $title, $s->page_id );
4513 $colours[$pdbk] = $sk->getLinkColour( $s, $threshold );
4514 //add id to the extension todolist
4515 $linkcolour_ids[$s->page_id] = $pdbk;
4516 }
4517 //pass an array of page_ids to an extension
4518 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4519 }
4520 wfProfileOut( $fname.'-check' );
4521
4522 # Do a second query for different language variants of links and categories
4523 if($wgContLang->hasVariants()){
4524 $linkBatch = new LinkBatch();
4525 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4526 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4527 $varCategories = array(); // category replacements oldDBkey => newDBkey
4528
4529 $categories = $this->mOutput->getCategoryLinks();
4530
4531 // Add variants of links to link batch
4532 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4533 $title = $this->mLinkHolders['titles'][$key];
4534 if ( is_null( $title ) )
4535 continue;
4536
4537 $pdbk = $title->getPrefixedDBkey();
4538 $titleText = $title->getText();
4539
4540 // generate all variants of the link title text
4541 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4542
4543 // if link was not found (in first query), add all variants to query
4544 if ( !isset($colours[$pdbk]) ){
4545 foreach($allTextVariants as $textVariant){
4546 if($textVariant != $titleText){
4547 $variantTitle = Title::makeTitle( $ns, $textVariant );
4548 if(is_null($variantTitle)) continue;
4549 $linkBatch->addObj( $variantTitle );
4550 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4551 }
4552 }
4553 }
4554 }
4555
4556 // process categories, check if a category exists in some variant
4557 foreach( $categories as $category ){
4558 $variants = $wgContLang->convertLinkToAllVariants($category);
4559 foreach($variants as $variant){
4560 if($variant != $category){
4561 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
4562 if(is_null($variantTitle)) continue;
4563 $linkBatch->addObj( $variantTitle );
4564 $categoryMap[$variant] = $category;
4565 }
4566 }
4567 }
4568
4569
4570 if(!$linkBatch->isEmpty()){
4571 // construct query
4572 $titleClause = $linkBatch->constructSet('page', $dbr);
4573
4574 $variantQuery = "SELECT page_id, page_namespace, page_title";
4575 if ( $threshold > 0 ) {
4576 $variantQuery .= ', page_len, page_is_redirect';
4577 }
4578
4579 $variantQuery .= " FROM $page WHERE $titleClause";
4580 if ( $options & RLH_FOR_UPDATE ) {
4581 $variantQuery .= ' FOR UPDATE';
4582 }
4583
4584 $varRes = $dbr->query( $variantQuery, $fname );
4585
4586 // for each found variants, figure out link holders and replace
4587 while ( $s = $dbr->fetchObject($varRes) ) {
4588
4589 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
4590 $varPdbk = $variantTitle->getPrefixedDBkey();
4591 $vardbk = $variantTitle->getDBkey();
4592
4593 $holderKeys = array();
4594 if(isset($variantMap[$varPdbk])){
4595 $holderKeys = $variantMap[$varPdbk];
4596 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle );
4597 $this->mOutput->addLink( $variantTitle, $s->page_id );
4598 }
4599
4600 // loop over link holders
4601 foreach($holderKeys as $key){
4602 $title = $this->mLinkHolders['titles'][$key];
4603 if ( is_null( $title ) ) continue;
4604
4605 $pdbk = $title->getPrefixedDBkey();
4606
4607 if(!isset($colours[$pdbk])){
4608 // found link in some of the variants, replace the link holder data
4609 $this->mLinkHolders['titles'][$key] = $variantTitle;
4610 $this->mLinkHolders['dbkeys'][$key] = $variantTitle->getDBkey();
4611
4612 // set pdbk and colour
4613 $pdbks[$key] = $varPdbk;
4614 $colours[$varPdbk] = $sk->getLinkColour( $s, $threshold );
4615 $linkcolour_ids[$s->page_id] = $pdbk;
4616 }
4617 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4618 }
4619
4620 // check if the object is a variant of a category
4621 if(isset($categoryMap[$vardbk])){
4622 $oldkey = $categoryMap[$vardbk];
4623 if($oldkey != $vardbk)
4624 $varCategories[$oldkey]=$vardbk;
4625 }
4626 }
4627
4628 // rebuild the categories in original order (if there are replacements)
4629 if(count($varCategories)>0){
4630 $newCats = array();
4631 $originalCats = $this->mOutput->getCategories();
4632 foreach($originalCats as $cat => $sortkey){
4633 // make the replacement
4634 if( array_key_exists($cat,$varCategories) )
4635 $newCats[$varCategories[$cat]] = $sortkey;
4636 else $newCats[$cat] = $sortkey;
4637 }
4638 $this->mOutput->setCategoryLinks($newCats);
4639 }
4640 }
4641 }
4642
4643 # Construct search and replace arrays
4644 wfProfileIn( $fname.'-construct' );
4645 $replacePairs = array();
4646 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4647 $pdbk = $pdbks[$key];
4648 $searchkey = "<!--LINK $key-->";
4649 $title = $this->mLinkHolders['titles'][$key];
4650 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] == 'new' ) {
4651 $linkCache->addBadLinkObj( $title );
4652 $colours[$pdbk] = 'new';
4653 $this->mOutput->addLink( $title, 0 );
4654 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4655 $this->mLinkHolders['texts'][$key],
4656 $this->mLinkHolders['queries'][$key] );
4657 } else {
4658 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4659 $this->mLinkHolders['texts'][$key],
4660 $this->mLinkHolders['queries'][$key] );
4661 }
4662 }
4663 $replacer = new HashtableReplacer( $replacePairs, 1 );
4664 wfProfileOut( $fname.'-construct' );
4665
4666 # Do the thing
4667 wfProfileIn( $fname.'-replace' );
4668 $text = preg_replace_callback(
4669 '/(<!--LINK .*?-->)/',
4670 $replacer->cb(),
4671 $text);
4672
4673 wfProfileOut( $fname.'-replace' );
4674 }
4675
4676 # Now process interwiki link holders
4677 # This is quite a bit simpler than internal links
4678 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4679 wfProfileIn( $fname.'-interwiki' );
4680 # Make interwiki link HTML
4681 $replacePairs = array();
4682 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4683 $title = $this->mInterwikiLinkHolders['titles'][$key];
4684 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4685 }
4686 $replacer = new HashtableReplacer( $replacePairs, 1 );
4687
4688 $text = preg_replace_callback(
4689 '/<!--IWLINK (.*?)-->/',
4690 $replacer->cb(),
4691 $text );
4692 wfProfileOut( $fname.'-interwiki' );
4693 }
4694
4695 wfProfileOut( $fname );
4696 return $colours;
4697 }
4698
4699 /**
4700 * Replace <!--LINK--> link placeholders with plain text of links
4701 * (not HTML-formatted).
4702 * @param string $text
4703 * @return string
4704 */
4705 function replaceLinkHoldersText( $text ) {
4706 $fname = 'Parser::replaceLinkHoldersText';
4707 wfProfileIn( $fname );
4708
4709 $text = preg_replace_callback(
4710 '/<!--(LINK|IWLINK) (.*?)-->/',
4711 array( &$this, 'replaceLinkHoldersTextCallback' ),
4712 $text );
4713
4714 wfProfileOut( $fname );
4715 return $text;
4716 }
4717
4718 /**
4719 * @param array $matches
4720 * @return string
4721 * @private
4722 */
4723 function replaceLinkHoldersTextCallback( $matches ) {
4724 $type = $matches[1];
4725 $key = $matches[2];
4726 if( $type == 'LINK' ) {
4727 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4728 return $this->mLinkHolders['texts'][$key];
4729 }
4730 } elseif( $type == 'IWLINK' ) {
4731 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4732 return $this->mInterwikiLinkHolders['texts'][$key];
4733 }
4734 }
4735 return $matches[0];
4736 }
4737
4738 /**
4739 * Tag hook handler for 'pre'.
4740 */
4741 function renderPreTag( $text, $attribs ) {
4742 // Backwards-compatibility hack
4743 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4744
4745 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4746 return wfOpenElement( 'pre', $attribs ) .
4747 Xml::escapeTagsOnly( $content ) .
4748 '</pre>';
4749 }
4750
4751 /**
4752 * Renders an image gallery from a text with one line per image.
4753 * text labels may be given by using |-style alternative text. E.g.
4754 * Image:one.jpg|The number "1"
4755 * Image:tree.jpg|A tree
4756 * given as text will return the HTML of a gallery with two images,
4757 * labeled 'The number "1"' and
4758 * 'A tree'.
4759 */
4760 function renderImageGallery( $text, $params ) {
4761 $ig = new ImageGallery();
4762 $ig->setContextTitle( $this->mTitle );
4763 $ig->setShowBytes( false );
4764 $ig->setShowFilename( false );
4765 $ig->setParser( $this );
4766 $ig->setHideBadImages();
4767 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4768 $ig->useSkin( $this->mOptions->getSkin() );
4769 $ig->mRevisionId = $this->mRevisionId;
4770
4771 if( isset( $params['caption'] ) ) {
4772 $caption = $params['caption'];
4773 $caption = htmlspecialchars( $caption );
4774 $caption = $this->replaceInternalLinks( $caption );
4775 $ig->setCaptionHtml( $caption );
4776 }
4777 if( isset( $params['perrow'] ) ) {
4778 $ig->setPerRow( $params['perrow'] );
4779 }
4780 if( isset( $params['widths'] ) ) {
4781 $ig->setWidths( $params['widths'] );
4782 }
4783 if( isset( $params['heights'] ) ) {
4784 $ig->setHeights( $params['heights'] );
4785 }
4786
4787 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4788
4789 $lines = explode( "\n", $text );
4790 foreach ( $lines as $line ) {
4791 # match lines like these:
4792 # Image:someimage.jpg|This is some image
4793 $matches = array();
4794 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4795 # Skip empty lines
4796 if ( count( $matches ) == 0 ) {
4797 continue;
4798 }
4799 $tp = Title::newFromText( $matches[1] );
4800 $nt =& $tp;
4801 if( is_null( $nt ) ) {
4802 # Bogus title. Ignore these so we don't bomb out later.
4803 continue;
4804 }
4805 if ( isset( $matches[3] ) ) {
4806 $label = $matches[3];
4807 } else {
4808 $label = '';
4809 }
4810
4811 $html = $this->recursiveTagParse( trim( $label ) );
4812
4813 $ig->add( $nt, $html );
4814
4815 # Only add real images (bug #5586)
4816 if ( $nt->getNamespace() == NS_IMAGE ) {
4817 $this->mOutput->addImage( $nt->getDBkey() );
4818 }
4819 }
4820 return $ig->toHTML();
4821 }
4822
4823 function getImageParams( $handler ) {
4824 if ( $handler ) {
4825 $handlerClass = get_class( $handler );
4826 } else {
4827 $handlerClass = '';
4828 }
4829 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4830 // Initialise static lists
4831 static $internalParamNames = array(
4832 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4833 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4834 'bottom', 'text-bottom' ),
4835 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4836 'upright', 'border' ),
4837 );
4838 static $internalParamMap;
4839 if ( !$internalParamMap ) {
4840 $internalParamMap = array();
4841 foreach ( $internalParamNames as $type => $names ) {
4842 foreach ( $names as $name ) {
4843 $magicName = str_replace( '-', '_', "img_$name" );
4844 $internalParamMap[$magicName] = array( $type, $name );
4845 }
4846 }
4847 }
4848
4849 // Add handler params
4850 $paramMap = $internalParamMap;
4851 if ( $handler ) {
4852 $handlerParamMap = $handler->getParamMap();
4853 foreach ( $handlerParamMap as $magic => $paramName ) {
4854 $paramMap[$magic] = array( 'handler', $paramName );
4855 }
4856 }
4857 $this->mImageParams[$handlerClass] = $paramMap;
4858 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4859 }
4860 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4861 }
4862
4863 /**
4864 * Parse image options text and use it to make an image
4865 */
4866 function makeImage( $title, $options ) {
4867 # @TODO: let the MediaHandler specify its transform parameters
4868 #
4869 # Check if the options text is of the form "options|alt text"
4870 # Options are:
4871 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4872 # * left no resizing, just left align. label is used for alt= only
4873 # * right same, but right aligned
4874 # * none same, but not aligned
4875 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4876 # * center center the image
4877 # * framed Keep original image size, no magnify-button.
4878 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4879 # * upright reduce width for upright images, rounded to full __0 px
4880 # * border draw a 1px border around the image
4881 # vertical-align values (no % or length right now):
4882 # * baseline
4883 # * sub
4884 # * super
4885 # * top
4886 # * text-top
4887 # * middle
4888 # * bottom
4889 # * text-bottom
4890
4891 $parts = array_map( 'trim', explode( '|', $options) );
4892 $sk = $this->mOptions->getSkin();
4893
4894 # Give extensions a chance to select the file revision for us
4895 $skip = $time = false;
4896 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4897
4898 if ( $skip ) {
4899 return $sk->makeLinkObj( $title );
4900 }
4901
4902 # Get parameter map
4903 $file = wfFindFile( $title, $time );
4904 $handler = $file ? $file->getHandler() : false;
4905
4906 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4907
4908 # Process the input parameters
4909 $caption = '';
4910 $params = array( 'frame' => array(), 'handler' => array(),
4911 'horizAlign' => array(), 'vertAlign' => array() );
4912 foreach( $parts as $part ) {
4913 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4914 if ( isset( $paramMap[$magicName] ) ) {
4915 list( $type, $paramName ) = $paramMap[$magicName];
4916 $params[$type][$paramName] = $value;
4917
4918 // Special case; width and height come in one variable together
4919 if( $type == 'handler' && $paramName == 'width' ) {
4920 $m = array();
4921 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4922 $params[$type]['width'] = intval( $m[1] );
4923 $params[$type]['height'] = intval( $m[2] );
4924 } else {
4925 $params[$type]['width'] = intval( $value );
4926 }
4927 }
4928 } else {
4929 $caption = $part;
4930 }
4931 }
4932
4933 # Process alignment parameters
4934 if ( $params['horizAlign'] ) {
4935 $params['frame']['align'] = key( $params['horizAlign'] );
4936 }
4937 if ( $params['vertAlign'] ) {
4938 $params['frame']['valign'] = key( $params['vertAlign'] );
4939 }
4940
4941 # Validate the handler parameters
4942 if ( $handler ) {
4943 foreach ( $params['handler'] as $name => $value ) {
4944 if ( !$handler->validateParam( $name, $value ) ) {
4945 unset( $params['handler'][$name] );
4946 }
4947 }
4948 }
4949
4950 # Strip bad stuff out of the alt text
4951 $alt = $this->replaceLinkHoldersText( $caption );
4952
4953 # make sure there are no placeholders in thumbnail attributes
4954 # that are later expanded to html- so expand them now and
4955 # remove the tags
4956 $alt = $this->mStripState->unstripBoth( $alt );
4957 $alt = Sanitizer::stripAllTags( $alt );
4958
4959 $params['frame']['alt'] = $alt;
4960 $params['frame']['caption'] = $caption;
4961
4962 # Linker does the rest
4963 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4964
4965 # Give the handler a chance to modify the parser object
4966 if ( $handler ) {
4967 $handler->parserTransformHook( $this, $file );
4968 }
4969
4970 return $ret;
4971 }
4972
4973 /**
4974 * Set a flag in the output object indicating that the content is dynamic and
4975 * shouldn't be cached.
4976 */
4977 function disableCache() {
4978 wfDebug( "Parser output marked as uncacheable.\n" );
4979 $this->mOutput->mCacheTime = -1;
4980 }
4981
4982 /**#@+
4983 * Callback from the Sanitizer for expanding items found in HTML attribute
4984 * values, so they can be safely tested and escaped.
4985 * @param string $text
4986 * @param PPFrame $frame
4987 * @return string
4988 * @private
4989 */
4990 function attributeStripCallback( &$text, $frame = false ) {
4991 $text = $this->replaceVariables( $text, $frame );
4992 $text = $this->mStripState->unstripBoth( $text );
4993 return $text;
4994 }
4995
4996 /**#@-*/
4997
4998 /**#@+
4999 * Accessor/mutator
5000 */
5001 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
5002 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
5003 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
5004 /**#@-*/
5005
5006 /**#@+
5007 * Accessor
5008 */
5009 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
5010 /**#@-*/
5011
5012
5013 /**
5014 * Break wikitext input into sections, and either pull or replace
5015 * some particular section's text.
5016 *
5017 * External callers should use the getSection and replaceSection methods.
5018 *
5019 * @param string $text Page wikitext
5020 * @param string $section A section identifier string of the form:
5021 * <flag1> - <flag2> - ... - <section number>
5022 *
5023 * Currently the only recognised flag is "T", which means the target section number
5024 * was derived during a template inclusion parse, in other words this is a template
5025 * section edit link. If no flags are given, it was an ordinary section edit link.
5026 * This flag is required to avoid a section numbering mismatch when a section is
5027 * enclosed by <includeonly> (bug 6563).
5028 *
5029 * The section number 0 pulls the text before the first heading; other numbers will
5030 * pull the given section along with its lower-level subsections. If the section is
5031 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5032 *
5033 * @param string $mode One of "get" or "replace"
5034 * @param string $newText Replacement text for section data.
5035 * @return string for "get", the extracted section text.
5036 * for "replace", the whole page with the section replaced.
5037 */
5038 private function extractSections( $text, $section, $mode, $newText='' ) {
5039 global $wgTitle;
5040 $this->clearState();
5041 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
5042 $this->mOptions = new ParserOptions;
5043 $this->setOutputType( OT_WIKI );
5044 $curIndex = 0;
5045 $outText = '';
5046 $frame = new PPFrame( $this );
5047
5048 // Process section extraction flags
5049 $flags = 0;
5050 $sectionParts = explode( '-', $section );
5051 $sectionIndex = array_pop( $sectionParts );
5052 foreach ( $sectionParts as $part ) {
5053 if ( $part == 'T' ) {
5054 $flags |= self::PTD_FOR_INCLUSION;
5055 }
5056 }
5057 // Preprocess the text
5058 $dom = $this->preprocessToDom( $text, $flags );
5059 $root = $dom->documentElement;
5060
5061 // <h> nodes indicate section breaks
5062 // They can only occur at the top level, so we can find them by iterating the root's children
5063 $node = $root->firstChild;
5064
5065 // Find the target section
5066 if ( $sectionIndex == 0 ) {
5067 // Section zero doesn't nest, level=big
5068 $targetLevel = 1000;
5069 } else {
5070 while ( $node ) {
5071 if ( $node->nodeName == 'h' ) {
5072 if ( $curIndex + 1 == $sectionIndex ) {
5073 break;
5074 }
5075 $curIndex++;
5076 }
5077 if ( $mode == 'replace' ) {
5078 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5079 }
5080 $node = $node->nextSibling;
5081 }
5082 if ( $node ) {
5083 $targetLevel = $node->getAttribute( 'level' );
5084 }
5085 }
5086
5087 if ( !$node ) {
5088 // Not found
5089 if ( $mode == 'get' ) {
5090 return $newText;
5091 } else {
5092 return $text;
5093 }
5094 }
5095
5096 // Find the end of the section, including nested sections
5097 do {
5098 if ( $node->nodeName == 'h' ) {
5099 $curIndex++;
5100 $curLevel = $node->getAttribute( 'level' );
5101 if ( $curIndex != $sectionIndex && $curLevel <= $targetLevel ) {
5102 break;
5103 }
5104 }
5105 if ( $mode == 'get' ) {
5106 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5107 }
5108 $node = $node->nextSibling;
5109 } while ( $node );
5110
5111 // Write out the remainder (in replace mode only)
5112 if ( $mode == 'replace' ) {
5113 // Output the replacement text
5114 // Add two newlines on -- trailing whitespace in $newText is conventionally
5115 // stripped by the editor, so we need both newlines to restore the paragraph gap
5116 $outText .= $newText . "\n\n";
5117 while ( $node ) {
5118 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5119 $node = $node->nextSibling;
5120 }
5121 }
5122
5123 if ( is_string( $outText ) ) {
5124 // Re-insert stripped tags
5125 $outText = trim( $this->mStripState->unstripBoth( $outText ) );
5126 }
5127
5128 return $outText;
5129 }
5130
5131 /**
5132 * This function returns the text of a section, specified by a number ($section).
5133 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5134 * the first section before any such heading (section 0).
5135 *
5136 * If a section contains subsections, these are also returned.
5137 *
5138 * @param string $text text to look in
5139 * @param string $section section identifier
5140 * @param string $deftext default to return if section is not found
5141 * @return string text of the requested section
5142 */
5143 public function getSection( $text, $section, $deftext='' ) {
5144 return $this->extractSections( $text, $section, "get", $deftext );
5145 }
5146
5147 public function replaceSection( $oldtext, $section, $text ) {
5148 return $this->extractSections( $oldtext, $section, "replace", $text );
5149 }
5150
5151 /**
5152 * Get the timestamp associated with the current revision, adjusted for
5153 * the default server-local timestamp
5154 */
5155 function getRevisionTimestamp() {
5156 if ( is_null( $this->mRevisionTimestamp ) ) {
5157 wfProfileIn( __METHOD__ );
5158 global $wgContLang;
5159 $dbr = wfGetDB( DB_SLAVE );
5160 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
5161 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
5162
5163 // Normalize timestamp to internal MW format for timezone processing.
5164 // This has the added side-effect of replacing a null value with
5165 // the current time, which gives us more sensible behavior for
5166 // previews.
5167 $timestamp = wfTimestamp( TS_MW, $timestamp );
5168
5169 // The cryptic '' timezone parameter tells to use the site-default
5170 // timezone offset instead of the user settings.
5171 //
5172 // Since this value will be saved into the parser cache, served
5173 // to other users, and potentially even used inside links and such,
5174 // it needs to be consistent for all visitors.
5175 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5176
5177 wfProfileOut( __METHOD__ );
5178 }
5179 return $this->mRevisionTimestamp;
5180 }
5181
5182 /**
5183 * Mutator for $mDefaultSort
5184 *
5185 * @param $sort New value
5186 */
5187 public function setDefaultSort( $sort ) {
5188 $this->mDefaultSort = $sort;
5189 }
5190
5191 /**
5192 * Accessor for $mDefaultSort
5193 * Will use the title/prefixed title if none is set
5194 *
5195 * @return string
5196 */
5197 public function getDefaultSort() {
5198 if( $this->mDefaultSort !== false ) {
5199 return $this->mDefaultSort;
5200 } else {
5201 return $this->mTitle->getNamespace() == NS_CATEGORY
5202 ? $this->mTitle->getText()
5203 : $this->mTitle->getPrefixedText();
5204 }
5205 }
5206
5207 /**
5208 * Try to guess the section anchor name based on a wikitext fragment
5209 * presumably extracted from a heading, for example "Header" from
5210 * "== Header ==".
5211 */
5212 public function guessSectionNameFromWikiText( $text ) {
5213 # Strip out wikitext links(they break the anchor)
5214 $text = $this->stripSectionName( $text );
5215 $headline = Sanitizer::decodeCharReferences( $text );
5216 # strip out HTML
5217 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
5218 $headline = trim( $headline );
5219 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5220 $replacearray = array(
5221 '%3A' => ':',
5222 '%' => '.'
5223 );
5224 return str_replace(
5225 array_keys( $replacearray ),
5226 array_values( $replacearray ),
5227 $sectionanchor );
5228 }
5229
5230 /**
5231 * Strips a text string of wikitext for use in a section anchor
5232 *
5233 * Accepts a text string and then removes all wikitext from the
5234 * string and leaves only the resultant text (i.e. the result of
5235 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5236 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5237 * to create valid section anchors by mimicing the output of the
5238 * parser when headings are parsed.
5239 *
5240 * @param $text string Text string to be stripped of wikitext
5241 * for use in a Section anchor
5242 * @return Filtered text string
5243 */
5244 public function stripSectionName( $text ) {
5245 # Strip internal link markup
5246 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5247 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5248
5249 # Strip external link markup (FIXME: Not Tolerant to blank link text
5250 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5251 # on how many empty links there are on the page - need to figure that out.
5252 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5253
5254 # Parse wikitext quotes (italics & bold)
5255 $text = $this->doQuotes($text);
5256
5257 # Strip HTML tags
5258 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5259 return $text;
5260 }
5261
5262 /**
5263 * strip/replaceVariables/unstrip for preprocessor regression testing
5264 */
5265 function srvus( $text ) {
5266 $text = $this->replaceVariables( $text );
5267 $text = $this->mStripState->unstripBoth( $text );
5268 $text = Sanitizer::removeHTMLtags( $text );
5269 return $text;
5270 }
5271 }
5272
5273 /**
5274 * @todo document, briefly.
5275 * @addtogroup Parser
5276 */
5277 class StripState {
5278 var $general, $nowiki;
5279
5280 function __construct() {
5281 $this->general = new ReplacementArray;
5282 $this->nowiki = new ReplacementArray;
5283 }
5284
5285 function unstripGeneral( $text ) {
5286 wfProfileIn( __METHOD__ );
5287 do {
5288 $oldText = $text;
5289 $text = $this->general->replace( $text );
5290 } while ( $text != $oldText );
5291 wfProfileOut( __METHOD__ );
5292 return $text;
5293 }
5294
5295 function unstripNoWiki( $text ) {
5296 wfProfileIn( __METHOD__ );
5297 do {
5298 $oldText = $text;
5299 $text = $this->nowiki->replace( $text );
5300 } while ( $text != $oldText );
5301 wfProfileOut( __METHOD__ );
5302 return $text;
5303 }
5304
5305 function unstripBoth( $text ) {
5306 wfProfileIn( __METHOD__ );
5307 do {
5308 $oldText = $text;
5309 $text = $this->general->replace( $text );
5310 $text = $this->nowiki->replace( $text );
5311 } while ( $text != $oldText );
5312 wfProfileOut( __METHOD__ );
5313 return $text;
5314 }
5315 }
5316
5317 /**
5318 * An expansion frame, used as a context to expand the result of preprocessToDom()
5319 */
5320 class PPFrame {
5321 var $parser, $title;
5322 var $titleCache;
5323
5324 /**
5325 * Hashtable listing templates which are disallowed for expansion in this frame,
5326 * having been encountered previously in parent frames.
5327 */
5328 var $loopCheckHash;
5329
5330 /**
5331 * Recursion depth of this frame, top = 0
5332 */
5333 var $depth;
5334
5335 const NO_ARGS = 1;
5336 const NO_TEMPLATES = 2;
5337 const STRIP_COMMENTS = 4;
5338 const NO_IGNORE = 8;
5339
5340 const RECOVER_ORIG = 11;
5341
5342 /**
5343 * Construct a new preprocessor frame.
5344 * @param Parser $parser The parent parser
5345 * @param Title $title The context title, or false if there isn't one
5346 */
5347 function __construct( $parser ) {
5348 $this->parser = $parser;
5349 $this->title = $parser->mTitle;
5350 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
5351 $this->loopCheckHash = array();
5352 $this->depth = 0;
5353 }
5354
5355 /**
5356 * Create a new child frame
5357 * $args is optionally a DOMNodeList containing the template arguments
5358 */
5359 function newChild( $args = false, $title = false ) {
5360 $namedArgs = array();
5361 $numberedArgs = array();
5362 if ( $title === false ) {
5363 $title = $this->title;
5364 }
5365 if ( $args !== false ) {
5366 $xpath = false;
5367 foreach ( $args as $arg ) {
5368 if ( !$xpath ) {
5369 $xpath = new DOMXPath( $arg->ownerDocument );
5370 }
5371
5372 $nameNodes = $xpath->query( 'name', $arg );
5373 $value = $xpath->query( 'value', $arg );
5374 if ( $nameNodes->item( 0 )->hasAttributes() ) {
5375 // Numbered parameter
5376 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
5377 $numberedArgs[$index] = $value->item( 0 );
5378 unset( $namedArgs[$index] );
5379 } else {
5380 // Named parameter
5381 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
5382 $namedArgs[$name] = $value->item( 0 );
5383 unset( $numberedArgs[$name] );
5384 }
5385 }
5386 }
5387 return new PPTemplateFrame( $this->parser, $this, $numberedArgs, $namedArgs, $title );
5388 }
5389
5390 /**
5391 * Expand a DOMNode describing a preprocessed document into plain wikitext,
5392 * using the current context
5393 * @param $root the node
5394 */
5395 function expand( $root, $flags = 0 ) {
5396 if ( is_string( $root ) ) {
5397 return $root;
5398 }
5399
5400 if ( $this->parser->ot['html']
5401 && ++$this->parser->mPPNodeCount > $this->parser->mOptions->mMaxPPNodeCount )
5402 {
5403 return $this->parser->insertStripItem( '<!-- node-count limit exceeded -->' );
5404 }
5405
5406 if ( is_array( $root ) ) {
5407 $s = '';
5408 foreach ( $root as $node ) {
5409 $s .= $this->expand( $node, $flags );
5410 }
5411 } elseif ( $root instanceof DOMNodeList ) {
5412 $s = '';
5413 foreach ( $root as $node ) {
5414 $s .= $this->expand( $node, $flags );
5415 }
5416 } elseif ( $root instanceof DOMNode ) {
5417 if ( $root->nodeType == XML_TEXT_NODE ) {
5418 $s = $root->nodeValue;
5419 } elseif ( $root->nodeName == 'template' ) {
5420 # Double-brace expansion
5421 $xpath = new DOMXPath( $root->ownerDocument );
5422 $titles = $xpath->query( 'title', $root );
5423 $title = $titles->item( 0 );
5424 $parts = $xpath->query( 'part', $root );
5425 if ( $flags & self::NO_TEMPLATES ) {
5426 $s = '{{' . $this->implodeWithFlags( '|', $flags, $title, $parts ) . '}}';
5427 } else {
5428 $lineStart = $root->getAttribute( 'lineStart' );
5429 $params = array(
5430 'title' => $title,
5431 'parts' => $parts,
5432 'lineStart' => $lineStart,
5433 'text' => 'FIXME' );
5434 $s = $this->parser->braceSubstitution( $params, $this );
5435 }
5436 } elseif ( $root->nodeName == 'tplarg' ) {
5437 # Triple-brace expansion
5438 $xpath = new DOMXPath( $root->ownerDocument );
5439 $titles = $xpath->query( 'title', $root );
5440 $title = $titles->item( 0 );
5441 $parts = $xpath->query( 'part', $root );
5442 if ( $flags & self::NO_ARGS || $this->parser->ot['msg'] ) {
5443 $s = '{{{' . $this->implodeWithFlags( '|', $flags, $title, $parts ) . '}}}';
5444 } else {
5445 $params = array( 'title' => $title, 'parts' => $parts, 'text' => 'FIXME' );
5446 $s = $this->parser->argSubstitution( $params, $this );
5447 }
5448 } elseif ( $root->nodeName == 'comment' ) {
5449 # HTML-style comment
5450 if ( $this->parser->ot['html']
5451 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
5452 || ( $flags & self::STRIP_COMMENTS ) )
5453 {
5454 $s = '';
5455 } else {
5456 $s = $root->textContent;
5457 }
5458 } elseif ( $root->nodeName == 'ignore' ) {
5459 # Output suppression used by <includeonly> etc.
5460 # OT_WIKI will only respect <ignore> in substed templates.
5461 # The other output types respect it unless NO_IGNORE is set.
5462 # extractSections() sets NO_IGNORE and so never respects it.
5463 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & self::NO_IGNORE ) ) {
5464 $s = $root->textContent;
5465 } else {
5466 $s = '';
5467 }
5468 } elseif ( $root->nodeName == 'ext' ) {
5469 # Extension tag
5470 $xpath = new DOMXPath( $root->ownerDocument );
5471 $names = $xpath->query( 'name', $root );
5472 $attrs = $xpath->query( 'attr', $root );
5473 $inners = $xpath->query( 'inner', $root );
5474 $closes = $xpath->query( 'close', $root );
5475 $params = array(
5476 'name' => $names->item( 0 ),
5477 'attr' => $attrs->length > 0 ? $attrs->item( 0 ) : null,
5478 'inner' => $inners->length > 0 ? $inners->item( 0 ) : null,
5479 'close' => $closes->length > 0 ? $closes->item( 0 ) : null,
5480 );
5481 $s = $this->parser->extensionSubstitution( $params, $this );
5482 } elseif ( $root->nodeName == 'h' ) {
5483 # Heading
5484 $s = $this->expand( $root->childNodes, $flags );
5485
5486 if ( $this->parser->ot['html'] ) {
5487 # Insert heading index marker
5488 $headingIndex = $root->getAttribute( 'i' );
5489 $titleText = $this->title->getPrefixedDBkey();
5490 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
5491 $serial = count( $this->parser->mHeadings ) - 1;
5492 $marker = "{$this->parser->mUniqPrefix}-h-$serial-{$this->parser->mMarkerSuffix}";
5493 $count = $root->getAttribute( 'level' );
5494 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
5495 $this->parser->mStripState->general->setPair( $marker, '' );
5496 }
5497 } else {
5498 # Generic recursive expansion
5499 $s = '';
5500 for ( $node = $root->firstChild; $node; $node = $node->nextSibling ) {
5501 if ( $node->nodeType == XML_TEXT_NODE ) {
5502 $s .= $node->nodeValue;
5503 } elseif ( $node->nodeType == XML_ELEMENT_NODE ) {
5504 $s .= $this->expand( $node, $flags );
5505 }
5506 }
5507 }
5508 } else {
5509 throw new MWException( __METHOD__.': Invalid parameter type' );
5510 }
5511 return $s;
5512 }
5513
5514 function implodeWithFlags( $sep, $flags /*, ... */ ) {
5515 $args = array_slice( func_get_args(), 2 );
5516
5517 $first = true;
5518 $s = '';
5519 foreach ( $args as $root ) {
5520 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
5521 $root = array( $root );
5522 }
5523 foreach ( $root as $node ) {
5524 if ( $first ) {
5525 $first = false;
5526 } else {
5527 $s .= $sep;
5528 }
5529 $s .= $this->expand( $node, $flags );
5530 }
5531 }
5532 return $s;
5533 }
5534
5535 function implode( $sep /*, ... */ ) {
5536 $args = func_get_args();
5537 $args = array_merge( array_slice( $args, 0, 1 ), array( 0 ), array_slice( $args, 1 ) );
5538 return call_user_func_array( array( $this, 'implodeWithFlags' ), $args );
5539 }
5540
5541 /**
5542 * Split an <arg> or <template> node into a three-element array:
5543 * DOMNode name, string index and DOMNode value
5544 */
5545 function splitBraceNode( $node ) {
5546 $xpath = new DOMXPath( $node->ownerDocument );
5547 $names = $xpath->query( 'name', $node );
5548 $values = $xpath->query( 'value', $node );
5549 if ( !$names->length || !$values->length ) {
5550 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
5551 }
5552 $name = $names->item( 0 );
5553 $index = $name->getAttribute( 'index' );
5554 return array( $name, $index, $values->item( 0 ) );
5555 }
5556
5557 /**
5558 * Split an <ext> node into an associative array containing name, attr, inner and close
5559 * All values in the resulting array are DOMNodes. Inner and close are optional.
5560 */
5561 function splitExtNode( $node ) {
5562 $xpath = new DOMXPath( $node->ownerDocument );
5563 $names = $xpath->query( 'name', $node );
5564 $attrs = $xpath->query( 'attr', $node );
5565 $inners = $xpath->query( 'inner', $node );
5566 $closes = $xpath->query( 'close', $node );
5567 if ( !$names->length || !$attrs->length ) {
5568 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
5569 }
5570 $parts = array(
5571 'name' => $names->item( 0 ),
5572 'attr' => $attrs->item( 0 ) );
5573 if ( $inners->length ) {
5574 $parts['inner'] = $inners->item( 0 );
5575 }
5576 if ( $closes->length ) {
5577 $parts['close'] = $closes->item( 0 );
5578 }
5579 return $parts;
5580 }
5581
5582 function __toString() {
5583 return 'frame{}';
5584 }
5585
5586 function getPDBK( $level = false ) {
5587 if ( $level === false ) {
5588 return $this->title->getPrefixedDBkey();
5589 } else {
5590 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
5591 }
5592 }
5593
5594 /**
5595 * Returns true if there are no arguments in this frame
5596 */
5597 function isEmpty() {
5598 return true;
5599 }
5600
5601 function getArgument( $name ) {
5602 return false;
5603 }
5604
5605 /**
5606 * Returns true if the infinite loop check is OK, false if a loop is detected
5607 */
5608 function loopCheck( $title ) {
5609 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
5610 }
5611 }
5612
5613 /**
5614 * Expansion frame with template arguments
5615 */
5616 class PPTemplateFrame extends PPFrame {
5617 var $numberedArgs, $namedArgs, $parent;
5618 var $numberedExpansionCache, $namedExpansionCache;
5619
5620 function __construct( $parser, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
5621 $this->parser = $parser;
5622 $this->parent = $parent;
5623 $this->numberedArgs = $numberedArgs;
5624 $this->namedArgs = $namedArgs;
5625 $this->title = $title;
5626 $pdbk = $title ? $title->getPrefixedDBkey() : false;
5627 $this->titleCache = $parent->titleCache;
5628 $this->titleCache[] = $pdbk;
5629 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
5630 if ( $pdbk !== false ) {
5631 $this->loopCheckHash[$pdbk] = true;
5632 }
5633 $this->depth = $parent->depth + 1;
5634 $this->numberedExpansionCache = $this->namedExpansionCache = array();
5635 }
5636
5637 function __toString() {
5638 $s = 'tplframe{';
5639 $first = true;
5640 $args = $this->numberedArgs + $this->namedArgs;
5641 foreach ( $args as $name => $value ) {
5642 if ( $first ) {
5643 $first = false;
5644 } else {
5645 $s .= ', ';
5646 }
5647 $s .= "\"$name\":\"" .
5648 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
5649 }
5650 $s .= '}';
5651 return $s;
5652 }
5653 /**
5654 * Returns true if there are no arguments in this frame
5655 */
5656 function isEmpty() {
5657 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
5658 }
5659
5660 function getNumberedArgument( $index ) {
5661 if ( !isset( $this->numberedArgs[$index] ) ) {
5662 return false;
5663 }
5664 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
5665 # No trimming for unnamed arguments
5666 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], self::STRIP_COMMENTS );
5667 }
5668 return $this->numberedExpansionCache[$index];
5669 }
5670
5671 function getNamedArgument( $name ) {
5672 if ( !isset( $this->namedArgs[$name] ) ) {
5673 return false;
5674 }
5675 if ( !isset( $this->namedExpansionCache[$name] ) ) {
5676 # Trim named arguments post-expand, for backwards compatibility
5677 $this->namedExpansionCache[$name] = trim(
5678 $this->parent->expand( $this->namedArgs[$name], self::STRIP_COMMENTS ) );
5679 }
5680 return $this->namedExpansionCache[$name];
5681 }
5682
5683 function getArgument( $name ) {
5684 wfDebug( __METHOD__." getting '$name'\n" );
5685 $text = $this->getNumberedArgument( $name );
5686 if ( $text === false ) {
5687 $text = $this->getNamedArgument( $name );
5688 }
5689 return $text;
5690 }
5691 }
5692
5693 /**
5694 * Stack class to help Parser::preprocessToDom()
5695 */
5696 class PPDStack {
5697 var $stack, $topAccum, $top;
5698
5699 function __construct() {
5700 $this->stack = array();
5701 $this->topAccum = '';
5702 $this->top = false;
5703 }
5704
5705 function &getAccum() {
5706 if ( count( $this->stack ) ) {
5707 return $this->top->getAccum();
5708 } else {
5709 return $this->topAccum;
5710 }
5711 }
5712
5713 function push( $data ) {
5714 if ( $data instanceof PPDStackElement ) {
5715 $this->stack[] = $data;
5716 } else {
5717 $this->stack[] = new PPDStackElement( $data );
5718 }
5719 $this->top =& $this->stack[ count( $this->stack ) - 1 ];
5720 }
5721
5722 function pop() {
5723 if ( !count( $this->stack ) ) {
5724 throw new MWException( __METHOD__.': no elements remaining' );
5725 }
5726 $temp = array_pop( $this->stack );
5727 if ( count( $this->stack ) ) {
5728 $this->top =& $this->stack[ count( $this->stack ) - 1 ];
5729 } else {
5730 $this->top = false;
5731 }
5732 }
5733
5734 function getFlags() {
5735 if ( !count( $this->stack ) ) {
5736 return array(
5737 'findEquals' => false,
5738 'findPipe' => false,
5739 'inHeading' => false,
5740 );
5741 } else {
5742 return $this->top->getFlags();
5743 }
5744 }
5745 }
5746
5747 class PPDStackElement {
5748 var $open, $close, $count, $parts, $eqpos, $lineStart;
5749
5750 function __construct( $data = array() ) {
5751 $this->parts = array( '' );
5752 $this->eqpos = array();
5753
5754 foreach ( $data as $name => $value ) {
5755 $this->$name = $value;
5756 }
5757 }
5758
5759 function &getAccum() {
5760 return $this->parts[count($this->parts) - 1];
5761 }
5762
5763 function addPart( $s = '' ) {
5764 $this->parts[] = $s;
5765 }
5766
5767 function getFlags() {
5768 $partCount = count( $this->parts );
5769 $findPipe = $this->open != "\n" && $this->open != '[';
5770 return array(
5771 'findPipe' => $findPipe,
5772 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->eqpos[$partCount - 1] ),
5773 'inHeading' => $this->open == "\n",
5774 );
5775 }
5776 }