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