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