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