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