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