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