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