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