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