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