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