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