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