* Not nice to sprinkle signatures in random languages
[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 return $this->mRevisionId;
2532 case 'revisionday':
2533 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2534 case 'revisionday2':
2535 return substr( $this->getRevisionTimestamp(), 6, 2 );
2536 case 'revisionmonth':
2537 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2538 case 'revisionyear':
2539 return substr( $this->getRevisionTimestamp(), 0, 4 );
2540 case 'revisiontimestamp':
2541 return $this->getRevisionTimestamp();
2542 case 'namespace':
2543 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2544 case 'namespacee':
2545 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2546 case 'talkspace':
2547 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2548 case 'talkspacee':
2549 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2550 case 'subjectspace':
2551 return $this->mTitle->getSubjectNsText();
2552 case 'subjectspacee':
2553 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2554 case 'currentdayname':
2555 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2556 case 'currentyear':
2557 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2558 case 'currenttime':
2559 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2560 case 'currenthour':
2561 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2562 case 'currentweek':
2563 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2564 // int to remove the padding
2565 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2566 case 'currentdow':
2567 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2568 case 'localdayname':
2569 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2570 case 'localyear':
2571 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2572 case 'localtime':
2573 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2574 case 'localhour':
2575 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2576 case 'localweek':
2577 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2578 // int to remove the padding
2579 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2580 case 'localdow':
2581 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2582 case 'numberofarticles':
2583 return $varCache[$index] = $wgContLang->formatNum( SiteStats::articles() );
2584 case 'numberoffiles':
2585 return $varCache[$index] = $wgContLang->formatNum( SiteStats::images() );
2586 case 'numberofusers':
2587 return $varCache[$index] = $wgContLang->formatNum( SiteStats::users() );
2588 case 'numberofpages':
2589 return $varCache[$index] = $wgContLang->formatNum( SiteStats::pages() );
2590 case 'numberofadmins':
2591 return $varCache[$index] = $wgContLang->formatNum( SiteStats::admins() );
2592 case 'numberofedits':
2593 return $varCache[$index] = $wgContLang->formatNum( SiteStats::edits() );
2594 case 'currenttimestamp':
2595 return $varCache[$index] = wfTimestampNow();
2596 case 'localtimestamp':
2597 return $varCache[$index] = $localTimestamp;
2598 case 'currentversion':
2599 return $varCache[$index] = SpecialVersion::getVersion();
2600 case 'sitename':
2601 return $wgSitename;
2602 case 'server':
2603 return $wgServer;
2604 case 'servername':
2605 return $wgServerName;
2606 case 'scriptpath':
2607 return $wgScriptPath;
2608 case 'directionmark':
2609 return $wgContLang->getDirMark();
2610 case 'contentlanguage':
2611 global $wgContLanguageCode;
2612 return $wgContLanguageCode;
2613 default:
2614 $ret = null;
2615 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2616 return $ret;
2617 else
2618 return null;
2619 }
2620 }
2621
2622 /**
2623 * initialise the magic variables (like CURRENTMONTHNAME)
2624 *
2625 * @private
2626 */
2627 function initialiseVariables() {
2628 $fname = 'Parser::initialiseVariables';
2629 wfProfileIn( $fname );
2630 $variableIDs = MagicWord::getVariableIDs();
2631
2632 $this->mVariables = array();
2633 foreach ( $variableIDs as $id ) {
2634 $mw =& MagicWord::get( $id );
2635 $mw->addToArray( $this->mVariables, $id );
2636 }
2637 wfProfileOut( $fname );
2638 }
2639
2640 /**
2641 * parse any parentheses in format ((title|part|part))
2642 * and call callbacks to get a replacement text for any found piece
2643 *
2644 * @param string $text The text to parse
2645 * @param array $callbacks rules in form:
2646 * '{' => array( # opening parentheses
2647 * 'end' => '}', # closing parentheses
2648 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2649 * 3 => callback # replacement callback to call if {{{..}}} is found
2650 * )
2651 * )
2652 * 'min' => 2, # Minimum parenthesis count in cb
2653 * 'max' => 3, # Maximum parenthesis count in cb
2654 * @private
2655 */
2656 function replace_callback ($text, $callbacks) {
2657 wfProfileIn( __METHOD__ );
2658 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2659 $lastOpeningBrace = -1; # last not closed parentheses
2660
2661 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2662
2663 $i = 0;
2664 while ( $i < strlen( $text ) ) {
2665 # Find next opening brace, closing brace or pipe
2666 if ( $lastOpeningBrace == -1 ) {
2667 $currentClosing = '';
2668 $search = $validOpeningBraces;
2669 } else {
2670 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2671 $search = $validOpeningBraces . '|' . $currentClosing;
2672 }
2673 $rule = null;
2674 $i += strcspn( $text, $search, $i );
2675 if ( $i < strlen( $text ) ) {
2676 if ( $text[$i] == '|' ) {
2677 $found = 'pipe';
2678 } elseif ( $text[$i] == $currentClosing ) {
2679 $found = 'close';
2680 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2681 $found = 'open';
2682 $rule = $callbacks[$text[$i]];
2683 } else {
2684 # Some versions of PHP have a strcspn which stops on null characters
2685 # Ignore and continue
2686 ++$i;
2687 continue;
2688 }
2689 } else {
2690 # All done
2691 break;
2692 }
2693
2694 if ( $found == 'open' ) {
2695 # found opening brace, let's add it to parentheses stack
2696 $piece = array('brace' => $text[$i],
2697 'braceEnd' => $rule['end'],
2698 'title' => '',
2699 'parts' => null);
2700
2701 # count opening brace characters
2702 $piece['count'] = strspn( $text, $piece['brace'], $i );
2703 $piece['startAt'] = $piece['partStart'] = $i + $piece['count'];
2704 $i += $piece['count'];
2705
2706 # we need to add to stack only if opening brace count is enough for one of the rules
2707 if ( $piece['count'] >= $rule['min'] ) {
2708 $lastOpeningBrace ++;
2709 $openingBraceStack[$lastOpeningBrace] = $piece;
2710 }
2711 } elseif ( $found == 'close' ) {
2712 # lets check if it is enough characters for closing brace
2713 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2714 $count = strspn( $text, $text[$i], $i, $maxCount );
2715
2716 # check for maximum matching characters (if there are 5 closing
2717 # characters, we will probably need only 3 - depending on the rules)
2718 $matchingCount = 0;
2719 $matchingCallback = null;
2720 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2721 if ( $count > $cbType['max'] ) {
2722 # The specified maximum exists in the callback array, unless the caller
2723 # has made an error
2724 $matchingCount = $cbType['max'];
2725 } else {
2726 # Count is less than the maximum
2727 # Skip any gaps in the callback array to find the true largest match
2728 # Need to use array_key_exists not isset because the callback can be null
2729 $matchingCount = $count;
2730 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2731 --$matchingCount;
2732 }
2733 }
2734
2735 if ($matchingCount <= 0) {
2736 $i += $count;
2737 continue;
2738 }
2739 $matchingCallback = $cbType['cb'][$matchingCount];
2740
2741 # let's set a title or last part (if '|' was found)
2742 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2743 $openingBraceStack[$lastOpeningBrace]['title'] =
2744 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2745 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2746 } else {
2747 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2748 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2749 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2750 }
2751
2752 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2753 $pieceEnd = $i + $matchingCount;
2754
2755 if( is_callable( $matchingCallback ) ) {
2756 $cbArgs = array (
2757 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2758 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2759 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2760 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2761 );
2762 # finally we can call a user callback and replace piece of text
2763 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2764 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2765 $i = $pieceStart + strlen($replaceWith);
2766 } else {
2767 # null value for callback means that parentheses should be parsed, but not replaced
2768 $i += $matchingCount;
2769 }
2770
2771 # reset last opening parentheses, but keep it in case there are unused characters
2772 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2773 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2774 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2775 'title' => '',
2776 'parts' => null,
2777 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2778 $openingBraceStack[$lastOpeningBrace--] = null;
2779
2780 if ($matchingCount < $piece['count']) {
2781 $piece['count'] -= $matchingCount;
2782 $piece['startAt'] -= $matchingCount;
2783 $piece['partStart'] = $piece['startAt'];
2784 # do we still qualify for any callback with remaining count?
2785 $currentCbList = $callbacks[$piece['brace']]['cb'];
2786 while ( $piece['count'] ) {
2787 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2788 $lastOpeningBrace++;
2789 $openingBraceStack[$lastOpeningBrace] = $piece;
2790 break;
2791 }
2792 --$piece['count'];
2793 }
2794 }
2795 } elseif ( $found == 'pipe' ) {
2796 # lets set a title if it is a first separator, or next part otherwise
2797 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2798 $openingBraceStack[$lastOpeningBrace]['title'] =
2799 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2800 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2801 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2802 } else {
2803 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2804 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2805 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2806 }
2807 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++$i;
2808 }
2809 }
2810
2811 wfProfileOut( __METHOD__ );
2812 return $text;
2813 }
2814
2815 /**
2816 * Replace magic variables, templates, and template arguments
2817 * with the appropriate text. Templates are substituted recursively,
2818 * taking care to avoid infinite loops.
2819 *
2820 * Note that the substitution depends on value of $mOutputType:
2821 * OT_WIKI: only {{subst:}} templates
2822 * OT_MSG: only magic variables
2823 * OT_HTML: all templates and magic variables
2824 *
2825 * @param string $tex The text to transform
2826 * @param array $args Key-value pairs representing template parameters to substitute
2827 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2828 * @private
2829 */
2830 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2831 # Prevent too big inclusions
2832 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2833 return $text;
2834 }
2835
2836 $fname = __METHOD__ /*. '-L' . count( $this->mArgStack )*/;
2837 wfProfileIn( $fname );
2838
2839 # This function is called recursively. To keep track of arguments we need a stack:
2840 array_push( $this->mArgStack, $args );
2841
2842 $braceCallbacks = array();
2843 if ( !$argsOnly ) {
2844 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2845 }
2846 if ( $this->mOutputType != OT_MSG ) {
2847 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2848 }
2849 if ( $braceCallbacks ) {
2850 $callbacks = array(
2851 '{' => array(
2852 'end' => '}',
2853 'cb' => $braceCallbacks,
2854 'min' => $argsOnly ? 3 : 2,
2855 'max' => isset( $braceCallbacks[3] ) ? 3 : 2,
2856 ),
2857 '[' => array(
2858 'end' => ']',
2859 'cb' => array(2=>null),
2860 'min' => 2,
2861 'max' => 2,
2862 )
2863 );
2864 $text = $this->replace_callback ($text, $callbacks);
2865
2866 array_pop( $this->mArgStack );
2867 }
2868 wfProfileOut( $fname );
2869 return $text;
2870 }
2871
2872 /**
2873 * Replace magic variables
2874 * @private
2875 */
2876 function variableSubstitution( $matches ) {
2877 global $wgContLang;
2878 $fname = 'Parser::variableSubstitution';
2879 $varname = $wgContLang->lc($matches[1]);
2880 wfProfileIn( $fname );
2881 $skip = false;
2882 if ( $this->mOutputType == OT_WIKI ) {
2883 # Do only magic variables prefixed by SUBST
2884 $mwSubst =& MagicWord::get( 'subst' );
2885 if (!$mwSubst->matchStartAndRemove( $varname ))
2886 $skip = true;
2887 # Note that if we don't substitute the variable below,
2888 # we don't remove the {{subst:}} magic word, in case
2889 # it is a template rather than a magic variable.
2890 }
2891 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2892 $id = $this->mVariables[$varname];
2893 # Now check if we did really match, case sensitive or not
2894 $mw =& MagicWord::get( $id );
2895 if ($mw->match($matches[1])) {
2896 $text = $this->getVariableValue( $id );
2897 $this->mOutput->mContainsOldMagic = true;
2898 } else {
2899 $text = $matches[0];
2900 }
2901 } else {
2902 $text = $matches[0];
2903 }
2904 wfProfileOut( $fname );
2905 return $text;
2906 }
2907
2908
2909 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2910 static function createAssocArgs( $args ) {
2911 $assocArgs = array();
2912 $index = 1;
2913 foreach( $args as $arg ) {
2914 $eqpos = strpos( $arg, '=' );
2915 if ( $eqpos === false ) {
2916 $assocArgs[$index++] = $arg;
2917 } else {
2918 $name = trim( substr( $arg, 0, $eqpos ) );
2919 $value = trim( substr( $arg, $eqpos+1 ) );
2920 if ( $value === false ) {
2921 $value = '';
2922 }
2923 if ( $name !== false ) {
2924 $assocArgs[$name] = $value;
2925 }
2926 }
2927 }
2928
2929 return $assocArgs;
2930 }
2931
2932 /**
2933 * Return the text of a template, after recursively
2934 * replacing any variables or templates within the template.
2935 *
2936 * @param array $piece The parts of the template
2937 * $piece['text']: matched text
2938 * $piece['title']: the title, i.e. the part before the |
2939 * $piece['parts']: the parameter array
2940 * @return string the text of the template
2941 * @private
2942 */
2943 function braceSubstitution( $piece ) {
2944 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2945 $fname = __METHOD__ /*. '-L' . count( $this->mArgStack )*/;
2946 wfProfileIn( $fname );
2947 wfProfileIn( __METHOD__.'-setup' );
2948
2949 # Flags
2950 $found = false; # $text has been filled
2951 $nowiki = false; # wiki markup in $text should be escaped
2952 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2953 $noargs = false; # Don't replace triple-brace arguments in $text
2954 $replaceHeadings = false; # Make the edit section links go to the template not the article
2955 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2956 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2957 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2958
2959 # Title object, where $text came from
2960 $title = NULL;
2961
2962 $linestart = '';
2963
2964
2965 # $part1 is the bit before the first |, and must contain only title characters
2966 # $args is a list of arguments, starting from index 0, not including $part1
2967
2968 $titleText = $part1 = $piece['title'];
2969 # If the third subpattern matched anything, it will start with |
2970
2971 if (null == $piece['parts']) {
2972 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2973 if ($replaceWith != $piece['text']) {
2974 $text = $replaceWith;
2975 $found = true;
2976 $noparse = true;
2977 $noargs = true;
2978 }
2979 }
2980
2981 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2982 wfProfileOut( __METHOD__.'-setup' );
2983
2984 # SUBST
2985 wfProfileIn( __METHOD__.'-modifiers' );
2986 if ( !$found ) {
2987 $mwSubst =& MagicWord::get( 'subst' );
2988 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
2989 # One of two possibilities is true:
2990 # 1) Found SUBST but not in the PST phase
2991 # 2) Didn't find SUBST and in the PST phase
2992 # In either case, return without further processing
2993 $text = $piece['text'];
2994 $found = true;
2995 $noparse = true;
2996 $noargs = true;
2997 }
2998 }
2999
3000 # MSG, MSGNW and RAW
3001 if ( !$found ) {
3002 # Check for MSGNW:
3003 $mwMsgnw =& MagicWord::get( 'msgnw' );
3004 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3005 $nowiki = true;
3006 } else {
3007 # Remove obsolete MSG:
3008 $mwMsg =& MagicWord::get( 'msg' );
3009 $mwMsg->matchStartAndRemove( $part1 );
3010 }
3011
3012 # Check for RAW:
3013 $mwRaw =& MagicWord::get( 'raw' );
3014 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3015 $forceRawInterwiki = true;
3016 }
3017 }
3018 wfProfileOut( __METHOD__.'-modifiers' );
3019
3020 //save path level before recursing into functions & templates.
3021 $lastPathLevel = $this->mTemplatePath;
3022
3023 # Parser functions
3024 if ( !$found ) {
3025 wfProfileIn( __METHOD__ . '-pfunc' );
3026
3027 $colonPos = strpos( $part1, ':' );
3028 if ( $colonPos !== false ) {
3029 # Case sensitive functions
3030 $function = substr( $part1, 0, $colonPos );
3031 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3032 $function = $this->mFunctionSynonyms[1][$function];
3033 } else {
3034 # Case insensitive functions
3035 $function = strtolower( $function );
3036 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3037 $function = $this->mFunctionSynonyms[0][$function];
3038 } else {
3039 $function = false;
3040 }
3041 }
3042 if ( $function ) {
3043 $funcArgs = array_map( 'trim', $args );
3044 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos + 1 ) ) ), $funcArgs );
3045 $result = call_user_func_array( $this->mFunctionHooks[$function], $funcArgs );
3046 $found = true;
3047
3048 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
3049 //$noargs = true;
3050 //$noparse = true;
3051
3052 if ( is_array( $result ) ) {
3053 if ( isset( $result[0] ) ) {
3054 $text = $linestart . $result[0];
3055 unset( $result[0] );
3056 }
3057
3058 // Extract flags into the local scope
3059 // This allows callers to set flags such as nowiki, noparse, found, etc.
3060 extract( $result );
3061 } else {
3062 $text = $linestart . $result;
3063 }
3064 }
3065 }
3066 wfProfileOut( __METHOD__ . '-pfunc' );
3067 }
3068
3069 # Template table test
3070
3071 # Did we encounter this template already? If yes, it is in the cache
3072 # and we need to check for loops.
3073 if ( !$found && isset( $this->mTemplates[$piece['title']] ) ) {
3074 $found = true;
3075
3076 # Infinite loop test
3077 if ( isset( $this->mTemplatePath[$part1] ) ) {
3078 $noparse = true;
3079 $noargs = true;
3080 $found = true;
3081 $text = $linestart .
3082 "[[$part1]]<!-- WARNING: template loop detected -->";
3083 wfDebug( __METHOD__.": template loop broken at '$part1'\n" );
3084 } else {
3085 # set $text to cached message.
3086 $text = $linestart . $this->mTemplates[$piece['title']];
3087 #treat title for cached page the same as others
3088 $ns = NS_TEMPLATE;
3089 $subpage = '';
3090 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3091 if ($subpage !== '') {
3092 $ns = $this->mTitle->getNamespace();
3093 }
3094 $title = Title::newFromText( $part1, $ns );
3095 //used by include size checking
3096 $titleText = $title->getPrefixedText();
3097 //used by edit section links
3098 $replaceHeadings = true;
3099
3100 }
3101 }
3102
3103 # Load from database
3104 if ( !$found ) {
3105 wfProfileIn( __METHOD__ . '-loadtpl' );
3106 $ns = NS_TEMPLATE;
3107 # declaring $subpage directly in the function call
3108 # does not work correctly with references and breaks
3109 # {{/subpage}}-style inclusions
3110 $subpage = '';
3111 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3112 if ($subpage !== '') {
3113 $ns = $this->mTitle->getNamespace();
3114 }
3115 $title = Title::newFromText( $part1, $ns );
3116
3117
3118 if ( !is_null( $title ) ) {
3119 $titleText = $title->getPrefixedText();
3120 # Check for language variants if the template is not found
3121 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3122 $wgContLang->findVariantLink($part1, $title);
3123 }
3124
3125 if ( !$title->isExternal() ) {
3126 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
3127 $text = SpecialPage::capturePath( $title );
3128 if ( is_string( $text ) ) {
3129 $found = true;
3130 $noparse = true;
3131 $noargs = true;
3132 $isHTML = true;
3133 $this->disableCache();
3134 }
3135 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3136 $found = false; //access denied
3137 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3138 } else {
3139 list($articleContent,$title) = $this->fetchTemplateAndtitle( $title );
3140 if ( $articleContent !== false ) {
3141 $found = true;
3142 $text = $articleContent;
3143 $replaceHeadings = true;
3144 }
3145 }
3146
3147 # If the title is valid but undisplayable, make a link to it
3148 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3149 $text = "[[:$titleText]]";
3150 $found = true;
3151 }
3152 } elseif ( $title->isTrans() ) {
3153 // Interwiki transclusion
3154 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3155 $text = $this->interwikiTransclude( $title, 'render' );
3156 $isHTML = true;
3157 $noparse = true;
3158 } else {
3159 $text = $this->interwikiTransclude( $title, 'raw' );
3160 $replaceHeadings = true;
3161 }
3162 $found = true;
3163 }
3164
3165 # Template cache array insertion
3166 # Use the original $piece['title'] not the mangled $part1, so that
3167 # modifiers such as RAW: produce separate cache entries
3168 if( $found ) {
3169 if( $isHTML ) {
3170 // A special page; don't store it in the template cache.
3171 } else {
3172 $this->mTemplates[$piece['title']] = $text;
3173 }
3174 $text = $linestart . $text;
3175 }
3176 }
3177 wfProfileOut( __METHOD__ . '-loadtpl' );
3178 }
3179
3180 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3181 # Error, oversize inclusion
3182 $text = $linestart .
3183 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3184 $noparse = true;
3185 $noargs = true;
3186 }
3187
3188 # Recursive parsing, escaping and link table handling
3189 # Only for HTML output
3190 if ( $nowiki && $found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3191 $text = wfEscapeWikiText( $text );
3192 } elseif ( !$this->ot['msg'] && $found ) {
3193 if ( $noargs ) {
3194 $assocArgs = array();
3195 } else {
3196 # Clean up argument array
3197 $assocArgs = self::createAssocArgs($args);
3198 # Add a new element to the templace recursion path
3199 $this->mTemplatePath[$part1] = 1;
3200 }
3201
3202 if ( !$noparse ) {
3203 # If there are any <onlyinclude> tags, only include them
3204 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3205 $replacer = new OnlyIncludeReplacer;
3206 StringUtils::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3207 array( &$replacer, 'replace' ), $text );
3208 $text = $replacer->output;
3209 }
3210 # Remove <noinclude> sections and <includeonly> tags
3211 $text = StringUtils::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3212 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3213
3214 if( $this->ot['html'] || $this->ot['pre'] ) {
3215 # Strip <nowiki>, <pre>, etc.
3216 $text = $this->strip( $text, $this->mStripState );
3217 if ( $this->ot['html'] ) {
3218 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3219 } elseif ( $this->ot['pre'] && $this->mOptions->getRemoveComments() ) {
3220 $text = Sanitizer::removeHTMLcomments( $text );
3221 }
3222 }
3223 $text = $this->replaceVariables( $text, $assocArgs );
3224
3225 # If the template begins with a table or block-level
3226 # element, it should be treated as beginning a new line.
3227 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3228 $text = "\n" . $text;
3229 }
3230 } elseif ( !$noargs ) {
3231 # $noparse and !$noargs
3232 # Just replace the arguments, not any double-brace items
3233 # This is used for rendered interwiki transclusion
3234 $text = $this->replaceVariables( $text, $assocArgs, true );
3235 }
3236 }
3237 # Prune lower levels off the recursion check path
3238 $this->mTemplatePath = $lastPathLevel;
3239
3240 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3241 # Error, oversize inclusion
3242 $text = $linestart .
3243 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3244 $noparse = true;
3245 $noargs = true;
3246 }
3247
3248 if ( !$found ) {
3249 wfProfileOut( $fname );
3250 return $piece['text'];
3251 } else {
3252 wfProfileIn( __METHOD__ . '-placeholders' );
3253 if ( $isHTML ) {
3254 # Replace raw HTML by a placeholder
3255 # Add a blank line preceding, to prevent it from mucking up
3256 # immediately preceding headings
3257 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
3258 } else {
3259 # replace ==section headers==
3260 # XXX this needs to go away once we have a better parser.
3261 if ( !$this->ot['wiki'] && !$this->ot['pre'] && $replaceHeadings ) {
3262 if( !is_null( $title ) )
3263 $encodedname = base64_encode($title->getPrefixedDBkey());
3264 else
3265 $encodedname = base64_encode("");
3266 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3267 PREG_SPLIT_DELIM_CAPTURE);
3268 $text = '';
3269 $nsec = $headingOffset;
3270
3271 for( $i = 0; $i < count($m); $i += 2 ) {
3272 $text .= $m[$i];
3273 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
3274 $hl = $m[$i + 1];
3275 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3276 $text .= $hl;
3277 continue;
3278 }
3279 $m2 = array();
3280 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3281 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3282 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3283
3284 $nsec++;
3285 }
3286 }
3287 }
3288 wfProfileOut( __METHOD__ . '-placeholders' );
3289 }
3290
3291 # Prune lower levels off the recursion check path
3292 $this->mTemplatePath = $lastPathLevel;
3293
3294 if ( !$found ) {
3295 wfProfileOut( $fname );
3296 return $piece['text'];
3297 } else {
3298 wfProfileOut( $fname );
3299 return $text;
3300 }
3301 }
3302
3303 /**
3304 * Fetch the unparsed text of a template and register a reference to it.
3305 */
3306 function fetchTemplateAndtitle( $title ) {
3307 $text = $skip = false;
3308 $finalTitle = $title;
3309 // Loop to fetch the article, with up to 1 redirect
3310 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3311 # Give extensions a chance to select the revision instead
3312 $id = false; // Assume current
3313 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( &$this, &$title, &$skip, &$id ) );
3314
3315 if( $skip ) {
3316 $text = false;
3317 $this->mOutput->addTemplate( $title, $title->getArticleID(), null );
3318 break;
3319 }
3320 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3321 $rev_id = $rev ? $rev->getId() : 0;
3322
3323 $this->mOutput->addTemplate( $title, $title->getArticleID(), $rev_id );
3324
3325 if( $rev ) {
3326 $text = $rev->getText();
3327 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3328 global $wgLang;
3329 $message = $wgLang->lcfirst( $title->getText() );
3330 $text = wfMsgForContentNoTrans( $message );
3331 if( wfEmptyMsg( $message, $text ) ) {
3332 $text = false;
3333 break;
3334 }
3335 } else {
3336 break;
3337 }
3338 if ( $text === false ) {
3339 break;
3340 }
3341 // Redirect?
3342 $finalTitle = $title;
3343 $title = Title::newFromRedirect( $text );
3344 }
3345 return array($text,$finalTitle);
3346 }
3347
3348 function fetchTemplate( $title ) {
3349 $rv = $this->fetchTemplateAndtitle($title);
3350 return $rv[0];
3351 }
3352
3353 /**
3354 * Transclude an interwiki link.
3355 */
3356 function interwikiTransclude( $title, $action ) {
3357 global $wgEnableScaryTranscluding;
3358
3359 if (!$wgEnableScaryTranscluding)
3360 return wfMsg('scarytranscludedisabled');
3361
3362 $url = $title->getFullUrl( "action=$action" );
3363
3364 if (strlen($url) > 255)
3365 return wfMsg('scarytranscludetoolong');
3366 return $this->fetchScaryTemplateMaybeFromCache($url);
3367 }
3368
3369 function fetchScaryTemplateMaybeFromCache($url) {
3370 global $wgTranscludeCacheExpiry;
3371 $dbr = wfGetDB(DB_SLAVE);
3372 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3373 array('tc_url' => $url));
3374 if ($obj) {
3375 $time = $obj->tc_time;
3376 $text = $obj->tc_contents;
3377 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3378 return $text;
3379 }
3380 }
3381
3382 $text = Http::get($url);
3383 if (!$text)
3384 return wfMsg('scarytranscludefailed', $url);
3385
3386 $dbw = wfGetDB(DB_MASTER);
3387 $dbw->replace('transcache', array('tc_url'), array(
3388 'tc_url' => $url,
3389 'tc_time' => time(),
3390 'tc_contents' => $text));
3391 return $text;
3392 }
3393
3394
3395 /**
3396 * Triple brace replacement -- used for template arguments
3397 * @private
3398 */
3399 function argSubstitution( $matches ) {
3400 $arg = trim( $matches['title'] );
3401 $text = $matches['text'];
3402 $inputArgs = end( $this->mArgStack );
3403
3404 if ( array_key_exists( $arg, $inputArgs ) ) {
3405 $text = $inputArgs[$arg];
3406 } else if (($this->mOutputType == OT_HTML || $this->mOutputType == OT_PREPROCESS ) &&
3407 null != $matches['parts'] && count($matches['parts']) > 0) {
3408 $text = $matches['parts'][0];
3409 }
3410 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3411 $text = $matches['text'] .
3412 '<!-- WARNING: argument omitted, expansion size too large -->';
3413 }
3414
3415 return $text;
3416 }
3417
3418 /**
3419 * Increment an include size counter
3420 *
3421 * @param string $type The type of expansion
3422 * @param integer $size The size of the text
3423 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3424 */
3425 function incrementIncludeSize( $type, $size ) {
3426 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
3427 return false;
3428 } else {
3429 $this->mIncludeSizes[$type] += $size;
3430 return true;
3431 }
3432 }
3433
3434 /**
3435 * Detect __NOGALLERY__ magic word and set a placeholder
3436 */
3437 function stripNoGallery( &$text ) {
3438 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3439 # do not add TOC
3440 $mw = MagicWord::get( 'nogallery' );
3441 $this->mOutput->mNoGallery = $mw->matchAndRemove( $text ) ;
3442 }
3443
3444 /**
3445 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3446 * placeholder that will then be replaced by the real TOC in
3447 * ->formatHeadings, this works because at this points real
3448 * comments will have already been discarded by the sanitizer.
3449 *
3450 * Any additional __TOC__ magic words left over will be discarded
3451 * as there can only be one TOC on the page.
3452 */
3453 function stripToc( $text ) {
3454 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3455 # do not add TOC
3456 $mw = MagicWord::get( 'notoc' );
3457 if( $mw->matchAndRemove( $text ) ) {
3458 $this->mShowToc = false;
3459 }
3460
3461 $mw = MagicWord::get( 'toc' );
3462 if( $mw->match( $text ) ) {
3463 $this->mShowToc = true;
3464 $this->mForceTocPosition = true;
3465
3466 // Set a placeholder. At the end we'll fill it in with the TOC.
3467 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3468
3469 // Only keep the first one.
3470 $text = $mw->replace( '', $text );
3471 }
3472 return $text;
3473 }
3474
3475 /**
3476 * This function accomplishes several tasks:
3477 * 1) Auto-number headings if that option is enabled
3478 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3479 * 3) Add a Table of contents on the top for users who have enabled the option
3480 * 4) Auto-anchor headings
3481 *
3482 * It loops through all headlines, collects the necessary data, then splits up the
3483 * string and re-inserts the newly formatted headlines.
3484 *
3485 * @param string $text
3486 * @param boolean $isMain
3487 * @private
3488 */
3489 function formatHeadings( $text, $isMain=true ) {
3490 global $wgMaxTocLevel, $wgContLang;
3491
3492 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3493 if( !$this->mTitle->quickUserCan( 'edit' ) ) {
3494 $showEditLink = 0;
3495 } else {
3496 $showEditLink = $this->mOptions->getEditSection();
3497 }
3498
3499 # Inhibit editsection links if requested in the page
3500 $esw =& MagicWord::get( 'noeditsection' );
3501 if( $esw->matchAndRemove( $text ) ) {
3502 $showEditLink = 0;
3503 }
3504
3505 # Get all headlines for numbering them and adding funky stuff like [edit]
3506 # links - this is for later, but we need the number of headlines right now
3507 $matches = array();
3508 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3509
3510 # if there are fewer than 4 headlines in the article, do not show TOC
3511 # unless it's been explicitly enabled.
3512 $enoughToc = $this->mShowToc &&
3513 (($numMatches >= 4) || $this->mForceTocPosition);
3514
3515 # Allow user to stipulate that a page should have a "new section"
3516 # link added via __NEWSECTIONLINK__
3517 $mw =& MagicWord::get( 'newsectionlink' );
3518 if( $mw->matchAndRemove( $text ) )
3519 $this->mOutput->setNewSection( true );
3520
3521 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3522 # override above conditions and always show TOC above first header
3523 $mw =& MagicWord::get( 'forcetoc' );
3524 if ($mw->matchAndRemove( $text ) ) {
3525 $this->mShowToc = true;
3526 $enoughToc = true;
3527 }
3528
3529 # We need this to perform operations on the HTML
3530 $sk = $this->mOptions->getSkin();
3531
3532 # headline counter
3533 $headlineCount = 0;
3534 $sectionCount = 0; # headlineCount excluding template sections
3535 $numVisible = 0;
3536
3537 # Ugh .. the TOC should have neat indentation levels which can be
3538 # passed to the skin functions. These are determined here
3539 $toc = '';
3540 $full = '';
3541 $head = array();
3542 $sublevelCount = array();
3543 $levelCount = array();
3544 $toclevel = 0;
3545 $level = 0;
3546 $prevlevel = 0;
3547 $toclevel = 0;
3548 $prevtoclevel = 0;
3549
3550 foreach( $matches[3] as $headline ) {
3551 $istemplate = 0;
3552 $templatetitle = '';
3553 $templatesection = 0;
3554 $numbering = '';
3555 $mat = array();
3556 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3557 $istemplate = 1;
3558 $templatetitle = base64_decode($mat[1]);
3559 $templatesection = 1 + (int)base64_decode($mat[2]);
3560 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3561 }
3562
3563 if( $toclevel ) {
3564 $prevlevel = $level;
3565 $prevtoclevel = $toclevel;
3566 }
3567 $level = $matches[1][$headlineCount];
3568
3569 if( $doNumberHeadings || $enoughToc ) {
3570
3571 if ( $level > $prevlevel ) {
3572 # Increase TOC level
3573 $toclevel++;
3574 $sublevelCount[$toclevel] = 0;
3575 if( $toclevel<$wgMaxTocLevel ) {
3576 $prevtoclevel = $toclevel;
3577 $toc .= $sk->tocIndent();
3578 $numVisible++;
3579 }
3580 }
3581 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3582 # Decrease TOC level, find level to jump to
3583
3584 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3585 # Can only go down to level 1
3586 $toclevel = 1;
3587 } else {
3588 for ($i = $toclevel; $i > 0; $i--) {
3589 if ( $levelCount[$i] == $level ) {
3590 # Found last matching level
3591 $toclevel = $i;
3592 break;
3593 }
3594 elseif ( $levelCount[$i] < $level ) {
3595 # Found first matching level below current level
3596 $toclevel = $i + 1;
3597 break;
3598 }
3599 }
3600 }
3601 if( $toclevel<$wgMaxTocLevel ) {
3602 if($prevtoclevel < $wgMaxTocLevel) {
3603 # Unindent only if the previous toc level was shown :p
3604 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3605 } else {
3606 $toc .= $sk->tocLineEnd();
3607 }
3608 }
3609 }
3610 else {
3611 # No change in level, end TOC line
3612 if( $toclevel<$wgMaxTocLevel ) {
3613 $toc .= $sk->tocLineEnd();
3614 }
3615 }
3616
3617 $levelCount[$toclevel] = $level;
3618
3619 # count number of headlines for each level
3620 @$sublevelCount[$toclevel]++;
3621 $dot = 0;
3622 for( $i = 1; $i <= $toclevel; $i++ ) {
3623 if( !empty( $sublevelCount[$i] ) ) {
3624 if( $dot ) {
3625 $numbering .= '.';
3626 }
3627 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3628 $dot = 1;
3629 }
3630 }
3631 }
3632
3633 # The canonized header is a version of the header text safe to use for links
3634 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3635 $canonized_headline = $this->mStripState->unstripBoth( $headline );
3636
3637 # Remove link placeholders by the link text.
3638 # <!--LINK number-->
3639 # turns into
3640 # link text with suffix
3641 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3642 "\$this->mLinkHolders['texts'][\$1]",
3643 $canonized_headline );
3644 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3645 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3646 $canonized_headline );
3647
3648 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3649 $tocline = preg_replace(
3650 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3651 array( '', '<$1>'),
3652 $canonized_headline
3653 );
3654 $tocline = trim( $tocline );
3655
3656 # For the anchor, strip out HTML-y stuff period
3657 $canonized_headline = preg_replace( '/<.*?'.'>/', '', $canonized_headline );
3658 $canonized_headline = trim( $canonized_headline );
3659
3660 # Save headline for section edit hint before it's escaped
3661 $headline_hint = $canonized_headline;
3662 $canonized_headline = Sanitizer::escapeId( $canonized_headline );
3663 $refers[$headlineCount] = $canonized_headline;
3664
3665 # count how many in assoc. array so we can track dupes in anchors
3666 isset( $refers[$canonized_headline] ) ? $refers[$canonized_headline]++ : $refers[$canonized_headline] = 1;
3667 $refcount[$headlineCount]=$refers[$canonized_headline];
3668
3669 # Don't number the heading if it is the only one (looks silly)
3670 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3671 # the two are different if the line contains a link
3672 $headline=$numbering . ' ' . $headline;
3673 }
3674
3675 # Create the anchor for linking from the TOC to the section
3676 $anchor = $canonized_headline;
3677 if($refcount[$headlineCount] > 1 ) {
3678 $anchor .= '_' . $refcount[$headlineCount];
3679 }
3680 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3681 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3682 }
3683 # give headline the correct <h#> tag
3684 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3685 if( $istemplate )
3686 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3687 else
3688 $editlink = $sk->editSectionLink($this->mTitle, $sectionCount+1, $headline_hint);
3689 } else {
3690 $editlink = '';
3691 }
3692 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3693
3694 $headlineCount++;
3695 if( !$istemplate )
3696 $sectionCount++;
3697 }
3698
3699 # Never ever show TOC if no headers
3700 if( $numVisible < 1 ) {
3701 $enoughToc = false;
3702 }
3703
3704 if( $enoughToc ) {
3705 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3706 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3707 }
3708 $toc = $sk->tocList( $toc );
3709 }
3710
3711 # split up and insert constructed headlines
3712
3713 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3714 $i = 0;
3715
3716 foreach( $blocks as $block ) {
3717 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3718 # This is the [edit] link that appears for the top block of text when
3719 # section editing is enabled
3720
3721 # Disabled because it broke block formatting
3722 # For example, a bullet point in the top line
3723 # $full .= $sk->editSectionLink(0);
3724 }
3725 $full .= $block;
3726 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3727 # Top anchor now in skin
3728 $full = $full.$toc;
3729 }
3730
3731 if( !empty( $head[$i] ) ) {
3732 $full .= $head[$i];
3733 }
3734 $i++;
3735 }
3736 if( $this->mForceTocPosition ) {
3737 return str_replace( '<!--MWTOC-->', $toc, $full );
3738 } else {
3739 return $full;
3740 }
3741 }
3742
3743 /**
3744 * Transform wiki markup when saving a page by doing \r\n -> \n
3745 * conversion, substitting signatures, {{subst:}} templates, etc.
3746 *
3747 * @param string $text the text to transform
3748 * @param Title &$title the Title object for the current article
3749 * @param User &$user the User object describing the current user
3750 * @param ParserOptions $options parsing options
3751 * @param bool $clearState whether to clear the parser state first
3752 * @return string the altered wiki markup
3753 * @public
3754 */
3755 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3756 $this->mOptions = $options;
3757 $this->mTitle =& $title;
3758 $this->setOutputType( OT_WIKI );
3759
3760 if ( $clearState ) {
3761 $this->clearState();
3762 }
3763
3764 $stripState = new StripState;
3765 $pairs = array(
3766 "\r\n" => "\n",
3767 );
3768 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3769 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3770 $text = $this->pstPass2( $text, $stripState, $user );
3771 $text = $stripState->unstripBoth( $text );
3772 return $text;
3773 }
3774
3775 /**
3776 * Pre-save transform helper function
3777 * @private
3778 */
3779 function pstPass2( $text, &$stripState, $user ) {
3780 global $wgContLang, $wgLocaltimezone;
3781
3782 /* Note: This is the timestamp saved as hardcoded wikitext to
3783 * the database, we use $wgContLang here in order to give
3784 * everyone the same signature and use the default one rather
3785 * than the one selected in each user's preferences.
3786 */
3787 if ( isset( $wgLocaltimezone ) ) {
3788 $oldtz = getenv( 'TZ' );
3789 putenv( 'TZ='.$wgLocaltimezone );
3790 }
3791 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3792 ' (' . date( 'T' ) . ')';
3793 if ( isset( $wgLocaltimezone ) ) {
3794 putenv( 'TZ='.$oldtz );
3795 }
3796
3797 # Variable replacement
3798 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3799 $text = $this->replaceVariables( $text );
3800
3801 # Strip out <nowiki> etc. added via replaceVariables
3802 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3803
3804 # Signatures
3805 $sigText = $this->getUserSig( $user );
3806 $text = strtr( $text, array(
3807 '~~~~~' => $d,
3808 '~~~~' => "$sigText $d",
3809 '~~~' => $sigText
3810 ) );
3811
3812 # Context links: [[|name]] and [[name (context)|]]
3813 #
3814 global $wgLegalTitleChars;
3815 $tc = "[$wgLegalTitleChars]";
3816 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3817
3818 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3819 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3820 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3821
3822 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3823 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3824 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3825
3826 $t = $this->mTitle->getText();
3827 $m = array();
3828 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3829 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3830 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3831 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3832 } else {
3833 # if there's no context, don't bother duplicating the title
3834 $text = preg_replace( $p2, '[[\\1]]', $text );
3835 }
3836
3837 # Trim trailing whitespace
3838 $text = rtrim( $text );
3839
3840 return $text;
3841 }
3842
3843 /**
3844 * Fetch the user's signature text, if any, and normalize to
3845 * validated, ready-to-insert wikitext.
3846 *
3847 * @param User $user
3848 * @return string
3849 * @private
3850 */
3851 function getUserSig( &$user ) {
3852 global $wgMaxSigChars;
3853
3854 $username = $user->getName();
3855 $nickname = $user->getOption( 'nickname' );
3856 $nickname = $nickname === '' ? $username : $nickname;
3857
3858 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3859 $nickname = $username;
3860 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
3861 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3862 # Sig. might contain markup; validate this
3863 if( $this->validateSig( $nickname ) !== false ) {
3864 # Validated; clean up (if needed) and return it
3865 return $this->cleanSig( $nickname, true );
3866 } else {
3867 # Failed to validate; fall back to the default
3868 $nickname = $username;
3869 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3870 }
3871 }
3872
3873 // Make sure nickname doesnt get a sig in a sig
3874 $nickname = $this->cleanSigInSig( $nickname );
3875
3876 # If we're still here, make it a link to the user page
3877 $userpage = $user->getUserPage();
3878 if ( $user->isAnon() ) {
3879 $title = SpecialPage::getTitleFor('Contributions' );
3880 return ( wfMsgForContent( 'signature-ip',
3881 $title->getPrefixedText() . '/' . wfEscapeWikiText( $username ),
3882 wfEscapeWikiText( $nickname ),
3883 $userpage->getTalkPage(), wfMsgForContent('talkpagelinktext') ) );
3884 } else {
3885 return ( wfMsgForContent( 'signature', $userpage->getPrefixedText(),
3886 wfEscapeWikiText( $nickname ),
3887 $userpage->getTalkPage(), wfMsgForContent('talkpagelinktext') ) );
3888 }
3889 }
3890
3891 /**
3892 * Check that the user's signature contains no bad XML
3893 *
3894 * @param string $text
3895 * @return mixed An expanded string, or false if invalid.
3896 */
3897 function validateSig( $text ) {
3898 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3899 }
3900
3901 /**
3902 * Clean up signature text
3903 *
3904 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3905 * 2) Substitute all transclusions
3906 *
3907 * @param string $text
3908 * @param $parsing Whether we're cleaning (preferences save) or parsing
3909 * @return string Signature text
3910 */
3911 function cleanSig( $text, $parsing = false ) {
3912 global $wgTitle;
3913 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI : OT_MSG );
3914
3915 $substWord = MagicWord::get( 'subst' );
3916 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3917 $substText = '{{' . $substWord->getSynonym( 0 );
3918
3919 $text = preg_replace( $substRegex, $substText, $text );
3920 $text = $this->cleanSigInSig( $text );
3921 $text = $this->replaceVariables( $text );
3922
3923 $this->clearState();
3924 return $text;
3925 }
3926
3927 /**
3928 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3929 * @param string $text
3930 * @return string Signature text with /~{3,5}/ removed
3931 */
3932 function cleanSigInSig( $text ) {
3933 $text = preg_replace( '/~{3,5}/', '', $text );
3934 return $text;
3935 }
3936
3937 /**
3938 * Set up some variables which are usually set up in parse()
3939 * so that an external function can call some class members with confidence
3940 * @public
3941 */
3942 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3943 $this->mTitle =& $title;
3944 $this->mOptions = $options;
3945 $this->setOutputType( $outputType );
3946 if ( $clearState ) {
3947 $this->clearState();
3948 }
3949 }
3950
3951 /**
3952 * Transform a MediaWiki message by replacing magic variables.
3953 *
3954 * @param string $text the text to transform
3955 * @param ParserOptions $options options
3956 * @return string the text with variables substituted
3957 * @public
3958 */
3959 function transformMsg( $text, $options ) {
3960 global $wgTitle;
3961 static $executing = false;
3962
3963 $fname = "Parser::transformMsg";
3964
3965 # Guard against infinite recursion
3966 if ( $executing ) {
3967 return $text;
3968 }
3969 $executing = true;
3970
3971 wfProfileIn($fname);
3972
3973 if ( $wgTitle && !( $wgTitle instanceof FakeTitle ) ) {
3974 $this->mTitle = $wgTitle;
3975 } else {
3976 $this->mTitle = Title::newFromText('msg');
3977 }
3978 $this->mOptions = $options;
3979 $this->setOutputType( OT_MSG );
3980 $this->clearState();
3981 $text = $this->replaceVariables( $text );
3982
3983 $executing = false;
3984 wfProfileOut($fname);
3985 return $text;
3986 }
3987
3988 /**
3989 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3990 * The callback should have the following form:
3991 * function myParserHook( $text, $params, &$parser ) { ... }
3992 *
3993 * Transform and return $text. Use $parser for any required context, e.g. use
3994 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3995 *
3996 * @public
3997 *
3998 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3999 * @param mixed $callback The callback function (and object) to use for the tag
4000 *
4001 * @return The old value of the mTagHooks array associated with the hook
4002 */
4003 function setHook( $tag, $callback ) {
4004 $tag = strtolower( $tag );
4005 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4006 $this->mTagHooks[$tag] = $callback;
4007
4008 return $oldVal;
4009 }
4010
4011 function setTransparentTagHook( $tag, $callback ) {
4012 $tag = strtolower( $tag );
4013 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4014 $this->mTransparentTagHooks[$tag] = $callback;
4015
4016 return $oldVal;
4017 }
4018
4019 /**
4020 * Create a function, e.g. {{sum:1|2|3}}
4021 * The callback function should have the form:
4022 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4023 *
4024 * The callback may either return the text result of the function, or an array with the text
4025 * in element 0, and a number of flags in the other elements. The names of the flags are
4026 * specified in the keys. Valid flags are:
4027 * found The text returned is valid, stop processing the template. This
4028 * is on by default.
4029 * nowiki Wiki markup in the return value should be escaped
4030 * noparse Unsafe HTML tags should not be stripped, etc.
4031 * noargs Don't replace triple-brace arguments in the return value
4032 * isHTML The returned text is HTML, armour it against wikitext transformation
4033 *
4034 * @public
4035 *
4036 * @param string $id The magic word ID
4037 * @param mixed $callback The callback function (and object) to use
4038 * @param integer $flags a combination of the following flags:
4039 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4040 *
4041 * @return The old callback function for this name, if any
4042 */
4043 function setFunctionHook( $id, $callback, $flags = 0 ) {
4044 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id] : null;
4045 $this->mFunctionHooks[$id] = $callback;
4046
4047 # Add to function cache
4048 $mw = MagicWord::get( $id );
4049 if( !$mw )
4050 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4051
4052 $synonyms = $mw->getSynonyms();
4053 $sensitive = intval( $mw->isCaseSensitive() );
4054
4055 foreach ( $synonyms as $syn ) {
4056 # Case
4057 if ( !$sensitive ) {
4058 $syn = strtolower( $syn );
4059 }
4060 # Add leading hash
4061 if ( !( $flags & SFH_NO_HASH ) ) {
4062 $syn = '#' . $syn;
4063 }
4064 # Remove trailing colon
4065 if ( substr( $syn, -1, 1 ) == ':' ) {
4066 $syn = substr( $syn, 0, -1 );
4067 }
4068 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4069 }
4070 return $oldVal;
4071 }
4072
4073 /**
4074 * Get all registered function hook identifiers
4075 *
4076 * @return array
4077 */
4078 function getFunctionHooks() {
4079 return array_keys( $this->mFunctionHooks );
4080 }
4081
4082 /**
4083 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4084 * Placeholders created in Skin::makeLinkObj()
4085 * Returns an array of links found, indexed by PDBK:
4086 * 0 - broken
4087 * 1 - normal link
4088 * 2 - stub
4089 * $options is a bit field, RLH_FOR_UPDATE to select for update
4090 */
4091 function replaceLinkHolders( &$text, $options = 0 ) {
4092 global $wgUser;
4093 global $wgContLang;
4094
4095 $fname = 'Parser::replaceLinkHolders';
4096 wfProfileIn( $fname );
4097
4098 $pdbks = array();
4099 $colours = array();
4100 $sk = $this->mOptions->getSkin();
4101 $linkCache =& LinkCache::singleton();
4102
4103 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
4104 wfProfileIn( $fname.'-check' );
4105 $dbr = wfGetDB( DB_SLAVE );
4106 $page = $dbr->tableName( 'page' );
4107 $threshold = $wgUser->getOption('stubthreshold');
4108
4109 # Sort by namespace
4110 asort( $this->mLinkHolders['namespaces'] );
4111
4112 # Generate query
4113 $query = false;
4114 $current = null;
4115 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4116 # Make title object
4117 $title = $this->mLinkHolders['titles'][$key];
4118
4119 # Skip invalid entries.
4120 # Result will be ugly, but prevents crash.
4121 if ( is_null( $title ) ) {
4122 continue;
4123 }
4124 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4125
4126 # Check if it's a static known link, e.g. interwiki
4127 if ( $title->isAlwaysKnown() ) {
4128 $colours[$pdbk] = 1;
4129 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4130 $colours[$pdbk] = 1;
4131 $this->mOutput->addLink( $title, $id );
4132 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4133 $colours[$pdbk] = 0;
4134 } elseif ( $title->getNamespace() == NS_SPECIAL && !SpecialPage::exists( $pdbk ) ) {
4135 $colours[$pdbk] = 0;
4136 } else {
4137 # Not in the link cache, add it to the query
4138 if ( !isset( $current ) ) {
4139 $current = $ns;
4140 $query = "SELECT page_id, page_namespace, page_title";
4141 if ( $threshold > 0 ) {
4142 $query .= ', page_len, page_is_redirect';
4143 }
4144 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4145 } elseif ( $current != $ns ) {
4146 $current = $ns;
4147 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4148 } else {
4149 $query .= ', ';
4150 }
4151
4152 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
4153 }
4154 }
4155 if ( $query ) {
4156 $query .= '))';
4157 if ( $options & RLH_FOR_UPDATE ) {
4158 $query .= ' FOR UPDATE';
4159 }
4160
4161 $res = $dbr->query( $query, $fname );
4162
4163 # Fetch data and form into an associative array
4164 # non-existent = broken
4165 # 1 = known
4166 # 2 = stub
4167 while ( $s = $dbr->fetchObject($res) ) {
4168 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
4169 $pdbk = $title->getPrefixedDBkey();
4170 $linkCache->addGoodLinkObj( $s->page_id, $title );
4171 $this->mOutput->addLink( $title, $s->page_id );
4172
4173 $colours[$pdbk] = ( $threshold == 0 || (
4174 $s->page_len >= $threshold || # always true if $threshold <= 0
4175 $s->page_is_redirect ||
4176 !Namespace::isContent( $s->page_namespace ) )
4177 ? 1 : 2 );
4178 }
4179 }
4180 wfProfileOut( $fname.'-check' );
4181
4182 # Do a second query for different language variants of links and categories
4183 if($wgContLang->hasVariants()){
4184 $linkBatch = new LinkBatch();
4185 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4186 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4187 $varCategories = array(); // category replacements oldDBkey => newDBkey
4188
4189 $categories = $this->mOutput->getCategoryLinks();
4190
4191 // Add variants of links to link batch
4192 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4193 $title = $this->mLinkHolders['titles'][$key];
4194 if ( is_null( $title ) )
4195 continue;
4196
4197 $pdbk = $title->getPrefixedDBkey();
4198 $titleText = $title->getText();
4199
4200 // generate all variants of the link title text
4201 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4202
4203 // if link was not found (in first query), add all variants to query
4204 if ( !isset($colours[$pdbk]) ){
4205 foreach($allTextVariants as $textVariant){
4206 if($textVariant != $titleText){
4207 $variantTitle = Title::makeTitle( $ns, $textVariant );
4208 if(is_null($variantTitle)) continue;
4209 $linkBatch->addObj( $variantTitle );
4210 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4211 }
4212 }
4213 }
4214 }
4215
4216 // process categories, check if a category exists in some variant
4217 foreach( $categories as $category ){
4218 $variants = $wgContLang->convertLinkToAllVariants($category);
4219 foreach($variants as $variant){
4220 if($variant != $category){
4221 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
4222 if(is_null($variantTitle)) continue;
4223 $linkBatch->addObj( $variantTitle );
4224 $categoryMap[$variant] = $category;
4225 }
4226 }
4227 }
4228
4229
4230 if(!$linkBatch->isEmpty()){
4231 // construct query
4232 $titleClause = $linkBatch->constructSet('page', $dbr);
4233
4234 $variantQuery = "SELECT page_id, page_namespace, page_title";
4235 if ( $threshold > 0 ) {
4236 $variantQuery .= ', page_len, page_is_redirect';
4237 }
4238
4239 $variantQuery .= " FROM $page WHERE $titleClause";
4240 if ( $options & RLH_FOR_UPDATE ) {
4241 $variantQuery .= ' FOR UPDATE';
4242 }
4243
4244 $varRes = $dbr->query( $variantQuery, $fname );
4245
4246 // for each found variants, figure out link holders and replace
4247 while ( $s = $dbr->fetchObject($varRes) ) {
4248
4249 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
4250 $varPdbk = $variantTitle->getPrefixedDBkey();
4251 $vardbk = $variantTitle->getDBkey();
4252
4253 $holderKeys = array();
4254 if(isset($variantMap[$varPdbk])){
4255 $holderKeys = $variantMap[$varPdbk];
4256 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle );
4257 $this->mOutput->addLink( $variantTitle, $s->page_id );
4258 }
4259
4260 // loop over link holders
4261 foreach($holderKeys as $key){
4262 $title = $this->mLinkHolders['titles'][$key];
4263 if ( is_null( $title ) ) continue;
4264
4265 $pdbk = $title->getPrefixedDBkey();
4266
4267 if(!isset($colours[$pdbk])){
4268 // found link in some of the variants, replace the link holder data
4269 $this->mLinkHolders['titles'][$key] = $variantTitle;
4270 $this->mLinkHolders['dbkeys'][$key] = $variantTitle->getDBkey();
4271
4272 // set pdbk and colour
4273 $pdbks[$key] = $varPdbk;
4274 if ( $threshold > 0 ) {
4275 $size = $s->page_len;
4276 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
4277 $colours[$varPdbk] = 1;
4278 } else {
4279 $colours[$varPdbk] = 2;
4280 }
4281 }
4282 else {
4283 $colours[$varPdbk] = 1;
4284 }
4285 }
4286 }
4287
4288 // check if the object is a variant of a category
4289 if(isset($categoryMap[$vardbk])){
4290 $oldkey = $categoryMap[$vardbk];
4291 if($oldkey != $vardbk)
4292 $varCategories[$oldkey]=$vardbk;
4293 }
4294 }
4295
4296 // rebuild the categories in original order (if there are replacements)
4297 if(count($varCategories)>0){
4298 $newCats = array();
4299 $originalCats = $this->mOutput->getCategories();
4300 foreach($originalCats as $cat => $sortkey){
4301 // make the replacement
4302 if( array_key_exists($cat,$varCategories) )
4303 $newCats[$varCategories[$cat]] = $sortkey;
4304 else $newCats[$cat] = $sortkey;
4305 }
4306 $this->mOutput->setCategoryLinks($newCats);
4307 }
4308 }
4309 }
4310
4311 # Construct search and replace arrays
4312 wfProfileIn( $fname.'-construct' );
4313 $replacePairs = array();
4314 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4315 $pdbk = $pdbks[$key];
4316 $searchkey = "<!--LINK $key-->";
4317 $title = $this->mLinkHolders['titles'][$key];
4318 if ( empty( $colours[$pdbk] ) ) {
4319 $linkCache->addBadLinkObj( $title );
4320 $colours[$pdbk] = 0;
4321 $this->mOutput->addLink( $title, 0 );
4322 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4323 $this->mLinkHolders['texts'][$key],
4324 $this->mLinkHolders['queries'][$key] );
4325 } elseif ( $colours[$pdbk] == 1 ) {
4326 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4327 $this->mLinkHolders['texts'][$key],
4328 $this->mLinkHolders['queries'][$key] );
4329 } elseif ( $colours[$pdbk] == 2 ) {
4330 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4331 $this->mLinkHolders['texts'][$key],
4332 $this->mLinkHolders['queries'][$key] );
4333 }
4334 }
4335 $replacer = new HashtableReplacer( $replacePairs, 1 );
4336 wfProfileOut( $fname.'-construct' );
4337
4338 # Do the thing
4339 wfProfileIn( $fname.'-replace' );
4340 $text = preg_replace_callback(
4341 '/(<!--LINK .*?-->)/',
4342 $replacer->cb(),
4343 $text);
4344
4345 wfProfileOut( $fname.'-replace' );
4346 }
4347
4348 # Now process interwiki link holders
4349 # This is quite a bit simpler than internal links
4350 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4351 wfProfileIn( $fname.'-interwiki' );
4352 # Make interwiki link HTML
4353 $replacePairs = array();
4354 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4355 $title = $this->mInterwikiLinkHolders['titles'][$key];
4356 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4357 }
4358 $replacer = new HashtableReplacer( $replacePairs, 1 );
4359
4360 $text = preg_replace_callback(
4361 '/<!--IWLINK (.*?)-->/',
4362 $replacer->cb(),
4363 $text );
4364 wfProfileOut( $fname.'-interwiki' );
4365 }
4366
4367 wfProfileOut( $fname );
4368 return $colours;
4369 }
4370
4371 /**
4372 * Replace <!--LINK--> link placeholders with plain text of links
4373 * (not HTML-formatted).
4374 * @param string $text
4375 * @return string
4376 */
4377 function replaceLinkHoldersText( $text ) {
4378 $fname = 'Parser::replaceLinkHoldersText';
4379 wfProfileIn( $fname );
4380
4381 $text = preg_replace_callback(
4382 '/<!--(LINK|IWLINK) (.*?)-->/',
4383 array( &$this, 'replaceLinkHoldersTextCallback' ),
4384 $text );
4385
4386 wfProfileOut( $fname );
4387 return $text;
4388 }
4389
4390 /**
4391 * @param array $matches
4392 * @return string
4393 * @private
4394 */
4395 function replaceLinkHoldersTextCallback( $matches ) {
4396 $type = $matches[1];
4397 $key = $matches[2];
4398 if( $type == 'LINK' ) {
4399 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4400 return $this->mLinkHolders['texts'][$key];
4401 }
4402 } elseif( $type == 'IWLINK' ) {
4403 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4404 return $this->mInterwikiLinkHolders['texts'][$key];
4405 }
4406 }
4407 return $matches[0];
4408 }
4409
4410 /**
4411 * Tag hook handler for 'pre'.
4412 */
4413 function renderPreTag( $text, $attribs ) {
4414 // Backwards-compatibility hack
4415 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4416
4417 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4418 return wfOpenElement( 'pre', $attribs ) .
4419 Xml::escapeTagsOnly( $content ) .
4420 '</pre>';
4421 }
4422
4423 /**
4424 * Renders an image gallery from a text with one line per image.
4425 * text labels may be given by using |-style alternative text. E.g.
4426 * Image:one.jpg|The number "1"
4427 * Image:tree.jpg|A tree
4428 * given as text will return the HTML of a gallery with two images,
4429 * labeled 'The number "1"' and
4430 * 'A tree'.
4431 */
4432 function renderImageGallery( $text, $params ) {
4433 $ig = new ImageGallery();
4434 $ig->setContextTitle( $this->mTitle );
4435 $ig->setShowBytes( false );
4436 $ig->setShowFilename( false );
4437 $ig->setParser( $this );
4438 $ig->setHideBadImages();
4439 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4440 $ig->useSkin( $this->mOptions->getSkin() );
4441 $ig->mRevisionId = $this->mRevisionId;
4442
4443 if( isset( $params['caption'] ) ) {
4444 $caption = $params['caption'];
4445 $caption = htmlspecialchars( $caption );
4446 $caption = $this->replaceInternalLinks( $caption );
4447 $ig->setCaptionHtml( $caption );
4448 }
4449 if( isset( $params['perrow'] ) ) {
4450 $ig->setPerRow( $params['perrow'] );
4451 }
4452 if( isset( $params['widths'] ) ) {
4453 $ig->setWidths( $params['widths'] );
4454 }
4455 if( isset( $params['heights'] ) ) {
4456 $ig->setHeights( $params['heights'] );
4457 }
4458
4459 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4460
4461 $lines = explode( "\n", $text );
4462 foreach ( $lines as $line ) {
4463 # match lines like these:
4464 # Image:someimage.jpg|This is some image
4465 $matches = array();
4466 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4467 # Skip empty lines
4468 if ( count( $matches ) == 0 ) {
4469 continue;
4470 }
4471 $tp = Title::newFromText( $matches[1] );
4472 $nt =& $tp;
4473 if( is_null( $nt ) ) {
4474 # Bogus title. Ignore these so we don't bomb out later.
4475 continue;
4476 }
4477 if ( isset( $matches[3] ) ) {
4478 $label = $matches[3];
4479 } else {
4480 $label = '';
4481 }
4482
4483 $pout = $this->parse( $label,
4484 $this->mTitle,
4485 $this->mOptions,
4486 false, // Strip whitespace...?
4487 false // Don't clear state!
4488 );
4489 $html = $pout->getText();
4490
4491 $ig->add( $nt, $html );
4492
4493 # Only add real images (bug #5586)
4494 if ( $nt->getNamespace() == NS_IMAGE ) {
4495 $this->mOutput->addImage( $nt->getDBkey() );
4496 }
4497 }
4498 return $ig->toHTML();
4499 }
4500
4501 function getImageParams( $handler ) {
4502 if ( $handler ) {
4503 $handlerClass = get_class( $handler );
4504 } else {
4505 $handlerClass = '';
4506 }
4507 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4508 // Initialise static lists
4509 static $internalParamNames = array(
4510 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4511 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4512 'bottom', 'text-bottom' ),
4513 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4514 'upright', 'border' ),
4515 );
4516 static $internalParamMap;
4517 if ( !$internalParamMap ) {
4518 $internalParamMap = array();
4519 foreach ( $internalParamNames as $type => $names ) {
4520 foreach ( $names as $name ) {
4521 $magicName = str_replace( '-', '_', "img_$name" );
4522 $internalParamMap[$magicName] = array( $type, $name );
4523 }
4524 }
4525 }
4526
4527 // Add handler params
4528 $paramMap = $internalParamMap;
4529 if ( $handler ) {
4530 $handlerParamMap = $handler->getParamMap();
4531 foreach ( $handlerParamMap as $magic => $paramName ) {
4532 $paramMap[$magic] = array( 'handler', $paramName );
4533 }
4534 }
4535 $this->mImageParams[$handlerClass] = $paramMap;
4536 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4537 }
4538 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4539 }
4540
4541 /**
4542 * Parse image options text and use it to make an image
4543 */
4544 function makeImage( $title, $options ) {
4545 # @TODO: let the MediaHandler specify its transform parameters
4546 #
4547 # Check if the options text is of the form "options|alt text"
4548 # Options are:
4549 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4550 # * left no resizing, just left align. label is used for alt= only
4551 # * right same, but right aligned
4552 # * none same, but not aligned
4553 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4554 # * center center the image
4555 # * framed Keep original image size, no magnify-button.
4556 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4557 # * upright reduce width for upright images, rounded to full __0 px
4558 # * border draw a 1px border around the image
4559 # vertical-align values (no % or length right now):
4560 # * baseline
4561 # * sub
4562 # * super
4563 # * top
4564 # * text-top
4565 # * middle
4566 # * bottom
4567 # * text-bottom
4568
4569 $parts = array_map( 'trim', explode( '|', $options) );
4570 $sk = $this->mOptions->getSkin();
4571
4572 # Give extensions a chance to select the file revision for us
4573 $skip = $time = false;
4574 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4575
4576 if ( $skip ) {
4577 return $sk->makeLinkObj( $title );
4578 }
4579
4580 # Get parameter map
4581 $file = wfFindFile( $title, $time );
4582 $handler = $file ? $file->getHandler() : false;
4583
4584 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4585
4586 # Process the input parameters
4587 $caption = '';
4588 $params = array( 'frame' => array(), 'handler' => array(),
4589 'horizAlign' => array(), 'vertAlign' => array() );
4590 foreach( $parts as $part ) {
4591 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4592 if ( isset( $paramMap[$magicName] ) ) {
4593 list( $type, $paramName ) = $paramMap[$magicName];
4594 $params[$type][$paramName] = $value;
4595
4596 // Special case; width and height come in one variable together
4597 if( $type == 'handler' && $paramName == 'width' ) {
4598 $m = array();
4599 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4600 $params[$type]['width'] = intval( $m[1] );
4601 $params[$type]['height'] = intval( $m[2] );
4602 } else {
4603 $params[$type]['width'] = intval( $value );
4604 }
4605 }
4606 } else {
4607 $caption = $part;
4608 }
4609 }
4610
4611 # Process alignment parameters
4612 if ( $params['horizAlign'] ) {
4613 $params['frame']['align'] = key( $params['horizAlign'] );
4614 }
4615 if ( $params['vertAlign'] ) {
4616 $params['frame']['valign'] = key( $params['vertAlign'] );
4617 }
4618
4619 # Validate the handler parameters
4620 if ( $handler ) {
4621 foreach ( $params['handler'] as $name => $value ) {
4622 if ( !$handler->validateParam( $name, $value ) ) {
4623 unset( $params['handler'][$name] );
4624 }
4625 }
4626 }
4627
4628 # Strip bad stuff out of the alt text
4629 $alt = $this->replaceLinkHoldersText( $caption );
4630
4631 # make sure there are no placeholders in thumbnail attributes
4632 # that are later expanded to html- so expand them now and
4633 # remove the tags
4634 $alt = $this->mStripState->unstripBoth( $alt );
4635 $alt = Sanitizer::stripAllTags( $alt );
4636
4637 $params['frame']['alt'] = $alt;
4638 $params['frame']['caption'] = $caption;
4639
4640 # Linker does the rest
4641 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4642
4643 # Give the handler a chance to modify the parser object
4644 if ( $handler ) {
4645 $handler->parserTransformHook( $this, $file );
4646 }
4647
4648 return $ret;
4649 }
4650
4651 /**
4652 * Set a flag in the output object indicating that the content is dynamic and
4653 * shouldn't be cached.
4654 */
4655 function disableCache() {
4656 wfDebug( "Parser output marked as uncacheable.\n" );
4657 $this->mOutput->mCacheTime = -1;
4658 }
4659
4660 /**#@+
4661 * Callback from the Sanitizer for expanding items found in HTML attribute
4662 * values, so they can be safely tested and escaped.
4663 * @param string $text
4664 * @param array $args
4665 * @return string
4666 * @private
4667 */
4668 function attributeStripCallback( &$text, $args ) {
4669 $text = $this->replaceVariables( $text, $args );
4670 $text = $this->mStripState->unstripBoth( $text );
4671 return $text;
4672 }
4673
4674 /**#@-*/
4675
4676 /**#@+
4677 * Accessor/mutator
4678 */
4679 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4680 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4681 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4682 /**#@-*/
4683
4684 /**#@+
4685 * Accessor
4686 */
4687 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4688 /**#@-*/
4689
4690
4691 /**
4692 * Break wikitext input into sections, and either pull or replace
4693 * some particular section's text.
4694 *
4695 * External callers should use the getSection and replaceSection methods.
4696 *
4697 * @param $text Page wikitext
4698 * @param $section Numbered section. 0 pulls the text before the first
4699 * heading; other numbers will pull the given section
4700 * along with its lower-level subsections.
4701 * @param $mode One of "get" or "replace"
4702 * @param $newtext Replacement text for section data.
4703 * @return string for "get", the extracted section text.
4704 * for "replace", the whole page with the section replaced.
4705 */
4706 private function extractSections( $text, $section, $mode, $newtext='' ) {
4707 # I.... _hope_ this is right.
4708 # Otherwise, sometimes we don't have things initialized properly.
4709 $this->clearState();
4710
4711 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4712 # comments to be stripped as well)
4713 $stripState = new StripState;
4714
4715 $oldOutputType = $this->mOutputType;
4716 $oldOptions = $this->mOptions;
4717 $this->mOptions = new ParserOptions();
4718 $this->setOutputType( OT_WIKI );
4719
4720 $striptext = $this->strip( $text, $stripState, true );
4721
4722 $this->setOutputType( $oldOutputType );
4723 $this->mOptions = $oldOptions;
4724
4725 # now that we can be sure that no pseudo-sections are in the source,
4726 # split it up by section
4727 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4728 $comment = "(?:$uniq-!--.*?QINU\x07)";
4729 $secs = preg_split(
4730 "/
4731 (
4732 ^
4733 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4734 (=+) # Should this be limited to 6?
4735 .+? # Section title...
4736 \\2 # Ending = count must match start
4737 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4738 $
4739 |
4740 <h([1-6])\b.*?>
4741 .*?
4742 <\/h\\3\s*>
4743 )
4744 /mix",
4745 $striptext, -1,
4746 PREG_SPLIT_DELIM_CAPTURE);
4747
4748 if( $mode == "get" ) {
4749 if( $section == 0 ) {
4750 // "Section 0" returns the content before any other section.
4751 $rv = $secs[0];
4752 } else {
4753 //track missing section, will replace if found.
4754 $rv = $newtext;
4755 }
4756 } elseif( $mode == "replace" ) {
4757 if( $section == 0 ) {
4758 $rv = $newtext . "\n\n";
4759 $remainder = true;
4760 } else {
4761 $rv = $secs[0];
4762 $remainder = false;
4763 }
4764 }
4765 $count = 0;
4766 $sectionLevel = 0;
4767 for( $index = 1; $index < count( $secs ); ) {
4768 $headerLine = $secs[$index++];
4769 if( $secs[$index] ) {
4770 // A wiki header
4771 $headerLevel = strlen( $secs[$index++] );
4772 } else {
4773 // An HTML header
4774 $index++;
4775 $headerLevel = intval( $secs[$index++] );
4776 }
4777 $content = $secs[$index++];
4778
4779 $count++;
4780 if( $mode == "get" ) {
4781 if( $count == $section ) {
4782 $rv = $headerLine . $content;
4783 $sectionLevel = $headerLevel;
4784 } elseif( $count > $section ) {
4785 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4786 $rv .= $headerLine . $content;
4787 } else {
4788 // Broke out to a higher-level section
4789 break;
4790 }
4791 }
4792 } elseif( $mode == "replace" ) {
4793 if( $count < $section ) {
4794 $rv .= $headerLine . $content;
4795 } elseif( $count == $section ) {
4796 $rv .= $newtext . "\n\n";
4797 $sectionLevel = $headerLevel;
4798 } elseif( $count > $section ) {
4799 if( $headerLevel <= $sectionLevel ) {
4800 // Passed the section's sub-parts.
4801 $remainder = true;
4802 }
4803 if( $remainder ) {
4804 $rv .= $headerLine . $content;
4805 }
4806 }
4807 }
4808 }
4809 if (is_string($rv))
4810 # reinsert stripped tags
4811 $rv = trim( $stripState->unstripBoth( $rv ) );
4812
4813 return $rv;
4814 }
4815
4816 /**
4817 * This function returns the text of a section, specified by a number ($section).
4818 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4819 * the first section before any such heading (section 0).
4820 *
4821 * If a section contains subsections, these are also returned.
4822 *
4823 * @param $text String: text to look in
4824 * @param $section Integer: section number
4825 * @param $deftext: default to return if section is not found
4826 * @return string text of the requested section
4827 */
4828 public function getSection( $text, $section, $deftext='' ) {
4829 return $this->extractSections( $text, $section, "get", $deftext );
4830 }
4831
4832 public function replaceSection( $oldtext, $section, $text ) {
4833 return $this->extractSections( $oldtext, $section, "replace", $text );
4834 }
4835
4836 /**
4837 * Get the timestamp associated with the current revision, adjusted for
4838 * the default server-local timestamp
4839 */
4840 function getRevisionTimestamp() {
4841 if ( is_null( $this->mRevisionTimestamp ) ) {
4842 wfProfileIn( __METHOD__ );
4843 global $wgContLang;
4844 $dbr = wfGetDB( DB_SLAVE );
4845 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4846 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4847
4848 // Normalize timestamp to internal MW format for timezone processing.
4849 // This has the added side-effect of replacing a null value with
4850 // the current time, which gives us more sensible behavior for
4851 // previews.
4852 $timestamp = wfTimestamp( TS_MW, $timestamp );
4853
4854 // The cryptic '' timezone parameter tells to use the site-default
4855 // timezone offset instead of the user settings.
4856 //
4857 // Since this value will be saved into the parser cache, served
4858 // to other users, and potentially even used inside links and such,
4859 // it needs to be consistent for all visitors.
4860 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4861
4862 wfProfileOut( __METHOD__ );
4863 }
4864 return $this->mRevisionTimestamp;
4865 }
4866
4867 /**
4868 * Mutator for $mDefaultSort
4869 *
4870 * @param $sort New value
4871 */
4872 public function setDefaultSort( $sort ) {
4873 $this->mDefaultSort = $sort;
4874 }
4875
4876 /**
4877 * Accessor for $mDefaultSort
4878 * Will use the title/prefixed title if none is set
4879 *
4880 * @return string
4881 */
4882 public function getDefaultSort() {
4883 if( $this->mDefaultSort !== false ) {
4884 return $this->mDefaultSort;
4885 } else {
4886 return $this->mTitle->getNamespace() == NS_CATEGORY
4887 ? $this->mTitle->getText()
4888 : $this->mTitle->getPrefixedText();
4889 }
4890 }
4891
4892 /**
4893 * Try to guess the section anchor name based on a wikitext fragment
4894 * presumably extracted from a heading, for example "Header" from
4895 * "== Header ==".
4896 */
4897 public function guessSectionNameFromWikiText( $text ) {
4898 # Strip out wikitext links(they break the anchor)
4899 $text = $this->stripSectionName( $text );
4900 $headline = Sanitizer::decodeCharReferences( $text );
4901 # strip out HTML
4902 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
4903 $headline = trim( $headline );
4904 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4905 $replacearray = array(
4906 '%3A' => ':',
4907 '%' => '.'
4908 );
4909 return str_replace(
4910 array_keys( $replacearray ),
4911 array_values( $replacearray ),
4912 $sectionanchor );
4913 }
4914
4915 /**
4916 * Strips a text string of wikitext for use in a section anchor
4917 *
4918 * Accepts a text string and then removes all wikitext from the
4919 * string and leaves only the resultant text (i.e. the result of
4920 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4921 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4922 * to create valid section anchors by mimicing the output of the
4923 * parser when headings are parsed.
4924 *
4925 * @param $text string Text string to be stripped of wikitext
4926 * for use in a Section anchor
4927 * @return Filtered text string
4928 */
4929 public function stripSectionName( $text ) {
4930 # Strip internal link markup
4931 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4932 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4933
4934 # Strip external link markup (FIXME: Not Tolerant to blank link text
4935 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4936 # on how many empty links there are on the page - need to figure that out.
4937 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4938
4939 # Parse wikitext quotes (italics & bold)
4940 $text = $this->doQuotes($text);
4941
4942 # Strip HTML tags
4943 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
4944 return $text;
4945 }
4946 }
4947
4948 /**
4949 * @todo document, briefly.
4950 * @addtogroup Parser
4951 */
4952 class OnlyIncludeReplacer {
4953 var $output = '';
4954
4955 function replace( $matches ) {
4956 if ( substr( $matches[1], -1 ) == "\n" ) {
4957 $this->output .= substr( $matches[1], 0, -1 );
4958 } else {
4959 $this->output .= $matches[1];
4960 }
4961 }
4962 }
4963
4964 /**
4965 * @todo document, briefly.
4966 * @addtogroup Parser
4967 */
4968 class StripState {
4969 var $general, $nowiki;
4970
4971 function __construct() {
4972 $this->general = new ReplacementArray;
4973 $this->nowiki = new ReplacementArray;
4974 }
4975
4976 function unstripGeneral( $text ) {
4977 wfProfileIn( __METHOD__ );
4978 $text = $this->general->replace( $text );
4979 wfProfileOut( __METHOD__ );
4980 return $text;
4981 }
4982
4983 function unstripNoWiki( $text ) {
4984 wfProfileIn( __METHOD__ );
4985 $text = $this->nowiki->replace( $text );
4986 wfProfileOut( __METHOD__ );
4987 return $text;
4988 }
4989
4990 function unstripBoth( $text ) {
4991 wfProfileIn( __METHOD__ );
4992 $text = $this->general->replace( $text );
4993 $text = $this->nowiki->replace( $text );
4994 wfProfileOut( __METHOD__ );
4995 return $text;
4996 }
4997 }