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