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