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