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