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