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