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