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