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