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