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