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