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