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