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