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