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