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