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