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