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