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