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