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