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