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