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