Moved EditPage::sectionAnchor() and EditPage::pseudoParseSectionAnchor() to Parser...
[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 $mImageParams, $mImageParamsMagicArray;
102
103 # Cleared with clearState():
104 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
105 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
106 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
107 var $mIncludeSizes, $mDefaultSort;
108 var $mTemplates, // cache of already loaded templates, avoids
109 // multiple SQL queries for the same string
110 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
111 // in this path. Used for loop detection.
112
113 # Temporary
114 # These are variables reset at least once per parse regardless of $clearState
115 var $mOptions, // ParserOptions object
116 $mTitle, // Title context, used for self-link rendering and similar things
117 $mOutputType, // Output type, one of the OT_xxx constants
118 $ot, // Shortcut alias, see setOutputType()
119 $mRevisionId, // ID to display in {{REVISIONID}} tags
120 $mRevisionTimestamp, // The timestamp of the specified revision ID
121 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
122
123 /**#@-*/
124
125 /**
126 * Constructor
127 *
128 * @public
129 */
130 function Parser() {
131 $this->mTagHooks = array();
132 $this->mTransparentTagHooks = array();
133 $this->mFunctionHooks = array();
134 $this->mFunctionSynonyms = array( 0 => array(), 1 => array() );
135 $this->mFirstCall = true;
136 }
137
138 /**
139 * Do various kinds of initialisation on the first call of the parser
140 */
141 function firstCallInit() {
142 if ( !$this->mFirstCall ) {
143 return;
144 }
145
146 wfProfileIn( __METHOD__ );
147 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
148
149 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
150
151 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH );
152 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH );
153 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH );
154 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH );
155 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH );
156 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH );
157 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH );
158 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH );
159 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH );
160 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH );
161 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH );
162 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH );
163 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH );
164 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH );
165 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH );
166 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH );
167 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH );
168 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH );
169 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH );
170 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH );
171 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH );
172 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH );
173 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH );
174 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH );
175 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
176 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH );
177
178 if ( $wgAllowDisplayTitle ) {
179 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH );
180 }
181 if ( $wgAllowSlowParserFunctions ) {
182 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH );
183 }
184
185 $this->initialiseVariables();
186 $this->mFirstCall = false;
187 wfProfileOut( __METHOD__ );
188 }
189
190 /**
191 * Clear Parser state
192 *
193 * @private
194 */
195 function clearState() {
196 wfProfileIn( __METHOD__ );
197 if ( $this->mFirstCall ) {
198 $this->firstCallInit();
199 }
200 $this->mOutput = new ParserOutput;
201 $this->mAutonumber = 0;
202 $this->mLastSection = '';
203 $this->mDTopen = false;
204 $this->mIncludeCount = array();
205 $this->mStripState = new StripState;
206 $this->mArgStack = array();
207 $this->mInPre = false;
208 $this->mInterwikiLinkHolders = array(
209 'texts' => array(),
210 'titles' => array()
211 );
212 $this->mLinkHolders = array(
213 'namespaces' => array(),
214 'dbkeys' => array(),
215 'queries' => array(),
216 'texts' => array(),
217 'titles' => array()
218 );
219 $this->mRevisionTimestamp = $this->mRevisionId = null;
220
221 /**
222 * Prefix for temporary replacement strings for the multipass parser.
223 * \x07 should never appear in input as it's disallowed in XML.
224 * Using it at the front also gives us a little extra robustness
225 * since it shouldn't match when butted up against identifier-like
226 * string constructs.
227 */
228 $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
229
230 # Clear these on every parse, bug 4549
231 $this->mTemplates = array();
232 $this->mTemplatePath = array();
233
234 $this->mShowToc = true;
235 $this->mForceTocPosition = false;
236 $this->mIncludeSizes = array(
237 'pre-expand' => 0,
238 'post-expand' => 0,
239 'arg' => 0
240 );
241 $this->mDefaultSort = false;
242
243 wfRunHooks( 'ParserClearState', array( &$this ) );
244 wfProfileOut( __METHOD__ );
245 }
246
247 function setOutputType( $ot ) {
248 $this->mOutputType = $ot;
249 // Shortcut alias
250 $this->ot = array(
251 'html' => $ot == OT_HTML,
252 'wiki' => $ot == OT_WIKI,
253 'msg' => $ot == OT_MSG,
254 'pre' => $ot == OT_PREPROCESS,
255 );
256 }
257
258 /**
259 * Accessor for mUniqPrefix.
260 *
261 * @public
262 */
263 function uniqPrefix() {
264 return $this->mUniqPrefix;
265 }
266
267 /**
268 * Convert wikitext to HTML
269 * Do not call this function recursively.
270 *
271 * @param string $text Text we want to parse
272 * @param Title &$title A title object
273 * @param array $options
274 * @param boolean $linestart
275 * @param boolean $clearState
276 * @param int $revid number to pass in {{REVISIONID}}
277 * @return ParserOutput a ParserOutput
278 */
279 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
280 /**
281 * First pass--just handle <nowiki> sections, pass the rest off
282 * to internalParse() which does all the real work.
283 */
284
285 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
286 $fname = 'Parser::parse-' . wfGetCaller();
287 wfProfileIn( __METHOD__ );
288 wfProfileIn( $fname );
289
290 if ( $clearState ) {
291 $this->clearState();
292 }
293
294 $this->mOptions = $options;
295 $this->mTitle =& $title;
296 $oldRevisionId = $this->mRevisionId;
297 $oldRevisionTimestamp = $this->mRevisionTimestamp;
298 if( $revid !== null ) {
299 $this->mRevisionId = $revid;
300 $this->mRevisionTimestamp = null;
301 }
302 $this->setOutputType( OT_HTML );
303 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
304 $text = $this->strip( $text, $this->mStripState );
305 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
306 $text = $this->internalParse( $text );
307 $text = $this->mStripState->unstripGeneral( $text );
308
309 # Clean up special characters, only run once, next-to-last before doBlockLevels
310 $fixtags = array(
311 # french spaces, last one Guillemet-left
312 # only if there is something before the space
313 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&nbsp;\\2',
314 # french spaces, Guillemet-right
315 '/(\\302\\253) /' => '\\1&nbsp;',
316 );
317 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
318
319 # only once and last
320 $text = $this->doBlockLevels( $text, $linestart );
321
322 $this->replaceLinkHolders( $text );
323
324 # the position of the parserConvert() call should not be changed. it
325 # assumes that the links are all replaced and the only thing left
326 # is the <nowiki> mark.
327 # Side-effects: this calls $this->mOutput->setTitleText()
328 $text = $wgContLang->parserConvert( $text, $this );
329
330 $text = $this->mStripState->unstripNoWiki( $text );
331
332 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
333
334 //!JF Move to its own function
335
336 $uniq_prefix = $this->mUniqPrefix;
337 $matches = array();
338 $elements = array_keys( $this->mTransparentTagHooks );
339 $text = Parser::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
340
341 foreach( $matches as $marker => $data ) {
342 list( $element, $content, $params, $tag ) = $data;
343 $tagName = strtolower( $element );
344 if( isset( $this->mTransparentTagHooks[$tagName] ) ) {
345 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName],
346 array( $content, $params, $this ) );
347 } else {
348 $output = $tag;
349 }
350 $this->mStripState->general->setPair( $marker, $output );
351 }
352 $text = $this->mStripState->unstripGeneral( $text );
353
354 $text = Sanitizer::normalizeCharReferences( $text );
355
356 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
357 $text = Parser::tidy($text);
358 } else {
359 # attempt to sanitize at least some nesting problems
360 # (bug #2702 and quite a few others)
361 $tidyregs = array(
362 # ''Something [http://www.cool.com cool''] -->
363 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
364 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
365 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
366 # fix up an anchor inside another anchor, only
367 # at least for a single single nested link (bug 3695)
368 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
369 '\\1\\2</a>\\3</a>\\1\\4</a>',
370 # fix div inside inline elements- doBlockLevels won't wrap a line which
371 # contains a div, so fix it up here; replace
372 # div with escaped text
373 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
374 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
375 # remove empty italic or bold tag pairs, some
376 # introduced by rules above
377 '/<([bi])><\/\\1>/' => '',
378 );
379
380 $text = preg_replace(
381 array_keys( $tidyregs ),
382 array_values( $tidyregs ),
383 $text );
384 }
385
386 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
387
388 # Information on include size limits, for the benefit of users who try to skirt them
389 if ( max( $this->mIncludeSizes ) > 1000 ) {
390 $max = $this->mOptions->getMaxIncludeSize();
391 $text .= "<!-- \n" .
392 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
393 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
394 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
395 "Maximum: $max bytes\n" .
396 "-->\n";
397 }
398 $this->mOutput->setText( $text );
399 $this->mRevisionId = $oldRevisionId;
400 $this->mRevisionTimestamp = $oldRevisionTimestamp;
401 wfProfileOut( $fname );
402 wfProfileOut( __METHOD__ );
403
404 return $this->mOutput;
405 }
406
407 /**
408 * Recursive parser entry point that can be called from an extension tag
409 * hook.
410 */
411 function recursiveTagParse( $text ) {
412 wfProfileIn( __METHOD__ );
413 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
414 $text = $this->strip( $text, $this->mStripState );
415 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
416 $text = $this->internalParse( $text );
417 wfProfileOut( __METHOD__ );
418 return $text;
419 }
420
421 /**
422 * Expand templates and variables in the text, producing valid, static wikitext.
423 * Also removes comments.
424 */
425 function preprocess( $text, $title, $options, $revid = null ) {
426 wfProfileIn( __METHOD__ );
427 $this->clearState();
428 $this->setOutputType( OT_PREPROCESS );
429 $this->mOptions = $options;
430 $this->mTitle = $title;
431 if( $revid !== null ) {
432 $this->mRevisionId = $revid;
433 }
434 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
435 $text = $this->strip( $text, $this->mStripState );
436 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
437 if ( $this->mOptions->getRemoveComments() ) {
438 $text = Sanitizer::removeHTMLcomments( $text );
439 }
440 $text = $this->replaceVariables( $text );
441 $text = $this->mStripState->unstripBoth( $text );
442 wfProfileOut( __METHOD__ );
443 return $text;
444 }
445
446 /**
447 * Get a random string
448 *
449 * @private
450 * @static
451 */
452 function getRandomString() {
453 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
454 }
455
456 function &getTitle() { return $this->mTitle; }
457 function getOptions() { return $this->mOptions; }
458
459 function getFunctionLang() {
460 global $wgLang, $wgContLang;
461 return $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
462 }
463
464 /**
465 * Replaces all occurrences of HTML-style comments and the given tags
466 * in the text with a random marker and returns teh next text. The output
467 * parameter $matches will be an associative array filled with data in
468 * the form:
469 * 'UNIQ-xxxxx' => array(
470 * 'element',
471 * 'tag content',
472 * array( 'param' => 'x' ),
473 * '<element param="x">tag content</element>' ) )
474 *
475 * @param $elements list of element names. Comments are always extracted.
476 * @param $text Source text string.
477 * @param $uniq_prefix
478 *
479 * @public
480 * @static
481 */
482 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
483 static $n = 1;
484 $stripped = '';
485 $matches = array();
486
487 $taglist = implode( '|', $elements );
488 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
489
490 while ( '' != $text ) {
491 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
492 $stripped .= $p[0];
493 if( count( $p ) < 5 ) {
494 break;
495 }
496 if( count( $p ) > 5 ) {
497 // comment
498 $element = $p[4];
499 $attributes = '';
500 $close = '';
501 $inside = $p[5];
502 } else {
503 // tag
504 $element = $p[1];
505 $attributes = $p[2];
506 $close = $p[3];
507 $inside = $p[4];
508 }
509
510 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++) . "-QINU\x07";
511 $stripped .= $marker;
512
513 if ( $close === '/>' ) {
514 // Empty element tag, <tag />
515 $content = null;
516 $text = $inside;
517 $tail = null;
518 } else {
519 if( $element == '!--' ) {
520 $end = '/(-->)/';
521 } else {
522 $end = "/(<\\/$element\\s*>)/i";
523 }
524 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
525 $content = $q[0];
526 if( count( $q ) < 3 ) {
527 # No end tag -- let it run out to the end of the text.
528 $tail = '';
529 $text = '';
530 } else {
531 $tail = $q[1];
532 $text = $q[2];
533 }
534 }
535
536 $matches[$marker] = array( $element,
537 $content,
538 Sanitizer::decodeTagAttributes( $attributes ),
539 "<$element$attributes$close$content$tail" );
540 }
541 return $stripped;
542 }
543
544 /**
545 * Strips and renders nowiki, pre, math, hiero
546 * If $render is set, performs necessary rendering operations on plugins
547 * Returns the text, and fills an array with data needed in unstrip()
548 *
549 * @param StripState $state
550 *
551 * @param bool $stripcomments when set, HTML comments <!-- like this -->
552 * will be stripped in addition to other tags. This is important
553 * for section editing, where these comments cause confusion when
554 * counting the sections in the wikisource
555 *
556 * @param array dontstrip contains tags which should not be stripped;
557 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
558 *
559 * @private
560 */
561 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
562 global $wgContLang;
563 wfProfileIn( __METHOD__ );
564 $render = ($this->mOutputType == OT_HTML);
565
566 $uniq_prefix = $this->mUniqPrefix;
567 $commentState = new ReplacementArray;
568 $nowikiItems = array();
569 $generalItems = array();
570
571 $elements = array_merge(
572 array( 'nowiki', 'gallery' ),
573 array_keys( $this->mTagHooks ) );
574 global $wgRawHtml;
575 if( $wgRawHtml ) {
576 $elements[] = 'html';
577 }
578 if( $this->mOptions->getUseTeX() ) {
579 $elements[] = 'math';
580 }
581
582 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
583 foreach ( $elements AS $k => $v ) {
584 if ( !in_array ( $v , $dontstrip ) ) continue;
585 unset ( $elements[$k] );
586 }
587
588 $matches = array();
589 $text = Parser::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
590
591 foreach( $matches as $marker => $data ) {
592 list( $element, $content, $params, $tag ) = $data;
593 if( $render ) {
594 $tagName = strtolower( $element );
595 wfProfileIn( __METHOD__."-render-$tagName" );
596 switch( $tagName ) {
597 case '!--':
598 // Comment
599 if( substr( $tag, -3 ) == '-->' ) {
600 $output = $tag;
601 } else {
602 // Unclosed comment in input.
603 // Close it so later stripping can remove it
604 $output = "$tag-->";
605 }
606 break;
607 case 'html':
608 if( $wgRawHtml ) {
609 $output = $content;
610 break;
611 }
612 // Shouldn't happen otherwise. :)
613 case 'nowiki':
614 $output = Xml::escapeTagsOnly( $content );
615 break;
616 case 'math':
617 $output = $wgContLang->armourMath(
618 MathRenderer::renderMath( $content, $params ) );
619 break;
620 case 'gallery':
621 $output = $this->renderImageGallery( $content, $params );
622 break;
623 default:
624 if( isset( $this->mTagHooks[$tagName] ) ) {
625 $output = call_user_func_array( $this->mTagHooks[$tagName],
626 array( $content, $params, $this ) );
627 } else {
628 throw new MWException( "Invalid call hook $element" );
629 }
630 }
631 wfProfileOut( __METHOD__."-render-$tagName" );
632 } else {
633 // Just stripping tags; keep the source
634 $output = $tag;
635 }
636
637 // Unstrip the output, to support recursive strip() calls
638 $output = $state->unstripBoth( $output );
639
640 if( !$stripcomments && $element == '!--' ) {
641 $commentState->setPair( $marker, $output );
642 } elseif ( $element == 'html' || $element == 'nowiki' ) {
643 $nowikiItems[$marker] = $output;
644 } else {
645 $generalItems[$marker] = $output;
646 }
647 }
648 # Add the new items to the state
649 # We do this after the loop instead of during it to avoid slowing
650 # down the recursive unstrip
651 $state->nowiki->mergeArray( $nowikiItems );
652 $state->general->mergeArray( $generalItems );
653
654 # Unstrip comments unless explicitly told otherwise.
655 # (The comments are always stripped prior to this point, so as to
656 # not invoke any extension tags / parser hooks contained within
657 # a comment.)
658 if ( !$stripcomments ) {
659 // Put them all back and forget them
660 $text = $commentState->replace( $text );
661 }
662
663 wfProfileOut( __METHOD__ );
664 return $text;
665 }
666
667 /**
668 * Restores pre, math, and other extensions removed by strip()
669 *
670 * always call unstripNoWiki() after this one
671 * @private
672 * @deprecated use $this->mStripState->unstrip()
673 */
674 function unstrip( $text, $state ) {
675 return $state->unstripGeneral( $text );
676 }
677
678 /**
679 * Always call this after unstrip() to preserve the order
680 *
681 * @private
682 * @deprecated use $this->mStripState->unstrip()
683 */
684 function unstripNoWiki( $text, $state ) {
685 return $state->unstripNoWiki( $text );
686 }
687
688 /**
689 * @deprecated use $this->mStripState->unstripBoth()
690 */
691 function unstripForHTML( $text ) {
692 return $this->mStripState->unstripBoth( $text );
693 }
694
695 /**
696 * Add an item to the strip state
697 * Returns the unique tag which must be inserted into the stripped text
698 * The tag will be replaced with the original text in unstrip()
699 *
700 * @private
701 */
702 function insertStripItem( $text, &$state ) {
703 $rnd = $this->mUniqPrefix . '-item' . Parser::getRandomString();
704 $state->general->setPair( $rnd, $text );
705 return $rnd;
706 }
707
708 /**
709 * Interface with html tidy, used if $wgUseTidy = true.
710 * If tidy isn't able to correct the markup, the original will be
711 * returned in all its glory with a warning comment appended.
712 *
713 * Either the external tidy program or the in-process tidy extension
714 * will be used depending on availability. Override the default
715 * $wgTidyInternal setting to disable the internal if it's not working.
716 *
717 * @param string $text Hideous HTML input
718 * @return string Corrected HTML output
719 * @public
720 * @static
721 */
722 function tidy( $text ) {
723 global $wgTidyInternal;
724 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
725 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
726 '<head><title>test</title></head><body>'.$text.'</body></html>';
727 if( $wgTidyInternal ) {
728 $correctedtext = Parser::internalTidy( $wrappedtext );
729 } else {
730 $correctedtext = Parser::externalTidy( $wrappedtext );
731 }
732 if( is_null( $correctedtext ) ) {
733 wfDebug( "Tidy error detected!\n" );
734 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
735 }
736 return $correctedtext;
737 }
738
739 /**
740 * Spawn an external HTML tidy process and get corrected markup back from it.
741 *
742 * @private
743 * @static
744 */
745 function externalTidy( $text ) {
746 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
747 $fname = 'Parser::externalTidy';
748 wfProfileIn( $fname );
749
750 $cleansource = '';
751 $opts = ' -utf8';
752
753 $descriptorspec = array(
754 0 => array('pipe', 'r'),
755 1 => array('pipe', 'w'),
756 2 => array('file', wfGetNull(), 'a')
757 );
758 $pipes = array();
759 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
760 if (is_resource($process)) {
761 // Theoretically, this style of communication could cause a deadlock
762 // here. If the stdout buffer fills up, then writes to stdin could
763 // block. This doesn't appear to happen with tidy, because tidy only
764 // writes to stdout after it's finished reading from stdin. Search
765 // for tidyParseStdin and tidySaveStdout in console/tidy.c
766 fwrite($pipes[0], $text);
767 fclose($pipes[0]);
768 while (!feof($pipes[1])) {
769 $cleansource .= fgets($pipes[1], 1024);
770 }
771 fclose($pipes[1]);
772 proc_close($process);
773 }
774
775 wfProfileOut( $fname );
776
777 if( $cleansource == '' && $text != '') {
778 // Some kind of error happened, so we couldn't get the corrected text.
779 // Just give up; we'll use the source text and append a warning.
780 return null;
781 } else {
782 return $cleansource;
783 }
784 }
785
786 /**
787 * Use the HTML tidy PECL extension to use the tidy library in-process,
788 * saving the overhead of spawning a new process. Currently written to
789 * the PHP 4.3.x version of the extension, may not work on PHP 5.
790 *
791 * 'pear install tidy' should be able to compile the extension module.
792 *
793 * @private
794 * @static
795 */
796 function internalTidy( $text ) {
797 global $wgTidyConf;
798 $fname = 'Parser::internalTidy';
799 wfProfileIn( $fname );
800
801 tidy_load_config( $wgTidyConf );
802 tidy_set_encoding( 'utf8' );
803 tidy_parse_string( $text );
804 tidy_clean_repair();
805 if( tidy_get_status() == 2 ) {
806 // 2 is magic number for fatal error
807 // http://www.php.net/manual/en/function.tidy-get-status.php
808 $cleansource = null;
809 } else {
810 $cleansource = tidy_get_output();
811 }
812 wfProfileOut( $fname );
813 return $cleansource;
814 }
815
816 /**
817 * parse the wiki syntax used to render tables
818 *
819 * @private
820 */
821 function doTableStuff ( $text ) {
822 $fname = 'Parser::doTableStuff';
823 wfProfileIn( $fname );
824
825 $lines = explode ( "\n" , $text );
826 $td_history = array (); // Is currently a td tag open?
827 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
828 $tr_history = array (); // Is currently a tr tag open?
829 $tr_attributes = array (); // history of tr attributes
830 $has_opened_tr = array(); // Did this table open a <tr> element?
831 $indent_level = 0; // indent level of the table
832 foreach ( $lines as $key => $line )
833 {
834 $line = trim ( $line );
835
836 if( $line == '' ) { // empty line, go to next line
837 continue;
838 }
839 $first_character = $line{0};
840 $matches = array();
841
842 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
843 // First check if we are starting a new table
844 $indent_level = strlen( $matches[1] );
845
846 $attributes = $this->mStripState->unstripBoth( $matches[2] );
847 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'table' );
848
849 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
850 array_push ( $td_history , false );
851 array_push ( $last_tag_history , '' );
852 array_push ( $tr_history , false );
853 array_push ( $tr_attributes , '' );
854 array_push ( $has_opened_tr , false );
855 } else if ( count ( $td_history ) == 0 ) {
856 // Don't do any of the following
857 continue;
858 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
859 // We are ending a table
860 $line = '</table>' . substr ( $line , 2 );
861 $last_tag = array_pop ( $last_tag_history );
862
863 if ( !array_pop ( $has_opened_tr ) ) {
864 $line = "<tr><td></td></tr>{$line}";
865 }
866
867 if ( array_pop ( $tr_history ) ) {
868 $line = "</tr>{$line}";
869 }
870
871 if ( array_pop ( $td_history ) ) {
872 $line = "</{$last_tag}>{$line}";
873 }
874 array_pop ( $tr_attributes );
875 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
876 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
877 // Now we have a table row
878 $line = preg_replace( '#^\|-+#', '', $line );
879
880 // Whats after the tag is now only attributes
881 $attributes = $this->mStripState->unstripBoth( $line );
882 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'tr' );
883 array_pop ( $tr_attributes );
884 array_push ( $tr_attributes , $attributes );
885
886 $line = '';
887 $last_tag = array_pop ( $last_tag_history );
888 array_pop ( $has_opened_tr );
889 array_push ( $has_opened_tr , true );
890
891 if ( array_pop ( $tr_history ) ) {
892 $line = '</tr>';
893 }
894
895 if ( array_pop ( $td_history ) ) {
896 $line = "</{$last_tag}>{$line}";
897 }
898
899 $lines[$key] = $line;
900 array_push ( $tr_history , false );
901 array_push ( $td_history , false );
902 array_push ( $last_tag_history , '' );
903 }
904 else if ( $first_character == '|' || $first_character == '!' || substr ( $line , 0 , 2 ) == '|+' ) {
905 // This might be cell elements, td, th or captions
906 if ( substr ( $line , 0 , 2 ) == '|+' ) {
907 $first_character = '+';
908 $line = substr ( $line , 1 );
909 }
910
911 $line = substr ( $line , 1 );
912
913 if ( $first_character == '!' ) {
914 $line = str_replace ( '!!' , '||' , $line );
915 }
916
917 // Split up multiple cells on the same line.
918 // FIXME : This can result in improper nesting of tags processed
919 // by earlier parser steps, but should avoid splitting up eg
920 // attribute values containing literal "||".
921 $cells = StringUtils::explodeMarkup( '||' , $line );
922
923 $lines[$key] = '';
924
925 // Loop through each table cell
926 foreach ( $cells as $cell )
927 {
928 $previous = '';
929 if ( $first_character != '+' )
930 {
931 $tr_after = array_pop ( $tr_attributes );
932 if ( !array_pop ( $tr_history ) ) {
933 $previous = "<tr{$tr_after}>\n";
934 }
935 array_push ( $tr_history , true );
936 array_push ( $tr_attributes , '' );
937 array_pop ( $has_opened_tr );
938 array_push ( $has_opened_tr , true );
939 }
940
941 $last_tag = array_pop ( $last_tag_history );
942
943 if ( array_pop ( $td_history ) ) {
944 $previous = "</{$last_tag}>{$previous}";
945 }
946
947 if ( $first_character == '|' ) {
948 $last_tag = 'td';
949 } else if ( $first_character == '!' ) {
950 $last_tag = 'th';
951 } else if ( $first_character == '+' ) {
952 $last_tag = 'caption';
953 } else {
954 $last_tag = '';
955 }
956
957 array_push ( $last_tag_history , $last_tag );
958
959 // A cell could contain both parameters and data
960 $cell_data = explode ( '|' , $cell , 2 );
961
962 // Bug 553: Note that a '|' inside an invalid link should not
963 // be mistaken as delimiting cell parameters
964 if ( strpos( $cell_data[0], '[[' ) !== false ) {
965 $cell = "{$previous}<{$last_tag}>{$cell}";
966 } else if ( count ( $cell_data ) == 1 )
967 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
968 else {
969 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
970 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag );
971 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
972 }
973
974 $lines[$key] .= $cell;
975 array_push ( $td_history , true );
976 }
977 }
978 }
979
980 // Closing open td, tr && table
981 while ( count ( $td_history ) > 0 )
982 {
983 if ( array_pop ( $td_history ) ) {
984 $lines[] = '</td>' ;
985 }
986 if ( array_pop ( $tr_history ) ) {
987 $lines[] = '</tr>' ;
988 }
989 if ( !array_pop ( $has_opened_tr ) ) {
990 $lines[] = "<tr><td></td></tr>" ;
991 }
992
993 $lines[] = '</table>' ;
994 }
995
996 $output = implode ( "\n" , $lines ) ;
997
998 // special case: don't return empty table
999 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
1000 $output = '';
1001 }
1002
1003 wfProfileOut( $fname );
1004
1005 return $output;
1006 }
1007
1008 /**
1009 * Helper function for parse() that transforms wiki markup into
1010 * HTML. Only called for $mOutputType == OT_HTML.
1011 *
1012 * @private
1013 */
1014 function internalParse( $text ) {
1015 $args = array();
1016 $isMain = true;
1017 $fname = 'Parser::internalParse';
1018 wfProfileIn( $fname );
1019
1020 # Hook to suspend the parser in this state
1021 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
1022 wfProfileOut( $fname );
1023 return $text ;
1024 }
1025
1026 # Remove <noinclude> tags and <includeonly> sections
1027 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
1028 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
1029 $text = StringUtils::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
1030
1031 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), array(), array_keys( $this->mTransparentTagHooks ) );
1032
1033 $text = $this->replaceVariables( $text, $args );
1034 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
1035
1036 // Tables need to come after variable replacement for things to work
1037 // properly; putting them before other transformations should keep
1038 // exciting things like link expansions from showing up in surprising
1039 // places.
1040 $text = $this->doTableStuff( $text );
1041
1042 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1043
1044 $text = $this->stripToc( $text );
1045 $this->stripNoGallery( $text );
1046 $text = $this->doHeadings( $text );
1047 if($this->mOptions->getUseDynamicDates()) {
1048 $df =& DateFormatter::getInstance();
1049 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
1050 }
1051 $text = $this->doAllQuotes( $text );
1052 $text = $this->replaceInternalLinks( $text );
1053 $text = $this->replaceExternalLinks( $text );
1054
1055 # replaceInternalLinks may sometimes leave behind
1056 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1057 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
1058
1059 $text = $this->doMagicLinks( $text );
1060 $text = $this->formatHeadings( $text, $isMain );
1061
1062 wfProfileOut( $fname );
1063 return $text;
1064 }
1065
1066 /**
1067 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1068 * magic external links.
1069 *
1070 * @private
1071 */
1072 function &doMagicLinks( &$text ) {
1073 wfProfileIn( __METHOD__ );
1074 $text = preg_replace_callback(
1075 '!(?: # Start cases
1076 <a.*?</a> | # Skip link text
1077 <.*?> | # Skip stuff inside HTML elements
1078 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1079 ISBN\s+(\b # ISBN, capture number as m[2]
1080 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1081 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1082 [0-9Xx] # check digit
1083 \b)
1084 )!x', array( &$this, 'magicLinkCallback' ), $text );
1085 wfProfileOut( __METHOD__ );
1086 return $text;
1087 }
1088
1089 function magicLinkCallback( $m ) {
1090 if ( substr( $m[0], 0, 1 ) == '<' ) {
1091 # Skip HTML element
1092 return $m[0];
1093 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1094 $isbn = $m[2];
1095 $num = strtr( $isbn, array(
1096 '-' => '',
1097 ' ' => '',
1098 'x' => 'X',
1099 ));
1100 $titleObj = SpecialPage::getTitleFor( 'Booksources' );
1101 $text = '<a href="' .
1102 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1103 "\" class=\"internal\">ISBN $isbn</a>";
1104 } else {
1105 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1106 $keyword = 'RFC';
1107 $urlmsg = 'rfcurl';
1108 $id = $m[1];
1109 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1110 $keyword = 'PMID';
1111 $urlmsg = 'pubmedurl';
1112 $id = $m[1];
1113 } else {
1114 throw new MWException( __METHOD__.': unrecognised match type "' .
1115 substr($m[0], 0, 20 ) . '"' );
1116 }
1117
1118 $url = wfMsg( $urlmsg, $id);
1119 $sk = $this->mOptions->getSkin();
1120 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1121 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1122 }
1123 return $text;
1124 }
1125
1126 /**
1127 * Parse headers and return html
1128 *
1129 * @private
1130 */
1131 function doHeadings( $text ) {
1132 $fname = 'Parser::doHeadings';
1133 wfProfileIn( $fname );
1134 for ( $i = 6; $i >= 1; --$i ) {
1135 $h = str_repeat( '=', $i );
1136 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1137 "<h{$i}>\\1</h{$i}>\\2", $text );
1138 }
1139 wfProfileOut( $fname );
1140 return $text;
1141 }
1142
1143 /**
1144 * Replace single quotes with HTML markup
1145 * @private
1146 * @return string the altered text
1147 */
1148 function doAllQuotes( $text ) {
1149 $fname = 'Parser::doAllQuotes';
1150 wfProfileIn( $fname );
1151 $outtext = '';
1152 $lines = explode( "\n", $text );
1153 foreach ( $lines as $line ) {
1154 $outtext .= $this->doQuotes ( $line ) . "\n";
1155 }
1156 $outtext = substr($outtext, 0,-1);
1157 wfProfileOut( $fname );
1158 return $outtext;
1159 }
1160
1161 /**
1162 * Helper function for doAllQuotes()
1163 */
1164 public 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 (other than plain <sup> and <sub>: bug 8393)
3644 $tocline = preg_replace(
3645 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3646 array( '', '<$1>'),
3647 $canonized_headline
3648 );
3649 $tocline = trim( $tocline );
3650
3651 # For the anchor, strip out HTML-y stuff period
3652 $canonized_headline = preg_replace( '/<.*?'.'>/', '', $canonized_headline );
3653 $canonized_headline = trim( $canonized_headline );
3654
3655 # Save headline for section edit hint before it's escaped
3656 $headline_hint = $canonized_headline;
3657 $canonized_headline = Sanitizer::escapeId( $canonized_headline );
3658 $refers[$headlineCount] = $canonized_headline;
3659
3660 # count how many in assoc. array so we can track dupes in anchors
3661 isset( $refers[$canonized_headline] ) ? $refers[$canonized_headline]++ : $refers[$canonized_headline] = 1;
3662 $refcount[$headlineCount]=$refers[$canonized_headline];
3663
3664 # Don't number the heading if it is the only one (looks silly)
3665 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3666 # the two are different if the line contains a link
3667 $headline=$numbering . ' ' . $headline;
3668 }
3669
3670 # Create the anchor for linking from the TOC to the section
3671 $anchor = $canonized_headline;
3672 if($refcount[$headlineCount] > 1 ) {
3673 $anchor .= '_' . $refcount[$headlineCount];
3674 }
3675 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3676 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3677 }
3678 # give headline the correct <h#> tag
3679 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3680 if( $istemplate )
3681 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3682 else
3683 $editlink = $sk->editSectionLink($this->mTitle, $sectionCount+1, $headline_hint);
3684 } else {
3685 $editlink = '';
3686 }
3687 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3688
3689 $headlineCount++;
3690 if( !$istemplate )
3691 $sectionCount++;
3692 }
3693
3694 # Never ever show TOC if no headers
3695 if( $numVisible < 1 ) {
3696 $enoughToc = false;
3697 }
3698
3699 if( $enoughToc ) {
3700 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3701 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3702 }
3703 $toc = $sk->tocList( $toc );
3704 }
3705
3706 # split up and insert constructed headlines
3707
3708 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3709 $i = 0;
3710
3711 foreach( $blocks as $block ) {
3712 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3713 # This is the [edit] link that appears for the top block of text when
3714 # section editing is enabled
3715
3716 # Disabled because it broke block formatting
3717 # For example, a bullet point in the top line
3718 # $full .= $sk->editSectionLink(0);
3719 }
3720 $full .= $block;
3721 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3722 # Top anchor now in skin
3723 $full = $full.$toc;
3724 }
3725
3726 if( !empty( $head[$i] ) ) {
3727 $full .= $head[$i];
3728 }
3729 $i++;
3730 }
3731 if( $this->mForceTocPosition ) {
3732 return str_replace( '<!--MWTOC-->', $toc, $full );
3733 } else {
3734 return $full;
3735 }
3736 }
3737
3738 /**
3739 * Transform wiki markup when saving a page by doing \r\n -> \n
3740 * conversion, substitting signatures, {{subst:}} templates, etc.
3741 *
3742 * @param string $text the text to transform
3743 * @param Title &$title the Title object for the current article
3744 * @param User &$user the User object describing the current user
3745 * @param ParserOptions $options parsing options
3746 * @param bool $clearState whether to clear the parser state first
3747 * @return string the altered wiki markup
3748 * @public
3749 */
3750 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3751 $this->mOptions = $options;
3752 $this->mTitle =& $title;
3753 $this->setOutputType( OT_WIKI );
3754
3755 if ( $clearState ) {
3756 $this->clearState();
3757 }
3758
3759 $stripState = new StripState;
3760 $pairs = array(
3761 "\r\n" => "\n",
3762 );
3763 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3764 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3765 $text = $this->pstPass2( $text, $stripState, $user );
3766 $text = $stripState->unstripBoth( $text );
3767 return $text;
3768 }
3769
3770 /**
3771 * Pre-save transform helper function
3772 * @private
3773 */
3774 function pstPass2( $text, &$stripState, $user ) {
3775 global $wgContLang, $wgLocaltimezone;
3776
3777 /* Note: This is the timestamp saved as hardcoded wikitext to
3778 * the database, we use $wgContLang here in order to give
3779 * everyone the same signature and use the default one rather
3780 * than the one selected in each user's preferences.
3781 */
3782 if ( isset( $wgLocaltimezone ) ) {
3783 $oldtz = getenv( 'TZ' );
3784 putenv( 'TZ='.$wgLocaltimezone );
3785 }
3786 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3787 ' (' . date( 'T' ) . ')';
3788 if ( isset( $wgLocaltimezone ) ) {
3789 putenv( 'TZ='.$oldtz );
3790 }
3791
3792 # Variable replacement
3793 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3794 $text = $this->replaceVariables( $text );
3795
3796 # Strip out <nowiki> etc. added via replaceVariables
3797 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3798
3799 # Signatures
3800 $sigText = $this->getUserSig( $user );
3801 $text = strtr( $text, array(
3802 '~~~~~' => $d,
3803 '~~~~' => "$sigText $d",
3804 '~~~' => $sigText
3805 ) );
3806
3807 # Context links: [[|name]] and [[name (context)|]]
3808 #
3809 global $wgLegalTitleChars;
3810 $tc = "[$wgLegalTitleChars]";
3811 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3812
3813 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3814 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3815 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3816
3817 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3818 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3819 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3820
3821 $t = $this->mTitle->getText();
3822 $m = array();
3823 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3824 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3825 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3826 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3827 } else {
3828 # if there's no context, don't bother duplicating the title
3829 $text = preg_replace( $p2, '[[\\1]]', $text );
3830 }
3831
3832 # Trim trailing whitespace
3833 $text = rtrim( $text );
3834
3835 return $text;
3836 }
3837
3838 /**
3839 * Fetch the user's signature text, if any, and normalize to
3840 * validated, ready-to-insert wikitext.
3841 *
3842 * @param User $user
3843 * @return string
3844 * @private
3845 */
3846 function getUserSig( &$user ) {
3847 global $wgMaxSigChars;
3848
3849 $username = $user->getName();
3850 $nickname = $user->getOption( 'nickname' );
3851 $nickname = $nickname === '' ? $username : $nickname;
3852
3853 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3854 $nickname = $username;
3855 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
3856 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3857 # Sig. might contain markup; validate this
3858 if( $this->validateSig( $nickname ) !== false ) {
3859 # Validated; clean up (if needed) and return it
3860 return $this->cleanSig( $nickname, true );
3861 } else {
3862 # Failed to validate; fall back to the default
3863 $nickname = $username;
3864 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3865 }
3866 }
3867
3868 // Make sure nickname doesnt get a sig in a sig
3869 $nickname = $this->cleanSigInSig( $nickname );
3870
3871 # If we're still here, make it a link to the user page
3872 $userpage = $user->getUserPage();
3873 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3874 }
3875
3876 /**
3877 * Check that the user's signature contains no bad XML
3878 *
3879 * @param string $text
3880 * @return mixed An expanded string, or false if invalid.
3881 */
3882 function validateSig( $text ) {
3883 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3884 }
3885
3886 /**
3887 * Clean up signature text
3888 *
3889 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3890 * 2) Substitute all transclusions
3891 *
3892 * @param string $text
3893 * @param $parsing Whether we're cleaning (preferences save) or parsing
3894 * @return string Signature text
3895 */
3896 function cleanSig( $text, $parsing = false ) {
3897 global $wgTitle;
3898 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI : OT_MSG );
3899
3900 $substWord = MagicWord::get( 'subst' );
3901 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3902 $substText = '{{' . $substWord->getSynonym( 0 );
3903
3904 $text = preg_replace( $substRegex, $substText, $text );
3905 $text = $this->cleanSigInSig( $text );
3906 $text = $this->replaceVariables( $text );
3907
3908 $this->clearState();
3909 return $text;
3910 }
3911
3912 /**
3913 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3914 * @param string $text
3915 * @return string Signature text with /~{3,5}/ removed
3916 */
3917 function cleanSigInSig( $text ) {
3918 $text = preg_replace( '/~{3,5}/', '', $text );
3919 return $text;
3920 }
3921
3922 /**
3923 * Set up some variables which are usually set up in parse()
3924 * so that an external function can call some class members with confidence
3925 * @public
3926 */
3927 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3928 $this->mTitle =& $title;
3929 $this->mOptions = $options;
3930 $this->setOutputType( $outputType );
3931 if ( $clearState ) {
3932 $this->clearState();
3933 }
3934 }
3935
3936 /**
3937 * Transform a MediaWiki message by replacing magic variables.
3938 *
3939 * @param string $text the text to transform
3940 * @param ParserOptions $options options
3941 * @return string the text with variables substituted
3942 * @public
3943 */
3944 function transformMsg( $text, $options ) {
3945 global $wgTitle;
3946 static $executing = false;
3947
3948 $fname = "Parser::transformMsg";
3949
3950 # Guard against infinite recursion
3951 if ( $executing ) {
3952 return $text;
3953 }
3954 $executing = true;
3955
3956 wfProfileIn($fname);
3957
3958 if ( $wgTitle && !( $wgTitle instanceof FakeTitle ) ) {
3959 $this->mTitle = $wgTitle;
3960 } else {
3961 $this->mTitle = Title::newFromText('msg');
3962 }
3963 $this->mOptions = $options;
3964 $this->setOutputType( OT_MSG );
3965 $this->clearState();
3966 $text = $this->replaceVariables( $text );
3967
3968 $executing = false;
3969 wfProfileOut($fname);
3970 return $text;
3971 }
3972
3973 /**
3974 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3975 * The callback should have the following form:
3976 * function myParserHook( $text, $params, &$parser ) { ... }
3977 *
3978 * Transform and return $text. Use $parser for any required context, e.g. use
3979 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3980 *
3981 * @public
3982 *
3983 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3984 * @param mixed $callback The callback function (and object) to use for the tag
3985 *
3986 * @return The old value of the mTagHooks array associated with the hook
3987 */
3988 function setHook( $tag, $callback ) {
3989 $tag = strtolower( $tag );
3990 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
3991 $this->mTagHooks[$tag] = $callback;
3992
3993 return $oldVal;
3994 }
3995
3996 function setTransparentTagHook( $tag, $callback ) {
3997 $tag = strtolower( $tag );
3998 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
3999 $this->mTransparentTagHooks[$tag] = $callback;
4000
4001 return $oldVal;
4002 }
4003
4004 /**
4005 * Create a function, e.g. {{sum:1|2|3}}
4006 * The callback function should have the form:
4007 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4008 *
4009 * The callback may either return the text result of the function, or an array with the text
4010 * in element 0, and a number of flags in the other elements. The names of the flags are
4011 * specified in the keys. Valid flags are:
4012 * found The text returned is valid, stop processing the template. This
4013 * is on by default.
4014 * nowiki Wiki markup in the return value should be escaped
4015 * noparse Unsafe HTML tags should not be stripped, etc.
4016 * noargs Don't replace triple-brace arguments in the return value
4017 * isHTML The returned text is HTML, armour it against wikitext transformation
4018 *
4019 * @public
4020 *
4021 * @param string $id The magic word ID
4022 * @param mixed $callback The callback function (and object) to use
4023 * @param integer $flags a combination of the following flags:
4024 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4025 *
4026 * @return The old callback function for this name, if any
4027 */
4028 function setFunctionHook( $id, $callback, $flags = 0 ) {
4029 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id] : null;
4030 $this->mFunctionHooks[$id] = $callback;
4031
4032 # Add to function cache
4033 $mw = MagicWord::get( $id );
4034 if( !$mw )
4035 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4036
4037 $synonyms = $mw->getSynonyms();
4038 $sensitive = intval( $mw->isCaseSensitive() );
4039
4040 foreach ( $synonyms as $syn ) {
4041 # Case
4042 if ( !$sensitive ) {
4043 $syn = strtolower( $syn );
4044 }
4045 # Add leading hash
4046 if ( !( $flags & SFH_NO_HASH ) ) {
4047 $syn = '#' . $syn;
4048 }
4049 # Remove trailing colon
4050 if ( substr( $syn, -1, 1 ) == ':' ) {
4051 $syn = substr( $syn, 0, -1 );
4052 }
4053 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4054 }
4055 return $oldVal;
4056 }
4057
4058 /**
4059 * Get all registered function hook identifiers
4060 *
4061 * @return array
4062 */
4063 function getFunctionHooks() {
4064 return array_keys( $this->mFunctionHooks );
4065 }
4066
4067 /**
4068 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4069 * Placeholders created in Skin::makeLinkObj()
4070 * Returns an array of links found, indexed by PDBK:
4071 * 0 - broken
4072 * 1 - normal link
4073 * 2 - stub
4074 * $options is a bit field, RLH_FOR_UPDATE to select for update
4075 */
4076 function replaceLinkHolders( &$text, $options = 0 ) {
4077 global $wgUser;
4078 global $wgContLang;
4079
4080 $fname = 'Parser::replaceLinkHolders';
4081 wfProfileIn( $fname );
4082
4083 $pdbks = array();
4084 $colours = array();
4085 $sk = $this->mOptions->getSkin();
4086 $linkCache =& LinkCache::singleton();
4087
4088 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
4089 wfProfileIn( $fname.'-check' );
4090 $dbr = wfGetDB( DB_SLAVE );
4091 $page = $dbr->tableName( 'page' );
4092 $threshold = $wgUser->getOption('stubthreshold');
4093
4094 # Sort by namespace
4095 asort( $this->mLinkHolders['namespaces'] );
4096
4097 # Generate query
4098 $query = false;
4099 $current = null;
4100 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4101 # Make title object
4102 $title = $this->mLinkHolders['titles'][$key];
4103
4104 # Skip invalid entries.
4105 # Result will be ugly, but prevents crash.
4106 if ( is_null( $title ) ) {
4107 continue;
4108 }
4109 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4110
4111 # Check if it's a static known link, e.g. interwiki
4112 if ( $title->isAlwaysKnown() ) {
4113 $colours[$pdbk] = 1;
4114 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4115 $colours[$pdbk] = 1;
4116 $this->mOutput->addLink( $title, $id );
4117 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4118 $colours[$pdbk] = 0;
4119 } elseif ( $title->getNamespace() == NS_SPECIAL && !SpecialPage::exists( $pdbk ) ) {
4120 $colours[$pdbk] = 0;
4121 } else {
4122 # Not in the link cache, add it to the query
4123 if ( !isset( $current ) ) {
4124 $current = $ns;
4125 $query = "SELECT page_id, page_namespace, page_title";
4126 if ( $threshold > 0 ) {
4127 $query .= ', page_len, page_is_redirect';
4128 }
4129 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4130 } elseif ( $current != $ns ) {
4131 $current = $ns;
4132 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4133 } else {
4134 $query .= ', ';
4135 }
4136
4137 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
4138 }
4139 }
4140 if ( $query ) {
4141 $query .= '))';
4142 if ( $options & RLH_FOR_UPDATE ) {
4143 $query .= ' FOR UPDATE';
4144 }
4145
4146 $res = $dbr->query( $query, $fname );
4147
4148 # Fetch data and form into an associative array
4149 # non-existent = broken
4150 # 1 = known
4151 # 2 = stub
4152 while ( $s = $dbr->fetchObject($res) ) {
4153 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
4154 $pdbk = $title->getPrefixedDBkey();
4155 $linkCache->addGoodLinkObj( $s->page_id, $title );
4156 $this->mOutput->addLink( $title, $s->page_id );
4157
4158 $colours[$pdbk] = ( $threshold == 0 || (
4159 $s->page_len >= $threshold || # always true if $threshold <= 0
4160 $s->page_is_redirect ||
4161 !Namespace::isContent( $s->page_namespace ) )
4162 ? 1 : 2 );
4163 }
4164 }
4165 wfProfileOut( $fname.'-check' );
4166
4167 # Do a second query for different language variants of links and categories
4168 if($wgContLang->hasVariants()){
4169 $linkBatch = new LinkBatch();
4170 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4171 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4172 $varCategories = array(); // category replacements oldDBkey => newDBkey
4173
4174 $categories = $this->mOutput->getCategoryLinks();
4175
4176 // Add variants of links to link batch
4177 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4178 $title = $this->mLinkHolders['titles'][$key];
4179 if ( is_null( $title ) )
4180 continue;
4181
4182 $pdbk = $title->getPrefixedDBkey();
4183 $titleText = $title->getText();
4184
4185 // generate all variants of the link title text
4186 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4187
4188 // if link was not found (in first query), add all variants to query
4189 if ( !isset($colours[$pdbk]) ){
4190 foreach($allTextVariants as $textVariant){
4191 if($textVariant != $titleText){
4192 $variantTitle = Title::makeTitle( $ns, $textVariant );
4193 if(is_null($variantTitle)) continue;
4194 $linkBatch->addObj( $variantTitle );
4195 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4196 }
4197 }
4198 }
4199 }
4200
4201 // process categories, check if a category exists in some variant
4202 foreach( $categories as $category ){
4203 $variants = $wgContLang->convertLinkToAllVariants($category);
4204 foreach($variants as $variant){
4205 if($variant != $category){
4206 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
4207 if(is_null($variantTitle)) continue;
4208 $linkBatch->addObj( $variantTitle );
4209 $categoryMap[$variant] = $category;
4210 }
4211 }
4212 }
4213
4214
4215 if(!$linkBatch->isEmpty()){
4216 // construct query
4217 $titleClause = $linkBatch->constructSet('page', $dbr);
4218
4219 $variantQuery = "SELECT page_id, page_namespace, page_title";
4220 if ( $threshold > 0 ) {
4221 $variantQuery .= ', page_len, page_is_redirect';
4222 }
4223
4224 $variantQuery .= " FROM $page WHERE $titleClause";
4225 if ( $options & RLH_FOR_UPDATE ) {
4226 $variantQuery .= ' FOR UPDATE';
4227 }
4228
4229 $varRes = $dbr->query( $variantQuery, $fname );
4230
4231 // for each found variants, figure out link holders and replace
4232 while ( $s = $dbr->fetchObject($varRes) ) {
4233
4234 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
4235 $varPdbk = $variantTitle->getPrefixedDBkey();
4236 $vardbk = $variantTitle->getDBkey();
4237
4238 $holderKeys = array();
4239 if(isset($variantMap[$varPdbk])){
4240 $holderKeys = $variantMap[$varPdbk];
4241 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle );
4242 $this->mOutput->addLink( $variantTitle, $s->page_id );
4243 }
4244
4245 // loop over link holders
4246 foreach($holderKeys as $key){
4247 $title = $this->mLinkHolders['titles'][$key];
4248 if ( is_null( $title ) ) continue;
4249
4250 $pdbk = $title->getPrefixedDBkey();
4251
4252 if(!isset($colours[$pdbk])){
4253 // found link in some of the variants, replace the link holder data
4254 $this->mLinkHolders['titles'][$key] = $variantTitle;
4255 $this->mLinkHolders['dbkeys'][$key] = $variantTitle->getDBkey();
4256
4257 // set pdbk and colour
4258 $pdbks[$key] = $varPdbk;
4259 if ( $threshold > 0 ) {
4260 $size = $s->page_len;
4261 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
4262 $colours[$varPdbk] = 1;
4263 } else {
4264 $colours[$varPdbk] = 2;
4265 }
4266 }
4267 else {
4268 $colours[$varPdbk] = 1;
4269 }
4270 }
4271 }
4272
4273 // check if the object is a variant of a category
4274 if(isset($categoryMap[$vardbk])){
4275 $oldkey = $categoryMap[$vardbk];
4276 if($oldkey != $vardbk)
4277 $varCategories[$oldkey]=$vardbk;
4278 }
4279 }
4280
4281 // rebuild the categories in original order (if there are replacements)
4282 if(count($varCategories)>0){
4283 $newCats = array();
4284 $originalCats = $this->mOutput->getCategories();
4285 foreach($originalCats as $cat => $sortkey){
4286 // make the replacement
4287 if( array_key_exists($cat,$varCategories) )
4288 $newCats[$varCategories[$cat]] = $sortkey;
4289 else $newCats[$cat] = $sortkey;
4290 }
4291 $this->mOutput->setCategoryLinks($newCats);
4292 }
4293 }
4294 }
4295
4296 # Construct search and replace arrays
4297 wfProfileIn( $fname.'-construct' );
4298 $replacePairs = array();
4299 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4300 $pdbk = $pdbks[$key];
4301 $searchkey = "<!--LINK $key-->";
4302 $title = $this->mLinkHolders['titles'][$key];
4303 if ( empty( $colours[$pdbk] ) ) {
4304 $linkCache->addBadLinkObj( $title );
4305 $colours[$pdbk] = 0;
4306 $this->mOutput->addLink( $title, 0 );
4307 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4308 $this->mLinkHolders['texts'][$key],
4309 $this->mLinkHolders['queries'][$key] );
4310 } elseif ( $colours[$pdbk] == 1 ) {
4311 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4312 $this->mLinkHolders['texts'][$key],
4313 $this->mLinkHolders['queries'][$key] );
4314 } elseif ( $colours[$pdbk] == 2 ) {
4315 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4316 $this->mLinkHolders['texts'][$key],
4317 $this->mLinkHolders['queries'][$key] );
4318 }
4319 }
4320 $replacer = new HashtableReplacer( $replacePairs, 1 );
4321 wfProfileOut( $fname.'-construct' );
4322
4323 # Do the thing
4324 wfProfileIn( $fname.'-replace' );
4325 $text = preg_replace_callback(
4326 '/(<!--LINK .*?-->)/',
4327 $replacer->cb(),
4328 $text);
4329
4330 wfProfileOut( $fname.'-replace' );
4331 }
4332
4333 # Now process interwiki link holders
4334 # This is quite a bit simpler than internal links
4335 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4336 wfProfileIn( $fname.'-interwiki' );
4337 # Make interwiki link HTML
4338 $replacePairs = array();
4339 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4340 $title = $this->mInterwikiLinkHolders['titles'][$key];
4341 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4342 }
4343 $replacer = new HashtableReplacer( $replacePairs, 1 );
4344
4345 $text = preg_replace_callback(
4346 '/<!--IWLINK (.*?)-->/',
4347 $replacer->cb(),
4348 $text );
4349 wfProfileOut( $fname.'-interwiki' );
4350 }
4351
4352 wfProfileOut( $fname );
4353 return $colours;
4354 }
4355
4356 /**
4357 * Replace <!--LINK--> link placeholders with plain text of links
4358 * (not HTML-formatted).
4359 * @param string $text
4360 * @return string
4361 */
4362 function replaceLinkHoldersText( $text ) {
4363 $fname = 'Parser::replaceLinkHoldersText';
4364 wfProfileIn( $fname );
4365
4366 $text = preg_replace_callback(
4367 '/<!--(LINK|IWLINK) (.*?)-->/',
4368 array( &$this, 'replaceLinkHoldersTextCallback' ),
4369 $text );
4370
4371 wfProfileOut( $fname );
4372 return $text;
4373 }
4374
4375 /**
4376 * @param array $matches
4377 * @return string
4378 * @private
4379 */
4380 function replaceLinkHoldersTextCallback( $matches ) {
4381 $type = $matches[1];
4382 $key = $matches[2];
4383 if( $type == 'LINK' ) {
4384 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4385 return $this->mLinkHolders['texts'][$key];
4386 }
4387 } elseif( $type == 'IWLINK' ) {
4388 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4389 return $this->mInterwikiLinkHolders['texts'][$key];
4390 }
4391 }
4392 return $matches[0];
4393 }
4394
4395 /**
4396 * Tag hook handler for 'pre'.
4397 */
4398 function renderPreTag( $text, $attribs ) {
4399 // Backwards-compatibility hack
4400 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4401
4402 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4403 return wfOpenElement( 'pre', $attribs ) .
4404 Xml::escapeTagsOnly( $content ) .
4405 '</pre>';
4406 }
4407
4408 /**
4409 * Renders an image gallery from a text with one line per image.
4410 * text labels may be given by using |-style alternative text. E.g.
4411 * Image:one.jpg|The number "1"
4412 * Image:tree.jpg|A tree
4413 * given as text will return the HTML of a gallery with two images,
4414 * labeled 'The number "1"' and
4415 * 'A tree'.
4416 */
4417 function renderImageGallery( $text, $params ) {
4418 $ig = new ImageGallery();
4419 $ig->setContextTitle( $this->mTitle );
4420 $ig->setShowBytes( false );
4421 $ig->setShowFilename( false );
4422 $ig->setParser( $this );
4423 $ig->setHideBadImages();
4424 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4425 $ig->useSkin( $this->mOptions->getSkin() );
4426 $ig->mRevisionId = $this->mRevisionId;
4427
4428 if( isset( $params['caption'] ) ) {
4429 $caption = $params['caption'];
4430 $caption = htmlspecialchars( $caption );
4431 $caption = $this->replaceInternalLinks( $caption );
4432 $ig->setCaptionHtml( $caption );
4433 }
4434 if( isset( $params['perrow'] ) ) {
4435 $ig->setPerRow( $params['perrow'] );
4436 }
4437 if( isset( $params['widths'] ) ) {
4438 $ig->setWidths( $params['widths'] );
4439 }
4440 if( isset( $params['heights'] ) ) {
4441 $ig->setHeights( $params['heights'] );
4442 }
4443
4444 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4445
4446 $lines = explode( "\n", $text );
4447 foreach ( $lines as $line ) {
4448 # match lines like these:
4449 # Image:someimage.jpg|This is some image
4450 $matches = array();
4451 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4452 # Skip empty lines
4453 if ( count( $matches ) == 0 ) {
4454 continue;
4455 }
4456 $tp = Title::newFromText( $matches[1] );
4457 $nt =& $tp;
4458 if( is_null( $nt ) ) {
4459 # Bogus title. Ignore these so we don't bomb out later.
4460 continue;
4461 }
4462 if ( isset( $matches[3] ) ) {
4463 $label = $matches[3];
4464 } else {
4465 $label = '';
4466 }
4467
4468 $pout = $this->parse( $label,
4469 $this->mTitle,
4470 $this->mOptions,
4471 false, // Strip whitespace...?
4472 false // Don't clear state!
4473 );
4474 $html = $pout->getText();
4475
4476 $ig->add( $nt, $html );
4477
4478 # Only add real images (bug #5586)
4479 if ( $nt->getNamespace() == NS_IMAGE ) {
4480 $this->mOutput->addImage( $nt->getDBkey() );
4481 }
4482 }
4483 return $ig->toHTML();
4484 }
4485
4486 function getImageParams( $handler ) {
4487 if ( $handler ) {
4488 $handlerClass = get_class( $handler );
4489 } else {
4490 $handlerClass = '';
4491 }
4492 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4493 // Initialise static lists
4494 static $internalParamNames = array(
4495 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4496 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4497 'bottom', 'text-bottom' ),
4498 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4499 'upright', 'border' ),
4500 );
4501 static $internalParamMap;
4502 if ( !$internalParamMap ) {
4503 $internalParamMap = array();
4504 foreach ( $internalParamNames as $type => $names ) {
4505 foreach ( $names as $name ) {
4506 $magicName = str_replace( '-', '_', "img_$name" );
4507 $internalParamMap[$magicName] = array( $type, $name );
4508 }
4509 }
4510 }
4511
4512 // Add handler params
4513 $paramMap = $internalParamMap;
4514 if ( $handler ) {
4515 $handlerParamMap = $handler->getParamMap();
4516 foreach ( $handlerParamMap as $magic => $paramName ) {
4517 $paramMap[$magic] = array( 'handler', $paramName );
4518 }
4519 }
4520 $this->mImageParams[$handlerClass] = $paramMap;
4521 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4522 }
4523 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4524 }
4525
4526 /**
4527 * Parse image options text and use it to make an image
4528 */
4529 function makeImage( $title, $options ) {
4530 # @TODO: let the MediaHandler specify its transform parameters
4531 #
4532 # Check if the options text is of the form "options|alt text"
4533 # Options are:
4534 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4535 # * left no resizing, just left align. label is used for alt= only
4536 # * right same, but right aligned
4537 # * none same, but not aligned
4538 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4539 # * center center the image
4540 # * framed Keep original image size, no magnify-button.
4541 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4542 # * upright reduce width for upright images, rounded to full __0 px
4543 # * border draw a 1px border around the image
4544 # vertical-align values (no % or length right now):
4545 # * baseline
4546 # * sub
4547 # * super
4548 # * top
4549 # * text-top
4550 # * middle
4551 # * bottom
4552 # * text-bottom
4553
4554 $parts = array_map( 'trim', explode( '|', $options) );
4555 $sk = $this->mOptions->getSkin();
4556
4557 # Give extensions a chance to select the file revision for us
4558 $skip = $time = false;
4559 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4560
4561 if ( $skip ) {
4562 return $sk->makeLinkObj( $title );
4563 }
4564
4565 # Get parameter map
4566 $file = wfFindFile( $title, $time );
4567 $handler = $file ? $file->getHandler() : false;
4568
4569 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4570
4571 # Process the input parameters
4572 $caption = '';
4573 $params = array( 'frame' => array(), 'handler' => array(),
4574 'horizAlign' => array(), 'vertAlign' => array() );
4575 foreach( $parts as $part ) {
4576 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4577 if ( isset( $paramMap[$magicName] ) ) {
4578 list( $type, $paramName ) = $paramMap[$magicName];
4579 $params[$type][$paramName] = $value;
4580
4581 // Special case; width and height come in one variable together
4582 if( $type == 'handler' && $paramName == 'width' ) {
4583 $m = array();
4584 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4585 $params[$type]['width'] = intval( $m[1] );
4586 $params[$type]['height'] = intval( $m[2] );
4587 } else {
4588 $params[$type]['width'] = intval( $value );
4589 }
4590 }
4591 } else {
4592 $caption = $part;
4593 }
4594 }
4595
4596 # Process alignment parameters
4597 if ( $params['horizAlign'] ) {
4598 $params['frame']['align'] = key( $params['horizAlign'] );
4599 }
4600 if ( $params['vertAlign'] ) {
4601 $params['frame']['valign'] = key( $params['vertAlign'] );
4602 }
4603
4604 # Validate the handler parameters
4605 if ( $handler ) {
4606 foreach ( $params['handler'] as $name => $value ) {
4607 if ( !$handler->validateParam( $name, $value ) ) {
4608 unset( $params['handler'][$name] );
4609 }
4610 }
4611 }
4612
4613 # Strip bad stuff out of the alt text
4614 $alt = $this->replaceLinkHoldersText( $caption );
4615
4616 # make sure there are no placeholders in thumbnail attributes
4617 # that are later expanded to html- so expand them now and
4618 # remove the tags
4619 $alt = $this->mStripState->unstripBoth( $alt );
4620 $alt = Sanitizer::stripAllTags( $alt );
4621
4622 $params['frame']['alt'] = $alt;
4623 $params['frame']['caption'] = $caption;
4624
4625 # Linker does the rest
4626 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4627
4628 # Give the handler a chance to modify the parser object
4629 if ( $handler ) {
4630 $handler->parserTransformHook( $this, $file );
4631 }
4632
4633 return $ret;
4634 }
4635
4636 /**
4637 * Set a flag in the output object indicating that the content is dynamic and
4638 * shouldn't be cached.
4639 */
4640 function disableCache() {
4641 wfDebug( "Parser output marked as uncacheable.\n" );
4642 $this->mOutput->mCacheTime = -1;
4643 }
4644
4645 /**#@+
4646 * Callback from the Sanitizer for expanding items found in HTML attribute
4647 * values, so they can be safely tested and escaped.
4648 * @param string $text
4649 * @param array $args
4650 * @return string
4651 * @private
4652 */
4653 function attributeStripCallback( &$text, $args ) {
4654 $text = $this->replaceVariables( $text, $args );
4655 $text = $this->mStripState->unstripBoth( $text );
4656 return $text;
4657 }
4658
4659 /**#@-*/
4660
4661 /**#@+
4662 * Accessor/mutator
4663 */
4664 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4665 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4666 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4667 /**#@-*/
4668
4669 /**#@+
4670 * Accessor
4671 */
4672 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4673 /**#@-*/
4674
4675
4676 /**
4677 * Break wikitext input into sections, and either pull or replace
4678 * some particular section's text.
4679 *
4680 * External callers should use the getSection and replaceSection methods.
4681 *
4682 * @param $text Page wikitext
4683 * @param $section Numbered section. 0 pulls the text before the first
4684 * heading; other numbers will pull the given section
4685 * along with its lower-level subsections.
4686 * @param $mode One of "get" or "replace"
4687 * @param $newtext Replacement text for section data.
4688 * @return string for "get", the extracted section text.
4689 * for "replace", the whole page with the section replaced.
4690 */
4691 private function extractSections( $text, $section, $mode, $newtext='' ) {
4692 # I.... _hope_ this is right.
4693 # Otherwise, sometimes we don't have things initialized properly.
4694 $this->clearState();
4695
4696 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4697 # comments to be stripped as well)
4698 $stripState = new StripState;
4699
4700 $oldOutputType = $this->mOutputType;
4701 $oldOptions = $this->mOptions;
4702 $this->mOptions = new ParserOptions();
4703 $this->setOutputType( OT_WIKI );
4704
4705 $striptext = $this->strip( $text, $stripState, true );
4706
4707 $this->setOutputType( $oldOutputType );
4708 $this->mOptions = $oldOptions;
4709
4710 # now that we can be sure that no pseudo-sections are in the source,
4711 # split it up by section
4712 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4713 $comment = "(?:$uniq-!--.*?QINU\x07)";
4714 $secs = preg_split(
4715 "/
4716 (
4717 ^
4718 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4719 (=+) # Should this be limited to 6?
4720 .+? # Section title...
4721 \\2 # Ending = count must match start
4722 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4723 $
4724 |
4725 <h([1-6])\b.*?>
4726 .*?
4727 <\/h\\3\s*>
4728 )
4729 /mix",
4730 $striptext, -1,
4731 PREG_SPLIT_DELIM_CAPTURE);
4732
4733 if( $mode == "get" ) {
4734 if( $section == 0 ) {
4735 // "Section 0" returns the content before any other section.
4736 $rv = $secs[0];
4737 } else {
4738 //track missing section, will replace if found.
4739 $rv = $newtext;
4740 }
4741 } elseif( $mode == "replace" ) {
4742 if( $section == 0 ) {
4743 $rv = $newtext . "\n\n";
4744 $remainder = true;
4745 } else {
4746 $rv = $secs[0];
4747 $remainder = false;
4748 }
4749 }
4750 $count = 0;
4751 $sectionLevel = 0;
4752 for( $index = 1; $index < count( $secs ); ) {
4753 $headerLine = $secs[$index++];
4754 if( $secs[$index] ) {
4755 // A wiki header
4756 $headerLevel = strlen( $secs[$index++] );
4757 } else {
4758 // An HTML header
4759 $index++;
4760 $headerLevel = intval( $secs[$index++] );
4761 }
4762 $content = $secs[$index++];
4763
4764 $count++;
4765 if( $mode == "get" ) {
4766 if( $count == $section ) {
4767 $rv = $headerLine . $content;
4768 $sectionLevel = $headerLevel;
4769 } elseif( $count > $section ) {
4770 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4771 $rv .= $headerLine . $content;
4772 } else {
4773 // Broke out to a higher-level section
4774 break;
4775 }
4776 }
4777 } elseif( $mode == "replace" ) {
4778 if( $count < $section ) {
4779 $rv .= $headerLine . $content;
4780 } elseif( $count == $section ) {
4781 $rv .= $newtext . "\n\n";
4782 $sectionLevel = $headerLevel;
4783 } elseif( $count > $section ) {
4784 if( $headerLevel <= $sectionLevel ) {
4785 // Passed the section's sub-parts.
4786 $remainder = true;
4787 }
4788 if( $remainder ) {
4789 $rv .= $headerLine . $content;
4790 }
4791 }
4792 }
4793 }
4794 if (is_string($rv))
4795 # reinsert stripped tags
4796 $rv = trim( $stripState->unstripBoth( $rv ) );
4797
4798 return $rv;
4799 }
4800
4801 /**
4802 * This function returns the text of a section, specified by a number ($section).
4803 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4804 * the first section before any such heading (section 0).
4805 *
4806 * If a section contains subsections, these are also returned.
4807 *
4808 * @param $text String: text to look in
4809 * @param $section Integer: section number
4810 * @param $deftext: default to return if section is not found
4811 * @return string text of the requested section
4812 */
4813 public function getSection( $text, $section, $deftext='' ) {
4814 return $this->extractSections( $text, $section, "get", $deftext );
4815 }
4816
4817 public function replaceSection( $oldtext, $section, $text ) {
4818 return $this->extractSections( $oldtext, $section, "replace", $text );
4819 }
4820
4821 /**
4822 * Get the timestamp associated with the current revision, adjusted for
4823 * the default server-local timestamp
4824 */
4825 function getRevisionTimestamp() {
4826 if ( is_null( $this->mRevisionTimestamp ) ) {
4827 wfProfileIn( __METHOD__ );
4828 global $wgContLang;
4829 $dbr = wfGetDB( DB_SLAVE );
4830 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4831 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4832
4833 // Normalize timestamp to internal MW format for timezone processing.
4834 // This has the added side-effect of replacing a null value with
4835 // the current time, which gives us more sensible behavior for
4836 // previews.
4837 $timestamp = wfTimestamp( TS_MW, $timestamp );
4838
4839 // The cryptic '' timezone parameter tells to use the site-default
4840 // timezone offset instead of the user settings.
4841 //
4842 // Since this value will be saved into the parser cache, served
4843 // to other users, and potentially even used inside links and such,
4844 // it needs to be consistent for all visitors.
4845 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4846
4847 wfProfileOut( __METHOD__ );
4848 }
4849 return $this->mRevisionTimestamp;
4850 }
4851
4852 /**
4853 * Mutator for $mDefaultSort
4854 *
4855 * @param $sort New value
4856 */
4857 public function setDefaultSort( $sort ) {
4858 $this->mDefaultSort = $sort;
4859 }
4860
4861 /**
4862 * Accessor for $mDefaultSort
4863 * Will use the title/prefixed title if none is set
4864 *
4865 * @return string
4866 */
4867 public function getDefaultSort() {
4868 if( $this->mDefaultSort !== false ) {
4869 return $this->mDefaultSort;
4870 } else {
4871 return $this->mTitle->getNamespace() == NS_CATEGORY
4872 ? $this->mTitle->getText()
4873 : $this->mTitle->getPrefixedText();
4874 }
4875 }
4876
4877 /**
4878 * Try to guess the section anchor name based on a wikitext fragment
4879 * presumably extracted from a heading, for example "Header" from
4880 * "== Header ==".
4881 */
4882 public function guessSectionNameFromWikiText( $text ) {
4883 # Strip out wikitext links(they break the anchor)
4884 $text = $this->stripSectionName( $text );
4885 $headline = Sanitizer::decodeCharReferences( $text );
4886 # strip out HTML
4887 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
4888 $headline = trim( $headline );
4889 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4890 $replacearray = array(
4891 '%3A' => ':',
4892 '%' => '.'
4893 );
4894 return str_replace(
4895 array_keys( $replacearray ),
4896 array_values( $replacearray ),
4897 $sectionanchor );
4898 }
4899
4900 /**
4901 * Strips a text string of wikitext for use in a section anchor
4902 *
4903 * Accepts a text string and then removes all wikitext from the
4904 * string and leaves only the resultant text (i.e. the result of
4905 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4906 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4907 * to create valid section anchors by mimicing the output of the
4908 * parser when headings are parsed.
4909 *
4910 * @param $text string Text string to be stripped of wikitext
4911 * for use in a Section anchor
4912 * @return Filtered text string
4913 */
4914 public function stripSectionName( $text ) {
4915 # Strip internal link markup
4916 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4917 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4918
4919 # Strip external link markup (FIXME: Not Tolerant to blank link text
4920 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4921 # on how many empty links there are on the page - need to figure that out.
4922 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4923
4924 # Parse wikitext quotes (italics & bold)
4925 $text = $this->doQuotes($text);
4926
4927 # Strip HTML tags
4928 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
4929 return $text;
4930 }
4931 }
4932
4933 /**
4934 * @todo document, briefly.
4935 * @addtogroup Parser
4936 */
4937 class OnlyIncludeReplacer {
4938 var $output = '';
4939
4940 function replace( $matches ) {
4941 if ( substr( $matches[1], -1 ) == "\n" ) {
4942 $this->output .= substr( $matches[1], 0, -1 );
4943 } else {
4944 $this->output .= $matches[1];
4945 }
4946 }
4947 }
4948
4949 /**
4950 * @todo document, briefly.
4951 * @addtogroup Parser
4952 */
4953 class StripState {
4954 var $general, $nowiki;
4955
4956 function __construct() {
4957 $this->general = new ReplacementArray;
4958 $this->nowiki = new ReplacementArray;
4959 }
4960
4961 function unstripGeneral( $text ) {
4962 wfProfileIn( __METHOD__ );
4963 $text = $this->general->replace( $text );
4964 wfProfileOut( __METHOD__ );
4965 return $text;
4966 }
4967
4968 function unstripNoWiki( $text ) {
4969 wfProfileIn( __METHOD__ );
4970 $text = $this->nowiki->replace( $text );
4971 wfProfileOut( __METHOD__ );
4972 return $text;
4973 }
4974
4975 function unstripBoth( $text ) {
4976 wfProfileIn( __METHOD__ );
4977 $text = $this->general->replace( $text );
4978 $text = $this->nowiki->replace( $text );
4979 wfProfileOut( __METHOD__ );
4980 return $text;
4981 }
4982 }