@fixme this is probably *horribly wrong*
[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.2';
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 $accum .= htmlspecialchars( substr( $text, $i ) );
2697 if ( $this->ot['html'] ) {
2698 // Close it so later stripping can remove it
2699 $accum .= htmlspecialchars( '-->' );
2700 }
2701 $i = strlen( $text );
2702 continue;
2703 }
2704 $accum .= htmlspecialchars( substr( $text, $i, $endpos - $i + 3 ) );
2705 #$inner = substr( $text, $i + 4, $endpos - $i - 4 );
2706 #$accum .= '<ext><name>!--</name><inner>' . htmlspecialchars( $inner ) . '</inner></ext>';
2707 $i = $endpos + 3;
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 if ( !$dom->loadXML( $topAccum ) ) {
2989 throw new MWException( __METHOD__.' generated invalid XML' );
2990 }
2991 wfProfileOut( __METHOD__.'-loadXML' );
2992 wfProfileOut( __METHOD__ );
2993 return $dom;
2994 }
2995
2996 /*
2997 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2998 */
2999 public static function splitWhitespace( $s ) {
3000 $ltrimmed = ltrim( $s );
3001 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3002 $trimmed = rtrim( $ltrimmed );
3003 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3004 if ( $diff > 0 ) {
3005 $w2 = substr( $ltrimmed, -$diff );
3006 } else {
3007 $w2 = '';
3008 }
3009 return array( $w1, $trimmed, $w2 );
3010 }
3011
3012 /**
3013 * Replace magic variables, templates, and template arguments
3014 * with the appropriate text. Templates are substituted recursively,
3015 * taking care to avoid infinite loops.
3016 *
3017 * Note that the substitution depends on value of $mOutputType:
3018 * OT_WIKI: only {{subst:}} templates
3019 * OT_MSG: only magic variables
3020 * OT_HTML: all templates and magic variables
3021 *
3022 * @param string $tex The text to transform
3023 * @param PPFrame $frame Object describing the arguments passed to the template
3024 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
3025 * @private
3026 */
3027 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3028 # Prevent too big inclusions
3029 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
3030 return $text;
3031 }
3032
3033 $fname = __METHOD__;
3034 wfProfileIn( $fname );
3035
3036 if ( $frame === false ) {
3037 $frame = new PPFrame( $this );
3038 } elseif ( !( $frame instanceof PPFrame ) ) {
3039 throw new MWException( __METHOD__ . ' called using the old argument format' );
3040 }
3041
3042 $dom = $this->preprocessToDom( $text );
3043 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3044 $text = $frame->expand( $dom, $flags );
3045
3046 wfProfileOut( $fname );
3047 return $text;
3048 }
3049
3050 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3051 static function createAssocArgs( $args ) {
3052 $assocArgs = array();
3053 $index = 1;
3054 foreach( $args as $arg ) {
3055 $eqpos = strpos( $arg, '=' );
3056 if ( $eqpos === false ) {
3057 $assocArgs[$index++] = $arg;
3058 } else {
3059 $name = trim( substr( $arg, 0, $eqpos ) );
3060 $value = trim( substr( $arg, $eqpos+1 ) );
3061 if ( $value === false ) {
3062 $value = '';
3063 }
3064 if ( $name !== false ) {
3065 $assocArgs[$name] = $value;
3066 }
3067 }
3068 }
3069
3070 return $assocArgs;
3071 }
3072
3073 /**
3074 * Return the text of a template, after recursively
3075 * replacing any variables or templates within the template.
3076 *
3077 * @param array $piece The parts of the template
3078 * $piece['text']: matched text
3079 * $piece['title']: the title, i.e. the part before the |
3080 * $piece['parts']: the parameter array
3081 * @param PPFrame The current frame, contains template arguments
3082 * @return string the text of the template
3083 * @private
3084 */
3085 function braceSubstitution( $piece, $frame ) {
3086 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
3087 $fname = __METHOD__;
3088 wfProfileIn( $fname );
3089 wfProfileIn( __METHOD__.'-setup' );
3090
3091 # Flags
3092 $found = false; # $text has been filled
3093 $nowiki = false; # wiki markup in $text should be escaped
3094 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
3095 $noargs = false; # Don't replace triple-brace arguments in $text
3096 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3097 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3098 $isDOM = false; # $text is a DOM node needing expansion
3099
3100 # Title object, where $text came from
3101 $title = NULL;
3102
3103 # $part1 is the bit before the first |, and must contain only title characters.
3104 # Various prefixes will be stripped from it later.
3105 $titleWithSpaces = $frame->expand( $piece['title'] );
3106 $part1 = trim( $titleWithSpaces );
3107 $titleText = false;
3108
3109 # Original title text preserved for various purposes
3110 $originalTitle = $part1;
3111
3112 # $args is a list of argument nodes, starting from index 0, not including $part1
3113 $args = (null == $piece['parts']) ? array() : $piece['parts'];
3114 wfProfileOut( __METHOD__.'-setup' );
3115
3116 # SUBST
3117 wfProfileIn( __METHOD__.'-modifiers' );
3118 if ( !$found ) {
3119 $mwSubst =& MagicWord::get( 'subst' );
3120 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
3121 # One of two possibilities is true:
3122 # 1) Found SUBST but not in the PST phase
3123 # 2) Didn't find SUBST and in the PST phase
3124 # In either case, return without further processing
3125 $text = '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3126 $found = true;
3127 $noparse = true;
3128 $noargs = true;
3129 }
3130 }
3131
3132 # Variables
3133 if ( !$found && $args->length == 0 ) {
3134 $id = $this->mVariables->matchStartToEnd( $part1 );
3135 if ( $id !== false ) {
3136 $text = $this->getVariableValue( $id );
3137 $this->mOutput->mContainsOldMagic = true;
3138 $found = true;
3139 $noparse = true;
3140 $noargs = true;
3141 }
3142 }
3143
3144 # MSG, MSGNW and RAW
3145 if ( !$found ) {
3146 # Check for MSGNW:
3147 $mwMsgnw =& MagicWord::get( 'msgnw' );
3148 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3149 $nowiki = true;
3150 } else {
3151 # Remove obsolete MSG:
3152 $mwMsg =& MagicWord::get( 'msg' );
3153 $mwMsg->matchStartAndRemove( $part1 );
3154 }
3155
3156 # Check for RAW:
3157 $mwRaw =& MagicWord::get( 'raw' );
3158 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3159 $forceRawInterwiki = true;
3160 }
3161 }
3162 wfProfileOut( __METHOD__.'-modifiers' );
3163
3164 # Save path level before recursing into functions & templates.
3165 $lastPathLevel = $this->mTemplatePath;
3166
3167 # Parser functions
3168 if ( !$found ) {
3169 wfProfileIn( __METHOD__ . '-pfunc' );
3170
3171 $colonPos = strpos( $part1, ':' );
3172 if ( $colonPos !== false ) {
3173 # Case sensitive functions
3174 $function = substr( $part1, 0, $colonPos );
3175 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3176 $function = $this->mFunctionSynonyms[1][$function];
3177 } else {
3178 # Case insensitive functions
3179 $function = strtolower( $function );
3180 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3181 $function = $this->mFunctionSynonyms[0][$function];
3182 } else {
3183 $function = false;
3184 }
3185 }
3186 if ( $function ) {
3187 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3188 $initialArgs = array( &$this );
3189 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3190 if ( $flags & SFH_OBJECT_ARGS ) {
3191 # Add a frame parameter, and pass the arguments as an array
3192 $allArgs = $initialArgs;
3193 $allArgs[] = $frame;
3194 foreach ( $args as $arg ) {
3195 $funcArgs[] = $arg;
3196 }
3197 $allArgs[] = $funcArgs;
3198 } else {
3199 # Convert arguments to plain text
3200 foreach ( $args as $arg ) {
3201 $funcArgs[] = trim( $frame->expand( $arg ) );
3202 }
3203 $allArgs = array_merge( $initialArgs, $funcArgs );
3204 }
3205
3206 $result = call_user_func_array( $callback, $allArgs );
3207 $found = true;
3208
3209 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
3210 $noargs = true;
3211 $noparse = true;
3212
3213 if ( is_array( $result ) ) {
3214 if ( isset( $result[0] ) ) {
3215 $text = $result[0];
3216 unset( $result[0] );
3217 }
3218
3219 // Extract flags into the local scope
3220 // This allows callers to set flags such as nowiki, noparse, found, etc.
3221 extract( $result );
3222 } else {
3223 $text = $result;
3224 }
3225 }
3226 }
3227 wfProfileOut( __METHOD__ . '-pfunc' );
3228 }
3229
3230 # Finish mangling title and then check for loops.
3231 # Set $title to a Title object and $titleText to the PDBK
3232 if ( !$found ) {
3233 $ns = NS_TEMPLATE;
3234 # Split the title into page and subpage
3235 $subpage = '';
3236 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3237 if ($subpage !== '') {
3238 $ns = $this->mTitle->getNamespace();
3239 }
3240 $title = Title::newFromText( $part1, $ns );
3241 if ( $title ) {
3242 $titleText = $title->getPrefixedText();
3243 # Check for language variants if the template is not found
3244 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3245 $wgContLang->findVariantLink($part1, $title);
3246 }
3247 # Do infinite loop check
3248 if ( isset( $this->mTemplatePath[$titleText] ) ) {
3249 $noparse = true;
3250 $noargs = true;
3251 $found = true;
3252 $text = "[[$part1]]" . $this->insertStripItem( '<!-- WARNING: template loop detected -->' );
3253 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
3254 }
3255 }
3256 }
3257
3258 # Load from database
3259 if ( !$found && $title ) {
3260 wfProfileIn( __METHOD__ . '-loadtpl' );
3261 if ( !$title->isExternal() ) {
3262 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
3263 $text = SpecialPage::capturePath( $title );
3264 if ( is_string( $text ) ) {
3265 $found = true;
3266 $noparse = true;
3267 $noargs = true;
3268 $isHTML = true;
3269 $this->disableCache();
3270 }
3271 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3272 $found = false; //access denied
3273 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3274 } else {
3275 list( $text, $title ) = $this->getTemplateDom( $title );
3276 if ( $text !== false ) {
3277 $found = true;
3278 $isDOM = true;
3279 }
3280 }
3281
3282 # If the title is valid but undisplayable, make a link to it
3283 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3284 $text = "[[:$titleText]]";
3285 $found = true;
3286 }
3287 } elseif ( $title->isTrans() ) {
3288 // Interwiki transclusion
3289 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3290 $text = $this->interwikiTransclude( $title, 'render' );
3291 $isHTML = true;
3292 $noparse = true;
3293 } else {
3294 $text = $this->interwikiTransclude( $title, 'raw' );
3295 }
3296 $found = true;
3297 }
3298 wfProfileOut( __METHOD__ . '-loadtpl' );
3299 }
3300
3301 # Recursive parsing, escaping and link table handling
3302 # Only for HTML output
3303 if ( $nowiki && $found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3304 if ( $isDOM ) {
3305 $text = $frame->expand( $text );
3306 }
3307 $text = wfEscapeWikiText( $text );
3308 } elseif ( !$this->ot['msg'] && $found ) {
3309 if ( $noargs ) {
3310 $newFrame = $frame->newChild();
3311 } else {
3312 # Clean up argument array
3313 $newFrame = $frame->newChild( $args, $title );
3314 # Add a new element to the templace recursion path
3315 $this->mTemplatePath[$titleText] = 1;
3316 }
3317
3318 if ( !$noparse ) {
3319 if ( $isDOM ) {
3320 if ( $titleText !== false && count( $newFrame->args ) == 0 ) {
3321 # Expansion is eligible for the empty-frame cache
3322 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3323 $text = $this->mTplExpandCache[$titleText];
3324 } else {
3325 $text = $newFrame->expand( $text );
3326 $this->mTplExpandCache[$titleText] = $text;
3327 }
3328 } else {
3329 $text = $newFrame->expand( $text );
3330 }
3331 } else {
3332 $text = $this->replaceVariables( $text, $newFrame );
3333 }
3334
3335 # strip woz 'ere 2004-07
3336
3337 # Bug 529: if the template begins with a table or block-level
3338 # element, it should be treated as beginning a new line.
3339 # This behaviour is somewhat controversial.
3340 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3341 $text = "\n" . $text;
3342 }
3343 } elseif ( !$noargs ) {
3344 # $noparse and !$noargs
3345 # Just replace the arguments, not any double-brace items
3346 # This is used for rendered interwiki transclusion
3347 if ( $isDOM ) {
3348 $text = $newFrame->expand( $text, PPFrame::NO_TEMPLATES );
3349 } else {
3350 $text = $this->replaceVariables( $text, $newFrame, true );
3351 }
3352 } elseif ( $isDOM ) {
3353 $text = $frame->expand( $text );
3354 }
3355 } elseif ( $isDOM ) {
3356 $text = $frame->expand( $text, PPFrame::NO_TEMPLATES | PPFrame::NO_ARGS );
3357 }
3358
3359 # Prune lower levels off the recursion check path
3360 $this->mTemplatePath = $lastPathLevel;
3361
3362 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3363 # Error, oversize inclusion
3364 $text = "[[$originalTitle]]" .
3365 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3366 $noparse = true;
3367 $noargs = true;
3368 }
3369
3370 if ( !$found ) {
3371 wfProfileOut( $fname );
3372 return '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3373 } else {
3374 wfProfileIn( __METHOD__ . '-placeholders' );
3375 if ( $isHTML ) {
3376 # Replace raw HTML by a placeholder
3377 # Add a blank line preceding, to prevent it from mucking up
3378 # immediately preceding headings
3379 $text = "\n\n" . $this->insertStripItem( $text );
3380 }
3381 wfProfileOut( __METHOD__ . '-placeholders' );
3382 }
3383
3384 # Prune lower levels off the recursion check path
3385 $this->mTemplatePath = $lastPathLevel;
3386
3387 if ( !$found ) {
3388 wfProfileOut( $fname );
3389 return '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3390 } else {
3391 wfProfileOut( $fname );
3392 return $text;
3393 }
3394 }
3395
3396 /**
3397 * Get the semi-parsed DOM representation of a template with a given title,
3398 * and its redirect destination title. Cached.
3399 */
3400 function getTemplateDom( $title ) {
3401 $cacheTitle = $title;
3402 $titleText = $title->getPrefixedDBkey();
3403
3404 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3405 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3406 $title = Title::makeTitle( $ns, $dbk );
3407 $titleText = $title->getPrefixedDBkey();
3408 }
3409 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3410 return array( $this->mTplDomCache[$titleText], $title );
3411 }
3412
3413 // Cache miss, go to the database
3414 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3415
3416 if ( $text === false ) {
3417 $this->mTplDomCache[$titleText] = false;
3418 return array( false, $title );
3419 }
3420
3421 # If there are any <onlyinclude> tags, only include them
3422 if ( !$this->ot['msg'] ) {
3423 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3424 $replacer = new OnlyIncludeReplacer;
3425 StringUtils::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3426 array( &$replacer, 'replace' ), $text );
3427 $text = $replacer->output;
3428 }
3429 # Remove <noinclude> sections and <includeonly> tags
3430 $text = StringUtils::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3431 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3432 }
3433
3434 $dom = $this->preprocessToDom( $text );
3435
3436 $this->mTplDomCache[ $titleText ] = $dom;
3437
3438 if (! $title->equals($cacheTitle)) {
3439 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3440 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3441 }
3442
3443 return array( $dom, $title );
3444 }
3445
3446 /**
3447 * Fetch the unparsed text of a template and register a reference to it.
3448 */
3449 function fetchTemplateAndTitle( $title ) {
3450 $templateCb = $this->mOptions->getTemplateCallback();
3451 $stuff = call_user_func( $templateCb, $title );
3452 $text = $stuff['text'];
3453 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3454 if ( isset( $stuff['deps'] ) ) {
3455 foreach ( $stuff['deps'] as $dep ) {
3456 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3457 }
3458 }
3459 return array($text,$finalTitle);
3460 }
3461
3462 function fetchTemplate( $title ) {
3463 $rv = $this->fetchTemplateAndTitle($title);
3464 return $rv[0];
3465 }
3466
3467 /**
3468 * Static function to get a template
3469 * Can be overridden via ParserOptions::setTemplateCallback().
3470 */
3471 static function statelessFetchTemplate( $title ) {
3472 $text = $skip = false;
3473 $finalTitle = $title;
3474 $deps = array();
3475
3476 // Loop to fetch the article, with up to 1 redirect
3477 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3478 # Give extensions a chance to select the revision instead
3479 $id = false; // Assume current
3480 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3481
3482 if( $skip ) {
3483 $text = false;
3484 $deps[] = array(
3485 'title' => $title,
3486 'page_id' => $title->getArticleID(),
3487 'rev_id' => null );
3488 break;
3489 }
3490 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3491 $rev_id = $rev ? $rev->getId() : 0;
3492
3493 $deps[] = array(
3494 'title' => $title,
3495 'page_id' => $title->getArticleID(),
3496 'rev_id' => $rev_id );
3497
3498 if( $rev ) {
3499 $text = $rev->getText();
3500 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3501 global $wgLang;
3502 $message = $wgLang->lcfirst( $title->getText() );
3503 $text = wfMsgForContentNoTrans( $message );
3504 if( wfEmptyMsg( $message, $text ) ) {
3505 $text = false;
3506 break;
3507 }
3508 } else {
3509 break;
3510 }
3511 if ( $text === false ) {
3512 break;
3513 }
3514 // Redirect?
3515 $finalTitle = $title;
3516 $title = Title::newFromRedirect( $text );
3517 }
3518 return array(
3519 'text' => $text,
3520 'finalTitle' => $finalTitle,
3521 'deps' => $deps );
3522 }
3523
3524 /**
3525 * Transclude an interwiki link.
3526 */
3527 function interwikiTransclude( $title, $action ) {
3528 global $wgEnableScaryTranscluding;
3529
3530 if (!$wgEnableScaryTranscluding)
3531 return wfMsg('scarytranscludedisabled');
3532
3533 $url = $title->getFullUrl( "action=$action" );
3534
3535 if (strlen($url) > 255)
3536 return wfMsg('scarytranscludetoolong');
3537 return $this->fetchScaryTemplateMaybeFromCache($url);
3538 }
3539
3540 function fetchScaryTemplateMaybeFromCache($url) {
3541 global $wgTranscludeCacheExpiry;
3542 $dbr = wfGetDB(DB_SLAVE);
3543 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3544 array('tc_url' => $url));
3545 if ($obj) {
3546 $time = $obj->tc_time;
3547 $text = $obj->tc_contents;
3548 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3549 return $text;
3550 }
3551 }
3552
3553 $text = Http::get($url);
3554 if (!$text)
3555 return wfMsg('scarytranscludefailed', $url);
3556
3557 $dbw = wfGetDB(DB_MASTER);
3558 $dbw->replace('transcache', array('tc_url'), array(
3559 'tc_url' => $url,
3560 'tc_time' => time(),
3561 'tc_contents' => $text));
3562 return $text;
3563 }
3564
3565
3566 /**
3567 * Triple brace replacement -- used for template arguments
3568 * @private
3569 */
3570 function argSubstitution( $piece, $frame ) {
3571 wfProfileIn( __METHOD__ );
3572
3573 $text = false;
3574 $error = false;
3575 $parts = $piece['parts'];
3576 $argWithSpaces = $frame->expand( $piece['title'] );
3577 $arg = trim( $argWithSpaces );
3578
3579 if ( isset( $frame->args[$arg] ) ) {
3580 $text = $frame->parent->expand( $frame->args[$arg] );
3581 } else if ( ( $this->ot['html'] || $this->ot['pre'] ) && $parts->length > 0 ) {
3582 $text = $frame->expand( $parts->item( 0 ) );
3583 }
3584 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3585 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3586 }
3587
3588 if ( $text === false ) {
3589 $text = '{{{' . $frame->implode( '|', $argWithSpaces, $parts ) . '}}}';
3590 }
3591 if ( $error !== false ) {
3592 $text .= $error;
3593 }
3594
3595 wfProfileOut( __METHOD__ );
3596 return $text;
3597 }
3598
3599 /**
3600 * Return the text to be used for a given extension tag.
3601 * This is the ghost of strip().
3602 *
3603 * @param array $params Associative array of parameters:
3604 * name DOMNode for the tag name
3605 * attrText DOMNode for unparsed text where tag attributes are thought to be
3606 * inner Contents of extension element
3607 * noClose Original text did not have a close tag
3608 * @param PPFrame $frame
3609 */
3610 function extensionSubstitution( $params, $frame ) {
3611 global $wgRawHtml, $wgContLang;
3612 static $n = 1;
3613
3614 $name = $frame->expand( $params['name'] );
3615 $attrText = is_null( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3616 $content = is_null( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3617
3618 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $n++) . $this->mMarkerSuffix;
3619
3620 if ( $this->ot['html'] ) {
3621 if ( $name == '!--' ) {
3622 return '';
3623 }
3624 $name = strtolower( $name );
3625
3626 $params = Sanitizer::decodeTagAttributes( $attrText );
3627 switch ( $name ) {
3628 case 'html':
3629 if( $wgRawHtml ) {
3630 $output = $content;
3631 break;
3632 } else {
3633 throw new MWException( '<html> extension tag encountered unexpectedly' );
3634 }
3635 case 'nowiki':
3636 $output = Xml::escapeTagsOnly( $content );
3637 break;
3638 case 'math':
3639 $output = $wgContLang->armourMath(
3640 MathRenderer::renderMath( $content, $params ) );
3641 break;
3642 case 'gallery':
3643 $output = $this->renderImageGallery( $content, $params );
3644 break;
3645 default:
3646 if( isset( $this->mTagHooks[$name] ) ) {
3647 $output = call_user_func_array( $this->mTagHooks[$name],
3648 array( $content, $params, $this ) );
3649 } else {
3650 throw new MWException( "Invalid call hook $name" );
3651 }
3652 }
3653 } else {
3654 if ( $name == '!--' ) {
3655 $output = '<!--' . $content . '-->';
3656 } else {
3657 if ( $content === null ) {
3658 $output = "<$name$attrText/>";
3659 } else {
3660 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3661 $output = "<$name$attrText>$content$close";
3662 }
3663 }
3664 }
3665
3666 if ( $name == 'html' || $name == 'nowiki' ) {
3667 $this->mStripState->nowiki->setPair( $marker, $output );
3668 } else {
3669 $this->mStripState->general->setPair( $marker, $output );
3670 }
3671 return $marker;
3672 }
3673
3674 /**
3675 * Increment an include size counter
3676 *
3677 * @param string $type The type of expansion
3678 * @param integer $size The size of the text
3679 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3680 */
3681 function incrementIncludeSize( $type, $size ) {
3682 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3683 return false;
3684 } else {
3685 $this->mIncludeSizes[$type] += $size;
3686 return true;
3687 }
3688 }
3689
3690 /**
3691 * Detect __NOGALLERY__ magic word and set a placeholder
3692 */
3693 function stripNoGallery( &$text ) {
3694 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3695 # do not add TOC
3696 $mw = MagicWord::get( 'nogallery' );
3697 $this->mOutput->mNoGallery = $mw->matchAndRemove( $text ) ;
3698 }
3699
3700 /**
3701 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3702 * placeholder that will then be replaced by the real TOC in
3703 * ->formatHeadings, this works because at this points real
3704 * comments will have already been discarded by the sanitizer.
3705 *
3706 * Any additional __TOC__ magic words left over will be discarded
3707 * as there can only be one TOC on the page.
3708 */
3709 function stripToc( $text ) {
3710 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3711 # do not add TOC
3712 $mw = MagicWord::get( 'notoc' );
3713 if( $mw->matchAndRemove( $text ) ) {
3714 $this->mShowToc = false;
3715 }
3716
3717 $mw = MagicWord::get( 'toc' );
3718 if( $mw->match( $text ) ) {
3719 $this->mShowToc = true;
3720 $this->mForceTocPosition = true;
3721
3722 // Set a placeholder. At the end we'll fill it in with the TOC.
3723 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3724
3725 // Only keep the first one.
3726 $text = $mw->replace( '', $text );
3727 }
3728 return $text;
3729 }
3730
3731 /**
3732 * This function accomplishes several tasks:
3733 * 1) Auto-number headings if that option is enabled
3734 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3735 * 3) Add a Table of contents on the top for users who have enabled the option
3736 * 4) Auto-anchor headings
3737 *
3738 * It loops through all headlines, collects the necessary data, then splits up the
3739 * string and re-inserts the newly formatted headlines.
3740 *
3741 * @param string $text
3742 * @param boolean $isMain
3743 * @private
3744 */
3745 function formatHeadings( $text, $isMain=true ) {
3746 global $wgMaxTocLevel, $wgContLang;
3747
3748 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3749 if( !$this->mTitle->quickUserCan( 'edit' ) ) {
3750 $showEditLink = 0;
3751 } else {
3752 $showEditLink = $this->mOptions->getEditSection();
3753 }
3754
3755 # Inhibit editsection links if requested in the page
3756 $esw =& MagicWord::get( 'noeditsection' );
3757 if( $esw->matchAndRemove( $text ) ) {
3758 $showEditLink = 0;
3759 }
3760
3761 # Get all headlines for numbering them and adding funky stuff like [edit]
3762 # links - this is for later, but we need the number of headlines right now
3763 $matches = array();
3764 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3765
3766 # if there are fewer than 4 headlines in the article, do not show TOC
3767 # unless it's been explicitly enabled.
3768 $enoughToc = $this->mShowToc &&
3769 (($numMatches >= 4) || $this->mForceTocPosition);
3770
3771 # Allow user to stipulate that a page should have a "new section"
3772 # link added via __NEWSECTIONLINK__
3773 $mw =& MagicWord::get( 'newsectionlink' );
3774 if( $mw->matchAndRemove( $text ) )
3775 $this->mOutput->setNewSection( true );
3776
3777 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3778 # override above conditions and always show TOC above first header
3779 $mw =& MagicWord::get( 'forcetoc' );
3780 if ($mw->matchAndRemove( $text ) ) {
3781 $this->mShowToc = true;
3782 $enoughToc = true;
3783 }
3784
3785 # We need this to perform operations on the HTML
3786 $sk = $this->mOptions->getSkin();
3787
3788 # headline counter
3789 $headlineCount = 0;
3790 $numVisible = 0;
3791
3792 # Ugh .. the TOC should have neat indentation levels which can be
3793 # passed to the skin functions. These are determined here
3794 $toc = '';
3795 $full = '';
3796 $head = array();
3797 $sublevelCount = array();
3798 $levelCount = array();
3799 $toclevel = 0;
3800 $level = 0;
3801 $prevlevel = 0;
3802 $toclevel = 0;
3803 $prevtoclevel = 0;
3804 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-{$this->mMarkerSuffix}";
3805 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3806
3807 foreach( $matches[3] as $headline ) {
3808 $isTemplate = false;
3809 $titleText = false;
3810 $sectionIndex = false;
3811 $numbering = '';
3812 $markerMatches = array();
3813 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3814 $serial = $markerMatches[1];
3815 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3816 $isTemplate = ($titleText != $baseTitleText);
3817 $headline = preg_replace("/^$markerRegex/", "", $headline);
3818 }
3819
3820 if( $toclevel ) {
3821 $prevlevel = $level;
3822 $prevtoclevel = $toclevel;
3823 }
3824 $level = $matches[1][$headlineCount];
3825
3826 if( $doNumberHeadings || $enoughToc ) {
3827
3828 if ( $level > $prevlevel ) {
3829 # Increase TOC level
3830 $toclevel++;
3831 $sublevelCount[$toclevel] = 0;
3832 if( $toclevel<$wgMaxTocLevel ) {
3833 $prevtoclevel = $toclevel;
3834 $toc .= $sk->tocIndent();
3835 $numVisible++;
3836 }
3837 }
3838 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3839 # Decrease TOC level, find level to jump to
3840
3841 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3842 # Can only go down to level 1
3843 $toclevel = 1;
3844 } else {
3845 for ($i = $toclevel; $i > 0; $i--) {
3846 if ( $levelCount[$i] == $level ) {
3847 # Found last matching level
3848 $toclevel = $i;
3849 break;
3850 }
3851 elseif ( $levelCount[$i] < $level ) {
3852 # Found first matching level below current level
3853 $toclevel = $i + 1;
3854 break;
3855 }
3856 }
3857 }
3858 if( $toclevel<$wgMaxTocLevel ) {
3859 if($prevtoclevel < $wgMaxTocLevel) {
3860 # Unindent only if the previous toc level was shown :p
3861 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3862 } else {
3863 $toc .= $sk->tocLineEnd();
3864 }
3865 }
3866 }
3867 else {
3868 # No change in level, end TOC line
3869 if( $toclevel<$wgMaxTocLevel ) {
3870 $toc .= $sk->tocLineEnd();
3871 }
3872 }
3873
3874 $levelCount[$toclevel] = $level;
3875
3876 # count number of headlines for each level
3877 @$sublevelCount[$toclevel]++;
3878 $dot = 0;
3879 for( $i = 1; $i <= $toclevel; $i++ ) {
3880 if( !empty( $sublevelCount[$i] ) ) {
3881 if( $dot ) {
3882 $numbering .= '.';
3883 }
3884 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3885 $dot = 1;
3886 }
3887 }
3888 }
3889
3890 # The safe header is a version of the header text safe to use for links
3891 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3892 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3893
3894 # Remove link placeholders by the link text.
3895 # <!--LINK number-->
3896 # turns into
3897 # link text with suffix
3898 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3899 "\$this->mLinkHolders['texts'][\$1]",
3900 $safeHeadline );
3901 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3902 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3903 $safeHeadline );
3904
3905 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3906 $tocline = preg_replace(
3907 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3908 array( '', '<$1>'),
3909 $safeHeadline
3910 );
3911 $tocline = trim( $tocline );
3912
3913 # For the anchor, strip out HTML-y stuff period
3914 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3915 $safeHeadline = trim( $safeHeadline );
3916
3917 # Save headline for section edit hint before it's escaped
3918 $headlineHint = $safeHeadline;
3919 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
3920 $refers[$headlineCount] = $safeHeadline;
3921
3922 # count how many in assoc. array so we can track dupes in anchors
3923 isset( $refers[$safeHeadline] ) ? $refers[$safeHeadline]++ : $refers[$safeHeadline] = 1;
3924 $refcount[$headlineCount] = $refers[$safeHeadline];
3925
3926 # Don't number the heading if it is the only one (looks silly)
3927 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3928 # the two are different if the line contains a link
3929 $headline=$numbering . ' ' . $headline;
3930 }
3931
3932 # Create the anchor for linking from the TOC to the section
3933 $anchor = $safeHeadline;
3934 if($refcount[$headlineCount] > 1 ) {
3935 $anchor .= '_' . $refcount[$headlineCount];
3936 }
3937 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3938 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3939 }
3940 # give headline the correct <h#> tag
3941 if( $showEditLink && $sectionIndex !== false ) {
3942 if( $isTemplate )
3943 $editlink = $sk->editSectionLinkForOther($titleText, $sectionIndex);
3944 else
3945 $editlink = $sk->editSectionLink($this->mTitle, $sectionIndex, $headlineHint);
3946 } else {
3947 $editlink = '';
3948 }
3949 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3950
3951 $headlineCount++;
3952 }
3953
3954 # Never ever show TOC if no headers
3955 if( $numVisible < 1 ) {
3956 $enoughToc = false;
3957 }
3958
3959 if( $enoughToc ) {
3960 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3961 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3962 }
3963 $toc = $sk->tocList( $toc );
3964 }
3965
3966 # split up and insert constructed headlines
3967
3968 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3969 $i = 0;
3970
3971 foreach( $blocks as $block ) {
3972 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3973 # This is the [edit] link that appears for the top block of text when
3974 # section editing is enabled
3975
3976 # Disabled because it broke block formatting
3977 # For example, a bullet point in the top line
3978 # $full .= $sk->editSectionLink(0);
3979 }
3980 $full .= $block;
3981 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3982 # Top anchor now in skin
3983 $full = $full.$toc;
3984 }
3985
3986 if( !empty( $head[$i] ) ) {
3987 $full .= $head[$i];
3988 }
3989 $i++;
3990 }
3991 if( $this->mForceTocPosition ) {
3992 return str_replace( '<!--MWTOC-->', $toc, $full );
3993 } else {
3994 return $full;
3995 }
3996 }
3997
3998 /**
3999 * Transform wiki markup when saving a page by doing \r\n -> \n
4000 * conversion, substitting signatures, {{subst:}} templates, etc.
4001 *
4002 * @param string $text the text to transform
4003 * @param Title &$title the Title object for the current article
4004 * @param User &$user the User object describing the current user
4005 * @param ParserOptions $options parsing options
4006 * @param bool $clearState whether to clear the parser state first
4007 * @return string the altered wiki markup
4008 * @public
4009 */
4010 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
4011 $this->mOptions = $options;
4012 $this->mTitle =& $title;
4013 $this->setOutputType( OT_WIKI );
4014
4015 if ( $clearState ) {
4016 $this->clearState();
4017 }
4018
4019 $pairs = array(
4020 "\r\n" => "\n",
4021 );
4022 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4023 $text = $this->pstPass2( $text, $user );
4024 $text = $this->mStripState->unstripBoth( $text );
4025 return $text;
4026 }
4027
4028 /**
4029 * Pre-save transform helper function
4030 * @private
4031 */
4032 function pstPass2( $text, $user ) {
4033 global $wgContLang, $wgLocaltimezone;
4034
4035 /* Note: This is the timestamp saved as hardcoded wikitext to
4036 * the database, we use $wgContLang here in order to give
4037 * everyone the same signature and use the default one rather
4038 * than the one selected in each user's preferences.
4039 */
4040 if ( isset( $wgLocaltimezone ) ) {
4041 $oldtz = getenv( 'TZ' );
4042 putenv( 'TZ='.$wgLocaltimezone );
4043 }
4044 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
4045 ' (' . date( 'T' ) . ')';
4046 if ( isset( $wgLocaltimezone ) ) {
4047 putenv( 'TZ='.$oldtz );
4048 }
4049
4050 # Variable replacement
4051 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4052 $text = $this->replaceVariables( $text );
4053
4054 # Strip out <nowiki> etc. added via replaceVariables
4055 #$text = $this->strip( $text, $this->mStripState, false, array( 'gallery' ) );
4056
4057 # Signatures
4058 $sigText = $this->getUserSig( $user );
4059 $text = strtr( $text, array(
4060 '~~~~~' => $d,
4061 '~~~~' => "$sigText $d",
4062 '~~~' => $sigText
4063 ) );
4064
4065 # Context links: [[|name]] and [[name (context)|]]
4066 #
4067 global $wgLegalTitleChars;
4068 $tc = "[$wgLegalTitleChars]";
4069 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
4070
4071 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4072 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4073 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4074
4075 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4076 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4077 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4078
4079 $t = $this->mTitle->getText();
4080 $m = array();
4081 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4082 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4083 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
4084 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4085 } else {
4086 # if there's no context, don't bother duplicating the title
4087 $text = preg_replace( $p2, '[[\\1]]', $text );
4088 }
4089
4090 # Trim trailing whitespace
4091 $text = rtrim( $text );
4092
4093 return $text;
4094 }
4095
4096 /**
4097 * Fetch the user's signature text, if any, and normalize to
4098 * validated, ready-to-insert wikitext.
4099 *
4100 * @param User $user
4101 * @return string
4102 * @private
4103 */
4104 function getUserSig( &$user ) {
4105 global $wgMaxSigChars;
4106
4107 $username = $user->getName();
4108 $nickname = $user->getOption( 'nickname' );
4109 $nickname = $nickname === '' ? $username : $nickname;
4110
4111 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4112 $nickname = $username;
4113 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4114 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
4115 # Sig. might contain markup; validate this
4116 if( $this->validateSig( $nickname ) !== false ) {
4117 # Validated; clean up (if needed) and return it
4118 return $this->cleanSig( $nickname, true );
4119 } else {
4120 # Failed to validate; fall back to the default
4121 $nickname = $username;
4122 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
4123 }
4124 }
4125
4126 // Make sure nickname doesnt get a sig in a sig
4127 $nickname = $this->cleanSigInSig( $nickname );
4128
4129 # If we're still here, make it a link to the user page
4130 $userText = wfEscapeWikiText( $username );
4131 $nickText = wfEscapeWikiText( $nickname );
4132 if ( $user->isAnon() ) {
4133 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4134 } else {
4135 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4136 }
4137 }
4138
4139 /**
4140 * Check that the user's signature contains no bad XML
4141 *
4142 * @param string $text
4143 * @return mixed An expanded string, or false if invalid.
4144 */
4145 function validateSig( $text ) {
4146 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
4147 }
4148
4149 /**
4150 * Clean up signature text
4151 *
4152 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4153 * 2) Substitute all transclusions
4154 *
4155 * @param string $text
4156 * @param $parsing Whether we're cleaning (preferences save) or parsing
4157 * @return string Signature text
4158 */
4159 function cleanSig( $text, $parsing = false ) {
4160 if ( !$parsing ) {
4161 global $wgTitle;
4162 $this->startExternalParse( $wgTitle, new ParserOptions(), OT_MSG );
4163 }
4164
4165 # FIXME: regex doesn't respect extension tags or nowiki
4166 # => Move this logic to braceSubstitution()
4167 $substWord = MagicWord::get( 'subst' );
4168 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4169 $substText = '{{' . $substWord->getSynonym( 0 );
4170
4171 $text = preg_replace( $substRegex, $substText, $text );
4172 $text = $this->cleanSigInSig( $text );
4173 $dom = $this->preprocessToDom( $text );
4174 $frame = new PPFrame( $this );
4175 $text = $frame->expand( $dom->documentElement );
4176
4177 if ( !$parsing ) {
4178 $text = $this->mStripState->unstripBoth( $text );
4179 }
4180
4181 return $text;
4182 }
4183
4184 /**
4185 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4186 * @param string $text
4187 * @return string Signature text with /~{3,5}/ removed
4188 */
4189 function cleanSigInSig( $text ) {
4190 $text = preg_replace( '/~{3,5}/', '', $text );
4191 return $text;
4192 }
4193
4194 /**
4195 * Set up some variables which are usually set up in parse()
4196 * so that an external function can call some class members with confidence
4197 * @public
4198 */
4199 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4200 $this->mTitle =& $title;
4201 $this->mOptions = $options;
4202 $this->setOutputType( $outputType );
4203 if ( $clearState ) {
4204 $this->clearState();
4205 }
4206 }
4207
4208 /**
4209 * Transform a MediaWiki message by replacing magic variables.
4210 *
4211 * For some unknown reason, it also expands templates, but only to the
4212 * first recursion level. This is wrong and broken, probably introduced
4213 * accidentally during refactoring, but probably relied upon by thousands
4214 * of users.
4215 *
4216 * @param string $text the text to transform
4217 * @param ParserOptions $options options
4218 * @return string the text with variables substituted
4219 * @public
4220 */
4221 function transformMsg( $text, $options ) {
4222 global $wgTitle;
4223 static $executing = false;
4224
4225 $fname = "Parser::transformMsg";
4226
4227 # Guard against infinite recursion
4228 if ( $executing ) {
4229 return $text;
4230 }
4231 $executing = true;
4232
4233 wfProfileIn($fname);
4234
4235 if ( $wgTitle && !( $wgTitle instanceof FakeTitle ) ) {
4236 $this->mTitle = $wgTitle;
4237 } else {
4238 $this->mTitle = Title::newFromText('msg');
4239 }
4240 $this->mOptions = $options;
4241 $this->setOutputType( OT_MSG );
4242 $this->clearState();
4243 $text = $this->replaceVariables( $text );
4244 $text = $this->mStripState->unstripBoth( $text );
4245
4246 $executing = false;
4247 wfProfileOut($fname);
4248 return $text;
4249 }
4250
4251 /**
4252 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4253 * The callback should have the following form:
4254 * function myParserHook( $text, $params, &$parser ) { ... }
4255 *
4256 * Transform and return $text. Use $parser for any required context, e.g. use
4257 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4258 *
4259 * @public
4260 *
4261 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4262 * @param mixed $callback The callback function (and object) to use for the tag
4263 *
4264 * @return The old value of the mTagHooks array associated with the hook
4265 */
4266 function setHook( $tag, $callback ) {
4267 $tag = strtolower( $tag );
4268 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4269 $this->mTagHooks[$tag] = $callback;
4270 $this->mStripList[] = $tag;
4271
4272 return $oldVal;
4273 }
4274
4275 function setTransparentTagHook( $tag, $callback ) {
4276 $tag = strtolower( $tag );
4277 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4278 $this->mTransparentTagHooks[$tag] = $callback;
4279
4280 return $oldVal;
4281 }
4282
4283 /**
4284 * Create a function, e.g. {{sum:1|2|3}}
4285 * The callback function should have the form:
4286 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4287 *
4288 * The callback may either return the text result of the function, or an array with the text
4289 * in element 0, and a number of flags in the other elements. The names of the flags are
4290 * specified in the keys. Valid flags are:
4291 * found The text returned is valid, stop processing the template. This
4292 * is on by default.
4293 * nowiki Wiki markup in the return value should be escaped
4294 * noparse Unsafe HTML tags should not be stripped, etc.
4295 * noargs Don't replace triple-brace arguments in the return value
4296 * isHTML The returned text is HTML, armour it against wikitext transformation
4297 *
4298 * @public
4299 *
4300 * @param string $id The magic word ID
4301 * @param mixed $callback The callback function (and object) to use
4302 * @param integer $flags a combination of the following flags:
4303 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4304 *
4305 * @return The old callback function for this name, if any
4306 */
4307 function setFunctionHook( $id, $callback, $flags = 0 ) {
4308 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4309 $this->mFunctionHooks[$id] = array( $callback, $flags );
4310
4311 # Add to function cache
4312 $mw = MagicWord::get( $id );
4313 if( !$mw )
4314 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4315
4316 $synonyms = $mw->getSynonyms();
4317 $sensitive = intval( $mw->isCaseSensitive() );
4318
4319 foreach ( $synonyms as $syn ) {
4320 # Case
4321 if ( !$sensitive ) {
4322 $syn = strtolower( $syn );
4323 }
4324 # Add leading hash
4325 if ( !( $flags & SFH_NO_HASH ) ) {
4326 $syn = '#' . $syn;
4327 }
4328 # Remove trailing colon
4329 if ( substr( $syn, -1, 1 ) == ':' ) {
4330 $syn = substr( $syn, 0, -1 );
4331 }
4332 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4333 }
4334 return $oldVal;
4335 }
4336
4337 /**
4338 * Get all registered function hook identifiers
4339 *
4340 * @return array
4341 */
4342 function getFunctionHooks() {
4343 return array_keys( $this->mFunctionHooks );
4344 }
4345
4346 /**
4347 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4348 * Placeholders created in Skin::makeLinkObj()
4349 * Returns an array of link CSS classes, indexed by PDBK.
4350 * $options is a bit field, RLH_FOR_UPDATE to select for update
4351 */
4352 function replaceLinkHolders( &$text, $options = 0 ) {
4353 global $wgUser;
4354 global $wgContLang;
4355
4356 $fname = 'Parser::replaceLinkHolders';
4357 wfProfileIn( $fname );
4358
4359 $pdbks = array();
4360 $colours = array();
4361 $linkcolour_ids = array();
4362 $sk = $this->mOptions->getSkin();
4363 $linkCache =& LinkCache::singleton();
4364
4365 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
4366 wfProfileIn( $fname.'-check' );
4367 $dbr = wfGetDB( DB_SLAVE );
4368 $page = $dbr->tableName( 'page' );
4369 $threshold = $wgUser->getOption('stubthreshold');
4370
4371 # Sort by namespace
4372 asort( $this->mLinkHolders['namespaces'] );
4373
4374 # Generate query
4375 $query = false;
4376 $current = null;
4377 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4378 # Make title object
4379 $title = $this->mLinkHolders['titles'][$key];
4380
4381 # Skip invalid entries.
4382 # Result will be ugly, but prevents crash.
4383 if ( is_null( $title ) ) {
4384 continue;
4385 }
4386 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4387
4388 # Check if it's a static known link, e.g. interwiki
4389 if ( $title->isAlwaysKnown() ) {
4390 $colours[$pdbk] = '';
4391 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4392 $colours[$pdbk] = '';
4393 $this->mOutput->addLink( $title, $id );
4394 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4395 $colours[$pdbk] = 'new';
4396 } elseif ( $title->getNamespace() == NS_SPECIAL && !SpecialPage::exists( $pdbk ) ) {
4397 $colours[$pdbk] = 'new';
4398 } else {
4399 # Not in the link cache, add it to the query
4400 if ( !isset( $current ) ) {
4401 $current = $ns;
4402 $query = "SELECT page_id, page_namespace, page_title";
4403 if ( $threshold > 0 ) {
4404 $query .= ', page_len, page_is_redirect';
4405 }
4406 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4407 } elseif ( $current != $ns ) {
4408 $current = $ns;
4409 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4410 } else {
4411 $query .= ', ';
4412 }
4413
4414 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
4415 }
4416 }
4417 if ( $query ) {
4418 $query .= '))';
4419 if ( $options & RLH_FOR_UPDATE ) {
4420 $query .= ' FOR UPDATE';
4421 }
4422
4423 $res = $dbr->query( $query, $fname );
4424
4425 # Fetch data and form into an associative array
4426 # non-existent = broken
4427 while ( $s = $dbr->fetchObject($res) ) {
4428 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
4429 $pdbk = $title->getPrefixedDBkey();
4430 $linkCache->addGoodLinkObj( $s->page_id, $title );
4431 $this->mOutput->addLink( $title, $s->page_id );
4432 $colours[$pdbk] = $sk->getLinkColour( $s, $threshold );
4433 //add id to the extension todolist
4434 $linkcolour_ids[$s->page_id] = $pdbk;
4435 }
4436 //pass an array of page_ids to an extension
4437 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4438 }
4439 wfProfileOut( $fname.'-check' );
4440
4441 # Do a second query for different language variants of links and categories
4442 if($wgContLang->hasVariants()){
4443 $linkBatch = new LinkBatch();
4444 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4445 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4446 $varCategories = array(); // category replacements oldDBkey => newDBkey
4447
4448 $categories = $this->mOutput->getCategoryLinks();
4449
4450 // Add variants of links to link batch
4451 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4452 $title = $this->mLinkHolders['titles'][$key];
4453 if ( is_null( $title ) )
4454 continue;
4455
4456 $pdbk = $title->getPrefixedDBkey();
4457 $titleText = $title->getText();
4458
4459 // generate all variants of the link title text
4460 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4461
4462 // if link was not found (in first query), add all variants to query
4463 if ( !isset($colours[$pdbk]) ){
4464 foreach($allTextVariants as $textVariant){
4465 if($textVariant != $titleText){
4466 $variantTitle = Title::makeTitle( $ns, $textVariant );
4467 if(is_null($variantTitle)) continue;
4468 $linkBatch->addObj( $variantTitle );
4469 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4470 }
4471 }
4472 }
4473 }
4474
4475 // process categories, check if a category exists in some variant
4476 foreach( $categories as $category ){
4477 $variants = $wgContLang->convertLinkToAllVariants($category);
4478 foreach($variants as $variant){
4479 if($variant != $category){
4480 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
4481 if(is_null($variantTitle)) continue;
4482 $linkBatch->addObj( $variantTitle );
4483 $categoryMap[$variant] = $category;
4484 }
4485 }
4486 }
4487
4488
4489 if(!$linkBatch->isEmpty()){
4490 // construct query
4491 $titleClause = $linkBatch->constructSet('page', $dbr);
4492
4493 $variantQuery = "SELECT page_id, page_namespace, page_title";
4494 if ( $threshold > 0 ) {
4495 $variantQuery .= ', page_len, page_is_redirect';
4496 }
4497
4498 $variantQuery .= " FROM $page WHERE $titleClause";
4499 if ( $options & RLH_FOR_UPDATE ) {
4500 $variantQuery .= ' FOR UPDATE';
4501 }
4502
4503 $varRes = $dbr->query( $variantQuery, $fname );
4504
4505 // for each found variants, figure out link holders and replace
4506 while ( $s = $dbr->fetchObject($varRes) ) {
4507
4508 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
4509 $varPdbk = $variantTitle->getPrefixedDBkey();
4510 $vardbk = $variantTitle->getDBkey();
4511
4512 $holderKeys = array();
4513 if(isset($variantMap[$varPdbk])){
4514 $holderKeys = $variantMap[$varPdbk];
4515 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle );
4516 $this->mOutput->addLink( $variantTitle, $s->page_id );
4517 }
4518
4519 // loop over link holders
4520 foreach($holderKeys as $key){
4521 $title = $this->mLinkHolders['titles'][$key];
4522 if ( is_null( $title ) ) continue;
4523
4524 $pdbk = $title->getPrefixedDBkey();
4525
4526 if(!isset($colours[$pdbk])){
4527 // found link in some of the variants, replace the link holder data
4528 $this->mLinkHolders['titles'][$key] = $variantTitle;
4529 $this->mLinkHolders['dbkeys'][$key] = $variantTitle->getDBkey();
4530
4531 // set pdbk and colour
4532 $pdbks[$key] = $varPdbk;
4533 $colours[$varPdbk] = $sk->getLinkColour( $s, $threshold );
4534 $linkcolour_ids[$s->page_id] = $pdbk;
4535 }
4536 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4537 }
4538
4539 // check if the object is a variant of a category
4540 if(isset($categoryMap[$vardbk])){
4541 $oldkey = $categoryMap[$vardbk];
4542 if($oldkey != $vardbk)
4543 $varCategories[$oldkey]=$vardbk;
4544 }
4545 }
4546
4547 // rebuild the categories in original order (if there are replacements)
4548 if(count($varCategories)>0){
4549 $newCats = array();
4550 $originalCats = $this->mOutput->getCategories();
4551 foreach($originalCats as $cat => $sortkey){
4552 // make the replacement
4553 if( array_key_exists($cat,$varCategories) )
4554 $newCats[$varCategories[$cat]] = $sortkey;
4555 else $newCats[$cat] = $sortkey;
4556 }
4557 $this->mOutput->setCategoryLinks($newCats);
4558 }
4559 }
4560 }
4561
4562 # Construct search and replace arrays
4563 wfProfileIn( $fname.'-construct' );
4564 $replacePairs = array();
4565 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4566 $pdbk = $pdbks[$key];
4567 $searchkey = "<!--LINK $key-->";
4568 $title = $this->mLinkHolders['titles'][$key];
4569 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] == 'new' ) {
4570 $linkCache->addBadLinkObj( $title );
4571 $colours[$pdbk] = 'new';
4572 $this->mOutput->addLink( $title, 0 );
4573 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4574 $this->mLinkHolders['texts'][$key],
4575 $this->mLinkHolders['queries'][$key] );
4576 } else {
4577 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4578 $this->mLinkHolders['texts'][$key],
4579 $this->mLinkHolders['queries'][$key] );
4580 }
4581 }
4582 $replacer = new HashtableReplacer( $replacePairs, 1 );
4583 wfProfileOut( $fname.'-construct' );
4584
4585 # Do the thing
4586 wfProfileIn( $fname.'-replace' );
4587 $text = preg_replace_callback(
4588 '/(<!--LINK .*?-->)/',
4589 $replacer->cb(),
4590 $text);
4591
4592 wfProfileOut( $fname.'-replace' );
4593 }
4594
4595 # Now process interwiki link holders
4596 # This is quite a bit simpler than internal links
4597 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4598 wfProfileIn( $fname.'-interwiki' );
4599 # Make interwiki link HTML
4600 $replacePairs = array();
4601 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4602 $title = $this->mInterwikiLinkHolders['titles'][$key];
4603 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4604 }
4605 $replacer = new HashtableReplacer( $replacePairs, 1 );
4606
4607 $text = preg_replace_callback(
4608 '/<!--IWLINK (.*?)-->/',
4609 $replacer->cb(),
4610 $text );
4611 wfProfileOut( $fname.'-interwiki' );
4612 }
4613
4614 wfProfileOut( $fname );
4615 return $colours;
4616 }
4617
4618 /**
4619 * Replace <!--LINK--> link placeholders with plain text of links
4620 * (not HTML-formatted).
4621 * @param string $text
4622 * @return string
4623 */
4624 function replaceLinkHoldersText( $text ) {
4625 $fname = 'Parser::replaceLinkHoldersText';
4626 wfProfileIn( $fname );
4627
4628 $text = preg_replace_callback(
4629 '/<!--(LINK|IWLINK) (.*?)-->/',
4630 array( &$this, 'replaceLinkHoldersTextCallback' ),
4631 $text );
4632
4633 wfProfileOut( $fname );
4634 return $text;
4635 }
4636
4637 /**
4638 * @param array $matches
4639 * @return string
4640 * @private
4641 */
4642 function replaceLinkHoldersTextCallback( $matches ) {
4643 $type = $matches[1];
4644 $key = $matches[2];
4645 if( $type == 'LINK' ) {
4646 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4647 return $this->mLinkHolders['texts'][$key];
4648 }
4649 } elseif( $type == 'IWLINK' ) {
4650 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4651 return $this->mInterwikiLinkHolders['texts'][$key];
4652 }
4653 }
4654 return $matches[0];
4655 }
4656
4657 /**
4658 * Tag hook handler for 'pre'.
4659 */
4660 function renderPreTag( $text, $attribs ) {
4661 // Backwards-compatibility hack
4662 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4663
4664 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4665 return wfOpenElement( 'pre', $attribs ) .
4666 Xml::escapeTagsOnly( $content ) .
4667 '</pre>';
4668 }
4669
4670 /**
4671 * Renders an image gallery from a text with one line per image.
4672 * text labels may be given by using |-style alternative text. E.g.
4673 * Image:one.jpg|The number "1"
4674 * Image:tree.jpg|A tree
4675 * given as text will return the HTML of a gallery with two images,
4676 * labeled 'The number "1"' and
4677 * 'A tree'.
4678 */
4679 function renderImageGallery( $text, $params ) {
4680 $ig = new ImageGallery();
4681 $ig->setContextTitle( $this->mTitle );
4682 $ig->setShowBytes( false );
4683 $ig->setShowFilename( false );
4684 $ig->setParser( $this );
4685 $ig->setHideBadImages();
4686 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4687 $ig->useSkin( $this->mOptions->getSkin() );
4688 $ig->mRevisionId = $this->mRevisionId;
4689
4690 if( isset( $params['caption'] ) ) {
4691 $caption = $params['caption'];
4692 $caption = htmlspecialchars( $caption );
4693 $caption = $this->replaceInternalLinks( $caption );
4694 $ig->setCaptionHtml( $caption );
4695 }
4696 if( isset( $params['perrow'] ) ) {
4697 $ig->setPerRow( $params['perrow'] );
4698 }
4699 if( isset( $params['widths'] ) ) {
4700 $ig->setWidths( $params['widths'] );
4701 }
4702 if( isset( $params['heights'] ) ) {
4703 $ig->setHeights( $params['heights'] );
4704 }
4705
4706 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4707
4708 $lines = explode( "\n", $text );
4709 foreach ( $lines as $line ) {
4710 # match lines like these:
4711 # Image:someimage.jpg|This is some image
4712 $matches = array();
4713 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4714 # Skip empty lines
4715 if ( count( $matches ) == 0 ) {
4716 continue;
4717 }
4718 $tp = Title::newFromText( $matches[1] );
4719 $nt =& $tp;
4720 if( is_null( $nt ) ) {
4721 # Bogus title. Ignore these so we don't bomb out later.
4722 continue;
4723 }
4724 if ( isset( $matches[3] ) ) {
4725 $label = $matches[3];
4726 } else {
4727 $label = '';
4728 }
4729
4730 $pout = $this->parse( $label,
4731 $this->mTitle,
4732 $this->mOptions,
4733 false, // Strip whitespace...?
4734 false // Don't clear state!
4735 );
4736 $html = $pout->getText();
4737
4738 $ig->add( $nt, $html );
4739
4740 # Only add real images (bug #5586)
4741 if ( $nt->getNamespace() == NS_IMAGE ) {
4742 $this->mOutput->addImage( $nt->getDBkey() );
4743 }
4744 }
4745 return $ig->toHTML();
4746 }
4747
4748 function getImageParams( $handler ) {
4749 if ( $handler ) {
4750 $handlerClass = get_class( $handler );
4751 } else {
4752 $handlerClass = '';
4753 }
4754 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4755 // Initialise static lists
4756 static $internalParamNames = array(
4757 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4758 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4759 'bottom', 'text-bottom' ),
4760 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4761 'upright', 'border' ),
4762 );
4763 static $internalParamMap;
4764 if ( !$internalParamMap ) {
4765 $internalParamMap = array();
4766 foreach ( $internalParamNames as $type => $names ) {
4767 foreach ( $names as $name ) {
4768 $magicName = str_replace( '-', '_', "img_$name" );
4769 $internalParamMap[$magicName] = array( $type, $name );
4770 }
4771 }
4772 }
4773
4774 // Add handler params
4775 $paramMap = $internalParamMap;
4776 if ( $handler ) {
4777 $handlerParamMap = $handler->getParamMap();
4778 foreach ( $handlerParamMap as $magic => $paramName ) {
4779 $paramMap[$magic] = array( 'handler', $paramName );
4780 }
4781 }
4782 $this->mImageParams[$handlerClass] = $paramMap;
4783 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4784 }
4785 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4786 }
4787
4788 /**
4789 * Parse image options text and use it to make an image
4790 */
4791 function makeImage( $title, $options ) {
4792 # @TODO: let the MediaHandler specify its transform parameters
4793 #
4794 # Check if the options text is of the form "options|alt text"
4795 # Options are:
4796 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4797 # * left no resizing, just left align. label is used for alt= only
4798 # * right same, but right aligned
4799 # * none same, but not aligned
4800 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4801 # * center center the image
4802 # * framed Keep original image size, no magnify-button.
4803 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4804 # * upright reduce width for upright images, rounded to full __0 px
4805 # * border draw a 1px border around the image
4806 # vertical-align values (no % or length right now):
4807 # * baseline
4808 # * sub
4809 # * super
4810 # * top
4811 # * text-top
4812 # * middle
4813 # * bottom
4814 # * text-bottom
4815
4816 $parts = array_map( 'trim', explode( '|', $options) );
4817 $sk = $this->mOptions->getSkin();
4818
4819 # Give extensions a chance to select the file revision for us
4820 $skip = $time = false;
4821 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4822
4823 if ( $skip ) {
4824 return $sk->makeLinkObj( $title );
4825 }
4826
4827 # Get parameter map
4828 $file = wfFindFile( $title, $time );
4829 $handler = $file ? $file->getHandler() : false;
4830
4831 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4832
4833 # Process the input parameters
4834 $caption = '';
4835 $params = array( 'frame' => array(), 'handler' => array(),
4836 'horizAlign' => array(), 'vertAlign' => array() );
4837 foreach( $parts as $part ) {
4838 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4839 if ( isset( $paramMap[$magicName] ) ) {
4840 list( $type, $paramName ) = $paramMap[$magicName];
4841 $params[$type][$paramName] = $value;
4842
4843 // Special case; width and height come in one variable together
4844 if( $type == 'handler' && $paramName == 'width' ) {
4845 $m = array();
4846 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4847 $params[$type]['width'] = intval( $m[1] );
4848 $params[$type]['height'] = intval( $m[2] );
4849 } else {
4850 $params[$type]['width'] = intval( $value );
4851 }
4852 }
4853 } else {
4854 $caption = $part;
4855 }
4856 }
4857
4858 # Process alignment parameters
4859 if ( $params['horizAlign'] ) {
4860 $params['frame']['align'] = key( $params['horizAlign'] );
4861 }
4862 if ( $params['vertAlign'] ) {
4863 $params['frame']['valign'] = key( $params['vertAlign'] );
4864 }
4865
4866 # Validate the handler parameters
4867 if ( $handler ) {
4868 foreach ( $params['handler'] as $name => $value ) {
4869 if ( !$handler->validateParam( $name, $value ) ) {
4870 unset( $params['handler'][$name] );
4871 }
4872 }
4873 }
4874
4875 # Strip bad stuff out of the alt text
4876 $alt = $this->replaceLinkHoldersText( $caption );
4877
4878 # make sure there are no placeholders in thumbnail attributes
4879 # that are later expanded to html- so expand them now and
4880 # remove the tags
4881 $alt = $this->mStripState->unstripBoth( $alt );
4882 $alt = Sanitizer::stripAllTags( $alt );
4883
4884 $params['frame']['alt'] = $alt;
4885 $params['frame']['caption'] = $caption;
4886
4887 # Linker does the rest
4888 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4889
4890 # Give the handler a chance to modify the parser object
4891 if ( $handler ) {
4892 $handler->parserTransformHook( $this, $file );
4893 }
4894
4895 return $ret;
4896 }
4897
4898 /**
4899 * Set a flag in the output object indicating that the content is dynamic and
4900 * shouldn't be cached.
4901 */
4902 function disableCache() {
4903 wfDebug( "Parser output marked as uncacheable.\n" );
4904 $this->mOutput->mCacheTime = -1;
4905 }
4906
4907 /**#@+
4908 * Callback from the Sanitizer for expanding items found in HTML attribute
4909 * values, so they can be safely tested and escaped.
4910 * @param string $text
4911 * @param PPFrame $frame
4912 * @return string
4913 * @private
4914 */
4915 function attributeStripCallback( &$text, $frame = false ) {
4916 $text = $this->replaceVariables( $text, $frame );
4917 $text = $this->mStripState->unstripBoth( $text );
4918 return $text;
4919 }
4920
4921 /**#@-*/
4922
4923 /**#@+
4924 * Accessor/mutator
4925 */
4926 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4927 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4928 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4929 /**#@-*/
4930
4931 /**#@+
4932 * Accessor
4933 */
4934 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4935 /**#@-*/
4936
4937
4938 /**
4939 * Break wikitext input into sections, and either pull or replace
4940 * some particular section's text.
4941 *
4942 * External callers should use the getSection and replaceSection methods.
4943 *
4944 * @param $text Page wikitext
4945 * @param $section Numbered section. 0 pulls the text before the first
4946 * heading; other numbers will pull the given section
4947 * along with its lower-level subsections. If the section is
4948 * not found, $mode=get will return $newtext, and
4949 * $mode=replace will return $text.
4950 * @param $mode One of "get" or "replace"
4951 * @param $newText Replacement text for section data.
4952 * @return string for "get", the extracted section text.
4953 * for "replace", the whole page with the section replaced.
4954 */
4955 private function extractSections( $text, $section, $mode, $newText='' ) {
4956 $this->clearState();
4957 $this->mOptions = new ParserOptions;
4958 $this->setOutputType( OT_WIKI );
4959 $curIndex = 0;
4960 $outText = '';
4961 $frame = new PPFrame( $this );
4962
4963 // Preprocess the text
4964 $dom = $this->preprocessToDom( $text );
4965 $root = $dom->documentElement;
4966
4967 // <h> nodes indicate section breaks
4968 // They can only occur at the top level, so we can find them by iterating the root's children
4969 $node = $root->firstChild;
4970
4971 // Find the target section
4972 if ( $section == 0 ) {
4973 // Section zero doesn't nest, level=big
4974 $targetLevel = 1000;
4975 } else {
4976 while ( $node ) {
4977 if ( $node->nodeName == 'h' ) {
4978 if ( $curIndex + 1 == $section ) {
4979 break;
4980 }
4981 $curIndex++;
4982 }
4983 if ( $mode == 'replace' ) {
4984 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4985 }
4986 $node = $node->nextSibling;
4987 }
4988 if ( $node ) {
4989 $targetLevel = $node->getAttribute( 'level' );
4990 }
4991 }
4992
4993 if ( !$node ) {
4994 // Not found
4995 if ( $mode == 'get' ) {
4996 return $newText;
4997 } else {
4998 return $text;
4999 }
5000 }
5001
5002 // Find the end of the section, including nested sections
5003 do {
5004 if ( $node->nodeName == 'h' ) {
5005 $curIndex++;
5006 $curLevel = $node->getAttribute( 'level' );
5007 if ( $curIndex != $section && $curLevel <= $targetLevel ) {
5008 break;
5009 }
5010 }
5011 if ( $mode == 'get' ) {
5012 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5013 }
5014 $node = $node->nextSibling;
5015 } while ( $node );
5016
5017 // Write out the remainder (in replace mode only)
5018 if ( $mode == 'replace' ) {
5019 // Output the replacement text
5020 // Add two newlines on -- trailing whitespace in $newText is conventionally
5021 // stripped by the editor, so we need both newlines to restore the paragraph gap
5022 $outText .= $newText . "\n\n";
5023 while ( $node ) {
5024 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5025 $node = $node->nextSibling;
5026 }
5027 }
5028
5029 if ( is_string( $outText ) ) {
5030 // Re-insert stripped tags
5031 $outText = trim( $this->mStripState->unstripBoth( $outText ) );
5032 }
5033
5034 return $outText;
5035 }
5036
5037 /**
5038 * This function returns the text of a section, specified by a number ($section).
5039 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5040 * the first section before any such heading (section 0).
5041 *
5042 * If a section contains subsections, these are also returned.
5043 *
5044 * @param $text String: text to look in
5045 * @param $section Integer: section number
5046 * @param $deftext: default to return if section is not found
5047 * @return string text of the requested section
5048 */
5049 public function getSection( $text, $section, $deftext='' ) {
5050 return $this->extractSections( $text, $section, "get", $deftext );
5051 }
5052
5053 public function replaceSection( $oldtext, $section, $text ) {
5054 return $this->extractSections( $oldtext, $section, "replace", $text );
5055 }
5056
5057 /**
5058 * Get the timestamp associated with the current revision, adjusted for
5059 * the default server-local timestamp
5060 */
5061 function getRevisionTimestamp() {
5062 if ( is_null( $this->mRevisionTimestamp ) ) {
5063 wfProfileIn( __METHOD__ );
5064 global $wgContLang;
5065 $dbr = wfGetDB( DB_SLAVE );
5066 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
5067 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
5068
5069 // Normalize timestamp to internal MW format for timezone processing.
5070 // This has the added side-effect of replacing a null value with
5071 // the current time, which gives us more sensible behavior for
5072 // previews.
5073 $timestamp = wfTimestamp( TS_MW, $timestamp );
5074
5075 // The cryptic '' timezone parameter tells to use the site-default
5076 // timezone offset instead of the user settings.
5077 //
5078 // Since this value will be saved into the parser cache, served
5079 // to other users, and potentially even used inside links and such,
5080 // it needs to be consistent for all visitors.
5081 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5082
5083 wfProfileOut( __METHOD__ );
5084 }
5085 return $this->mRevisionTimestamp;
5086 }
5087
5088 /**
5089 * Mutator for $mDefaultSort
5090 *
5091 * @param $sort New value
5092 */
5093 public function setDefaultSort( $sort ) {
5094 $this->mDefaultSort = $sort;
5095 }
5096
5097 /**
5098 * Accessor for $mDefaultSort
5099 * Will use the title/prefixed title if none is set
5100 *
5101 * @return string
5102 */
5103 public function getDefaultSort() {
5104 if( $this->mDefaultSort !== false ) {
5105 return $this->mDefaultSort;
5106 } else {
5107 return $this->mTitle->getNamespace() == NS_CATEGORY
5108 ? $this->mTitle->getText()
5109 : $this->mTitle->getPrefixedText();
5110 }
5111 }
5112
5113 /**
5114 * Try to guess the section anchor name based on a wikitext fragment
5115 * presumably extracted from a heading, for example "Header" from
5116 * "== Header ==".
5117 */
5118 public function guessSectionNameFromWikiText( $text ) {
5119 # Strip out wikitext links(they break the anchor)
5120 $text = $this->stripSectionName( $text );
5121 $headline = Sanitizer::decodeCharReferences( $text );
5122 # strip out HTML
5123 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
5124 $headline = trim( $headline );
5125 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5126 $replacearray = array(
5127 '%3A' => ':',
5128 '%' => '.'
5129 );
5130 return str_replace(
5131 array_keys( $replacearray ),
5132 array_values( $replacearray ),
5133 $sectionanchor );
5134 }
5135
5136 /**
5137 * Strips a text string of wikitext for use in a section anchor
5138 *
5139 * Accepts a text string and then removes all wikitext from the
5140 * string and leaves only the resultant text (i.e. the result of
5141 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5142 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5143 * to create valid section anchors by mimicing the output of the
5144 * parser when headings are parsed.
5145 *
5146 * @param $text string Text string to be stripped of wikitext
5147 * for use in a Section anchor
5148 * @return Filtered text string
5149 */
5150 public function stripSectionName( $text ) {
5151 # Strip internal link markup
5152 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5153 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5154
5155 # Strip external link markup (FIXME: Not Tolerant to blank link text
5156 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5157 # on how many empty links there are on the page - need to figure that out.
5158 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5159
5160 # Parse wikitext quotes (italics & bold)
5161 $text = $this->doQuotes($text);
5162
5163 # Strip HTML tags
5164 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5165 return $text;
5166 }
5167
5168 /**
5169 * strip/replaceVariables/unstrip for preprocessor regression testing
5170 */
5171 function srvus( $text ) {
5172 $text = $this->replaceVariables( $text );
5173 $text = $this->mStripState->unstripBoth( $text );
5174 return $text;
5175 }
5176 }
5177
5178 /**
5179 * @todo document, briefly.
5180 * @addtogroup Parser
5181 */
5182 class OnlyIncludeReplacer {
5183 var $output = '';
5184
5185 function replace( $matches ) {
5186 if ( substr( $matches[1], -1 ) == "\n" ) {
5187 $this->output .= substr( $matches[1], 0, -1 );
5188 } else {
5189 $this->output .= $matches[1];
5190 }
5191 }
5192 }
5193
5194 /**
5195 * @todo document, briefly.
5196 * @addtogroup Parser
5197 */
5198 class StripState {
5199 var $general, $nowiki;
5200
5201 function __construct() {
5202 $this->general = new ReplacementArray;
5203 $this->nowiki = new ReplacementArray;
5204 }
5205
5206 function unstripGeneral( $text ) {
5207 wfProfileIn( __METHOD__ );
5208 do {
5209 $oldText = $text;
5210 $text = $this->general->replace( $text );
5211 } while ( $text != $oldText );
5212 wfProfileOut( __METHOD__ );
5213 return $text;
5214 }
5215
5216 function unstripNoWiki( $text ) {
5217 wfProfileIn( __METHOD__ );
5218 do {
5219 $oldText = $text;
5220 $text = $this->nowiki->replace( $text );
5221 } while ( $text != $oldText );
5222 wfProfileOut( __METHOD__ );
5223 return $text;
5224 }
5225
5226 function unstripBoth( $text ) {
5227 wfProfileIn( __METHOD__ );
5228 do {
5229 $oldText = $text;
5230 $text = $this->general->replace( $text );
5231 $text = $this->nowiki->replace( $text );
5232 } while ( $text != $oldText );
5233 wfProfileOut( __METHOD__ );
5234 return $text;
5235 }
5236 }
5237
5238 /**
5239 * An expansion frame, used as a context to expand the result of preprocessToDom()
5240 */
5241 class PPFrame {
5242 var $parser, $title;
5243
5244 const NO_ARGS = 1;
5245 const NO_TEMPLATES = 2;
5246 const RECOVER_ORIG = 3;
5247
5248 /**
5249 * Construct a new preprocessor frame.
5250 * @param Parser $parser The parent parser
5251 * @param Title $title The context title, or false if there isn't one
5252 */
5253 function __construct( $parser ) {
5254 $this->parser = $parser;
5255 $this->title = $parser->mTitle;
5256 }
5257
5258 /**
5259 * Create a new child frame
5260 * $args is optionally a DOMNodeList containing the template arguments
5261 */
5262 function newChild( $args = false, $title = false ) {
5263 $assocArgs = array();
5264 if ( $title === false ) {
5265 $title = $this->title;
5266 }
5267 if ( $args !== false ) {
5268 $xpath = false;
5269 foreach ( $args as $arg ) {
5270 if ( !$xpath ) {
5271 $xpath = new DOMXPath( $arg->ownerDocument );
5272 }
5273
5274 $nameNodes = $xpath->query( 'name', $arg );
5275 if ( $nameNodes->item( 0 )->hasAttributes() ) {
5276 // Numbered parameter
5277 $name = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
5278 } else {
5279 // Named parameter
5280 $name = $this->expand( $nameNodes->item( 0 ) );
5281 }
5282
5283 $value = $xpath->query( 'value', $arg );
5284 $assocArgs[$name] = $value->item( 0 );
5285 }
5286 }
5287 return new PPTemplateFrame( $this->parser, $this, $assocArgs, $title );
5288 }
5289
5290 /**
5291 * Expand a DOMNode describing a preprocessed document into plain wikitext,
5292 * using the current context
5293 * @param $root the node
5294 */
5295 function expand( $root, $flags = 0 ) {
5296 if ( is_string( $root ) ) {
5297 return $root;
5298 }
5299
5300 if ( $this->parser->ot['html']
5301 && ++$this->parser->mPPNodeCount > $this->parser->mOptions->mMaxPPNodeCount )
5302 {
5303 return $this->parser->insertStripItem( '<!-- node-count limit exceeded -->' );
5304 }
5305
5306 if ( is_array( $root ) ) {
5307 $s = '';
5308 foreach ( $root as $node ) {
5309 $s .= $this->expand( $node, $flags );
5310 }
5311 } elseif ( $root instanceof DOMNodeList ) {
5312 $s = '';
5313 foreach ( $root as $node ) {
5314 $s .= $this->expand( $node, $flags );
5315 }
5316 } elseif ( $root instanceof DOMNode ) {
5317 if ( $root->nodeType == XML_TEXT_NODE ) {
5318 $s = $root->nodeValue;
5319 } elseif ( $root->nodeName == 'template' ) {
5320 # Double-brace expansion
5321 $xpath = new DOMXPath( $root->ownerDocument );
5322 $titles = $xpath->query( 'title', $root );
5323 $title = $titles->item( 0 );
5324 $parts = $xpath->query( 'part', $root );
5325 if ( $flags & self::NO_TEMPLATES ) {
5326 $s = '{{' . $this->implodeWithFlags( '|', $flags, $title, $parts ) . '}}';
5327 } else {
5328 $lineStart = $root->getAttribute( 'lineStart' );
5329 $params = array(
5330 'title' => $title,
5331 'parts' => $parts,
5332 'lineStart' => $lineStart,
5333 'text' => 'FIXME' );
5334 $s = $this->parser->braceSubstitution( $params, $this );
5335 }
5336 } elseif ( $root->nodeName == 'tplarg' ) {
5337 # Triple-brace expansion
5338 $xpath = new DOMXPath( $root->ownerDocument );
5339 $titles = $xpath->query( 'title', $root );
5340 $title = $titles->item( 0 );
5341 $parts = $xpath->query( 'part', $root );
5342 if ( $flags & self::NO_ARGS || $this->parser->ot['msg'] ) {
5343 $s = '{{{' . $this->implodeWithFlags( '|', $flags, $title, $parts ) . '}}}';
5344 } else {
5345 $params = array( 'title' => $title, 'parts' => $parts, 'text' => 'FIXME' );
5346 $s = $this->parser->argSubstitution( $params, $this );
5347 }
5348 } elseif ( $root->nodeName == 'ext' ) {
5349 # Extension tag
5350 $xpath = new DOMXPath( $root->ownerDocument );
5351 $names = $xpath->query( 'name', $root );
5352 $attrs = $xpath->query( 'attr', $root );
5353 $inners = $xpath->query( 'inner', $root );
5354 $closes = $xpath->query( 'close', $root );
5355 $params = array(
5356 'name' => $names->item( 0 ),
5357 'attr' => $attrs->length > 0 ? $attrs->item( 0 ) : null,
5358 'inner' => $inners->length > 0 ? $inners->item( 0 ) : null,
5359 'close' => $closes->length > 0 ? $closes->item( 0 ) : null,
5360 );
5361 $s = $this->parser->extensionSubstitution( $params, $this );
5362 } elseif ( $root->nodeName == 'h' ) {
5363 # Heading
5364 $s = $this->expand( $root->childNodes, $flags );
5365
5366 if ( $this->parser->ot['html'] ) {
5367 # Insert heading index marker
5368 $headingIndex = $root->getAttribute( 'i' );
5369 $titleText = $this->title->getPrefixedDBkey();
5370 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
5371 $serial = count( $this->parser->mHeadings ) - 1;
5372 $marker = "{$this->parser->mUniqPrefix}-h-$serial-{$this->parser->mMarkerSuffix}";
5373 $count = $root->getAttribute( 'level' );
5374 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
5375 $this->parser->mStripState->general->setPair( $marker, '' );
5376 }
5377 } else {
5378 # Generic recursive expansion
5379 $s = '';
5380 for ( $node = $root->firstChild; $node; $node = $node->nextSibling ) {
5381 if ( $node->nodeType == XML_TEXT_NODE ) {
5382 $s .= $node->nodeValue;
5383 } elseif ( $node->nodeType == XML_ELEMENT_NODE ) {
5384 $s .= $this->expand( $node, $flags );
5385 }
5386 }
5387 }
5388 } else {
5389 throw new MWException( __METHOD__.': Invalid parameter type' );
5390 }
5391 return $s;
5392 }
5393
5394 function implodeWithFlags( $sep, $flags /*, ... */ ) {
5395 $args = array_slice( func_get_args(), 2 );
5396
5397 $first = true;
5398 $s = '';
5399 foreach ( $args as $root ) {
5400 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
5401 $root = array( $root );
5402 }
5403 foreach ( $root as $node ) {
5404 if ( $first ) {
5405 $first = false;
5406 } else {
5407 $s .= $sep;
5408 }
5409 $s .= $this->expand( $node, $flags );
5410 }
5411 }
5412 return $s;
5413 }
5414
5415 function implode( $sep /*, ... */ ) {
5416 $args = func_get_args();
5417 $args = array_merge( array_slice( $args, 0, 1 ), array( 0 ), array_slice( $args, 1 ) );
5418 return call_user_func_array( array( $this, 'implodeWithFlags' ), $args );
5419 }
5420
5421 /**
5422 * Split an <arg> or <template> node into a three-element array:
5423 * DOMNode name, string index and DOMNode value
5424 */
5425 function splitBraceNode( $node ) {
5426 $xpath = new DOMXPath( $arg->ownerDocument );
5427 $names = $xpath->query( 'name', $node );
5428 $values = $xpath->query( 'value', $node );
5429 if ( !$names->length || !$values->length ) {
5430 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
5431 }
5432 $name = $names->item( 0 );
5433 $index = $name->getAttribute( 'index' );
5434 return array( $name, $index, $values->item( 0 ) );
5435 }
5436
5437 function __toString() {
5438 return 'frame{}';
5439 }
5440 }
5441
5442 /**
5443 * Expansion frame with template arguments
5444 */
5445 class PPTemplateFrame extends PPFrame {
5446 public $parser, $args, $parent, $serial;
5447
5448 function __construct( $parser, $parent = false, $args = array(), $title = false ) {
5449 $this->parser = $parser;
5450 $this->parent = $parent;
5451 $this->args = $args;
5452 $this->title = $title;
5453 }
5454
5455 function __toString() {
5456 $s = 'tplframe{';
5457 $first = true;
5458 foreach ( $this->args as $name => $value ) {
5459 if ( $first ) {
5460 $first = false;
5461 } else {
5462 $s .= ', ';
5463 }
5464 $s .= "\"$name\":\"" .
5465 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
5466 }
5467 $s .= '}';
5468 return $s;
5469 }
5470 }
5471