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