Revert last two commits. Broke wikibits and don't know how to fix it at the moment.
[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 /**
2793 * Return the text of a template, after recursively
2794 * replacing any variables or templates within the template.
2795 *
2796 * @param array $piece The parts of the template
2797 * $piece['text']: matched text
2798 * $piece['title']: the title, i.e. the part before the |
2799 * $piece['parts']: the parameter array
2800 * @return string the text of the template
2801 * @private
2802 */
2803 function braceSubstitution( $piece ) {
2804 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2805 $fname = __METHOD__ /*. '-L' . count( $this->mArgStack )*/;
2806 wfProfileIn( $fname );
2807 wfProfileIn( __METHOD__.'-setup' );
2808
2809 # Flags
2810 $found = false; # $text has been filled
2811 $nowiki = false; # wiki markup in $text should be escaped
2812 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2813 $noargs = false; # Don't replace triple-brace arguments in $text
2814 $replaceHeadings = false; # Make the edit section links go to the template not the article
2815 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2816 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2817
2818 # Title object, where $text came from
2819 $title = NULL;
2820
2821 $linestart = '';
2822
2823
2824 # $part1 is the bit before the first |, and must contain only title characters
2825 # $args is a list of arguments, starting from index 0, not including $part1
2826
2827 $titleText = $part1 = $piece['title'];
2828 # If the third subpattern matched anything, it will start with |
2829
2830 if (null == $piece['parts']) {
2831 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2832 if ($replaceWith != $piece['text']) {
2833 $text = $replaceWith;
2834 $found = true;
2835 $noparse = true;
2836 $noargs = true;
2837 }
2838 }
2839
2840 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2841 $argc = count( $args );
2842 wfProfileOut( __METHOD__.'-setup' );
2843
2844 # SUBST
2845 wfProfileIn( __METHOD__.'-modifiers' );
2846 if ( !$found ) {
2847 $mwSubst =& MagicWord::get( 'subst' );
2848 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
2849 # One of two possibilities is true:
2850 # 1) Found SUBST but not in the PST phase
2851 # 2) Didn't find SUBST and in the PST phase
2852 # In either case, return without further processing
2853 $text = $piece['text'];
2854 $found = true;
2855 $noparse = true;
2856 $noargs = true;
2857 }
2858 }
2859
2860 # MSG, MSGNW and RAW
2861 if ( !$found ) {
2862 # Check for MSGNW:
2863 $mwMsgnw =& MagicWord::get( 'msgnw' );
2864 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2865 $nowiki = true;
2866 } else {
2867 # Remove obsolete MSG:
2868 $mwMsg =& MagicWord::get( 'msg' );
2869 $mwMsg->matchStartAndRemove( $part1 );
2870 }
2871
2872 # Check for RAW:
2873 $mwRaw =& MagicWord::get( 'raw' );
2874 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2875 $forceRawInterwiki = true;
2876 }
2877 }
2878 wfProfileOut( __METHOD__.'-modifiers' );
2879
2880 # Parser functions
2881 if ( !$found ) {
2882 wfProfileIn( __METHOD__ . '-pfunc' );
2883
2884 $colonPos = strpos( $part1, ':' );
2885 if ( $colonPos !== false ) {
2886 # Case sensitive functions
2887 $function = substr( $part1, 0, $colonPos );
2888 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
2889 $function = $this->mFunctionSynonyms[1][$function];
2890 } else {
2891 # Case insensitive functions
2892 $function = strtolower( $function );
2893 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
2894 $function = $this->mFunctionSynonyms[0][$function];
2895 } else {
2896 $function = false;
2897 }
2898 }
2899 if ( $function ) {
2900 $funcArgs = array_map( 'trim', $args );
2901 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos + 1 ) ) ), $funcArgs );
2902 $result = call_user_func_array( $this->mFunctionHooks[$function], $funcArgs );
2903 $found = true;
2904
2905 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2906 //$noargs = true;
2907 //$noparse = true;
2908
2909 if ( is_array( $result ) ) {
2910 if ( isset( $result[0] ) ) {
2911 $text = $linestart . $result[0];
2912 unset( $result[0] );
2913 }
2914
2915 // Extract flags into the local scope
2916 // This allows callers to set flags such as nowiki, noparse, found, etc.
2917 extract( $result );
2918 } else {
2919 $text = $linestart . $result;
2920 }
2921 }
2922 }
2923 wfProfileOut( __METHOD__ . '-pfunc' );
2924 }
2925
2926 # Template table test
2927
2928 # Did we encounter this template already? If yes, it is in the cache
2929 # and we need to check for loops.
2930 if ( !$found && isset( $this->mTemplates[$piece['title']] ) ) {
2931 $found = true;
2932
2933 # Infinite loop test
2934 if ( isset( $this->mTemplatePath[$part1] ) ) {
2935 $noparse = true;
2936 $noargs = true;
2937 $found = true;
2938 $text = $linestart .
2939 "[[$part1]]<!-- WARNING: template loop detected -->";
2940 wfDebug( __METHOD__.": template loop broken at '$part1'\n" );
2941 } else {
2942 # set $text to cached message.
2943 $text = $linestart . $this->mTemplates[$piece['title']];
2944 }
2945 }
2946
2947 # Load from database
2948 $lastPathLevel = $this->mTemplatePath;
2949 if ( !$found ) {
2950 wfProfileIn( __METHOD__ . '-loadtpl' );
2951 $ns = NS_TEMPLATE;
2952 # declaring $subpage directly in the function call
2953 # does not work correctly with references and breaks
2954 # {{/subpage}}-style inclusions
2955 $subpage = '';
2956 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2957 if ($subpage !== '') {
2958 $ns = $this->mTitle->getNamespace();
2959 }
2960 $title = Title::newFromText( $part1, $ns );
2961
2962
2963 if ( !is_null( $title ) ) {
2964 $titleText = $title->getPrefixedText();
2965 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2966 # Check for language variants if the template is not found
2967 if($checkVariantLink && $title->getArticleID() == 0){
2968 $wgContLang->findVariantLink($part1, $title);
2969 }
2970
2971 if ( !$title->isExternal() ) {
2972 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
2973 $text = SpecialPage::capturePath( $title );
2974 if ( is_string( $text ) ) {
2975 $found = true;
2976 $noparse = true;
2977 $noargs = true;
2978 $isHTML = true;
2979 $this->disableCache();
2980 }
2981 } else {
2982 $articleContent = $this->fetchTemplate( $title );
2983 if ( $articleContent !== false ) {
2984 $found = true;
2985 $text = $articleContent;
2986 $replaceHeadings = true;
2987 }
2988 }
2989
2990 # If the title is valid but undisplayable, make a link to it
2991 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
2992 $text = "[[:$titleText]]";
2993 $found = true;
2994 }
2995 } elseif ( $title->isTrans() ) {
2996 // Interwiki transclusion
2997 if ( $this->ot['html'] && !$forceRawInterwiki ) {
2998 $text = $this->interwikiTransclude( $title, 'render' );
2999 $isHTML = true;
3000 $noparse = true;
3001 } else {
3002 $text = $this->interwikiTransclude( $title, 'raw' );
3003 $replaceHeadings = true;
3004 }
3005 $found = true;
3006 }
3007
3008 # Template cache array insertion
3009 # Use the original $piece['title'] not the mangled $part1, so that
3010 # modifiers such as RAW: produce separate cache entries
3011 if( $found ) {
3012 if( $isHTML ) {
3013 // A special page; don't store it in the template cache.
3014 } else {
3015 $this->mTemplates[$piece['title']] = $text;
3016 }
3017 $text = $linestart . $text;
3018 }
3019 }
3020 wfProfileOut( __METHOD__ . '-loadtpl' );
3021 }
3022
3023 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3024 # Error, oversize inclusion
3025 $text = $linestart .
3026 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3027 $noparse = true;
3028 $noargs = true;
3029 }
3030
3031 # Recursive parsing, escaping and link table handling
3032 # Only for HTML output
3033 if ( $nowiki && $found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3034 $text = wfEscapeWikiText( $text );
3035 } elseif ( !$this->ot['msg'] && $found ) {
3036 if ( $noargs ) {
3037 $assocArgs = array();
3038 } else {
3039 # Clean up argument array
3040 $assocArgs = array();
3041 $index = 1;
3042 foreach( $args as $arg ) {
3043 $eqpos = strpos( $arg, '=' );
3044 if ( $eqpos === false ) {
3045 $assocArgs[$index++] = $arg;
3046 } else {
3047 $name = trim( substr( $arg, 0, $eqpos ) );
3048 $value = trim( substr( $arg, $eqpos+1 ) );
3049 if ( $value === false ) {
3050 $value = '';
3051 }
3052 if ( $name !== false ) {
3053 $assocArgs[$name] = $value;
3054 }
3055 }
3056 }
3057
3058 # Add a new element to the templace recursion path
3059 $this->mTemplatePath[$part1] = 1;
3060 }
3061
3062 if ( !$noparse ) {
3063 # If there are any <onlyinclude> tags, only include them
3064 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3065 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
3066 $text = '';
3067 foreach ($m[1] as $piece)
3068 $text .= $piece;
3069 }
3070 # Remove <noinclude> sections and <includeonly> tags
3071 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
3072 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3073
3074 if( $this->ot['html'] || $this->ot['pre'] ) {
3075 # Strip <nowiki>, <pre>, etc.
3076 $text = $this->strip( $text, $this->mStripState );
3077 if ( $this->ot['html'] ) {
3078 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3079 } elseif ( $this->ot['pre'] && $this->mOptions->getRemoveComments() ) {
3080 $text = Sanitizer::removeHTMLcomments( $text );
3081 }
3082 }
3083 $text = $this->replaceVariables( $text, $assocArgs );
3084
3085 # If the template begins with a table or block-level
3086 # element, it should be treated as beginning a new line.
3087 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3088 $text = "\n" . $text;
3089 }
3090 } elseif ( !$noargs ) {
3091 # $noparse and !$noargs
3092 # Just replace the arguments, not any double-brace items
3093 # This is used for rendered interwiki transclusion
3094 $text = $this->replaceVariables( $text, $assocArgs, true );
3095 }
3096 }
3097 # Prune lower levels off the recursion check path
3098 $this->mTemplatePath = $lastPathLevel;
3099
3100 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3101 # Error, oversize inclusion
3102 $text = $linestart .
3103 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3104 $noparse = true;
3105 $noargs = true;
3106 }
3107
3108 if ( !$found ) {
3109 wfProfileOut( $fname );
3110 return $piece['text'];
3111 } else {
3112 wfProfileIn( __METHOD__ . '-placeholders' );
3113 if ( $isHTML ) {
3114 # Replace raw HTML by a placeholder
3115 # Add a blank line preceding, to prevent it from mucking up
3116 # immediately preceding headings
3117 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
3118 } else {
3119 # replace ==section headers==
3120 # XXX this needs to go away once we have a better parser.
3121 if ( !$this->ot['wiki'] && !$this->ot['pre'] && $replaceHeadings ) {
3122 if( !is_null( $title ) )
3123 $encodedname = base64_encode($title->getPrefixedDBkey());
3124 else
3125 $encodedname = base64_encode("");
3126 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3127 PREG_SPLIT_DELIM_CAPTURE);
3128 $text = '';
3129 $nsec = 0;
3130 for( $i = 0; $i < count($m); $i += 2 ) {
3131 $text .= $m[$i];
3132 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
3133 $hl = $m[$i + 1];
3134 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3135 $text .= $hl;
3136 continue;
3137 }
3138 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3139 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3140 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3141
3142 $nsec++;
3143 }
3144 }
3145 }
3146 wfProfileOut( __METHOD__ . '-placeholders' );
3147 }
3148
3149 # Prune lower levels off the recursion check path
3150 $this->mTemplatePath = $lastPathLevel;
3151
3152 if ( !$found ) {
3153 wfProfileOut( $fname );
3154 return $piece['text'];
3155 } else {
3156 wfProfileOut( $fname );
3157 return $text;
3158 }
3159 }
3160
3161 /**
3162 * Fetch the unparsed text of a template and register a reference to it.
3163 */
3164 function fetchTemplate( $title ) {
3165 $text = false;
3166 // Loop to fetch the article, with up to 1 redirect
3167 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3168 $rev = Revision::newFromTitle( $title );
3169 $this->mOutput->addTemplate( $title, $title->getArticleID() );
3170 if ( !$rev ) {
3171 break;
3172 }
3173 $text = $rev->getText();
3174 if ( $text === false ) {
3175 break;
3176 }
3177 // Redirect?
3178 $title = Title::newFromRedirect( $text );
3179 }
3180 return $text;
3181 }
3182
3183 /**
3184 * Transclude an interwiki link.
3185 */
3186 function interwikiTransclude( $title, $action ) {
3187 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3188
3189 if (!$wgEnableScaryTranscluding)
3190 return wfMsg('scarytranscludedisabled');
3191
3192 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3193 // But we'll handle it generally anyway
3194 if ( $title->getNamespace() ) {
3195 // Use the canonical namespace, which should work anywhere
3196 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3197 } else {
3198 $articleName = $title->getDBkey();
3199 }
3200
3201 $url = str_replace('$1', urlencode($articleName), Title::getInterwikiLink($title->getInterwiki()));
3202 $url .= "?action=$action";
3203 if (strlen($url) > 255)
3204 return wfMsg('scarytranscludetoolong');
3205 return $this->fetchScaryTemplateMaybeFromCache($url);
3206 }
3207
3208 function fetchScaryTemplateMaybeFromCache($url) {
3209 global $wgTranscludeCacheExpiry;
3210 $dbr =& wfGetDB(DB_SLAVE);
3211 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3212 array('tc_url' => $url));
3213 if ($obj) {
3214 $time = $obj->tc_time;
3215 $text = $obj->tc_contents;
3216 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3217 return $text;
3218 }
3219 }
3220
3221 $text = Http::get($url);
3222 if (!$text)
3223 return wfMsg('scarytranscludefailed', $url);
3224
3225 $dbw =& wfGetDB(DB_MASTER);
3226 $dbw->replace('transcache', array('tc_url'), array(
3227 'tc_url' => $url,
3228 'tc_time' => time(),
3229 'tc_contents' => $text));
3230 return $text;
3231 }
3232
3233
3234 /**
3235 * Triple brace replacement -- used for template arguments
3236 * @private
3237 */
3238 function argSubstitution( $matches ) {
3239 $arg = trim( $matches['title'] );
3240 $text = $matches['text'];
3241 $inputArgs = end( $this->mArgStack );
3242
3243 if ( array_key_exists( $arg, $inputArgs ) ) {
3244 $text = $inputArgs[$arg];
3245 } else if (($this->mOutputType == OT_HTML || $this->mOutputType == OT_PREPROCESS ) &&
3246 null != $matches['parts'] && count($matches['parts']) > 0) {
3247 $text = $matches['parts'][0];
3248 }
3249 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3250 $text = $matches['text'] .
3251 '<!-- WARNING: argument omitted, expansion size too large -->';
3252 }
3253
3254 return $text;
3255 }
3256
3257 /**
3258 * Increment an include size counter
3259 *
3260 * @param string $type The type of expansion
3261 * @param integer $size The size of the text
3262 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3263 */
3264 function incrementIncludeSize( $type, $size ) {
3265 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
3266 return false;
3267 } else {
3268 $this->mIncludeSizes[$type] += $size;
3269 return true;
3270 }
3271 }
3272
3273 /**
3274 * Detect __NOGALLERY__ magic word and set a placeholder
3275 */
3276 function stripNoGallery( &$text ) {
3277 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3278 # do not add TOC
3279 $mw = MagicWord::get( 'nogallery' );
3280 $this->mOutput->mNoGallery = $mw->matchAndRemove( $text ) ;
3281 }
3282
3283 /**
3284 * Detect __TOC__ magic word and set a placeholder
3285 */
3286 function stripToc( $text ) {
3287 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3288 # do not add TOC
3289 $mw = MagicWord::get( 'notoc' );
3290 if( $mw->matchAndRemove( $text ) ) {
3291 $this->mShowToc = false;
3292 }
3293
3294 $mw = MagicWord::get( 'toc' );
3295 if( $mw->match( $text ) ) {
3296 $this->mShowToc = true;
3297 $this->mForceTocPosition = true;
3298
3299 // Set a placeholder. At the end we'll fill it in with the TOC.
3300 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3301
3302 // Only keep the first one.
3303 $text = $mw->replace( '', $text );
3304 }
3305 return $text;
3306 }
3307
3308 /**
3309 * This function accomplishes several tasks:
3310 * 1) Auto-number headings if that option is enabled
3311 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3312 * 3) Add a Table of contents on the top for users who have enabled the option
3313 * 4) Auto-anchor headings
3314 *
3315 * It loops through all headlines, collects the necessary data, then splits up the
3316 * string and re-inserts the newly formatted headlines.
3317 *
3318 * @param string $text
3319 * @param boolean $isMain
3320 * @private
3321 */
3322 function formatHeadings( $text, $isMain=true ) {
3323 global $wgMaxTocLevel, $wgContLang;
3324
3325 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3326 if( !$this->mTitle->userCanEdit() ) {
3327 $showEditLink = 0;
3328 } else {
3329 $showEditLink = $this->mOptions->getEditSection();
3330 }
3331
3332 # Inhibit editsection links if requested in the page
3333 $esw =& MagicWord::get( 'noeditsection' );
3334 if( $esw->matchAndRemove( $text ) ) {
3335 $showEditLink = 0;
3336 }
3337
3338 # Get all headlines for numbering them and adding funky stuff like [edit]
3339 # links - this is for later, but we need the number of headlines right now
3340 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3341
3342 # if there are fewer than 4 headlines in the article, do not show TOC
3343 # unless it's been explicitly enabled.
3344 $enoughToc = $this->mShowToc &&
3345 (($numMatches >= 4) || $this->mForceTocPosition);
3346
3347 # Allow user to stipulate that a page should have a "new section"
3348 # link added via __NEWSECTIONLINK__
3349 $mw =& MagicWord::get( 'newsectionlink' );
3350 if( $mw->matchAndRemove( $text ) )
3351 $this->mOutput->setNewSection( true );
3352
3353 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3354 # override above conditions and always show TOC above first header
3355 $mw =& MagicWord::get( 'forcetoc' );
3356 if ($mw->matchAndRemove( $text ) ) {
3357 $this->mShowToc = true;
3358 $enoughToc = true;
3359 }
3360
3361 # Never ever show TOC if no headers
3362 if( $numMatches < 1 ) {
3363 $enoughToc = false;
3364 }
3365
3366 # We need this to perform operations on the HTML
3367 $sk =& $this->mOptions->getSkin();
3368
3369 # headline counter
3370 $headlineCount = 0;
3371 $sectionCount = 0; # headlineCount excluding template sections
3372
3373 # Ugh .. the TOC should have neat indentation levels which can be
3374 # passed to the skin functions. These are determined here
3375 $toc = '';
3376 $full = '';
3377 $head = array();
3378 $sublevelCount = array();
3379 $levelCount = array();
3380 $toclevel = 0;
3381 $level = 0;
3382 $prevlevel = 0;
3383 $toclevel = 0;
3384 $prevtoclevel = 0;
3385
3386 foreach( $matches[3] as $headline ) {
3387 $istemplate = 0;
3388 $templatetitle = '';
3389 $templatesection = 0;
3390 $numbering = '';
3391
3392 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3393 $istemplate = 1;
3394 $templatetitle = base64_decode($mat[1]);
3395 $templatesection = 1 + (int)base64_decode($mat[2]);
3396 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3397 }
3398
3399 if( $toclevel ) {
3400 $prevlevel = $level;
3401 $prevtoclevel = $toclevel;
3402 }
3403 $level = $matches[1][$headlineCount];
3404
3405 if( $doNumberHeadings || $enoughToc ) {
3406
3407 if ( $level > $prevlevel ) {
3408 # Increase TOC level
3409 $toclevel++;
3410 $sublevelCount[$toclevel] = 0;
3411 if( $toclevel<$wgMaxTocLevel ) {
3412 $toc .= $sk->tocIndent();
3413 }
3414 }
3415 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3416 # Decrease TOC level, find level to jump to
3417
3418 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3419 # Can only go down to level 1
3420 $toclevel = 1;
3421 } else {
3422 for ($i = $toclevel; $i > 0; $i--) {
3423 if ( $levelCount[$i] == $level ) {
3424 # Found last matching level
3425 $toclevel = $i;
3426 break;
3427 }
3428 elseif ( $levelCount[$i] < $level ) {
3429 # Found first matching level below current level
3430 $toclevel = $i + 1;
3431 break;
3432 }
3433 }
3434 }
3435 if( $toclevel<$wgMaxTocLevel ) {
3436 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3437 }
3438 }
3439 else {
3440 # No change in level, end TOC line
3441 if( $toclevel<$wgMaxTocLevel ) {
3442 $toc .= $sk->tocLineEnd();
3443 }
3444 }
3445
3446 $levelCount[$toclevel] = $level;
3447
3448 # count number of headlines for each level
3449 @$sublevelCount[$toclevel]++;
3450 $dot = 0;
3451 for( $i = 1; $i <= $toclevel; $i++ ) {
3452 if( !empty( $sublevelCount[$i] ) ) {
3453 if( $dot ) {
3454 $numbering .= '.';
3455 }
3456 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3457 $dot = 1;
3458 }
3459 }
3460 }
3461
3462 # The canonized header is a version of the header text safe to use for links
3463 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3464 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
3465 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
3466
3467 # Remove link placeholders by the link text.
3468 # <!--LINK number-->
3469 # turns into
3470 # link text with suffix
3471 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3472 "\$this->mLinkHolders['texts'][\$1]",
3473 $canonized_headline );
3474 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3475 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3476 $canonized_headline );
3477
3478 # strip out HTML
3479 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3480 $tocline = trim( $canonized_headline );
3481 # Save headline for section edit hint before it's escaped
3482 $headline_hint = trim( $canonized_headline );
3483 $canonized_headline = Sanitizer::escapeId( $tocline );
3484 $refers[$headlineCount] = $canonized_headline;
3485
3486 # count how many in assoc. array so we can track dupes in anchors
3487 @$refers[$canonized_headline]++;
3488 $refcount[$headlineCount]=$refers[$canonized_headline];
3489
3490 # Don't number the heading if it is the only one (looks silly)
3491 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3492 # the two are different if the line contains a link
3493 $headline=$numbering . ' ' . $headline;
3494 }
3495
3496 # Create the anchor for linking from the TOC to the section
3497 $anchor = $canonized_headline;
3498 if($refcount[$headlineCount] > 1 ) {
3499 $anchor .= '_' . $refcount[$headlineCount];
3500 }
3501 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3502 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3503 }
3504 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3505 if ( empty( $head[$headlineCount] ) ) {
3506 $head[$headlineCount] = '';
3507 }
3508 if( $istemplate )
3509 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3510 else
3511 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1, $headline_hint);
3512 }
3513
3514 # give headline the correct <h#> tag
3515 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3516
3517 $headlineCount++;
3518 if( !$istemplate )
3519 $sectionCount++;
3520 }
3521
3522 if( $enoughToc ) {
3523 if( $toclevel<$wgMaxTocLevel ) {
3524 $toc .= $sk->tocUnindent( $toclevel - 1 );
3525 }
3526 $toc = $sk->tocList( $toc );
3527 }
3528
3529 # split up and insert constructed headlines
3530
3531 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3532 $i = 0;
3533
3534 foreach( $blocks as $block ) {
3535 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3536 # This is the [edit] link that appears for the top block of text when
3537 # section editing is enabled
3538
3539 # Disabled because it broke block formatting
3540 # For example, a bullet point in the top line
3541 # $full .= $sk->editSectionLink(0);
3542 }
3543 $full .= $block;
3544 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3545 # Top anchor now in skin
3546 $full = $full.$toc;
3547 }
3548
3549 if( !empty( $head[$i] ) ) {
3550 $full .= $head[$i];
3551 }
3552 $i++;
3553 }
3554 if( $this->mForceTocPosition ) {
3555 return str_replace( '<!--MWTOC-->', $toc, $full );
3556 } else {
3557 return $full;
3558 }
3559 }
3560
3561 /**
3562 * Transform wiki markup when saving a page by doing \r\n -> \n
3563 * conversion, substitting signatures, {{subst:}} templates, etc.
3564 *
3565 * @param string $text the text to transform
3566 * @param Title &$title the Title object for the current article
3567 * @param User &$user the User object describing the current user
3568 * @param ParserOptions $options parsing options
3569 * @param bool $clearState whether to clear the parser state first
3570 * @return string the altered wiki markup
3571 * @public
3572 */
3573 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3574 $this->mOptions = $options;
3575 $this->mTitle =& $title;
3576 $this->setOutputType( OT_WIKI );
3577
3578 if ( $clearState ) {
3579 $this->clearState();
3580 }
3581
3582 $stripState = false;
3583 $pairs = array(
3584 "\r\n" => "\n",
3585 );
3586 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3587 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3588 $text = $this->pstPass2( $text, $stripState, $user );
3589 $text = $this->unstrip( $text, $stripState );
3590 $text = $this->unstripNoWiki( $text, $stripState );
3591 return $text;
3592 }
3593
3594 /**
3595 * Pre-save transform helper function
3596 * @private
3597 */
3598 function pstPass2( $text, &$stripState, &$user ) {
3599 global $wgContLang, $wgLocaltimezone;
3600
3601 /* Note: This is the timestamp saved as hardcoded wikitext to
3602 * the database, we use $wgContLang here in order to give
3603 * everyone the same signature and use the default one rather
3604 * than the one selected in each user's preferences.
3605 */
3606 if ( isset( $wgLocaltimezone ) ) {
3607 $oldtz = getenv( 'TZ' );
3608 putenv( 'TZ='.$wgLocaltimezone );
3609 }
3610 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3611 ' (' . date( 'T' ) . ')';
3612 if ( isset( $wgLocaltimezone ) ) {
3613 putenv( 'TZ='.$oldtz );
3614 }
3615
3616 # Variable replacement
3617 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3618 $text = $this->replaceVariables( $text );
3619
3620 # Strip out <nowiki> etc. added via replaceVariables
3621 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3622
3623 # Signatures
3624 $sigText = $this->getUserSig( $user );
3625 $text = strtr( $text, array(
3626 '~~~~~' => $d,
3627 '~~~~' => "$sigText $d",
3628 '~~~' => $sigText
3629 ) );
3630
3631 # Context links: [[|name]] and [[name (context)|]]
3632 #
3633 global $wgLegalTitleChars;
3634 $tc = "[$wgLegalTitleChars]";
3635 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3636
3637 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3638 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3639 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3640
3641 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3642 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3643 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3644
3645 $t = $this->mTitle->getText();
3646 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3647 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3648 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3649 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3650 } else {
3651 # if there's no context, don't bother duplicating the title
3652 $text = preg_replace( $p2, '[[\\1]]', $text );
3653 }
3654
3655 # Trim trailing whitespace
3656 # __END__ tag allows for trailing
3657 # whitespace to be deliberately included
3658 $text = rtrim( $text );
3659 $mw =& MagicWord::get( 'end' );
3660 $mw->matchAndRemove( $text );
3661
3662 return $text;
3663 }
3664
3665 /**
3666 * Fetch the user's signature text, if any, and normalize to
3667 * validated, ready-to-insert wikitext.
3668 *
3669 * @param User $user
3670 * @return string
3671 * @private
3672 */
3673 function getUserSig( &$user ) {
3674 $username = $user->getName();
3675 $nickname = $user->getOption( 'nickname' );
3676 $nickname = $nickname === '' ? $username : $nickname;
3677
3678 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3679 # Sig. might contain markup; validate this
3680 if( $this->validateSig( $nickname ) !== false ) {
3681 # Validated; clean up (if needed) and return it
3682 return $this->cleanSig( $nickname, true );
3683 } else {
3684 # Failed to validate; fall back to the default
3685 $nickname = $username;
3686 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3687 }
3688 }
3689
3690 // Make sure nickname doesnt get a sig in a sig
3691 $nickname = $this->cleanSigInSig( $nickname );
3692
3693 # If we're still here, make it a link to the user page
3694 $userpage = $user->getUserPage();
3695 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3696 }
3697
3698 /**
3699 * Check that the user's signature contains no bad XML
3700 *
3701 * @param string $text
3702 * @return mixed An expanded string, or false if invalid.
3703 */
3704 function validateSig( $text ) {
3705 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3706 }
3707
3708 /**
3709 * Clean up signature text
3710 *
3711 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3712 * 2) Substitute all transclusions
3713 *
3714 * @param string $text
3715 * @param $parsing Whether we're cleaning (preferences save) or parsing
3716 * @return string Signature text
3717 */
3718 function cleanSig( $text, $parsing = false ) {
3719 global $wgTitle;
3720 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI : OT_MSG );
3721
3722 $substWord = MagicWord::get( 'subst' );
3723 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3724 $substText = '{{' . $substWord->getSynonym( 0 );
3725
3726 $text = preg_replace( $substRegex, $substText, $text );
3727 $text = $this->cleanSigInSig( $text );
3728 $text = $this->replaceVariables( $text );
3729
3730 $this->clearState();
3731 return $text;
3732 }
3733
3734 /**
3735 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3736 * @param string $text
3737 * @return string Signature text with /~{3,5}/ removed
3738 */
3739 function cleanSigInSig( $text ) {
3740 $text = preg_replace( '/~{3,5}/', '', $text );
3741 return $text;
3742 }
3743
3744 /**
3745 * Set up some variables which are usually set up in parse()
3746 * so that an external function can call some class members with confidence
3747 * @public
3748 */
3749 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3750 $this->mTitle =& $title;
3751 $this->mOptions = $options;
3752 $this->setOutputType( $outputType );
3753 if ( $clearState ) {
3754 $this->clearState();
3755 }
3756 }
3757
3758 /**
3759 * Transform a MediaWiki message by replacing magic variables.
3760 *
3761 * @param string $text the text to transform
3762 * @param ParserOptions $options options
3763 * @return string the text with variables substituted
3764 * @public
3765 */
3766 function transformMsg( $text, $options ) {
3767 global $wgTitle;
3768 static $executing = false;
3769
3770 $fname = "Parser::transformMsg";
3771
3772 # Guard against infinite recursion
3773 if ( $executing ) {
3774 return $text;
3775 }
3776 $executing = true;
3777
3778 wfProfileIn($fname);
3779
3780 if ( $wgTitle ) {
3781 $this->mTitle = $wgTitle;
3782 } else {
3783 $this->mTitle = Title::newFromText('msg');
3784 }
3785 $this->mOptions = $options;
3786 $this->setOutputType( OT_MSG );
3787 $this->clearState();
3788 $text = $this->replaceVariables( $text );
3789
3790 $executing = false;
3791 wfProfileOut($fname);
3792 return $text;
3793 }
3794
3795 /**
3796 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3797 * The callback should have the following form:
3798 * function myParserHook( $text, $params, &$parser ) { ... }
3799 *
3800 * Transform and return $text. Use $parser for any required context, e.g. use
3801 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3802 *
3803 * @public
3804 *
3805 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3806 * @param mixed $callback The callback function (and object) to use for the tag
3807 *
3808 * @return The old value of the mTagHooks array associated with the hook
3809 */
3810 function setHook( $tag, $callback ) {
3811 $tag = strtolower( $tag );
3812 $oldVal = @$this->mTagHooks[$tag];
3813 $this->mTagHooks[$tag] = $callback;
3814
3815 return $oldVal;
3816 }
3817
3818 /**
3819 * Create a function, e.g. {{sum:1|2|3}}
3820 * The callback function should have the form:
3821 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3822 *
3823 * The callback may either return the text result of the function, or an array with the text
3824 * in element 0, and a number of flags in the other elements. The names of the flags are
3825 * specified in the keys. Valid flags are:
3826 * found The text returned is valid, stop processing the template. This
3827 * is on by default.
3828 * nowiki Wiki markup in the return value should be escaped
3829 * noparse Unsafe HTML tags should not be stripped, etc.
3830 * noargs Don't replace triple-brace arguments in the return value
3831 * isHTML The returned text is HTML, armour it against wikitext transformation
3832 *
3833 * @public
3834 *
3835 * @param string $id The magic word ID
3836 * @param mixed $callback The callback function (and object) to use
3837 * @param integer $flags a combination of the following flags:
3838 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3839 *
3840 * @return The old callback function for this name, if any
3841 */
3842 function setFunctionHook( $id, $callback, $flags = 0 ) {
3843 $oldVal = @$this->mFunctionHooks[$id];
3844 $this->mFunctionHooks[$id] = $callback;
3845
3846 # Add to function cache
3847 $mw = MagicWord::get( $id );
3848 if( !$mw )
3849 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3850
3851 $synonyms = $mw->getSynonyms();
3852 $sensitive = intval( $mw->isCaseSensitive() );
3853
3854 foreach ( $synonyms as $syn ) {
3855 # Case
3856 if ( !$sensitive ) {
3857 $syn = strtolower( $syn );
3858 }
3859 # Add leading hash
3860 if ( !( $flags & SFH_NO_HASH ) ) {
3861 $syn = '#' . $syn;
3862 }
3863 # Remove trailing colon
3864 if ( substr( $syn, -1, 1 ) == ':' ) {
3865 $syn = substr( $syn, 0, -1 );
3866 }
3867 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
3868 }
3869 return $oldVal;
3870 }
3871
3872 /**
3873 * Get all registered function hook identifiers
3874 *
3875 * @return array
3876 */
3877 function getFunctionHooks() {
3878 return array_keys( $this->mFunctionHooks );
3879 }
3880
3881 /**
3882 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3883 * Placeholders created in Skin::makeLinkObj()
3884 * Returns an array of links found, indexed by PDBK:
3885 * 0 - broken
3886 * 1 - normal link
3887 * 2 - stub
3888 * $options is a bit field, RLH_FOR_UPDATE to select for update
3889 */
3890 function replaceLinkHolders( &$text, $options = 0 ) {
3891 global $wgUser;
3892 global $wgOutputReplace;
3893 global $wgContLang, $wgLanguageCode;
3894
3895 $fname = 'Parser::replaceLinkHolders';
3896 wfProfileIn( $fname );
3897
3898 $pdbks = array();
3899 $colours = array();
3900 $sk =& $this->mOptions->getSkin();
3901 $linkCache =& LinkCache::singleton();
3902
3903 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3904 wfProfileIn( $fname.'-check' );
3905 $dbr =& wfGetDB( DB_SLAVE );
3906 $page = $dbr->tableName( 'page' );
3907 $threshold = $wgUser->getOption('stubthreshold');
3908
3909 # Sort by namespace
3910 asort( $this->mLinkHolders['namespaces'] );
3911
3912 # Generate query
3913 $query = false;
3914 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3915 # Make title object
3916 $title = $this->mLinkHolders['titles'][$key];
3917
3918 # Skip invalid entries.
3919 # Result will be ugly, but prevents crash.
3920 if ( is_null( $title ) ) {
3921 continue;
3922 }
3923 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3924
3925 # Check if it's a static known link, e.g. interwiki
3926 if ( $title->isAlwaysKnown() ) {
3927 $colours[$pdbk] = 1;
3928 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3929 $colours[$pdbk] = 1;
3930 $this->mOutput->addLink( $title, $id );
3931 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3932 $colours[$pdbk] = 0;
3933 } else {
3934 # Not in the link cache, add it to the query
3935 if ( !isset( $current ) ) {
3936 $current = $ns;
3937 $query = "SELECT page_id, page_namespace, page_title";
3938 if ( $threshold > 0 ) {
3939 $query .= ', page_len, page_is_redirect';
3940 }
3941 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3942 } elseif ( $current != $ns ) {
3943 $current = $ns;
3944 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3945 } else {
3946 $query .= ', ';
3947 }
3948
3949 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3950 }
3951 }
3952 if ( $query ) {
3953 $query .= '))';
3954 if ( $options & RLH_FOR_UPDATE ) {
3955 $query .= ' FOR UPDATE';
3956 }
3957
3958 $res = $dbr->query( $query, $fname );
3959
3960 # Fetch data and form into an associative array
3961 # non-existent = broken
3962 # 1 = known
3963 # 2 = stub
3964 while ( $s = $dbr->fetchObject($res) ) {
3965 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3966 $pdbk = $title->getPrefixedDBkey();
3967 $linkCache->addGoodLinkObj( $s->page_id, $title );
3968 $this->mOutput->addLink( $title, $s->page_id );
3969
3970 if ( $threshold > 0 ) {
3971 $size = $s->page_len;
3972 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3973 $colours[$pdbk] = 1;
3974 } else {
3975 $colours[$pdbk] = 2;
3976 }
3977 } else {
3978 $colours[$pdbk] = 1;
3979 }
3980 }
3981 }
3982 wfProfileOut( $fname.'-check' );
3983
3984 # Do a second query for different language variants of links (if needed)
3985 if($wgContLang->hasVariants()){
3986 $linkBatch = new LinkBatch();
3987 $variantMap = array(); // maps $pdbkey_Variant => $pdbkey_original
3988
3989 // Add variants of links to link batch
3990 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3991 $title = $this->mLinkHolders['titles'][$key];
3992 if ( is_null( $title ) )
3993 continue;
3994
3995 $pdbk = $title->getPrefixedDBkey();
3996
3997 // generate all variants of the link title text
3998 $allTextVariants = $wgContLang->convertLinkToAllVariants($title->getText());
3999
4000 // if link was not found (in first query), add all variants to query
4001 if ( !isset($colours[$pdbk]) ){
4002 foreach($allTextVariants as $textVariant){
4003 $variantTitle = Title::makeTitle( $ns, $textVariant );
4004 if(is_null($variantTitle)) continue;
4005 $linkBatch->addObj( $variantTitle );
4006 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4007 }
4008 }
4009 }
4010
4011
4012 if(!$linkBatch->isEmpty()){
4013 // construct query
4014 $titleClause = $linkBatch->constructSet('page', $dbr);
4015
4016 $variantQuery = "SELECT page_id, page_namespace, page_title";
4017 if ( $threshold > 0 ) {
4018 $variantQuery .= ', page_len, page_is_redirect';
4019 }
4020
4021 $variantQuery .= " FROM $page WHERE $titleClause";
4022 if ( $options & RLH_FOR_UPDATE ) {
4023 $variantQuery .= ' FOR UPDATE';
4024 }
4025
4026 $varRes = $dbr->query( $variantQuery, $fname );
4027
4028 // for each found variants, figure out link holders and replace
4029 while ( $s = $dbr->fetchObject($varRes) ) {
4030
4031 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
4032 $varPdbk = $variantTitle->getPrefixedDBkey();
4033 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle );
4034 $this->mOutput->addLink( $variantTitle, $s->page_id );
4035
4036 $holderKeys = $variantMap[$varPdbk];
4037
4038 // loop over link holders
4039 foreach($holderKeys as $key){
4040 $title = $this->mLinkHolders['titles'][$key];
4041 if ( is_null( $title ) ) continue;
4042
4043 $pdbk = $title->getPrefixedDBkey();
4044
4045 if(!isset($colours[$pdbk])){
4046 // found link in some of the variants, replace the link holder data
4047 $this->mLinkHolders['titles'][$key] = $variantTitle;
4048 $this->mLinkHolders['dbkeys'][$key] = $variantTitle->getDBkey();
4049
4050 // set pdbk and colour
4051 $pdbks[$key] = $varPdbk;
4052 if ( $threshold > 0 ) {
4053 $size = $s->page_len;
4054 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
4055 $colours[$varPdbk] = 1;
4056 } else {
4057 $colours[$varPdbk] = 2;
4058 }
4059 }
4060 else {
4061 $colours[$varPdbk] = 1;
4062 }
4063 }
4064 }
4065 }
4066 }
4067 }
4068
4069 # Construct search and replace arrays
4070 wfProfileIn( $fname.'-construct' );
4071 $wgOutputReplace = array();
4072 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4073 $pdbk = $pdbks[$key];
4074 $searchkey = "<!--LINK $key-->";
4075 $title = $this->mLinkHolders['titles'][$key];
4076 if ( empty( $colours[$pdbk] ) ) {
4077 $linkCache->addBadLinkObj( $title );
4078 $colours[$pdbk] = 0;
4079 $this->mOutput->addLink( $title, 0 );
4080 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
4081 $this->mLinkHolders['texts'][$key],
4082 $this->mLinkHolders['queries'][$key] );
4083 } elseif ( $colours[$pdbk] == 1 ) {
4084 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
4085 $this->mLinkHolders['texts'][$key],
4086 $this->mLinkHolders['queries'][$key] );
4087 } elseif ( $colours[$pdbk] == 2 ) {
4088 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
4089 $this->mLinkHolders['texts'][$key],
4090 $this->mLinkHolders['queries'][$key] );
4091 }
4092 }
4093 wfProfileOut( $fname.'-construct' );
4094
4095 # Do the thing
4096 wfProfileIn( $fname.'-replace' );
4097
4098 $text = preg_replace_callback(
4099 '/(<!--LINK .*?-->)/',
4100 "wfOutputReplaceMatches",
4101 $text);
4102
4103 wfProfileOut( $fname.'-replace' );
4104 }
4105
4106 # Now process interwiki link holders
4107 # This is quite a bit simpler than internal links
4108 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4109 wfProfileIn( $fname.'-interwiki' );
4110 # Make interwiki link HTML
4111 $wgOutputReplace = array();
4112 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4113 $title = $this->mInterwikiLinkHolders['titles'][$key];
4114 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
4115 }
4116
4117 $text = preg_replace_callback(
4118 '/<!--IWLINK (.*?)-->/',
4119 "wfOutputReplaceMatches",
4120 $text );
4121 wfProfileOut( $fname.'-interwiki' );
4122 }
4123
4124 wfProfileOut( $fname );
4125 return $colours;
4126 }
4127
4128 /**
4129 * Replace <!--LINK--> link placeholders with plain text of links
4130 * (not HTML-formatted).
4131 * @param string $text
4132 * @return string
4133 */
4134 function replaceLinkHoldersText( $text ) {
4135 $fname = 'Parser::replaceLinkHoldersText';
4136 wfProfileIn( $fname );
4137
4138 $text = preg_replace_callback(
4139 '/<!--(LINK|IWLINK) (.*?)-->/',
4140 array( &$this, 'replaceLinkHoldersTextCallback' ),
4141 $text );
4142
4143 wfProfileOut( $fname );
4144 return $text;
4145 }
4146
4147 /**
4148 * @param array $matches
4149 * @return string
4150 * @private
4151 */
4152 function replaceLinkHoldersTextCallback( $matches ) {
4153 $type = $matches[1];
4154 $key = $matches[2];
4155 if( $type == 'LINK' ) {
4156 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4157 return $this->mLinkHolders['texts'][$key];
4158 }
4159 } elseif( $type == 'IWLINK' ) {
4160 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4161 return $this->mInterwikiLinkHolders['texts'][$key];
4162 }
4163 }
4164 return $matches[0];
4165 }
4166
4167 /**
4168 * Tag hook handler for 'pre'.
4169 */
4170 function renderPreTag( $text, $attribs, $parser ) {
4171 // Backwards-compatibility hack
4172 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4173
4174 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4175 return wfOpenElement( 'pre', $attribs ) .
4176 wfEscapeHTMLTagsOnly( $content ) .
4177 '</pre>';
4178 }
4179
4180 /**
4181 * Renders an image gallery from a text with one line per image.
4182 * text labels may be given by using |-style alternative text. E.g.
4183 * Image:one.jpg|The number "1"
4184 * Image:tree.jpg|A tree
4185 * given as text will return the HTML of a gallery with two images,
4186 * labeled 'The number "1"' and
4187 * 'A tree'.
4188 */
4189 function renderImageGallery( $text, $params ) {
4190 $ig = new ImageGallery();
4191 $ig->setShowBytes( false );
4192 $ig->setShowFilename( false );
4193 $ig->setParsing();
4194 $ig->useSkin( $this->mOptions->getSkin() );
4195
4196 if( isset( $params['caption'] ) )
4197 $ig->setCaption( $params['caption'] );
4198
4199 $lines = explode( "\n", $text );
4200 foreach ( $lines as $line ) {
4201 # match lines like these:
4202 # Image:someimage.jpg|This is some image
4203 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4204 # Skip empty lines
4205 if ( count( $matches ) == 0 ) {
4206 continue;
4207 }
4208 $tp = Title::newFromText( $matches[1] );
4209 $nt =& $tp;
4210 if( is_null( $nt ) ) {
4211 # Bogus title. Ignore these so we don't bomb out later.
4212 continue;
4213 }
4214 if ( isset( $matches[3] ) ) {
4215 $label = $matches[3];
4216 } else {
4217 $label = '';
4218 }
4219
4220 $pout = $this->parse( $label,
4221 $this->mTitle,
4222 $this->mOptions,
4223 false, // Strip whitespace...?
4224 false // Don't clear state!
4225 );
4226 $html = $pout->getText();
4227
4228 $ig->add( new Image( $nt ), $html );
4229
4230 # Only add real images (bug #5586)
4231 if ( $nt->getNamespace() == NS_IMAGE ) {
4232 $this->mOutput->addImage( $nt->getDBkey() );
4233 }
4234 }
4235 return $ig->toHTML();
4236 }
4237
4238 /**
4239 * Parse image options text and use it to make an image
4240 */
4241 function makeImage( &$nt, $options ) {
4242 global $wgUseImageResize, $wgDjvuRenderer;
4243
4244 $align = '';
4245
4246 # Check if the options text is of the form "options|alt text"
4247 # Options are:
4248 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4249 # * left no resizing, just left align. label is used for alt= only
4250 # * right same, but right aligned
4251 # * none same, but not aligned
4252 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4253 # * center center the image
4254 # * framed Keep original image size, no magnify-button.
4255
4256 $part = explode( '|', $options);
4257
4258 $mwThumb =& MagicWord::get( 'img_thumbnail' );
4259 $mwManualThumb =& MagicWord::get( 'img_manualthumb' );
4260 $mwLeft =& MagicWord::get( 'img_left' );
4261 $mwRight =& MagicWord::get( 'img_right' );
4262 $mwNone =& MagicWord::get( 'img_none' );
4263 $mwWidth =& MagicWord::get( 'img_width' );
4264 $mwCenter =& MagicWord::get( 'img_center' );
4265 $mwFramed =& MagicWord::get( 'img_framed' );
4266 $mwPage =& MagicWord::get( 'img_page' );
4267 $caption = '';
4268
4269 $width = $height = $framed = $thumb = false;
4270 $page = null;
4271 $manual_thumb = '' ;
4272
4273 foreach( $part as $key => $val ) {
4274 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4275 $thumb=true;
4276 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4277 # use manually specified thumbnail
4278 $thumb=true;
4279 $manual_thumb = $match;
4280 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4281 # remember to set an alignment, don't render immediately
4282 $align = 'right';
4283 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4284 # remember to set an alignment, don't render immediately
4285 $align = 'left';
4286 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4287 # remember to set an alignment, don't render immediately
4288 $align = 'center';
4289 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4290 # remember to set an alignment, don't render immediately
4291 $align = 'none';
4292 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4293 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4294 # Select a page in a multipage document
4295 $page = $match;
4296 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4297 wfDebug( "img_width match: $match\n" );
4298 # $match is the image width in pixels
4299 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4300 $width = intval( $m[1] );
4301 $height = intval( $m[2] );
4302 } else {
4303 $width = intval($match);
4304 }
4305 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4306 $framed=true;
4307 } else {
4308 $caption = $val;
4309 }
4310 }
4311 # Strip bad stuff out of the alt text
4312 $alt = $this->replaceLinkHoldersText( $caption );
4313
4314 # make sure there are no placeholders in thumbnail attributes
4315 # that are later expanded to html- so expand them now and
4316 # remove the tags
4317 $alt = $this->unstrip($alt, $this->mStripState);
4318 $alt = Sanitizer::stripAllTags( $alt );
4319
4320 # Linker does the rest
4321 $sk =& $this->mOptions->getSkin();
4322 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4323 }
4324
4325 /**
4326 * Set a flag in the output object indicating that the content is dynamic and
4327 * shouldn't be cached.
4328 */
4329 function disableCache() {
4330 wfDebug( "Parser output marked as uncacheable.\n" );
4331 $this->mOutput->mCacheTime = -1;
4332 }
4333
4334 /**#@+
4335 * Callback from the Sanitizer for expanding items found in HTML attribute
4336 * values, so they can be safely tested and escaped.
4337 * @param string $text
4338 * @param array $args
4339 * @return string
4340 * @private
4341 */
4342 function attributeStripCallback( &$text, $args ) {
4343 $text = $this->replaceVariables( $text, $args );
4344 $text = $this->unstripForHTML( $text );
4345 return $text;
4346 }
4347
4348 function unstripForHTML( $text ) {
4349 $text = $this->unstrip( $text, $this->mStripState );
4350 $text = $this->unstripNoWiki( $text, $this->mStripState );
4351 return $text;
4352 }
4353 /**#@-*/
4354
4355 /**#@+
4356 * Accessor/mutator
4357 */
4358 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4359 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4360 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4361 /**#@-*/
4362
4363 /**#@+
4364 * Accessor
4365 */
4366 function getTags() { return array_keys( $this->mTagHooks ); }
4367 /**#@-*/
4368
4369
4370 /**
4371 * Break wikitext input into sections, and either pull or replace
4372 * some particular section's text.
4373 *
4374 * External callers should use the getSection and replaceSection methods.
4375 *
4376 * @param $text Page wikitext
4377 * @param $section Numbered section. 0 pulls the text before the first
4378 * heading; other numbers will pull the given section
4379 * along with its lower-level subsections.
4380 * @param $mode One of "get" or "replace"
4381 * @param $newtext Replacement text for section data.
4382 * @return string for "get", the extracted section text.
4383 * for "replace", the whole page with the section replaced.
4384 */
4385 private function extractSections( $text, $section, $mode, $newtext='' ) {
4386 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4387 # comments to be stripped as well)
4388 $striparray = array();
4389
4390 $oldOutputType = $this->mOutputType;
4391 $oldOptions = $this->mOptions;
4392 $this->mOptions = new ParserOptions();
4393 $this->setOutputType( OT_WIKI );
4394
4395 $striptext = $this->strip( $text, $striparray, true );
4396
4397 $this->setOutputType( $oldOutputType );
4398 $this->mOptions = $oldOptions;
4399
4400 # now that we can be sure that no pseudo-sections are in the source,
4401 # split it up by section
4402 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4403 $comment = "(?:$uniq-!--.*?QINU)";
4404 $secs = preg_split(
4405 /*
4406 "/
4407 ^(
4408 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4409 (?:
4410 (=+) # Should this be limited to 6?
4411 .+? # Section title...
4412 \\2 # Ending = count must match start
4413 |
4414 ^
4415 <h([1-6])\b.*?>
4416 .*?
4417 <\/h\\3\s*>
4418 )
4419 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4420 )$
4421 /mix",
4422 */
4423 "/
4424 (
4425 ^
4426 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4427 (=+) # Should this be limited to 6?
4428 .+? # Section title...
4429 \\2 # Ending = count must match start
4430 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4431 $
4432 |
4433 <h([1-6])\b.*?>
4434 .*?
4435 <\/h\\3\s*>
4436 )
4437 /mix",
4438 $striptext, -1,
4439 PREG_SPLIT_DELIM_CAPTURE);
4440
4441 if( $mode == "get" ) {
4442 if( $section == 0 ) {
4443 // "Section 0" returns the content before any other section.
4444 $rv = $secs[0];
4445 } else {
4446 $rv = "";
4447 }
4448 } elseif( $mode == "replace" ) {
4449 if( $section == 0 ) {
4450 $rv = $newtext . "\n\n";
4451 $remainder = true;
4452 } else {
4453 $rv = $secs[0];
4454 $remainder = false;
4455 }
4456 }
4457 $count = 0;
4458 $sectionLevel = 0;
4459 for( $index = 1; $index < count( $secs ); ) {
4460 $headerLine = $secs[$index++];
4461 if( $secs[$index] ) {
4462 // A wiki header
4463 $headerLevel = strlen( $secs[$index++] );
4464 } else {
4465 // An HTML header
4466 $index++;
4467 $headerLevel = intval( $secs[$index++] );
4468 }
4469 $content = $secs[$index++];
4470
4471 $count++;
4472 if( $mode == "get" ) {
4473 if( $count == $section ) {
4474 $rv = $headerLine . $content;
4475 $sectionLevel = $headerLevel;
4476 } elseif( $count > $section ) {
4477 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4478 $rv .= $headerLine . $content;
4479 } else {
4480 // Broke out to a higher-level section
4481 break;
4482 }
4483 }
4484 } elseif( $mode == "replace" ) {
4485 if( $count < $section ) {
4486 $rv .= $headerLine . $content;
4487 } elseif( $count == $section ) {
4488 $rv .= $newtext . "\n\n";
4489 $sectionLevel = $headerLevel;
4490 } elseif( $count > $section ) {
4491 if( $headerLevel <= $sectionLevel ) {
4492 // Passed the section's sub-parts.
4493 $remainder = true;
4494 }
4495 if( $remainder ) {
4496 $rv .= $headerLine . $content;
4497 }
4498 }
4499 }
4500 }
4501 # reinsert stripped tags
4502 $rv = $this->unstrip( $rv, $striparray );
4503 $rv = $this->unstripNoWiki( $rv, $striparray );
4504 $rv = trim( $rv );
4505 return $rv;
4506 }
4507
4508 /**
4509 * This function returns the text of a section, specified by a number ($section).
4510 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4511 * the first section before any such heading (section 0).
4512 *
4513 * If a section contains subsections, these are also returned.
4514 *
4515 * @param $text String: text to look in
4516 * @param $section Integer: section number
4517 * @return string text of the requested section
4518 */
4519 function getSection( $text, $section ) {
4520 return $this->extractSections( $text, $section, "get" );
4521 }
4522
4523 function replaceSection( $oldtext, $section, $text ) {
4524 return $this->extractSections( $oldtext, $section, "replace", $text );
4525 }
4526
4527 }
4528
4529 /**
4530 * @todo document
4531 * @package MediaWiki
4532 */
4533 class ParserOutput
4534 {
4535 var $mText, # The output text
4536 $mLanguageLinks, # List of the full text of language links, in the order they appear
4537 $mCategories, # Map of category names to sort keys
4538 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4539 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4540 $mVersion, # Compatibility check
4541 $mTitleText, # title text of the chosen language variant
4542 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4543 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4544 $mImages, # DB keys of the images used, in the array key only
4545 $mExternalLinks, # External link URLs, in the key only
4546 $mHTMLtitle, # Display HTML title
4547 $mSubtitle, # Additional subtitle
4548 $mNewSection, # Show a new section link?
4549 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4550
4551 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4552 $containsOldMagic = false, $titletext = '' )
4553 {
4554 $this->mText = $text;
4555 $this->mLanguageLinks = $languageLinks;
4556 $this->mCategories = $categoryLinks;
4557 $this->mContainsOldMagic = $containsOldMagic;
4558 $this->mCacheTime = '';
4559 $this->mVersion = MW_PARSER_VERSION;
4560 $this->mTitleText = $titletext;
4561 $this->mLinks = array();
4562 $this->mTemplates = array();
4563 $this->mImages = array();
4564 $this->mExternalLinks = array();
4565 $this->mHTMLtitle = "" ;
4566 $this->mSubtitle = "" ;
4567 $this->mNewSection = false;
4568 $this->mNoGallery = false;
4569 }
4570
4571 function getText() { return $this->mText; }
4572 function &getLanguageLinks() { return $this->mLanguageLinks; }
4573 function getCategoryLinks() { return array_keys( $this->mCategories ); }
4574 function &getCategories() { return $this->mCategories; }
4575 function getCacheTime() { return $this->mCacheTime; }
4576 function getTitleText() { return $this->mTitleText; }
4577 function &getLinks() { return $this->mLinks; }
4578 function &getTemplates() { return $this->mTemplates; }
4579 function &getImages() { return $this->mImages; }
4580 function &getExternalLinks() { return $this->mExternalLinks; }
4581 function getNoGallery() { return $this->mNoGallery; }
4582 function getSubtitle() { return $this->mSubtitle; }
4583
4584 function containsOldMagic() { return $this->mContainsOldMagic; }
4585 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
4586 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
4587 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
4588 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
4589 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
4590 function setTitleText( $t ) { return wfSetVar($this->mTitleText, $t); }
4591 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle, $st ); }
4592
4593 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
4594 function addImage( $name ) { $this->mImages[$name] = 1; }
4595 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
4596 function addExternalLink( $url ) { $this->mExternalLinks[$url] = 1; }
4597
4598 function setNewSection( $value ) {
4599 $this->mNewSection = (bool)$value;
4600 }
4601 function getNewSection() {
4602 return (bool)$this->mNewSection;
4603 }
4604
4605 function addLink( $title, $id = null ) {
4606 $ns = $title->getNamespace();
4607 $dbk = $title->getDBkey();
4608 if ( !isset( $this->mLinks[$ns] ) ) {
4609 $this->mLinks[$ns] = array();
4610 }
4611 if ( is_null( $id ) ) {
4612 $id = $title->getArticleID();
4613 }
4614 $this->mLinks[$ns][$dbk] = $id;
4615 }
4616
4617 function addTemplate( $title, $id ) {
4618 $ns = $title->getNamespace();
4619 $dbk = $title->getDBkey();
4620 if ( !isset( $this->mTemplates[$ns] ) ) {
4621 $this->mTemplates[$ns] = array();
4622 }
4623 $this->mTemplates[$ns][$dbk] = $id;
4624 }
4625
4626 /**
4627 * Return true if this cached output object predates the global or
4628 * per-article cache invalidation timestamps, or if it comes from
4629 * an incompatible older version.
4630 *
4631 * @param string $touched the affected article's last touched timestamp
4632 * @return bool
4633 * @public
4634 */
4635 function expired( $touched ) {
4636 global $wgCacheEpoch;
4637 return $this->getCacheTime() == -1 || // parser says it's uncacheable
4638 $this->getCacheTime() < $touched ||
4639 $this->getCacheTime() <= $wgCacheEpoch ||
4640 !isset( $this->mVersion ) ||
4641 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
4642 }
4643 }
4644
4645 /**
4646 * Set options of the Parser
4647 * @todo document
4648 * @package MediaWiki
4649 */
4650 class ParserOptions
4651 {
4652 # All variables are private
4653 var $mUseTeX; # Use texvc to expand <math> tags
4654 var $mUseDynamicDates; # Use DateFormatter to format dates
4655 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4656 var $mAllowExternalImages; # Allow external images inline
4657 var $mAllowExternalImagesFrom; # If not, any exception?
4658 var $mSkin; # Reference to the preferred skin
4659 var $mDateFormat; # Date format index
4660 var $mEditSection; # Create "edit section" links
4661 var $mNumberHeadings; # Automatically number headings
4662 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4663 var $mTidy; # Ask for tidy cleanup
4664 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4665 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4666 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4667
4668 var $mUser; # Stored user object, just used to initialise the skin
4669
4670 function getUseTeX() { return $this->mUseTeX; }
4671 function getUseDynamicDates() { return $this->mUseDynamicDates; }
4672 function getInterwikiMagic() { return $this->mInterwikiMagic; }
4673 function getAllowExternalImages() { return $this->mAllowExternalImages; }
4674 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
4675 function getEditSection() { return $this->mEditSection; }
4676 function getNumberHeadings() { return $this->mNumberHeadings; }
4677 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
4678 function getTidy() { return $this->mTidy; }
4679 function getInterfaceMessage() { return $this->mInterfaceMessage; }
4680 function getMaxIncludeSize() { return $this->mMaxIncludeSize; }
4681 function getRemoveComments() { return $this->mRemoveComments; }
4682
4683 function &getSkin() {
4684 if ( !isset( $this->mSkin ) ) {
4685 $this->mSkin = $this->mUser->getSkin();
4686 }
4687 return $this->mSkin;
4688 }
4689
4690 function getDateFormat() {
4691 if ( !isset( $this->mDateFormat ) ) {
4692 $this->mDateFormat = $this->mUser->getDatePreference();
4693 }
4694 return $this->mDateFormat;
4695 }
4696
4697 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
4698 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
4699 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
4700 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
4701 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
4702 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
4703 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
4704 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
4705 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
4706 function setTidy( $x ) { return wfSetVar( $this->mTidy, $x); }
4707 function setSkin( &$x ) { $this->mSkin =& $x; }
4708 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage, $x); }
4709 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize, $x ); }
4710 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments, $x ); }
4711
4712 function ParserOptions( $user = null ) {
4713 $this->initialiseFromUser( $user );
4714 }
4715
4716 /**
4717 * Get parser options
4718 * @static
4719 */
4720 static function newFromUser( $user ) {
4721 return new ParserOptions( $user );
4722 }
4723
4724 /** Get user options */
4725 function initialiseFromUser( $userInput ) {
4726 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4727 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4728 $fname = 'ParserOptions::initialiseFromUser';
4729 wfProfileIn( $fname );
4730 if ( !$userInput ) {
4731 global $wgUser;
4732 if ( isset( $wgUser ) ) {
4733 $user = $wgUser;
4734 } else {
4735 $user = new User;
4736 $user->setLoaded( true );
4737 }
4738 } else {
4739 $user =& $userInput;
4740 }
4741
4742 $this->mUser = $user;
4743
4744 $this->mUseTeX = $wgUseTeX;
4745 $this->mUseDynamicDates = $wgUseDynamicDates;
4746 $this->mInterwikiMagic = $wgInterwikiMagic;
4747 $this->mAllowExternalImages = $wgAllowExternalImages;
4748 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
4749 $this->mSkin = null; # Deferred
4750 $this->mDateFormat = null; # Deferred
4751 $this->mEditSection = true;
4752 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
4753 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
4754 $this->mTidy = false;
4755 $this->mInterfaceMessage = false;
4756 $this->mMaxIncludeSize = $wgMaxArticleSize * 1024;
4757 $this->mRemoveComments = true;
4758 wfProfileOut( $fname );
4759 }
4760 }
4761
4762 /**
4763 * Callback function used by Parser::replaceLinkHolders()
4764 * to substitute link placeholders.
4765 */
4766 function &wfOutputReplaceMatches( $matches ) {
4767 global $wgOutputReplace;
4768 return $wgOutputReplace[$matches[1]];
4769 }
4770
4771 /**
4772 * Return the total number of articles
4773 */
4774 function wfNumberOfArticles() {
4775 global $wgNumberOfArticles;
4776
4777 wfLoadSiteStats();
4778 return $wgNumberOfArticles;
4779 }
4780
4781 /**
4782 * Return the number of files
4783 */
4784 function wfNumberOfFiles() {
4785 $fname = 'wfNumberOfFiles';
4786
4787 wfProfileIn( $fname );
4788 $dbr =& wfGetDB( DB_SLAVE );
4789 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4790 wfProfileOut( $fname );
4791
4792 return $numImages;
4793 }
4794
4795 /**
4796 * Return the number of user accounts
4797 * @return integer
4798 */
4799 function wfNumberOfUsers() {
4800 wfProfileIn( 'wfNumberOfUsers' );
4801 $dbr =& wfGetDB( DB_SLAVE );
4802 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4803 wfProfileOut( 'wfNumberOfUsers' );
4804 return (int)$count;
4805 }
4806
4807 /**
4808 * Return the total number of pages
4809 * @return integer
4810 */
4811 function wfNumberOfPages() {
4812 wfProfileIn( 'wfNumberOfPages' );
4813 $dbr =& wfGetDB( DB_SLAVE );
4814 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4815 wfProfileOut( 'wfNumberOfPages' );
4816 return (int)$count;
4817 }
4818
4819 /**
4820 * Return the total number of admins
4821 *
4822 * @return integer
4823 */
4824 function wfNumberOfAdmins() {
4825 static $admins = -1;
4826 wfProfileIn( 'wfNumberOfAdmins' );
4827 if( $admins == -1 ) {
4828 $dbr =& wfGetDB( DB_SLAVE );
4829 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4830 }
4831 wfProfileOut( 'wfNumberOfAdmins' );
4832 return (int)$admins;
4833 }
4834
4835 /**
4836 * Count the number of pages in a particular namespace
4837 *
4838 * @param $ns Namespace
4839 * @return integer
4840 */
4841 function wfPagesInNs( $ns ) {
4842 static $pageCount = array();
4843 wfProfileIn( 'wfPagesInNs' );
4844 if( !isset( $pageCount[$ns] ) ) {
4845 $dbr =& wfGetDB( DB_SLAVE );
4846 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4847 }
4848 wfProfileOut( 'wfPagesInNs' );
4849 return (int)$pageCount[$ns];
4850 }
4851
4852 /**
4853 * Get various statistics from the database
4854 * @private
4855 */
4856 function wfLoadSiteStats() {
4857 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4858 $fname = 'wfLoadSiteStats';
4859
4860 if ( -1 != $wgNumberOfArticles ) return;
4861 $dbr =& wfGetDB( DB_SLAVE );
4862 $s = $dbr->selectRow( 'site_stats',
4863 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4864 array( 'ss_row_id' => 1 ), $fname
4865 );
4866
4867 if ( $s === false ) {
4868 return;
4869 } else {
4870 $wgTotalViews = $s->ss_total_views;
4871 $wgTotalEdits = $s->ss_total_edits;
4872 $wgNumberOfArticles = $s->ss_good_articles;
4873 }
4874 }
4875
4876 /**
4877 * Get revision timestamp from the database considering timecorrection
4878 *
4879 * @param $id Int: page revision id
4880 * @return integer
4881 */
4882 function wfRevisionTimestamp( $id ) {
4883 global $wgContLang;
4884 $fname = 'wfRevisionTimestamp';
4885
4886 wfProfileIn( $fname );
4887 $dbr =& wfGetDB( DB_SLAVE );
4888 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4889 array( 'rev_id' => $id ), __METHOD__ );
4890 $timestamp = $wgContLang->userAdjust( $timestamp );
4891 wfProfileOut( $fname );
4892
4893 return $timestamp;
4894 }
4895
4896 /**
4897 * Escape html tags
4898 * Basically replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
4899 *
4900 * @param $in String: text that might contain HTML tags.
4901 * @return string Escaped string
4902 */
4903 function wfEscapeHTMLTagsOnly( $in ) {
4904 return str_replace(
4905 array( '"', '>', '<' ),
4906 array( '&quot;', '&gt;', '&lt;' ),
4907 $in );
4908 }
4909
4910 ?>