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