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