Drop support for XHTML 1.0
[lhc/web/wiklou.git] / includes / parser / Parser.php
1 <?php
2 /**
3 * PHP parser that converts wiki markup to HTML.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Parser
22 */
23
24 /**
25 * @defgroup Parser Parser
26 */
27
28 /**
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
33 *
34 * There are seven main entry points into the Parser class:
35 *
36 * - Parser::parse()
37 * produces HTML output
38 * - Parser::preSaveTransform().
39 * produces altered wiki markup.
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * Cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * Return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * Replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * Removes <noinclude> sections, and <includeonly> tags.
50 *
51 * Globals used:
52 * object: $wgContLang
53 *
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
55 *
56 * @par Settings:
57 * $wgLocaltimezone
58 * $wgNamespacesWithSubpages
59 *
60 * @par Settings only within ParserOptions:
61 * $wgAllowExternalImages
62 * $wgAllowSpecialInclusion
63 * $wgInterwikiMagic
64 * $wgMaxArticleSize
65 *
66 * @ingroup Parser
67 */
68 class Parser {
69 /**
70 * Update this version number when the ParserOutput format
71 * changes in an incompatible way, so the parser cache
72 * can automatically discard old data.
73 */
74 const VERSION = '1.6.4';
75
76 /**
77 * Update this version number when the output of serialiseHalfParsedText()
78 * changes in an incompatible way
79 */
80 const HALF_PARSED_VERSION = 2;
81
82 # Flags for Parser::setFunctionHook
83 # Also available as global constants from Defines.php
84 const SFH_NO_HASH = 1;
85 const SFH_OBJECT_ARGS = 2;
86
87 # Constants needed for external link processing
88 # Everything except bracket, space, or control characters
89 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
90 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
91 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
92 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
93 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94
95 # State constants for the definition list colon extraction
96 const COLON_STATE_TEXT = 0;
97 const COLON_STATE_TAG = 1;
98 const COLON_STATE_TAGSTART = 2;
99 const COLON_STATE_CLOSETAG = 3;
100 const COLON_STATE_TAGSLASH = 4;
101 const COLON_STATE_COMMENT = 5;
102 const COLON_STATE_COMMENTDASH = 6;
103 const COLON_STATE_COMMENTDASHDASH = 7;
104
105 # Flags for preprocessToDom
106 const PTD_FOR_INCLUSION = 1;
107
108 # Allowed values for $this->mOutputType
109 # Parameter to startExternalParse().
110 const OT_HTML = 1; # like parse()
111 const OT_WIKI = 2; # like preSaveTransform()
112 const OT_PREPROCESS = 3; # like preprocess()
113 const OT_MSG = 3;
114 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
115
116 # Marker Suffix needs to be accessible staticly.
117 const MARKER_SUFFIX = "-QINU\x7f";
118
119 # Persistent:
120 var $mTagHooks = array();
121 var $mTransparentTagHooks = array();
122 var $mFunctionHooks = array();
123 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
124 var $mFunctionTagHooks = array();
125 var $mStripList = array();
126 var $mDefaultStripList = array();
127 var $mVarCache = array();
128 var $mImageParams = array();
129 var $mImageParamsMagicArray = array();
130 var $mMarkerIndex = 0;
131 var $mFirstCall = true;
132
133 # Initialised by initialiseVariables()
134
135 /**
136 * @var MagicWordArray
137 */
138 var $mVariables;
139
140 /**
141 * @var MagicWordArray
142 */
143 var $mSubstWords;
144 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
145
146 # Cleared with clearState():
147 /**
148 * @var ParserOutput
149 */
150 var $mOutput;
151 var $mAutonumber, $mDTopen;
152
153 /**
154 * @var StripState
155 */
156 var $mStripState;
157
158 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
159 /**
160 * @var LinkHolderArray
161 */
162 var $mLinkHolders;
163
164 var $mLinkID;
165 var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
166 var $mDefaultSort;
167 var $mTplExpandCache; # empty-frame expansion cache
168 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
169 var $mExpensiveFunctionCount; # number of expensive parser function calls
170 var $mShowToc, $mForceTocPosition;
171
172 /**
173 * @var User
174 */
175 var $mUser; # User object; only used when doing pre-save transform
176
177 # Temporary
178 # These are variables reset at least once per parse regardless of $clearState
179
180 /**
181 * @var ParserOptions
182 */
183 var $mOptions;
184
185 /**
186 * @var Title
187 */
188 var $mTitle; # Title context, used for self-link rendering and similar things
189 var $mOutputType; # Output type, one of the OT_xxx constants
190 var $ot; # Shortcut alias, see setOutputType()
191 var $mRevisionObject; # The revision object of the specified revision ID
192 var $mRevisionId; # ID to display in {{REVISIONID}} tags
193 var $mRevisionTimestamp; # The timestamp of the specified revision ID
194 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
195 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
196 var $mInputSize = false; # For {{PAGESIZE}} on current page.
197
198 /**
199 * @var string
200 */
201 var $mUniqPrefix;
202
203 /**
204 * @var Array with the language name of each language link (i.e. the
205 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
206 * duplicate language links to the ParserOutput.
207 */
208 var $mLangLinkLanguages;
209
210 /**
211 * Constructor
212 *
213 * @param $conf array
214 */
215 public function __construct( $conf = array() ) {
216 $this->mConf = $conf;
217 $this->mUrlProtocols = wfUrlProtocols();
218 $this->mExtLinkBracketedRegex = '/\[(((?i)' . $this->mUrlProtocols . ')' .
219 self::EXT_LINK_URL_CLASS . '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
220 if ( isset( $conf['preprocessorClass'] ) ) {
221 $this->mPreprocessorClass = $conf['preprocessorClass'];
222 } elseif ( defined( 'HPHP_VERSION' ) ) {
223 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
224 $this->mPreprocessorClass = 'Preprocessor_Hash';
225 } elseif ( extension_loaded( 'domxml' ) ) {
226 # PECL extension that conflicts with the core DOM extension (bug 13770)
227 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
228 $this->mPreprocessorClass = 'Preprocessor_Hash';
229 } elseif ( extension_loaded( 'dom' ) ) {
230 $this->mPreprocessorClass = 'Preprocessor_DOM';
231 } else {
232 $this->mPreprocessorClass = 'Preprocessor_Hash';
233 }
234 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" );
235 }
236
237 /**
238 * Reduce memory usage to reduce the impact of circular references
239 */
240 function __destruct() {
241 if ( isset( $this->mLinkHolders ) ) {
242 unset( $this->mLinkHolders );
243 }
244 foreach ( $this as $name => $value ) {
245 unset( $this->$name );
246 }
247 }
248
249 /**
250 * Allow extensions to clean up when the parser is cloned
251 */
252 function __clone() {
253 wfRunHooks( 'ParserCloned', array( $this ) );
254 }
255
256 /**
257 * Do various kinds of initialisation on the first call of the parser
258 */
259 function firstCallInit() {
260 if ( !$this->mFirstCall ) {
261 return;
262 }
263 $this->mFirstCall = false;
264
265 wfProfileIn( __METHOD__ );
266
267 CoreParserFunctions::register( $this );
268 CoreTagHooks::register( $this );
269 $this->initialiseVariables();
270
271 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
272 wfProfileOut( __METHOD__ );
273 }
274
275 /**
276 * Clear Parser state
277 *
278 * @private
279 */
280 function clearState() {
281 wfProfileIn( __METHOD__ );
282 if ( $this->mFirstCall ) {
283 $this->firstCallInit();
284 }
285 $this->mOutput = new ParserOutput;
286 $this->mOptions->registerWatcher( array( $this->mOutput, 'recordOption' ) );
287 $this->mAutonumber = 0;
288 $this->mLastSection = '';
289 $this->mDTopen = false;
290 $this->mIncludeCount = array();
291 $this->mArgStack = false;
292 $this->mInPre = false;
293 $this->mLinkHolders = new LinkHolderArray( $this );
294 $this->mLinkID = 0;
295 $this->mRevisionObject = $this->mRevisionTimestamp =
296 $this->mRevisionId = $this->mRevisionUser = null;
297 $this->mVarCache = array();
298 $this->mUser = null;
299 $this->mLangLinkLanguages = array();
300
301 /**
302 * Prefix for temporary replacement strings for the multipass parser.
303 * \x07 should never appear in input as it's disallowed in XML.
304 * Using it at the front also gives us a little extra robustness
305 * since it shouldn't match when butted up against identifier-like
306 * string constructs.
307 *
308 * Must not consist of all title characters, or else it will change
309 * the behavior of <nowiki> in a link.
310 */
311 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
312 $this->mStripState = new StripState( $this->mUniqPrefix );
313
314 # Clear these on every parse, bug 4549
315 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
316
317 $this->mShowToc = true;
318 $this->mForceTocPosition = false;
319 $this->mIncludeSizes = array(
320 'post-expand' => 0,
321 'arg' => 0,
322 );
323 $this->mPPNodeCount = 0;
324 $this->mGeneratedPPNodeCount = 0;
325 $this->mHighestExpansionDepth = 0;
326 $this->mDefaultSort = false;
327 $this->mHeadings = array();
328 $this->mDoubleUnderscores = array();
329 $this->mExpensiveFunctionCount = 0;
330
331 # Fix cloning
332 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
333 $this->mPreprocessor = null;
334 }
335
336 wfRunHooks( 'ParserClearState', array( &$this ) );
337 wfProfileOut( __METHOD__ );
338 }
339
340 /**
341 * Convert wikitext to HTML
342 * Do not call this function recursively.
343 *
344 * @param string $text text we want to parse
345 * @param $title Title object
346 * @param $options ParserOptions
347 * @param $linestart boolean
348 * @param $clearState boolean
349 * @param int $revid number to pass in {{REVISIONID}}
350 * @return ParserOutput a ParserOutput
351 */
352 public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) {
353 /**
354 * First pass--just handle <nowiki> sections, pass the rest off
355 * to internalParse() which does all the real work.
356 */
357
358 global $wgUseTidy, $wgAlwaysUseTidy;
359 $fname = __METHOD__ . '-' . wfGetCaller();
360 wfProfileIn( __METHOD__ );
361 wfProfileIn( $fname );
362
363 $this->startParse( $title, $options, self::OT_HTML, $clearState );
364
365 $this->mInputSize = strlen( $text );
366
367 # Remove the strip marker tag prefix from the input, if present.
368 if ( $clearState ) {
369 $text = str_replace( $this->mUniqPrefix, '', $text );
370 }
371
372 $oldRevisionId = $this->mRevisionId;
373 $oldRevisionObject = $this->mRevisionObject;
374 $oldRevisionTimestamp = $this->mRevisionTimestamp;
375 $oldRevisionUser = $this->mRevisionUser;
376 if ( $revid !== null ) {
377 $this->mRevisionId = $revid;
378 $this->mRevisionObject = null;
379 $this->mRevisionTimestamp = null;
380 $this->mRevisionUser = null;
381 }
382
383 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
384 # No more strip!
385 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
386 $text = $this->internalParse( $text );
387 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState ) );
388
389 $text = $this->mStripState->unstripGeneral( $text );
390
391 # Clean up special characters, only run once, next-to-last before doBlockLevels
392 $fixtags = array(
393 # french spaces, last one Guillemet-left
394 # only if there is something before the space
395 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&#160;',
396 # french spaces, Guillemet-right
397 '/(\\302\\253) /' => '\\1&#160;',
398 '/&#160;(!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
399 );
400 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
401
402 $text = $this->doBlockLevels( $text, $linestart );
403
404 $this->replaceLinkHolders( $text );
405
406 /**
407 * The input doesn't get language converted if
408 * a) It's disabled
409 * b) Content isn't converted
410 * c) It's a conversion table
411 * d) it is an interface message (which is in the user language)
412 */
413 if ( !( $options->getDisableContentConversion()
414 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) ) )
415 {
416 if ( !$this->mOptions->getInterfaceMessage() ) {
417 # The position of the convert() call should not be changed. it
418 # assumes that the links are all replaced and the only thing left
419 # is the <nowiki> mark.
420 $text = $this->getConverterLanguage()->convert( $text );
421 }
422 }
423
424 /**
425 * A converted title will be provided in the output object if title and
426 * content conversion are enabled, the article text does not contain
427 * a conversion-suppressing double-underscore tag, and no
428 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
429 * automatic link conversion.
430 */
431 if ( !( $options->getDisableTitleConversion()
432 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
433 || isset( $this->mDoubleUnderscores['notitleconvert'] )
434 || $this->mOutput->getDisplayTitle() !== false ) )
435 {
436 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
437 if ( $convruletitle ) {
438 $this->mOutput->setTitleText( $convruletitle );
439 } else {
440 $titleText = $this->getConverterLanguage()->convertTitle( $title );
441 $this->mOutput->setTitleText( $titleText );
442 }
443 }
444
445 $text = $this->mStripState->unstripNoWiki( $text );
446
447 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
448
449 $text = $this->replaceTransparentTags( $text );
450 $text = $this->mStripState->unstripGeneral( $text );
451
452 $text = Sanitizer::normalizeCharReferences( $text );
453
454 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) {
455 $text = MWTidy::tidy( $text );
456 } else {
457 # attempt to sanitize at least some nesting problems
458 # (bug #2702 and quite a few others)
459 $tidyregs = array(
460 # ''Something [http://www.cool.com cool''] -->
461 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
462 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
463 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
464 # fix up an anchor inside another anchor, only
465 # at least for a single single nested link (bug 3695)
466 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
467 '\\1\\2</a>\\3</a>\\1\\4</a>',
468 # fix div inside inline elements- doBlockLevels won't wrap a line which
469 # contains a div, so fix it up here; replace
470 # div with escaped text
471 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
472 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
473 # remove empty italic or bold tag pairs, some
474 # introduced by rules above
475 '/<([bi])><\/\\1>/' => '',
476 );
477
478 $text = preg_replace(
479 array_keys( $tidyregs ),
480 array_values( $tidyregs ),
481 $text );
482 }
483
484 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
485 $this->limitationWarn( 'expensive-parserfunction',
486 $this->mExpensiveFunctionCount,
487 $this->mOptions->getExpensiveParserFunctionLimit()
488 );
489 }
490
491 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
492
493 # Information on include size limits, for the benefit of users who try to skirt them
494 if ( $this->mOptions->getEnableLimitReport() ) {
495 $max = $this->mOptions->getMaxIncludeSize();
496 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
497 $limitReport =
498 "NewPP limit report\n" .
499 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
500 "Preprocessor generated node count: " .
501 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
502 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
503 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n" .
504 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n" .
505 $PFreport;
506 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
507
508 // Sanitize for comment. Note '‐' in the replacement is U+2010,
509 // which looks much like the problematic '-'.
510 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&amp;' ), $limitReport );
511
512 $text .= "\n<!-- \n$limitReport-->\n";
513
514 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
515 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' .
516 $this->mTitle->getPrefixedDBkey() );
517 }
518 }
519 $this->mOutput->setText( $text );
520
521 $this->mRevisionId = $oldRevisionId;
522 $this->mRevisionObject = $oldRevisionObject;
523 $this->mRevisionTimestamp = $oldRevisionTimestamp;
524 $this->mRevisionUser = $oldRevisionUser;
525 $this->mInputSize = false;
526 wfProfileOut( $fname );
527 wfProfileOut( __METHOD__ );
528
529 return $this->mOutput;
530 }
531
532 /**
533 * Recursive parser entry point that can be called from an extension tag
534 * hook.
535 *
536 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
537 *
538 * @param string $text text extension wants to have parsed
539 * @param $frame PPFrame: The frame to use for expanding any template variables
540 *
541 * @return string
542 */
543 function recursiveTagParse( $text, $frame = false ) {
544 wfProfileIn( __METHOD__ );
545 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
546 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
547 $text = $this->internalParse( $text, false, $frame );
548 wfProfileOut( __METHOD__ );
549 return $text;
550 }
551
552 /**
553 * Expand templates and variables in the text, producing valid, static wikitext.
554 * Also removes comments.
555 * @return mixed|string
556 */
557 function preprocess( $text, Title $title = null, ParserOptions $options, $revid = null ) {
558 wfProfileIn( __METHOD__ );
559 $this->startParse( $title, $options, self::OT_PREPROCESS, true );
560 if ( $revid !== null ) {
561 $this->mRevisionId = $revid;
562 }
563 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
564 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
565 $text = $this->replaceVariables( $text );
566 $text = $this->mStripState->unstripBoth( $text );
567 wfProfileOut( __METHOD__ );
568 return $text;
569 }
570
571 /**
572 * Recursive parser entry point that can be called from an extension tag
573 * hook.
574 *
575 * @param string $text text to be expanded
576 * @param $frame PPFrame: The frame to use for expanding any template variables
577 * @return String
578 * @since 1.19
579 */
580 public function recursivePreprocess( $text, $frame = false ) {
581 wfProfileIn( __METHOD__ );
582 $text = $this->replaceVariables( $text, $frame );
583 $text = $this->mStripState->unstripBoth( $text );
584 wfProfileOut( __METHOD__ );
585 return $text;
586 }
587
588 /**
589 * Process the wikitext for the "?preload=" feature. (bug 5210)
590 *
591 * "<noinclude>", "<includeonly>" etc. are parsed as for template
592 * transclusion, comments, templates, arguments, tags hooks and parser
593 * functions are untouched.
594 *
595 * @param $text String
596 * @param $title Title
597 * @param $options ParserOptions
598 * @return String
599 */
600 public function getPreloadText( $text, Title $title, ParserOptions $options ) {
601 # Parser (re)initialisation
602 $this->startParse( $title, $options, self::OT_PLAIN, true );
603
604 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
605 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
606 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
607 $text = $this->mStripState->unstripBoth( $text );
608 return $text;
609 }
610
611 /**
612 * Get a random string
613 *
614 * @return string
615 */
616 public static function getRandomString() {
617 return wfRandomString( 16 );
618 }
619
620 /**
621 * Set the current user.
622 * Should only be used when doing pre-save transform.
623 *
624 * @param $user Mixed: User object or null (to reset)
625 */
626 function setUser( $user ) {
627 $this->mUser = $user;
628 }
629
630 /**
631 * Accessor for mUniqPrefix.
632 *
633 * @return String
634 */
635 public function uniqPrefix() {
636 if ( !isset( $this->mUniqPrefix ) ) {
637 # @todo FIXME: This is probably *horribly wrong*
638 # LanguageConverter seems to want $wgParser's uniqPrefix, however
639 # if this is called for a parser cache hit, the parser may not
640 # have ever been initialized in the first place.
641 # Not really sure what the heck is supposed to be going on here.
642 return '';
643 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
644 }
645 return $this->mUniqPrefix;
646 }
647
648 /**
649 * Set the context title
650 *
651 * @param $t Title
652 */
653 function setTitle( $t ) {
654 if ( !$t || $t instanceof FakeTitle ) {
655 $t = Title::newFromText( 'NO TITLE' );
656 }
657
658 if ( strval( $t->getFragment() ) !== '' ) {
659 # Strip the fragment to avoid various odd effects
660 $this->mTitle = clone $t;
661 $this->mTitle->setFragment( '' );
662 } else {
663 $this->mTitle = $t;
664 }
665 }
666
667 /**
668 * Accessor for the Title object
669 *
670 * @return Title object
671 */
672 function getTitle() {
673 return $this->mTitle;
674 }
675
676 /**
677 * Accessor/mutator for the Title object
678 *
679 * @param $x Title object or null to just get the current one
680 * @return Title object
681 */
682 function Title( $x = null ) {
683 return wfSetVar( $this->mTitle, $x );
684 }
685
686 /**
687 * Set the output type
688 *
689 * @param $ot Integer: new value
690 */
691 function setOutputType( $ot ) {
692 $this->mOutputType = $ot;
693 # Shortcut alias
694 $this->ot = array(
695 'html' => $ot == self::OT_HTML,
696 'wiki' => $ot == self::OT_WIKI,
697 'pre' => $ot == self::OT_PREPROCESS,
698 'plain' => $ot == self::OT_PLAIN,
699 );
700 }
701
702 /**
703 * Accessor/mutator for the output type
704 *
705 * @param int|null $x New value or null to just get the current one
706 * @return Integer
707 */
708 function OutputType( $x = null ) {
709 return wfSetVar( $this->mOutputType, $x );
710 }
711
712 /**
713 * Get the ParserOutput object
714 *
715 * @return ParserOutput object
716 */
717 function getOutput() {
718 return $this->mOutput;
719 }
720
721 /**
722 * Get the ParserOptions object
723 *
724 * @return ParserOptions object
725 */
726 function getOptions() {
727 return $this->mOptions;
728 }
729
730 /**
731 * Accessor/mutator for the ParserOptions object
732 *
733 * @param $x ParserOptions New value or null to just get the current one
734 * @return ParserOptions Current ParserOptions object
735 */
736 function Options( $x = null ) {
737 return wfSetVar( $this->mOptions, $x );
738 }
739
740 /**
741 * @return int
742 */
743 function nextLinkID() {
744 return $this->mLinkID++;
745 }
746
747 /**
748 * @param $id int
749 */
750 function setLinkID( $id ) {
751 $this->mLinkID = $id;
752 }
753
754 /**
755 * Get a language object for use in parser functions such as {{FORMATNUM:}}
756 * @return Language
757 */
758 function getFunctionLang() {
759 return $this->getTargetLanguage();
760 }
761
762 /**
763 * Get the target language for the content being parsed. This is usually the
764 * language that the content is in.
765 *
766 * @since 1.19
767 *
768 * @throws MWException
769 * @return Language|null
770 */
771 public function getTargetLanguage() {
772 $target = $this->mOptions->getTargetLanguage();
773
774 if ( $target !== null ) {
775 return $target;
776 } elseif ( $this->mOptions->getInterfaceMessage() ) {
777 return $this->mOptions->getUserLangObj();
778 } elseif ( is_null( $this->mTitle ) ) {
779 throw new MWException( __METHOD__ . ': $this->mTitle is null' );
780 }
781
782 return $this->mTitle->getPageLanguage();
783 }
784
785 /**
786 * Get the language object for language conversion
787 */
788 function getConverterLanguage() {
789 return $this->getTargetLanguage();
790 }
791
792 /**
793 * Get a User object either from $this->mUser, if set, or from the
794 * ParserOptions object otherwise
795 *
796 * @return User object
797 */
798 function getUser() {
799 if ( !is_null( $this->mUser ) ) {
800 return $this->mUser;
801 }
802 return $this->mOptions->getUser();
803 }
804
805 /**
806 * Get a preprocessor object
807 *
808 * @return Preprocessor instance
809 */
810 function getPreprocessor() {
811 if ( !isset( $this->mPreprocessor ) ) {
812 $class = $this->mPreprocessorClass;
813 $this->mPreprocessor = new $class( $this );
814 }
815 return $this->mPreprocessor;
816 }
817
818 /**
819 * Replaces all occurrences of HTML-style comments and the given tags
820 * in the text with a random marker and returns the next text. The output
821 * parameter $matches will be an associative array filled with data in
822 * the form:
823 *
824 * @code
825 * 'UNIQ-xxxxx' => array(
826 * 'element',
827 * 'tag content',
828 * array( 'param' => 'x' ),
829 * '<element param="x">tag content</element>' ) )
830 * @endcode
831 *
832 * @param array $elements list of element names. Comments are always extracted.
833 * @param string $text Source text string.
834 * @param array $matches Out parameter, Array: extracted tags
835 * @param $uniq_prefix string
836 * @return String: stripped text
837 */
838 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
839 static $n = 1;
840 $stripped = '';
841 $matches = array();
842
843 $taglist = implode( '|', $elements );
844 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
845
846 while ( $text != '' ) {
847 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
848 $stripped .= $p[0];
849 if ( count( $p ) < 5 ) {
850 break;
851 }
852 if ( count( $p ) > 5 ) {
853 # comment
854 $element = $p[4];
855 $attributes = '';
856 $close = '';
857 $inside = $p[5];
858 } else {
859 # tag
860 $element = $p[1];
861 $attributes = $p[2];
862 $close = $p[3];
863 $inside = $p[4];
864 }
865
866 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
867 $stripped .= $marker;
868
869 if ( $close === '/>' ) {
870 # Empty element tag, <tag />
871 $content = null;
872 $text = $inside;
873 $tail = null;
874 } else {
875 if ( $element === '!--' ) {
876 $end = '/(-->)/';
877 } else {
878 $end = "/(<\\/$element\\s*>)/i";
879 }
880 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
881 $content = $q[0];
882 if ( count( $q ) < 3 ) {
883 # No end tag -- let it run out to the end of the text.
884 $tail = '';
885 $text = '';
886 } else {
887 $tail = $q[1];
888 $text = $q[2];
889 }
890 }
891
892 $matches[$marker] = array( $element,
893 $content,
894 Sanitizer::decodeTagAttributes( $attributes ),
895 "<$element$attributes$close$content$tail" );
896 }
897 return $stripped;
898 }
899
900 /**
901 * Get a list of strippable XML-like elements
902 *
903 * @return array
904 */
905 function getStripList() {
906 return $this->mStripList;
907 }
908
909 /**
910 * Add an item to the strip state
911 * Returns the unique tag which must be inserted into the stripped text
912 * The tag will be replaced with the original text in unstrip()
913 *
914 * @param $text string
915 *
916 * @return string
917 */
918 function insertStripItem( $text ) {
919 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
920 $this->mMarkerIndex++;
921 $this->mStripState->addGeneral( $rnd, $text );
922 return $rnd;
923 }
924
925 /**
926 * parse the wiki syntax used to render tables
927 *
928 * @private
929 * @return string
930 */
931 function doTableStuff( $text ) {
932 wfProfileIn( __METHOD__ );
933
934 $lines = StringUtils::explode( "\n", $text );
935 $out = '';
936 $td_history = array(); # Is currently a td tag open?
937 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
938 $tr_history = array(); # Is currently a tr tag open?
939 $tr_attributes = array(); # history of tr attributes
940 $has_opened_tr = array(); # Did this table open a <tr> element?
941 $indent_level = 0; # indent level of the table
942
943 foreach ( $lines as $outLine ) {
944 $line = trim( $outLine );
945
946 if ( $line === '' ) { # empty line, go to next line
947 $out .= $outLine . "\n";
948 continue;
949 }
950
951 $first_character = $line[0];
952 $matches = array();
953
954 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
955 # First check if we are starting a new table
956 $indent_level = strlen( $matches[1] );
957
958 $attributes = $this->mStripState->unstripBoth( $matches[2] );
959 $attributes = Sanitizer::fixTagAttributes( $attributes, 'table' );
960
961 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
962 array_push( $td_history, false );
963 array_push( $last_tag_history, '' );
964 array_push( $tr_history, false );
965 array_push( $tr_attributes, '' );
966 array_push( $has_opened_tr, false );
967 } elseif ( count( $td_history ) == 0 ) {
968 # Don't do any of the following
969 $out .= $outLine . "\n";
970 continue;
971 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
972 # We are ending a table
973 $line = '</table>' . substr( $line, 2 );
974 $last_tag = array_pop( $last_tag_history );
975
976 if ( !array_pop( $has_opened_tr ) ) {
977 $line = "<tr><td></td></tr>{$line}";
978 }
979
980 if ( array_pop( $tr_history ) ) {
981 $line = "</tr>{$line}";
982 }
983
984 if ( array_pop( $td_history ) ) {
985 $line = "</{$last_tag}>{$line}";
986 }
987 array_pop( $tr_attributes );
988 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
989 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
990 # Now we have a table row
991 $line = preg_replace( '#^\|-+#', '', $line );
992
993 # Whats after the tag is now only attributes
994 $attributes = $this->mStripState->unstripBoth( $line );
995 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' );
996 array_pop( $tr_attributes );
997 array_push( $tr_attributes, $attributes );
998
999 $line = '';
1000 $last_tag = array_pop( $last_tag_history );
1001 array_pop( $has_opened_tr );
1002 array_push( $has_opened_tr, true );
1003
1004 if ( array_pop( $tr_history ) ) {
1005 $line = '</tr>';
1006 }
1007
1008 if ( array_pop( $td_history ) ) {
1009 $line = "</{$last_tag}>{$line}";
1010 }
1011
1012 $outLine = $line;
1013 array_push( $tr_history, false );
1014 array_push( $td_history, false );
1015 array_push( $last_tag_history, '' );
1016 } elseif ( $first_character === '|' || $first_character === '!' || substr( $line, 0, 2 ) === '|+' ) {
1017 # This might be cell elements, td, th or captions
1018 if ( substr( $line, 0, 2 ) === '|+' ) {
1019 $first_character = '+';
1020 $line = substr( $line, 1 );
1021 }
1022
1023 $line = substr( $line, 1 );
1024
1025 if ( $first_character === '!' ) {
1026 $line = str_replace( '!!', '||', $line );
1027 }
1028
1029 # Split up multiple cells on the same line.
1030 # FIXME : This can result in improper nesting of tags processed
1031 # by earlier parser steps, but should avoid splitting up eg
1032 # attribute values containing literal "||".
1033 $cells = StringUtils::explodeMarkup( '||', $line );
1034
1035 $outLine = '';
1036
1037 # Loop through each table cell
1038 foreach ( $cells as $cell ) {
1039 $previous = '';
1040 if ( $first_character !== '+' ) {
1041 $tr_after = array_pop( $tr_attributes );
1042 if ( !array_pop( $tr_history ) ) {
1043 $previous = "<tr{$tr_after}>\n";
1044 }
1045 array_push( $tr_history, true );
1046 array_push( $tr_attributes, '' );
1047 array_pop( $has_opened_tr );
1048 array_push( $has_opened_tr, true );
1049 }
1050
1051 $last_tag = array_pop( $last_tag_history );
1052
1053 if ( array_pop( $td_history ) ) {
1054 $previous = "</{$last_tag}>\n{$previous}";
1055 }
1056
1057 if ( $first_character === '|' ) {
1058 $last_tag = 'td';
1059 } elseif ( $first_character === '!' ) {
1060 $last_tag = 'th';
1061 } elseif ( $first_character === '+' ) {
1062 $last_tag = 'caption';
1063 } else {
1064 $last_tag = '';
1065 }
1066
1067 array_push( $last_tag_history, $last_tag );
1068
1069 # A cell could contain both parameters and data
1070 $cell_data = explode( '|', $cell, 2 );
1071
1072 # Bug 553: Note that a '|' inside an invalid link should not
1073 # be mistaken as delimiting cell parameters
1074 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1075 $cell = "{$previous}<{$last_tag}>{$cell}";
1076 } elseif ( count( $cell_data ) == 1 ) {
1077 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1078 } else {
1079 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
1080 $attributes = Sanitizer::fixTagAttributes( $attributes, $last_tag );
1081 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1082 }
1083
1084 $outLine .= $cell;
1085 array_push( $td_history, true );
1086 }
1087 }
1088 $out .= $outLine . "\n";
1089 }
1090
1091 # Closing open td, tr && table
1092 while ( count( $td_history ) > 0 ) {
1093 if ( array_pop( $td_history ) ) {
1094 $out .= "</td>\n";
1095 }
1096 if ( array_pop( $tr_history ) ) {
1097 $out .= "</tr>\n";
1098 }
1099 if ( !array_pop( $has_opened_tr ) ) {
1100 $out .= "<tr><td></td></tr>\n";
1101 }
1102
1103 $out .= "</table>\n";
1104 }
1105
1106 # Remove trailing line-ending (b/c)
1107 if ( substr( $out, -1 ) === "\n" ) {
1108 $out = substr( $out, 0, -1 );
1109 }
1110
1111 # special case: don't return empty table
1112 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1113 $out = '';
1114 }
1115
1116 wfProfileOut( __METHOD__ );
1117
1118 return $out;
1119 }
1120
1121 /**
1122 * Helper function for parse() that transforms wiki markup into
1123 * HTML. Only called for $mOutputType == self::OT_HTML.
1124 *
1125 * @private
1126 *
1127 * @param $text string
1128 * @param $isMain bool
1129 * @param $frame bool
1130 *
1131 * @return string
1132 */
1133 function internalParse( $text, $isMain = true, $frame = false ) {
1134 wfProfileIn( __METHOD__ );
1135
1136 $origText = $text;
1137
1138 # Hook to suspend the parser in this state
1139 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
1140 wfProfileOut( __METHOD__ );
1141 return $text;
1142 }
1143
1144 # if $frame is provided, then use $frame for replacing any variables
1145 if ( $frame ) {
1146 # use frame depth to infer how include/noinclude tags should be handled
1147 # depth=0 means this is the top-level document; otherwise it's an included document
1148 if ( !$frame->depth ) {
1149 $flag = 0;
1150 } else {
1151 $flag = Parser::PTD_FOR_INCLUSION;
1152 }
1153 $dom = $this->preprocessToDom( $text, $flag );
1154 $text = $frame->expand( $dom );
1155 } else {
1156 # if $frame is not provided, then use old-style replaceVariables
1157 $text = $this->replaceVariables( $text );
1158 }
1159
1160 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState ) );
1161 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
1162 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
1163
1164 # Tables need to come after variable replacement for things to work
1165 # properly; putting them before other transformations should keep
1166 # exciting things like link expansions from showing up in surprising
1167 # places.
1168 $text = $this->doTableStuff( $text );
1169
1170 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1171
1172 $text = $this->doDoubleUnderscore( $text );
1173
1174 $text = $this->doHeadings( $text );
1175 $text = $this->replaceInternalLinks( $text );
1176 $text = $this->doAllQuotes( $text );
1177 $text = $this->replaceExternalLinks( $text );
1178
1179 # replaceInternalLinks may sometimes leave behind
1180 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1181 $text = str_replace( $this->mUniqPrefix . 'NOPARSE', '', $text );
1182
1183 $text = $this->doMagicLinks( $text );
1184 $text = $this->formatHeadings( $text, $origText, $isMain );
1185
1186 wfProfileOut( __METHOD__ );
1187 return $text;
1188 }
1189
1190 /**
1191 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1192 * magic external links.
1193 *
1194 * DML
1195 * @private
1196 *
1197 * @param $text string
1198 *
1199 * @return string
1200 */
1201 function doMagicLinks( $text ) {
1202 wfProfileIn( __METHOD__ );
1203 $prots = wfUrlProtocolsWithoutProtRel();
1204 $urlChar = self::EXT_LINK_URL_CLASS;
1205 $text = preg_replace_callback(
1206 '!(?: # Start cases
1207 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1208 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1209 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1210 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1211 ISBN\s+(\b # m[5]: ISBN, capture number
1212 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1213 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1214 [0-9Xx] # check digit
1215 \b)
1216 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1217 wfProfileOut( __METHOD__ );
1218 return $text;
1219 }
1220
1221 /**
1222 * @throws MWException
1223 * @param $m array
1224 * @return HTML|string
1225 */
1226 function magicLinkCallback( $m ) {
1227 if ( isset( $m[1] ) && $m[1] !== '' ) {
1228 # Skip anchor
1229 return $m[0];
1230 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1231 # Skip HTML element
1232 return $m[0];
1233 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1234 # Free external link
1235 return $this->makeFreeExternalLink( $m[0] );
1236 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1237 # RFC or PMID
1238 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1239 $keyword = 'RFC';
1240 $urlmsg = 'rfcurl';
1241 $CssClass = 'mw-magiclink-rfc';
1242 $id = $m[4];
1243 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1244 $keyword = 'PMID';
1245 $urlmsg = 'pubmedurl';
1246 $CssClass = 'mw-magiclink-pmid';
1247 $id = $m[4];
1248 } else {
1249 throw new MWException( __METHOD__ . ': unrecognised match type "' .
1250 substr( $m[0], 0, 20 ) . '"' );
1251 }
1252 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1253 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1254 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1255 # ISBN
1256 $isbn = $m[5];
1257 $num = strtr( $isbn, array(
1258 '-' => '',
1259 ' ' => '',
1260 'x' => 'X',
1261 ));
1262 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
1263 return '<a href="' .
1264 htmlspecialchars( $titleObj->getLocalURL() ) .
1265 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1266 } else {
1267 return $m[0];
1268 }
1269 }
1270
1271 /**
1272 * Make a free external link, given a user-supplied URL
1273 *
1274 * @param $url string
1275 *
1276 * @return string HTML
1277 * @private
1278 */
1279 function makeFreeExternalLink( $url ) {
1280 wfProfileIn( __METHOD__ );
1281
1282 $trail = '';
1283
1284 # The characters '<' and '>' (which were escaped by
1285 # removeHTMLtags()) should not be included in
1286 # URLs, per RFC 2396.
1287 $m2 = array();
1288 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1289 $trail = substr( $url, $m2[0][1] ) . $trail;
1290 $url = substr( $url, 0, $m2[0][1] );
1291 }
1292
1293 # Move trailing punctuation to $trail
1294 $sep = ',;\.:!?';
1295 # If there is no left bracket, then consider right brackets fair game too
1296 if ( strpos( $url, '(' ) === false ) {
1297 $sep .= ')';
1298 }
1299
1300 $numSepChars = strspn( strrev( $url ), $sep );
1301 if ( $numSepChars ) {
1302 $trail = substr( $url, -$numSepChars ) . $trail;
1303 $url = substr( $url, 0, -$numSepChars );
1304 }
1305
1306 $url = Sanitizer::cleanUrl( $url );
1307
1308 # Is this an external image?
1309 $text = $this->maybeMakeExternalImage( $url );
1310 if ( $text === false ) {
1311 # Not an image, make a link
1312 $text = Linker::makeExternalLink( $url,
1313 $this->getConverterLanguage()->markNoConversion( $url, true ),
1314 true, 'free',
1315 $this->getExternalLinkAttribs( $url ) );
1316 # Register it in the output object...
1317 # Replace unnecessary URL escape codes with their equivalent characters
1318 $pasteurized = self::replaceUnusualEscapes( $url );
1319 $this->mOutput->addExternalLink( $pasteurized );
1320 }
1321 wfProfileOut( __METHOD__ );
1322 return $text . $trail;
1323 }
1324
1325 /**
1326 * Parse headers and return html
1327 *
1328 * @private
1329 *
1330 * @param $text string
1331 *
1332 * @return string
1333 */
1334 function doHeadings( $text ) {
1335 wfProfileIn( __METHOD__ );
1336 for ( $i = 6; $i >= 1; --$i ) {
1337 $h = str_repeat( '=', $i );
1338 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1339 }
1340 wfProfileOut( __METHOD__ );
1341 return $text;
1342 }
1343
1344 /**
1345 * Replace single quotes with HTML markup
1346 * @private
1347 *
1348 * @param $text string
1349 *
1350 * @return string the altered text
1351 */
1352 function doAllQuotes( $text ) {
1353 wfProfileIn( __METHOD__ );
1354 $outtext = '';
1355 $lines = StringUtils::explode( "\n", $text );
1356 foreach ( $lines as $line ) {
1357 $outtext .= $this->doQuotes( $line ) . "\n";
1358 }
1359 $outtext = substr( $outtext, 0, -1 );
1360 wfProfileOut( __METHOD__ );
1361 return $outtext;
1362 }
1363
1364 /**
1365 * Helper function for doAllQuotes()
1366 *
1367 * @param $text string
1368 *
1369 * @return string
1370 */
1371 public function doQuotes( $text ) {
1372 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1373 if ( count( $arr ) == 1 ) {
1374 return $text;
1375 } else {
1376 # First, do some preliminary work. This may shift some apostrophes from
1377 # being mark-up to being text. It also counts the number of occurrences
1378 # of bold and italics mark-ups.
1379 $numbold = 0;
1380 $numitalics = 0;
1381 for ( $i = 0; $i < count( $arr ); $i++ ) {
1382 if ( ( $i % 2 ) == 1 ) {
1383 # If there are ever four apostrophes, assume the first is supposed to
1384 # be text, and the remaining three constitute mark-up for bold text.
1385 if ( strlen( $arr[$i] ) == 4 ) {
1386 $arr[$i - 1] .= "'";
1387 $arr[$i] = "'''";
1388 } elseif ( strlen( $arr[$i] ) > 5 ) {
1389 # If there are more than 5 apostrophes in a row, assume they're all
1390 # text except for the last 5.
1391 $arr[$i - 1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1392 $arr[$i] = "'''''";
1393 }
1394 # Count the number of occurrences of bold and italics mark-ups.
1395 # We are not counting sequences of five apostrophes.
1396 if ( strlen( $arr[$i] ) == 2 ) {
1397 $numitalics++;
1398 } elseif ( strlen( $arr[$i] ) == 3 ) {
1399 $numbold++;
1400 } elseif ( strlen( $arr[$i] ) == 5 ) {
1401 $numitalics++;
1402 $numbold++;
1403 }
1404 }
1405 }
1406
1407 # If there is an odd number of both bold and italics, it is likely
1408 # that one of the bold ones was meant to be an apostrophe followed
1409 # by italics. Which one we cannot know for certain, but it is more
1410 # likely to be one that has a single-letter word before it.
1411 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1412 $i = 0;
1413 $firstsingleletterword = -1;
1414 $firstmultiletterword = -1;
1415 $firstspace = -1;
1416 foreach ( $arr as $r ) {
1417 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1418 $x1 = substr( $arr[$i - 1], -1 );
1419 $x2 = substr( $arr[$i - 1], -2, 1 );
1420 if ( $x1 === ' ' ) {
1421 if ( $firstspace == -1 ) {
1422 $firstspace = $i;
1423 }
1424 } elseif ( $x2 === ' ' ) {
1425 if ( $firstsingleletterword == -1 ) {
1426 $firstsingleletterword = $i;
1427 }
1428 } else {
1429 if ( $firstmultiletterword == -1 ) {
1430 $firstmultiletterword = $i;
1431 }
1432 }
1433 }
1434 $i++;
1435 }
1436
1437 # If there is a single-letter word, use it!
1438 if ( $firstsingleletterword > -1 ) {
1439 $arr[$firstsingleletterword] = "''";
1440 $arr[$firstsingleletterword - 1] .= "'";
1441 } elseif ( $firstmultiletterword > -1 ) {
1442 # If not, but there's a multi-letter word, use that one.
1443 $arr[$firstmultiletterword] = "''";
1444 $arr[$firstmultiletterword - 1] .= "'";
1445 } elseif ( $firstspace > -1 ) {
1446 # ... otherwise use the first one that has neither.
1447 # (notice that it is possible for all three to be -1 if, for example,
1448 # there is only one pentuple-apostrophe in the line)
1449 $arr[$firstspace] = "''";
1450 $arr[$firstspace - 1] .= "'";
1451 }
1452 }
1453
1454 # Now let's actually convert our apostrophic mush to HTML!
1455 $output = '';
1456 $buffer = '';
1457 $state = '';
1458 $i = 0;
1459 foreach ( $arr as $r ) {
1460 if ( ( $i % 2 ) == 0 ) {
1461 if ( $state === 'both' ) {
1462 $buffer .= $r;
1463 } else {
1464 $output .= $r;
1465 }
1466 } else {
1467 if ( strlen( $r ) == 2 ) {
1468 if ( $state === 'i' ) {
1469 $output .= '</i>';
1470 $state = '';
1471 } elseif ( $state === 'bi' ) {
1472 $output .= '</i>';
1473 $state = 'b';
1474 } elseif ( $state === 'ib' ) {
1475 $output .= '</b></i><b>';
1476 $state = 'b';
1477 } elseif ( $state === 'both' ) {
1478 $output .= '<b><i>' . $buffer . '</i>';
1479 $state = 'b';
1480 } else { # $state can be 'b' or ''
1481 $output .= '<i>';
1482 $state .= 'i';
1483 }
1484 } elseif ( strlen( $r ) == 3 ) {
1485 if ( $state === 'b' ) {
1486 $output .= '</b>';
1487 $state = '';
1488 } elseif ( $state === 'bi' ) {
1489 $output .= '</i></b><i>';
1490 $state = 'i';
1491 } elseif ( $state === 'ib' ) {
1492 $output .= '</b>';
1493 $state = 'i';
1494 } elseif ( $state === 'both' ) {
1495 $output .= '<i><b>' . $buffer . '</b>';
1496 $state = 'i';
1497 } else { # $state can be 'i' or ''
1498 $output .= '<b>';
1499 $state .= 'b';
1500 }
1501 } elseif ( strlen( $r ) == 5 ) {
1502 if ( $state === 'b' ) {
1503 $output .= '</b><i>';
1504 $state = 'i';
1505 } elseif ( $state === 'i' ) {
1506 $output .= '</i><b>';
1507 $state = 'b';
1508 } elseif ( $state === 'bi' ) {
1509 $output .= '</i></b>';
1510 $state = '';
1511 } elseif ( $state === 'ib' ) {
1512 $output .= '</b></i>';
1513 $state = '';
1514 } elseif ( $state === 'both' ) {
1515 $output .= '<i><b>' . $buffer . '</b></i>';
1516 $state = '';
1517 } else { # ($state == '')
1518 $buffer = '';
1519 $state = 'both';
1520 }
1521 }
1522 }
1523 $i++;
1524 }
1525 # Now close all remaining tags. Notice that the order is important.
1526 if ( $state === 'b' || $state === 'ib' ) {
1527 $output .= '</b>';
1528 }
1529 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1530 $output .= '</i>';
1531 }
1532 if ( $state === 'bi' ) {
1533 $output .= '</b>';
1534 }
1535 # There might be lonely ''''', so make sure we have a buffer
1536 if ( $state === 'both' && $buffer ) {
1537 $output .= '<b><i>' . $buffer . '</i></b>';
1538 }
1539 return $output;
1540 }
1541 }
1542
1543 /**
1544 * Replace external links (REL)
1545 *
1546 * Note: this is all very hackish and the order of execution matters a lot.
1547 * Make sure to run maintenance/parserTests.php if you change this code.
1548 *
1549 * @private
1550 *
1551 * @param $text string
1552 *
1553 * @throws MWException
1554 * @return string
1555 */
1556 function replaceExternalLinks( $text ) {
1557 wfProfileIn( __METHOD__ );
1558
1559 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1560 if ( $bits === false ) {
1561 wfProfileOut( __METHOD__ );
1562 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1563 }
1564 $s = array_shift( $bits );
1565
1566 $i = 0;
1567 while ( $i < count( $bits ) ) {
1568 $url = $bits[$i++];
1569 $i++; // protocol
1570 $text = $bits[$i++];
1571 $trail = $bits[$i++];
1572
1573 # The characters '<' and '>' (which were escaped by
1574 # removeHTMLtags()) should not be included in
1575 # URLs, per RFC 2396.
1576 $m2 = array();
1577 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1578 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1579 $url = substr( $url, 0, $m2[0][1] );
1580 }
1581
1582 # If the link text is an image URL, replace it with an <img> tag
1583 # This happened by accident in the original parser, but some people used it extensively
1584 $img = $this->maybeMakeExternalImage( $text );
1585 if ( $img !== false ) {
1586 $text = $img;
1587 }
1588
1589 $dtrail = '';
1590
1591 # Set linktype for CSS - if URL==text, link is essentially free
1592 $linktype = ( $text === $url ) ? 'free' : 'text';
1593
1594 # No link text, e.g. [http://domain.tld/some.link]
1595 if ( $text == '' ) {
1596 # Autonumber
1597 $langObj = $this->getTargetLanguage();
1598 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1599 $linktype = 'autonumber';
1600 } else {
1601 # Have link text, e.g. [http://domain.tld/some.link text]s
1602 # Check for trail
1603 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1604 }
1605
1606 $text = $this->getConverterLanguage()->markNoConversion( $text );
1607
1608 $url = Sanitizer::cleanUrl( $url );
1609
1610 # Use the encoded URL
1611 # This means that users can paste URLs directly into the text
1612 # Funny characters like ö aren't valid in URLs anyway
1613 # This was changed in August 2004
1614 $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
1615 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1616
1617 # Register link in the output object.
1618 # Replace unnecessary URL escape codes with the referenced character
1619 # This prevents spammers from hiding links from the filters
1620 $pasteurized = self::replaceUnusualEscapes( $url );
1621 $this->mOutput->addExternalLink( $pasteurized );
1622 }
1623
1624 wfProfileOut( __METHOD__ );
1625 return $s;
1626 }
1627 /**
1628 * Get the rel attribute for a particular external link.
1629 *
1630 * @since 1.21
1631 * @param string|bool $url optional URL, to extract the domain from for rel =>
1632 * nofollow if appropriate
1633 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1634 * @return string|null rel attribute for $url
1635 */
1636 public static function getExternalLinkRel( $url = false, $title = null ) {
1637 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1638 $ns = $title ? $title->getNamespace() : false;
1639 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1640 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1641 {
1642 return 'nofollow';
1643 }
1644 return null;
1645 }
1646 /**
1647 * Get an associative array of additional HTML attributes appropriate for a
1648 * particular external link. This currently may include rel => nofollow
1649 * (depending on configuration, namespace, and the URL's domain) and/or a
1650 * target attribute (depending on configuration).
1651 *
1652 * @param string|bool $url optional URL, to extract the domain from for rel =>
1653 * nofollow if appropriate
1654 * @return Array associative array of HTML attributes
1655 */
1656 function getExternalLinkAttribs( $url = false ) {
1657 $attribs = array();
1658 $attribs['rel'] = self::getExternalLinkRel( $url, $this->mTitle );
1659
1660 if ( $this->mOptions->getExternalLinkTarget() ) {
1661 $attribs['target'] = $this->mOptions->getExternalLinkTarget();
1662 }
1663 return $attribs;
1664 }
1665
1666 /**
1667 * Replace unusual URL escape codes with their equivalent characters
1668 *
1669 * @param $url String
1670 * @return String
1671 *
1672 * @todo This can merge genuinely required bits in the path or query string,
1673 * breaking legit URLs. A proper fix would treat the various parts of
1674 * the URL differently; as a workaround, just use the output for
1675 * statistical records, not for actual linking/output.
1676 */
1677 static function replaceUnusualEscapes( $url ) {
1678 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1679 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
1680 }
1681
1682 /**
1683 * Callback function used in replaceUnusualEscapes().
1684 * Replaces unusual URL escape codes with their equivalent character
1685 *
1686 * @param $matches array
1687 *
1688 * @return string
1689 */
1690 private static function replaceUnusualEscapesCallback( $matches ) {
1691 $char = urldecode( $matches[0] );
1692 $ord = ord( $char );
1693 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1694 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1695 # No, shouldn't be escaped
1696 return $char;
1697 } else {
1698 # Yes, leave it escaped
1699 return $matches[0];
1700 }
1701 }
1702
1703 /**
1704 * make an image if it's allowed, either through the global
1705 * option, through the exception, or through the on-wiki whitelist
1706 * @private
1707 *
1708 * $param $url string
1709 *
1710 * @return string
1711 */
1712 function maybeMakeExternalImage( $url ) {
1713 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1714 $imagesexception = !empty( $imagesfrom );
1715 $text = false;
1716 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1717 if ( $imagesexception && is_array( $imagesfrom ) ) {
1718 $imagematch = false;
1719 foreach ( $imagesfrom as $match ) {
1720 if ( strpos( $url, $match ) === 0 ) {
1721 $imagematch = true;
1722 break;
1723 }
1724 }
1725 } elseif ( $imagesexception ) {
1726 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1727 } else {
1728 $imagematch = false;
1729 }
1730 if ( $this->mOptions->getAllowExternalImages()
1731 || ( $imagesexception && $imagematch ) ) {
1732 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1733 # Image found
1734 $text = Linker::makeExternalImage( $url );
1735 }
1736 }
1737 if ( !$text && $this->mOptions->getEnableImageWhitelist()
1738 && preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1739 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1740 foreach ( $whitelist as $entry ) {
1741 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1742 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
1743 continue;
1744 }
1745 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1746 # Image matches a whitelist entry
1747 $text = Linker::makeExternalImage( $url );
1748 break;
1749 }
1750 }
1751 }
1752 return $text;
1753 }
1754
1755 /**
1756 * Process [[ ]] wikilinks
1757 *
1758 * @param $s string
1759 *
1760 * @return String: processed text
1761 *
1762 * @private
1763 */
1764 function replaceInternalLinks( $s ) {
1765 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1766 return $s;
1767 }
1768
1769 /**
1770 * Process [[ ]] wikilinks (RIL)
1771 * @param $s
1772 * @throws MWException
1773 * @return LinkHolderArray
1774 *
1775 * @private
1776 */
1777 function replaceInternalLinks2( &$s ) {
1778 wfProfileIn( __METHOD__ );
1779
1780 wfProfileIn( __METHOD__ . '-setup' );
1781 static $tc = false, $e1, $e1_img;
1782 # the % is needed to support urlencoded titles as well
1783 if ( !$tc ) {
1784 $tc = Title::legalChars() . '#%';
1785 # Match a link having the form [[namespace:link|alternate]]trail
1786 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1787 # Match cases where there is no "]]", which might still be images
1788 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1789 }
1790
1791 $holders = new LinkHolderArray( $this );
1792
1793 # split the entire text string on occurrences of [[
1794 $a = StringUtils::explode( '[[', ' ' . $s );
1795 # get the first element (all text up to first [[), and remove the space we added
1796 $s = $a->current();
1797 $a->next();
1798 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1799 $s = substr( $s, 1 );
1800
1801 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1802 $e2 = null;
1803 if ( $useLinkPrefixExtension ) {
1804 # Match the end of a line for a word that's not followed by whitespace,
1805 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1806 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1807 }
1808
1809 if ( is_null( $this->mTitle ) ) {
1810 wfProfileOut( __METHOD__ . '-setup' );
1811 wfProfileOut( __METHOD__ );
1812 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
1813 }
1814 $nottalk = !$this->mTitle->isTalkPage();
1815
1816 if ( $useLinkPrefixExtension ) {
1817 $m = array();
1818 if ( preg_match( $e2, $s, $m ) ) {
1819 $first_prefix = $m[2];
1820 } else {
1821 $first_prefix = false;
1822 }
1823 } else {
1824 $prefix = '';
1825 }
1826
1827 $useSubpages = $this->areSubpagesAllowed();
1828 wfProfileOut( __METHOD__ . '-setup' );
1829
1830 # Loop for each link
1831 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1832 # Check for excessive memory usage
1833 if ( $holders->isBig() ) {
1834 # Too big
1835 # Do the existence check, replace the link holders and clear the array
1836 $holders->replace( $s );
1837 $holders->clear();
1838 }
1839
1840 if ( $useLinkPrefixExtension ) {
1841 wfProfileIn( __METHOD__ . '-prefixhandling' );
1842 if ( preg_match( $e2, $s, $m ) ) {
1843 $prefix = $m[2];
1844 $s = $m[1];
1845 } else {
1846 $prefix = '';
1847 }
1848 # first link
1849 if ( $first_prefix ) {
1850 $prefix = $first_prefix;
1851 $first_prefix = false;
1852 }
1853 wfProfileOut( __METHOD__ . '-prefixhandling' );
1854 }
1855
1856 $might_be_img = false;
1857
1858 wfProfileIn( __METHOD__ . "-e1" );
1859 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1860 $text = $m[2];
1861 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1862 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1863 # the real problem is with the $e1 regex
1864 # See bug 1300.
1865 #
1866 # Still some problems for cases where the ] is meant to be outside punctuation,
1867 # and no image is in sight. See bug 2095.
1868 #
1869 if ( $text !== '' &&
1870 substr( $m[3], 0, 1 ) === ']' &&
1871 strpos( $text, '[' ) !== false
1872 )
1873 {
1874 $text .= ']'; # so that replaceExternalLinks($text) works later
1875 $m[3] = substr( $m[3], 1 );
1876 }
1877 # fix up urlencoded title texts
1878 if ( strpos( $m[1], '%' ) !== false ) {
1879 # Should anchors '#' also be rejected?
1880 $m[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $m[1] ) );
1881 }
1882 $trail = $m[3];
1883 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1884 $might_be_img = true;
1885 $text = $m[2];
1886 if ( strpos( $m[1], '%' ) !== false ) {
1887 $m[1] = rawurldecode( $m[1] );
1888 }
1889 $trail = "";
1890 } else { # Invalid form; output directly
1891 $s .= $prefix . '[[' . $line;
1892 wfProfileOut( __METHOD__ . "-e1" );
1893 continue;
1894 }
1895 wfProfileOut( __METHOD__ . "-e1" );
1896 wfProfileIn( __METHOD__ . "-misc" );
1897
1898 # Don't allow internal links to pages containing
1899 # PROTO: where PROTO is a valid URL protocol; these
1900 # should be external links.
1901 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $m[1] ) ) {
1902 $s .= $prefix . '[[' . $line;
1903 wfProfileOut( __METHOD__ . "-misc" );
1904 continue;
1905 }
1906
1907 # Make subpage if necessary
1908 if ( $useSubpages ) {
1909 $link = $this->maybeDoSubpageLink( $m[1], $text );
1910 } else {
1911 $link = $m[1];
1912 }
1913
1914 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1915 if ( !$noforce ) {
1916 # Strip off leading ':'
1917 $link = substr( $link, 1 );
1918 }
1919
1920 wfProfileOut( __METHOD__ . "-misc" );
1921 wfProfileIn( __METHOD__ . "-title" );
1922 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
1923 if ( $nt === null ) {
1924 $s .= $prefix . '[[' . $line;
1925 wfProfileOut( __METHOD__ . "-title" );
1926 continue;
1927 }
1928
1929 $ns = $nt->getNamespace();
1930 $iw = $nt->getInterWiki();
1931 wfProfileOut( __METHOD__ . "-title" );
1932
1933 if ( $might_be_img ) { # if this is actually an invalid link
1934 wfProfileIn( __METHOD__ . "-might_be_img" );
1935 if ( $ns == NS_FILE && $noforce ) { # but might be an image
1936 $found = false;
1937 while ( true ) {
1938 # look at the next 'line' to see if we can close it there
1939 $a->next();
1940 $next_line = $a->current();
1941 if ( $next_line === false || $next_line === null ) {
1942 break;
1943 }
1944 $m = explode( ']]', $next_line, 3 );
1945 if ( count( $m ) == 3 ) {
1946 # the first ]] closes the inner link, the second the image
1947 $found = true;
1948 $text .= "[[{$m[0]}]]{$m[1]}";
1949 $trail = $m[2];
1950 break;
1951 } elseif ( count( $m ) == 2 ) {
1952 # if there's exactly one ]] that's fine, we'll keep looking
1953 $text .= "[[{$m[0]}]]{$m[1]}";
1954 } else {
1955 # if $next_line is invalid too, we need look no further
1956 $text .= '[[' . $next_line;
1957 break;
1958 }
1959 }
1960 if ( !$found ) {
1961 # we couldn't find the end of this imageLink, so output it raw
1962 # but don't ignore what might be perfectly normal links in the text we've examined
1963 $holders->merge( $this->replaceInternalLinks2( $text ) );
1964 $s .= "{$prefix}[[$link|$text";
1965 # note: no $trail, because without an end, there *is* no trail
1966 wfProfileOut( __METHOD__ . "-might_be_img" );
1967 continue;
1968 }
1969 } else { # it's not an image, so output it raw
1970 $s .= "{$prefix}[[$link|$text";
1971 # note: no $trail, because without an end, there *is* no trail
1972 wfProfileOut( __METHOD__ . "-might_be_img" );
1973 continue;
1974 }
1975 wfProfileOut( __METHOD__ . "-might_be_img" );
1976 }
1977
1978 $wasblank = ( $text == '' );
1979 if ( $wasblank ) {
1980 $text = $link;
1981 } else {
1982 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1983 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1984 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1985 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1986 $text = $this->doQuotes( $text );
1987 }
1988
1989 # Link not escaped by : , create the various objects
1990 if ( $noforce ) {
1991 # Interwikis
1992 wfProfileIn( __METHOD__ . "-interwiki" );
1993 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && Language::fetchLanguageName( $iw, null, 'mw' ) ) {
1994 // XXX: the above check prevents links to sites with identifiers that are not language codes
1995
1996 # Bug 24502: filter duplicates
1997 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
1998 $this->mLangLinkLanguages[$iw] = true;
1999 $this->mOutput->addLanguageLink( $nt->getFullText() );
2000 }
2001
2002 $s = rtrim( $s . $prefix );
2003 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
2004 wfProfileOut( __METHOD__ . "-interwiki" );
2005 continue;
2006 }
2007 wfProfileOut( __METHOD__ . "-interwiki" );
2008
2009 if ( $ns == NS_FILE ) {
2010 wfProfileIn( __METHOD__ . "-image" );
2011 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2012 if ( $wasblank ) {
2013 # if no parameters were passed, $text
2014 # becomes something like "File:Foo.png",
2015 # which we don't want to pass on to the
2016 # image generator
2017 $text = '';
2018 } else {
2019 # recursively parse links inside the image caption
2020 # actually, this will parse them in any other parameters, too,
2021 # but it might be hard to fix that, and it doesn't matter ATM
2022 $text = $this->replaceExternalLinks( $text );
2023 $holders->merge( $this->replaceInternalLinks2( $text ) );
2024 }
2025 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2026 $s .= $prefix . $this->armorLinks(
2027 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2028 } else {
2029 $s .= $prefix . $trail;
2030 }
2031 wfProfileOut( __METHOD__ . "-image" );
2032 continue;
2033 }
2034
2035 if ( $ns == NS_CATEGORY ) {
2036 wfProfileIn( __METHOD__ . "-category" );
2037 $s = rtrim( $s . "\n" ); # bug 87
2038
2039 if ( $wasblank ) {
2040 $sortkey = $this->getDefaultSort();
2041 } else {
2042 $sortkey = $text;
2043 }
2044 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2045 $sortkey = str_replace( "\n", '', $sortkey );
2046 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2047 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2048
2049 /**
2050 * Strip the whitespace Category links produce, see bug 87
2051 * @todo We might want to use trim($tmp, "\n") here.
2052 */
2053 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
2054
2055 wfProfileOut( __METHOD__ . "-category" );
2056 continue;
2057 }
2058 }
2059
2060 # Self-link checking
2061 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL ) {
2062 if ( $nt->equals( $this->mTitle ) || ( !$nt->isKnown() && in_array(
2063 $this->mTitle->getPrefixedText(),
2064 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2065 true
2066 ) ) ) {
2067 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
2068 continue;
2069 }
2070 }
2071
2072 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2073 # @todo FIXME: Should do batch file existence checks, see comment below
2074 if ( $ns == NS_MEDIA ) {
2075 wfProfileIn( __METHOD__ . "-media" );
2076 # Give extensions a chance to select the file revision for us
2077 $options = array();
2078 $descQuery = false;
2079 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2080 array( $this, $nt, &$options, &$descQuery ) );
2081 # Fetch and register the file (file title may be different via hooks)
2082 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2083 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2084 $s .= $prefix . $this->armorLinks(
2085 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2086 wfProfileOut( __METHOD__ . "-media" );
2087 continue;
2088 }
2089
2090 wfProfileIn( __METHOD__ . "-always_known" );
2091 # Some titles, such as valid special pages or files in foreign repos, should
2092 # be shown as bluelinks even though they're not included in the page table
2093 #
2094 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2095 # batch file existence checks for NS_FILE and NS_MEDIA
2096 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2097 $this->mOutput->addLink( $nt );
2098 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2099 } else {
2100 # Links will be added to the output link list after checking
2101 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2102 }
2103 wfProfileOut( __METHOD__ . "-always_known" );
2104 }
2105 wfProfileOut( __METHOD__ );
2106 return $holders;
2107 }
2108
2109 /**
2110 * Render a forced-blue link inline; protect against double expansion of
2111 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2112 * Since this little disaster has to split off the trail text to avoid
2113 * breaking URLs in the following text without breaking trails on the
2114 * wiki links, it's been made into a horrible function.
2115 *
2116 * @param $nt Title
2117 * @param $text String
2118 * @param array $query or String
2119 * @param $trail String
2120 * @param $prefix String
2121 * @return String: HTML-wikitext mix oh yuck
2122 */
2123 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2124 list( $inside, $trail ) = Linker::splitTrail( $trail );
2125
2126 if ( is_string( $query ) ) {
2127 $query = wfCgiToArray( $query );
2128 }
2129 if ( $text == '' ) {
2130 $text = htmlspecialchars( $nt->getPrefixedText() );
2131 }
2132
2133 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2134
2135 return $this->armorLinks( $link ) . $trail;
2136 }
2137
2138 /**
2139 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2140 * going to go through further parsing steps before inline URL expansion.
2141 *
2142 * Not needed quite as much as it used to be since free links are a bit
2143 * more sensible these days. But bracketed links are still an issue.
2144 *
2145 * @param string $text more-or-less HTML
2146 * @return String: less-or-more HTML with NOPARSE bits
2147 */
2148 function armorLinks( $text ) {
2149 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
2150 "{$this->mUniqPrefix}NOPARSE$1", $text );
2151 }
2152
2153 /**
2154 * Return true if subpage links should be expanded on this page.
2155 * @return Boolean
2156 */
2157 function areSubpagesAllowed() {
2158 # Some namespaces don't allow subpages
2159 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2160 }
2161
2162 /**
2163 * Handle link to subpage if necessary
2164 *
2165 * @param string $target the source of the link
2166 * @param &$text String: the link text, modified as necessary
2167 * @return string the full name of the link
2168 * @private
2169 */
2170 function maybeDoSubpageLink( $target, &$text ) {
2171 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2172 }
2173
2174 /**#@+
2175 * Used by doBlockLevels()
2176 * @private
2177 *
2178 * @return string
2179 */
2180 function closeParagraph() {
2181 $result = '';
2182 if ( $this->mLastSection != '' ) {
2183 $result = '</' . $this->mLastSection . ">\n";
2184 }
2185 $this->mInPre = false;
2186 $this->mLastSection = '';
2187 return $result;
2188 }
2189
2190 /**
2191 * getCommon() returns the length of the longest common substring
2192 * of both arguments, starting at the beginning of both.
2193 * @private
2194 *
2195 * @param $st1 string
2196 * @param $st2 string
2197 *
2198 * @return int
2199 */
2200 function getCommon( $st1, $st2 ) {
2201 $fl = strlen( $st1 );
2202 $shorter = strlen( $st2 );
2203 if ( $fl < $shorter ) {
2204 $shorter = $fl;
2205 }
2206
2207 for ( $i = 0; $i < $shorter; ++$i ) {
2208 if ( $st1[$i] != $st2[$i] ) {
2209 break;
2210 }
2211 }
2212 return $i;
2213 }
2214
2215 /**
2216 * These next three functions open, continue, and close the list
2217 * element appropriate to the prefix character passed into them.
2218 * @private
2219 *
2220 * @param $char string
2221 *
2222 * @return string
2223 */
2224 function openList( $char ) {
2225 $result = $this->closeParagraph();
2226
2227 if ( '*' === $char ) {
2228 $result .= '<ul><li>';
2229 } elseif ( '#' === $char ) {
2230 $result .= '<ol><li>';
2231 } elseif ( ':' === $char ) {
2232 $result .= '<dl><dd>';
2233 } elseif ( ';' === $char ) {
2234 $result .= '<dl><dt>';
2235 $this->mDTopen = true;
2236 } else {
2237 $result = '<!-- ERR 1 -->';
2238 }
2239
2240 return $result;
2241 }
2242
2243 /**
2244 * TODO: document
2245 * @param $char String
2246 * @private
2247 *
2248 * @return string
2249 */
2250 function nextItem( $char ) {
2251 if ( '*' === $char || '#' === $char ) {
2252 return '</li><li>';
2253 } elseif ( ':' === $char || ';' === $char ) {
2254 $close = '</dd>';
2255 if ( $this->mDTopen ) {
2256 $close = '</dt>';
2257 }
2258 if ( ';' === $char ) {
2259 $this->mDTopen = true;
2260 return $close . '<dt>';
2261 } else {
2262 $this->mDTopen = false;
2263 return $close . '<dd>';
2264 }
2265 }
2266 return '<!-- ERR 2 -->';
2267 }
2268
2269 /**
2270 * TODO: document
2271 * @param $char String
2272 * @private
2273 *
2274 * @return string
2275 */
2276 function closeList( $char ) {
2277 if ( '*' === $char ) {
2278 $text = '</li></ul>';
2279 } elseif ( '#' === $char ) {
2280 $text = '</li></ol>';
2281 } elseif ( ':' === $char ) {
2282 if ( $this->mDTopen ) {
2283 $this->mDTopen = false;
2284 $text = '</dt></dl>';
2285 } else {
2286 $text = '</dd></dl>';
2287 }
2288 } else {
2289 return '<!-- ERR 3 -->';
2290 }
2291 return $text . "\n";
2292 }
2293 /**#@-*/
2294
2295 /**
2296 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2297 *
2298 * @param $text String
2299 * @param $linestart Boolean: whether or not this is at the start of a line.
2300 * @private
2301 * @return string the lists rendered as HTML
2302 */
2303 function doBlockLevels( $text, $linestart ) {
2304 wfProfileIn( __METHOD__ );
2305
2306 # Parsing through the text line by line. The main thing
2307 # happening here is handling of block-level elements p, pre,
2308 # and making lists from lines starting with * # : etc.
2309 #
2310 $textLines = StringUtils::explode( "\n", $text );
2311
2312 $lastPrefix = $output = '';
2313 $this->mDTopen = $inBlockElem = false;
2314 $prefixLength = 0;
2315 $paragraphStack = false;
2316
2317 foreach ( $textLines as $oLine ) {
2318 # Fix up $linestart
2319 if ( !$linestart ) {
2320 $output .= $oLine;
2321 $linestart = true;
2322 continue;
2323 }
2324 # * = ul
2325 # # = ol
2326 # ; = dt
2327 # : = dd
2328
2329 $lastPrefixLength = strlen( $lastPrefix );
2330 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2331 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2332 # If not in a <pre> element, scan for and figure out what prefixes are there.
2333 if ( !$this->mInPre ) {
2334 # Multiple prefixes may abut each other for nested lists.
2335 $prefixLength = strspn( $oLine, '*#:;' );
2336 $prefix = substr( $oLine, 0, $prefixLength );
2337
2338 # eh?
2339 # ; and : are both from definition-lists, so they're equivalent
2340 # for the purposes of determining whether or not we need to open/close
2341 # elements.
2342 $prefix2 = str_replace( ';', ':', $prefix );
2343 $t = substr( $oLine, $prefixLength );
2344 $this->mInPre = (bool)$preOpenMatch;
2345 } else {
2346 # Don't interpret any other prefixes in preformatted text
2347 $prefixLength = 0;
2348 $prefix = $prefix2 = '';
2349 $t = $oLine;
2350 }
2351
2352 # List generation
2353 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2354 # Same as the last item, so no need to deal with nesting or opening stuff
2355 $output .= $this->nextItem( substr( $prefix, -1 ) );
2356 $paragraphStack = false;
2357
2358 if ( substr( $prefix, -1 ) === ';' ) {
2359 # The one nasty exception: definition lists work like this:
2360 # ; title : definition text
2361 # So we check for : in the remainder text to split up the
2362 # title and definition, without b0rking links.
2363 $term = $t2 = '';
2364 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2365 $t = $t2;
2366 $output .= $term . $this->nextItem( ':' );
2367 }
2368 }
2369 } elseif ( $prefixLength || $lastPrefixLength ) {
2370 # We need to open or close prefixes, or both.
2371
2372 # Either open or close a level...
2373 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2374 $paragraphStack = false;
2375
2376 # Close all the prefixes which aren't shared.
2377 while ( $commonPrefixLength < $lastPrefixLength ) {
2378 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2379 --$lastPrefixLength;
2380 }
2381
2382 # Continue the current prefix if appropriate.
2383 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2384 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2385 }
2386
2387 # Open prefixes where appropriate.
2388 while ( $prefixLength > $commonPrefixLength ) {
2389 $char = substr( $prefix, $commonPrefixLength, 1 );
2390 $output .= $this->openList( $char );
2391
2392 if ( ';' === $char ) {
2393 # @todo FIXME: This is dupe of code above
2394 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2395 $t = $t2;
2396 $output .= $term . $this->nextItem( ':' );
2397 }
2398 }
2399 ++$commonPrefixLength;
2400 }
2401 $lastPrefix = $prefix2;
2402 }
2403
2404 # If we have no prefixes, go to paragraph mode.
2405 if ( 0 == $prefixLength ) {
2406 wfProfileIn( __METHOD__ . "-paragraph" );
2407 # No prefix (not in list)--go to paragraph mode
2408 # XXX: use a stack for nestable elements like span, table and div
2409 $openmatch = preg_match( '/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2410 $closematch = preg_match(
2411 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2412 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|' . $this->mUniqPrefix . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2413 if ( $openmatch or $closematch ) {
2414 $paragraphStack = false;
2415 # TODO bug 5718: paragraph closed
2416 $output .= $this->closeParagraph();
2417 if ( $preOpenMatch and !$preCloseMatch ) {
2418 $this->mInPre = true;
2419 }
2420 $inBlockElem = !$closematch;
2421 } elseif ( !$inBlockElem && !$this->mInPre ) {
2422 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' || trim( $t ) != '' ) ) {
2423 # pre
2424 if ( $this->mLastSection !== 'pre' ) {
2425 $paragraphStack = false;
2426 $output .= $this->closeParagraph() . '<pre>';
2427 $this->mLastSection = 'pre';
2428 }
2429 $t = substr( $t, 1 );
2430 } else {
2431 # paragraph
2432 if ( trim( $t ) === '' ) {
2433 if ( $paragraphStack ) {
2434 $output .= $paragraphStack . '<br />';
2435 $paragraphStack = false;
2436 $this->mLastSection = 'p';
2437 } else {
2438 if ( $this->mLastSection !== 'p' ) {
2439 $output .= $this->closeParagraph();
2440 $this->mLastSection = '';
2441 $paragraphStack = '<p>';
2442 } else {
2443 $paragraphStack = '</p><p>';
2444 }
2445 }
2446 } else {
2447 if ( $paragraphStack ) {
2448 $output .= $paragraphStack;
2449 $paragraphStack = false;
2450 $this->mLastSection = 'p';
2451 } elseif ( $this->mLastSection !== 'p' ) {
2452 $output .= $this->closeParagraph() . '<p>';
2453 $this->mLastSection = 'p';
2454 }
2455 }
2456 }
2457 }
2458 wfProfileOut( __METHOD__ . "-paragraph" );
2459 }
2460 # somewhere above we forget to get out of pre block (bug 785)
2461 if ( $preCloseMatch && $this->mInPre ) {
2462 $this->mInPre = false;
2463 }
2464 if ( $paragraphStack === false ) {
2465 $output .= $t . "\n";
2466 }
2467 }
2468 while ( $prefixLength ) {
2469 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2470 --$prefixLength;
2471 }
2472 if ( $this->mLastSection != '' ) {
2473 $output .= '</' . $this->mLastSection . '>';
2474 $this->mLastSection = '';
2475 }
2476
2477 wfProfileOut( __METHOD__ );
2478 return $output;
2479 }
2480
2481 /**
2482 * Split up a string on ':', ignoring any occurrences inside tags
2483 * to prevent illegal overlapping.
2484 *
2485 * @param string $str the string to split
2486 * @param &$before String set to everything before the ':'
2487 * @param &$after String set to everything after the ':'
2488 * @throws MWException
2489 * @return String the position of the ':', or false if none found
2490 */
2491 function findColonNoLinks( $str, &$before, &$after ) {
2492 wfProfileIn( __METHOD__ );
2493
2494 $pos = strpos( $str, ':' );
2495 if ( $pos === false ) {
2496 # Nothing to find!
2497 wfProfileOut( __METHOD__ );
2498 return false;
2499 }
2500
2501 $lt = strpos( $str, '<' );
2502 if ( $lt === false || $lt > $pos ) {
2503 # Easy; no tag nesting to worry about
2504 $before = substr( $str, 0, $pos );
2505 $after = substr( $str, $pos + 1 );
2506 wfProfileOut( __METHOD__ );
2507 return $pos;
2508 }
2509
2510 # Ugly state machine to walk through avoiding tags.
2511 $state = self::COLON_STATE_TEXT;
2512 $stack = 0;
2513 $len = strlen( $str );
2514 for ( $i = 0; $i < $len; $i++ ) {
2515 $c = $str[$i];
2516
2517 switch ( $state ) {
2518 # (Using the number is a performance hack for common cases)
2519 case 0: # self::COLON_STATE_TEXT:
2520 switch ( $c ) {
2521 case "<":
2522 # Could be either a <start> tag or an </end> tag
2523 $state = self::COLON_STATE_TAGSTART;
2524 break;
2525 case ":":
2526 if ( $stack == 0 ) {
2527 # We found it!
2528 $before = substr( $str, 0, $i );
2529 $after = substr( $str, $i + 1 );
2530 wfProfileOut( __METHOD__ );
2531 return $i;
2532 }
2533 # Embedded in a tag; don't break it.
2534 break;
2535 default:
2536 # Skip ahead looking for something interesting
2537 $colon = strpos( $str, ':', $i );
2538 if ( $colon === false ) {
2539 # Nothing else interesting
2540 wfProfileOut( __METHOD__ );
2541 return false;
2542 }
2543 $lt = strpos( $str, '<', $i );
2544 if ( $stack === 0 ) {
2545 if ( $lt === false || $colon < $lt ) {
2546 # We found it!
2547 $before = substr( $str, 0, $colon );
2548 $after = substr( $str, $colon + 1 );
2549 wfProfileOut( __METHOD__ );
2550 return $i;
2551 }
2552 }
2553 if ( $lt === false ) {
2554 # Nothing else interesting to find; abort!
2555 # We're nested, but there's no close tags left. Abort!
2556 break 2;
2557 }
2558 # Skip ahead to next tag start
2559 $i = $lt;
2560 $state = self::COLON_STATE_TAGSTART;
2561 }
2562 break;
2563 case 1: # self::COLON_STATE_TAG:
2564 # In a <tag>
2565 switch ( $c ) {
2566 case ">":
2567 $stack++;
2568 $state = self::COLON_STATE_TEXT;
2569 break;
2570 case "/":
2571 # Slash may be followed by >?
2572 $state = self::COLON_STATE_TAGSLASH;
2573 break;
2574 default:
2575 # ignore
2576 }
2577 break;
2578 case 2: # self::COLON_STATE_TAGSTART:
2579 switch ( $c ) {
2580 case "/":
2581 $state = self::COLON_STATE_CLOSETAG;
2582 break;
2583 case "!":
2584 $state = self::COLON_STATE_COMMENT;
2585 break;
2586 case ">":
2587 # Illegal early close? This shouldn't happen D:
2588 $state = self::COLON_STATE_TEXT;
2589 break;
2590 default:
2591 $state = self::COLON_STATE_TAG;
2592 }
2593 break;
2594 case 3: # self::COLON_STATE_CLOSETAG:
2595 # In a </tag>
2596 if ( $c === ">" ) {
2597 $stack--;
2598 if ( $stack < 0 ) {
2599 wfDebug( __METHOD__ . ": Invalid input; too many close tags\n" );
2600 wfProfileOut( __METHOD__ );
2601 return false;
2602 }
2603 $state = self::COLON_STATE_TEXT;
2604 }
2605 break;
2606 case self::COLON_STATE_TAGSLASH:
2607 if ( $c === ">" ) {
2608 # Yes, a self-closed tag <blah/>
2609 $state = self::COLON_STATE_TEXT;
2610 } else {
2611 # Probably we're jumping the gun, and this is an attribute
2612 $state = self::COLON_STATE_TAG;
2613 }
2614 break;
2615 case 5: # self::COLON_STATE_COMMENT:
2616 if ( $c === "-" ) {
2617 $state = self::COLON_STATE_COMMENTDASH;
2618 }
2619 break;
2620 case self::COLON_STATE_COMMENTDASH:
2621 if ( $c === "-" ) {
2622 $state = self::COLON_STATE_COMMENTDASHDASH;
2623 } else {
2624 $state = self::COLON_STATE_COMMENT;
2625 }
2626 break;
2627 case self::COLON_STATE_COMMENTDASHDASH:
2628 if ( $c === ">" ) {
2629 $state = self::COLON_STATE_TEXT;
2630 } else {
2631 $state = self::COLON_STATE_COMMENT;
2632 }
2633 break;
2634 default:
2635 wfProfileOut( __METHOD__ );
2636 throw new MWException( "State machine error in " . __METHOD__ );
2637 }
2638 }
2639 if ( $stack > 0 ) {
2640 wfDebug( __METHOD__ . ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2641 wfProfileOut( __METHOD__ );
2642 return false;
2643 }
2644 wfProfileOut( __METHOD__ );
2645 return false;
2646 }
2647
2648 /**
2649 * Return value of a magic variable (like PAGENAME)
2650 *
2651 * @private
2652 *
2653 * @param $index integer
2654 * @param bool|\PPFrame $frame
2655 *
2656 * @throws MWException
2657 * @return string
2658 */
2659 function getVariableValue( $index, $frame = false ) {
2660 global $wgContLang, $wgSitename, $wgServer;
2661 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2662
2663 if ( is_null( $this->mTitle ) ) {
2664 // If no title set, bad things are going to happen
2665 // later. Title should always be set since this
2666 // should only be called in the middle of a parse
2667 // operation (but the unit-tests do funky stuff)
2668 throw new MWException( __METHOD__ . ' Should only be '
2669 . ' called while parsing (no title set)' );
2670 }
2671
2672 /**
2673 * Some of these require message or data lookups and can be
2674 * expensive to check many times.
2675 */
2676 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2677 if ( isset( $this->mVarCache[$index] ) ) {
2678 return $this->mVarCache[$index];
2679 }
2680 }
2681
2682 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2683 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2684
2685 # Use the time zone
2686 global $wgLocaltimezone;
2687 if ( isset( $wgLocaltimezone ) ) {
2688 $oldtz = date_default_timezone_get();
2689 date_default_timezone_set( $wgLocaltimezone );
2690 }
2691
2692 $localTimestamp = date( 'YmdHis', $ts );
2693 $localMonth = date( 'm', $ts );
2694 $localMonth1 = date( 'n', $ts );
2695 $localMonthName = date( 'n', $ts );
2696 $localDay = date( 'j', $ts );
2697 $localDay2 = date( 'd', $ts );
2698 $localDayOfWeek = date( 'w', $ts );
2699 $localWeek = date( 'W', $ts );
2700 $localYear = date( 'Y', $ts );
2701 $localHour = date( 'H', $ts );
2702 if ( isset( $wgLocaltimezone ) ) {
2703 date_default_timezone_set( $oldtz );
2704 }
2705
2706 $pageLang = $this->getFunctionLang();
2707
2708 switch ( $index ) {
2709 case 'currentmonth':
2710 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2711 break;
2712 case 'currentmonth1':
2713 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2714 break;
2715 case 'currentmonthname':
2716 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2717 break;
2718 case 'currentmonthnamegen':
2719 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2720 break;
2721 case 'currentmonthabbrev':
2722 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2723 break;
2724 case 'currentday':
2725 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2726 break;
2727 case 'currentday2':
2728 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2729 break;
2730 case 'localmonth':
2731 $value = $pageLang->formatNum( $localMonth );
2732 break;
2733 case 'localmonth1':
2734 $value = $pageLang->formatNum( $localMonth1 );
2735 break;
2736 case 'localmonthname':
2737 $value = $pageLang->getMonthName( $localMonthName );
2738 break;
2739 case 'localmonthnamegen':
2740 $value = $pageLang->getMonthNameGen( $localMonthName );
2741 break;
2742 case 'localmonthabbrev':
2743 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2744 break;
2745 case 'localday':
2746 $value = $pageLang->formatNum( $localDay );
2747 break;
2748 case 'localday2':
2749 $value = $pageLang->formatNum( $localDay2 );
2750 break;
2751 case 'pagename':
2752 $value = wfEscapeWikiText( $this->mTitle->getText() );
2753 break;
2754 case 'pagenamee':
2755 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2756 break;
2757 case 'fullpagename':
2758 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2759 break;
2760 case 'fullpagenamee':
2761 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2762 break;
2763 case 'subpagename':
2764 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2765 break;
2766 case 'subpagenamee':
2767 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2768 break;
2769 case 'rootpagename':
2770 $value = wfEscapeWikiText( $this->mTitle->getRootText() );
2771 break;
2772 case 'rootpagenamee':
2773 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getRootText() ) ) );
2774 break;
2775 case 'basepagename':
2776 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2777 break;
2778 case 'basepagenamee':
2779 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) ) );
2780 break;
2781 case 'talkpagename':
2782 if ( $this->mTitle->canTalk() ) {
2783 $talkPage = $this->mTitle->getTalkPage();
2784 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2785 } else {
2786 $value = '';
2787 }
2788 break;
2789 case 'talkpagenamee':
2790 if ( $this->mTitle->canTalk() ) {
2791 $talkPage = $this->mTitle->getTalkPage();
2792 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2793 } else {
2794 $value = '';
2795 }
2796 break;
2797 case 'subjectpagename':
2798 $subjPage = $this->mTitle->getSubjectPage();
2799 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2800 break;
2801 case 'subjectpagenamee':
2802 $subjPage = $this->mTitle->getSubjectPage();
2803 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2804 break;
2805 case 'pageid': // requested in bug 23427
2806 $pageid = $this->getTitle()->getArticleID();
2807 if ( $pageid == 0 ) {
2808 # 0 means the page doesn't exist in the database,
2809 # which means the user is previewing a new page.
2810 # The vary-revision flag must be set, because the magic word
2811 # will have a different value once the page is saved.
2812 $this->mOutput->setFlag( 'vary-revision' );
2813 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2814 }
2815 $value = $pageid ? $pageid : null;
2816 break;
2817 case 'revisionid':
2818 # Let the edit saving system know we should parse the page
2819 # *after* a revision ID has been assigned.
2820 $this->mOutput->setFlag( 'vary-revision' );
2821 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2822 $value = $this->mRevisionId;
2823 break;
2824 case 'revisionday':
2825 # Let the edit saving system know we should parse the page
2826 # *after* a revision ID has been assigned. This is for null edits.
2827 $this->mOutput->setFlag( 'vary-revision' );
2828 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2829 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2830 break;
2831 case 'revisionday2':
2832 # Let the edit saving system know we should parse the page
2833 # *after* a revision ID has been assigned. This is for null edits.
2834 $this->mOutput->setFlag( 'vary-revision' );
2835 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2836 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2837 break;
2838 case 'revisionmonth':
2839 # Let the edit saving system know we should parse the page
2840 # *after* a revision ID has been assigned. This is for null edits.
2841 $this->mOutput->setFlag( 'vary-revision' );
2842 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2843 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2844 break;
2845 case 'revisionmonth1':
2846 # Let the edit saving system know we should parse the page
2847 # *after* a revision ID has been assigned. This is for null edits.
2848 $this->mOutput->setFlag( 'vary-revision' );
2849 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2850 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2851 break;
2852 case 'revisionyear':
2853 # Let the edit saving system know we should parse the page
2854 # *after* a revision ID has been assigned. This is for null edits.
2855 $this->mOutput->setFlag( 'vary-revision' );
2856 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2857 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2858 break;
2859 case 'revisiontimestamp':
2860 # Let the edit saving system know we should parse the page
2861 # *after* a revision ID has been assigned. This is for null edits.
2862 $this->mOutput->setFlag( 'vary-revision' );
2863 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2864 $value = $this->getRevisionTimestamp();
2865 break;
2866 case 'revisionuser':
2867 # Let the edit saving system know we should parse the page
2868 # *after* a revision ID has been assigned. This is for null edits.
2869 $this->mOutput->setFlag( 'vary-revision' );
2870 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2871 $value = $this->getRevisionUser();
2872 break;
2873 case 'namespace':
2874 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2875 break;
2876 case 'namespacee':
2877 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2878 break;
2879 case 'namespacenumber':
2880 $value = $this->mTitle->getNamespace();
2881 break;
2882 case 'talkspace':
2883 $value = $this->mTitle->canTalk() ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() ) : '';
2884 break;
2885 case 'talkspacee':
2886 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2887 break;
2888 case 'subjectspace':
2889 $value = $this->mTitle->getSubjectNsText();
2890 break;
2891 case 'subjectspacee':
2892 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2893 break;
2894 case 'currentdayname':
2895 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2896 break;
2897 case 'currentyear':
2898 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2899 break;
2900 case 'currenttime':
2901 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2902 break;
2903 case 'currenthour':
2904 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2905 break;
2906 case 'currentweek':
2907 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2908 # int to remove the padding
2909 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2910 break;
2911 case 'currentdow':
2912 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2913 break;
2914 case 'localdayname':
2915 $value = $pageLang->getWeekdayName( $localDayOfWeek + 1 );
2916 break;
2917 case 'localyear':
2918 $value = $pageLang->formatNum( $localYear, true );
2919 break;
2920 case 'localtime':
2921 $value = $pageLang->time( $localTimestamp, false, false );
2922 break;
2923 case 'localhour':
2924 $value = $pageLang->formatNum( $localHour, true );
2925 break;
2926 case 'localweek':
2927 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2928 # int to remove the padding
2929 $value = $pageLang->formatNum( (int)$localWeek );
2930 break;
2931 case 'localdow':
2932 $value = $pageLang->formatNum( $localDayOfWeek );
2933 break;
2934 case 'numberofarticles':
2935 $value = $pageLang->formatNum( SiteStats::articles() );
2936 break;
2937 case 'numberoffiles':
2938 $value = $pageLang->formatNum( SiteStats::images() );
2939 break;
2940 case 'numberofusers':
2941 $value = $pageLang->formatNum( SiteStats::users() );
2942 break;
2943 case 'numberofactiveusers':
2944 $value = $pageLang->formatNum( SiteStats::activeUsers() );
2945 break;
2946 case 'numberofpages':
2947 $value = $pageLang->formatNum( SiteStats::pages() );
2948 break;
2949 case 'numberofadmins':
2950 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
2951 break;
2952 case 'numberofedits':
2953 $value = $pageLang->formatNum( SiteStats::edits() );
2954 break;
2955 case 'numberofviews':
2956 global $wgDisableCounters;
2957 $value = !$wgDisableCounters ? $pageLang->formatNum( SiteStats::views() ) : '';
2958 break;
2959 case 'currenttimestamp':
2960 $value = wfTimestamp( TS_MW, $ts );
2961 break;
2962 case 'localtimestamp':
2963 $value = $localTimestamp;
2964 break;
2965 case 'currentversion':
2966 $value = SpecialVersion::getVersion();
2967 break;
2968 case 'articlepath':
2969 return $wgArticlePath;
2970 case 'sitename':
2971 return $wgSitename;
2972 case 'server':
2973 return $wgServer;
2974 case 'servername':
2975 $serverParts = wfParseUrl( $wgServer );
2976 return $serverParts && isset( $serverParts['host'] ) ? $serverParts['host'] : $wgServer;
2977 case 'scriptpath':
2978 return $wgScriptPath;
2979 case 'stylepath':
2980 return $wgStylePath;
2981 case 'directionmark':
2982 return $pageLang->getDirMark();
2983 case 'contentlanguage':
2984 global $wgLanguageCode;
2985 return $wgLanguageCode;
2986 default:
2987 $ret = null;
2988 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ) ) {
2989 return $ret;
2990 } else {
2991 return null;
2992 }
2993 }
2994
2995 if ( $index ) {
2996 $this->mVarCache[$index] = $value;
2997 }
2998
2999 return $value;
3000 }
3001
3002 /**
3003 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3004 *
3005 * @private
3006 */
3007 function initialiseVariables() {
3008 wfProfileIn( __METHOD__ );
3009 $variableIDs = MagicWord::getVariableIDs();
3010 $substIDs = MagicWord::getSubstIDs();
3011
3012 $this->mVariables = new MagicWordArray( $variableIDs );
3013 $this->mSubstWords = new MagicWordArray( $substIDs );
3014 wfProfileOut( __METHOD__ );
3015 }
3016
3017 /**
3018 * Preprocess some wikitext and return the document tree.
3019 * This is the ghost of replace_variables().
3020 *
3021 * @param string $text The text to parse
3022 * @param $flags Integer: bitwise combination of:
3023 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
3024 * included. Default is to assume a direct page view.
3025 *
3026 * The generated DOM tree must depend only on the input text and the flags.
3027 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3028 *
3029 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3030 * change in the DOM tree for a given text, must be passed through the section identifier
3031 * in the section edit link and thus back to extractSections().
3032 *
3033 * The output of this function is currently only cached in process memory, but a persistent
3034 * cache may be implemented at a later date which takes further advantage of these strict
3035 * dependency requirements.
3036 *
3037 * @private
3038 *
3039 * @return PPNode
3040 */
3041 function preprocessToDom( $text, $flags = 0 ) {
3042 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3043 return $dom;
3044 }
3045
3046 /**
3047 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3048 *
3049 * @param $s string
3050 *
3051 * @return array
3052 */
3053 public static function splitWhitespace( $s ) {
3054 $ltrimmed = ltrim( $s );
3055 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3056 $trimmed = rtrim( $ltrimmed );
3057 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3058 if ( $diff > 0 ) {
3059 $w2 = substr( $ltrimmed, -$diff );
3060 } else {
3061 $w2 = '';
3062 }
3063 return array( $w1, $trimmed, $w2 );
3064 }
3065
3066 /**
3067 * Replace magic variables, templates, and template arguments
3068 * with the appropriate text. Templates are substituted recursively,
3069 * taking care to avoid infinite loops.
3070 *
3071 * Note that the substitution depends on value of $mOutputType:
3072 * self::OT_WIKI: only {{subst:}} templates
3073 * self::OT_PREPROCESS: templates but not extension tags
3074 * self::OT_HTML: all templates and extension tags
3075 *
3076 * @param string $text the text to transform
3077 * @param $frame PPFrame Object describing the arguments passed to the template.
3078 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3079 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3080 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3081 * @private
3082 *
3083 * @return string
3084 */
3085 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3086 # Is there any text? Also, Prevent too big inclusions!
3087 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
3088 return $text;
3089 }
3090 wfProfileIn( __METHOD__ );
3091
3092 if ( $frame === false ) {
3093 $frame = $this->getPreprocessor()->newFrame();
3094 } elseif ( !( $frame instanceof PPFrame ) ) {
3095 wfDebug( __METHOD__ . " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3096 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3097 }
3098
3099 $dom = $this->preprocessToDom( $text );
3100 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3101 $text = $frame->expand( $dom, $flags );
3102
3103 wfProfileOut( __METHOD__ );
3104 return $text;
3105 }
3106
3107 /**
3108 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3109 *
3110 * @param $args array
3111 *
3112 * @return array
3113 */
3114 static function createAssocArgs( $args ) {
3115 $assocArgs = array();
3116 $index = 1;
3117 foreach ( $args as $arg ) {
3118 $eqpos = strpos( $arg, '=' );
3119 if ( $eqpos === false ) {
3120 $assocArgs[$index++] = $arg;
3121 } else {
3122 $name = trim( substr( $arg, 0, $eqpos ) );
3123 $value = trim( substr( $arg, $eqpos + 1 ) );
3124 if ( $value === false ) {
3125 $value = '';
3126 }
3127 if ( $name !== false ) {
3128 $assocArgs[$name] = $value;
3129 }
3130 }
3131 }
3132
3133 return $assocArgs;
3134 }
3135
3136 /**
3137 * Warn the user when a parser limitation is reached
3138 * Will warn at most once the user per limitation type
3139 *
3140 * @param string $limitationType should be one of:
3141 * 'expensive-parserfunction' (corresponding messages:
3142 * 'expensive-parserfunction-warning',
3143 * 'expensive-parserfunction-category')
3144 * 'post-expand-template-argument' (corresponding messages:
3145 * 'post-expand-template-argument-warning',
3146 * 'post-expand-template-argument-category')
3147 * 'post-expand-template-inclusion' (corresponding messages:
3148 * 'post-expand-template-inclusion-warning',
3149 * 'post-expand-template-inclusion-category')
3150 * @param int|null $current Current value
3151 * @param int|null $max Maximum allowed, when an explicit limit has been
3152 * exceeded, provide the values (optional)
3153 */
3154 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3155 # does no harm if $current and $max are present but are unnecessary for the message
3156 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3157 ->inContentLanguage()->escaped();
3158 $this->mOutput->addWarning( $warning );
3159 $this->addTrackingCategory( "$limitationType-category" );
3160 }
3161
3162 /**
3163 * Return the text of a template, after recursively
3164 * replacing any variables or templates within the template.
3165 *
3166 * @param array $piece the parts of the template
3167 * $piece['title']: the title, i.e. the part before the |
3168 * $piece['parts']: the parameter array
3169 * $piece['lineStart']: whether the brace was at the start of a line
3170 * @param $frame PPFrame The current frame, contains template arguments
3171 * @throws MWException
3172 * @return String: the text of the template
3173 * @private
3174 */
3175 function braceSubstitution( $piece, $frame ) {
3176 wfProfileIn( __METHOD__ );
3177 wfProfileIn( __METHOD__ . '-setup' );
3178
3179 # Flags
3180 $found = false; # $text has been filled
3181 $nowiki = false; # wiki markup in $text should be escaped
3182 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3183 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3184 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3185 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3186
3187 # Title object, where $text came from
3188 $title = false;
3189
3190 # $part1 is the bit before the first |, and must contain only title characters.
3191 # Various prefixes will be stripped from it later.
3192 $titleWithSpaces = $frame->expand( $piece['title'] );
3193 $part1 = trim( $titleWithSpaces );
3194 $titleText = false;
3195
3196 # Original title text preserved for various purposes
3197 $originalTitle = $part1;
3198
3199 # $args is a list of argument nodes, starting from index 0, not including $part1
3200 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3201 $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
3202 wfProfileOut( __METHOD__ . '-setup' );
3203
3204 $titleProfileIn = null; // profile templates
3205
3206 # SUBST
3207 wfProfileIn( __METHOD__ . '-modifiers' );
3208 if ( !$found ) {
3209
3210 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3211
3212 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3213 # Decide whether to expand template or keep wikitext as-is.
3214 if ( $this->ot['wiki'] ) {
3215 if ( $substMatch === false ) {
3216 $literal = true; # literal when in PST with no prefix
3217 } else {
3218 $literal = false; # expand when in PST with subst: or safesubst:
3219 }
3220 } else {
3221 if ( $substMatch == 'subst' ) {
3222 $literal = true; # literal when not in PST with plain subst:
3223 } else {
3224 $literal = false; # expand when not in PST with safesubst: or no prefix
3225 }
3226 }
3227 if ( $literal ) {
3228 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3229 $isLocalObj = true;
3230 $found = true;
3231 }
3232 }
3233
3234 # Variables
3235 if ( !$found && $args->getLength() == 0 ) {
3236 $id = $this->mVariables->matchStartToEnd( $part1 );
3237 if ( $id !== false ) {
3238 $text = $this->getVariableValue( $id, $frame );
3239 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3240 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3241 }
3242 $found = true;
3243 }
3244 }
3245
3246 # MSG, MSGNW and RAW
3247 if ( !$found ) {
3248 # Check for MSGNW:
3249 $mwMsgnw = MagicWord::get( 'msgnw' );
3250 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3251 $nowiki = true;
3252 } else {
3253 # Remove obsolete MSG:
3254 $mwMsg = MagicWord::get( 'msg' );
3255 $mwMsg->matchStartAndRemove( $part1 );
3256 }
3257
3258 # Check for RAW:
3259 $mwRaw = MagicWord::get( 'raw' );
3260 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3261 $forceRawInterwiki = true;
3262 }
3263 }
3264 wfProfileOut( __METHOD__ . '-modifiers' );
3265
3266 # Parser functions
3267 if ( !$found ) {
3268 wfProfileIn( __METHOD__ . '-pfunc' );
3269
3270 $colonPos = strpos( $part1, ':' );
3271 if ( $colonPos !== false ) {
3272 $func = substr( $part1, 0, $colonPos );
3273 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3274 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3275 $funcArgs[] = $args->item( $i );
3276 }
3277 try {
3278 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3279 } catch ( Exception $ex ) {
3280 wfProfileOut( __METHOD__ . '-pfunc' );
3281 wfProfileOut( __METHOD__ );
3282 throw $ex;
3283 }
3284
3285 # The interface for parser functions allows for extracting
3286 # flags into the local scope. Extract any forwarded flags
3287 # here.
3288 extract( $result );
3289 }
3290 wfProfileOut( __METHOD__ . '-pfunc' );
3291 }
3292
3293 # Finish mangling title and then check for loops.
3294 # Set $title to a Title object and $titleText to the PDBK
3295 if ( !$found ) {
3296 $ns = NS_TEMPLATE;
3297 # Split the title into page and subpage
3298 $subpage = '';
3299 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3300 if ( $subpage !== '' ) {
3301 $ns = $this->mTitle->getNamespace();
3302 }
3303 $title = Title::newFromText( $part1, $ns );
3304 if ( $title ) {
3305 $titleText = $title->getPrefixedText();
3306 # Check for language variants if the template is not found
3307 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3308 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3309 }
3310 # Do recursion depth check
3311 $limit = $this->mOptions->getMaxTemplateDepth();
3312 if ( $frame->depth >= $limit ) {
3313 $found = true;
3314 $text = '<span class="error">'
3315 . wfMessage( 'parser-template-recursion-depth-warning' )
3316 ->numParams( $limit )->inContentLanguage()->text()
3317 . '</span>';
3318 }
3319 }
3320 }
3321
3322 # Load from database
3323 if ( !$found && $title ) {
3324 if ( !Profiler::instance()->isPersistent() ) {
3325 # Too many unique items can kill profiling DBs/collectors
3326 $titleProfileIn = __METHOD__ . "-title-" . $title->getDBkey();
3327 wfProfileIn( $titleProfileIn ); // template in
3328 }
3329 wfProfileIn( __METHOD__ . '-loadtpl' );
3330 if ( !$title->isExternal() ) {
3331 if ( $title->isSpecialPage()
3332 && $this->mOptions->getAllowSpecialInclusion()
3333 && $this->ot['html'] )
3334 {
3335 // Pass the template arguments as URL parameters.
3336 // "uselang" will have no effect since the Language object
3337 // is forced to the one defined in ParserOptions.
3338 $pageArgs = array();
3339 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3340 $bits = $args->item( $i )->splitArg();
3341 if ( strval( $bits['index'] ) === '' ) {
3342 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3343 $value = trim( $frame->expand( $bits['value'] ) );
3344 $pageArgs[$name] = $value;
3345 }
3346 }
3347
3348 // Create a new context to execute the special page
3349 $context = new RequestContext;
3350 $context->setTitle( $title );
3351 $context->setRequest( new FauxRequest( $pageArgs ) );
3352 $context->setUser( $this->getUser() );
3353 $context->setLanguage( $this->mOptions->getUserLangObj() );
3354 $ret = SpecialPageFactory::capturePath( $title, $context );
3355 if ( $ret ) {
3356 $text = $context->getOutput()->getHTML();
3357 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3358 $found = true;
3359 $isHTML = true;
3360 $this->disableCache();
3361 }
3362 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3363 $found = false; # access denied
3364 wfDebug( __METHOD__ . ": template inclusion denied for " . $title->getPrefixedDBkey() );
3365 } else {
3366 list( $text, $title ) = $this->getTemplateDom( $title );
3367 if ( $text !== false ) {
3368 $found = true;
3369 $isChildObj = true;
3370 }
3371 }
3372
3373 # If the title is valid but undisplayable, make a link to it
3374 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3375 $text = "[[:$titleText]]";
3376 $found = true;
3377 }
3378 } elseif ( $title->isTrans() ) {
3379 # Interwiki transclusion
3380 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3381 $text = $this->interwikiTransclude( $title, 'render' );
3382 $isHTML = true;
3383 } else {
3384 $text = $this->interwikiTransclude( $title, 'raw' );
3385 # Preprocess it like a template
3386 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3387 $isChildObj = true;
3388 }
3389 $found = true;
3390 }
3391
3392 # Do infinite loop check
3393 # This has to be done after redirect resolution to avoid infinite loops via redirects
3394 if ( !$frame->loopCheck( $title ) ) {
3395 $found = true;
3396 $text = '<span class="error">'
3397 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3398 . '</span>';
3399 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3400 }
3401 wfProfileOut( __METHOD__ . '-loadtpl' );
3402 }
3403
3404 # If we haven't found text to substitute by now, we're done
3405 # Recover the source wikitext and return it
3406 if ( !$found ) {
3407 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3408 if ( $titleProfileIn ) {
3409 wfProfileOut( $titleProfileIn ); // template out
3410 }
3411 wfProfileOut( __METHOD__ );
3412 return array( 'object' => $text );
3413 }
3414
3415 # Expand DOM-style return values in a child frame
3416 if ( $isChildObj ) {
3417 # Clean up argument array
3418 $newFrame = $frame->newChild( $args, $title );
3419
3420 if ( $nowiki ) {
3421 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3422 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3423 # Expansion is eligible for the empty-frame cache
3424 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3425 $text = $this->mTplExpandCache[$titleText];
3426 } else {
3427 $text = $newFrame->expand( $text );
3428 $this->mTplExpandCache[$titleText] = $text;
3429 }
3430 } else {
3431 # Uncached expansion
3432 $text = $newFrame->expand( $text );
3433 }
3434 }
3435 if ( $isLocalObj && $nowiki ) {
3436 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3437 $isLocalObj = false;
3438 }
3439
3440 if ( $titleProfileIn ) {
3441 wfProfileOut( $titleProfileIn ); // template out
3442 }
3443
3444 # Replace raw HTML by a placeholder
3445 if ( $isHTML ) {
3446 $text = $this->insertStripItem( $text );
3447 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3448 # Escape nowiki-style return values
3449 $text = wfEscapeWikiText( $text );
3450 } elseif ( is_string( $text )
3451 && !$piece['lineStart']
3452 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3453 {
3454 # Bug 529: if the template begins with a table or block-level
3455 # element, it should be treated as beginning a new line.
3456 # This behavior is somewhat controversial.
3457 $text = "\n" . $text;
3458 }
3459
3460 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3461 # Error, oversize inclusion
3462 if ( $titleText !== false ) {
3463 # Make a working, properly escaped link if possible (bug 23588)
3464 $text = "[[:$titleText]]";
3465 } else {
3466 # This will probably not be a working link, but at least it may
3467 # provide some hint of where the problem is
3468 preg_replace( '/^:/', '', $originalTitle );
3469 $text = "[[:$originalTitle]]";
3470 }
3471 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3472 $this->limitationWarn( 'post-expand-template-inclusion' );
3473 }
3474
3475 if ( $isLocalObj ) {
3476 $ret = array( 'object' => $text );
3477 } else {
3478 $ret = array( 'text' => $text );
3479 }
3480
3481 wfProfileOut( __METHOD__ );
3482 return $ret;
3483 }
3484
3485 /**
3486 * Call a parser function and return an array with text and flags.
3487 *
3488 * The returned array will always contain a boolean 'found', indicating
3489 * whether the parser function was found or not. It may also contain the
3490 * following:
3491 * text: string|object, resulting wikitext or PP DOM object
3492 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3493 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3494 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3495 * nowiki: bool, wiki markup in $text should be escaped
3496 *
3497 * @since 1.21
3498 * @param $frame PPFrame The current frame, contains template arguments
3499 * @param $function string Function name
3500 * @param $args array Arguments to the function
3501 * @return array
3502 */
3503 public function callParserFunction( $frame, $function, array $args = array() ) {
3504 global $wgContLang;
3505
3506 wfProfileIn( __METHOD__ );
3507
3508 # Case sensitive functions
3509 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3510 $function = $this->mFunctionSynonyms[1][$function];
3511 } else {
3512 # Case insensitive functions
3513 $function = $wgContLang->lc( $function );
3514 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3515 $function = $this->mFunctionSynonyms[0][$function];
3516 } else {
3517 wfProfileOut( __METHOD__ );
3518 return array( 'found' => false );
3519 }
3520 }
3521
3522 wfProfileIn( __METHOD__ . '-pfunc-' . $function );
3523 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3524
3525 # Workaround for PHP bug 35229 and similar
3526 if ( !is_callable( $callback ) ) {
3527 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3528 wfProfileOut( __METHOD__ );
3529 throw new MWException( "Tag hook for $function is not callable\n" );
3530 }
3531
3532 $allArgs = array( &$this );
3533 if ( $flags & SFH_OBJECT_ARGS ) {
3534 # Convert arguments to PPNodes and collect for appending to $allArgs
3535 $funcArgs = array();
3536 foreach ( $args as $k => $v ) {
3537 if ( $v instanceof PPNode || $k === 0 ) {
3538 $funcArgs[] = $v;
3539 } else {
3540 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( array( $k => $v ) )->item( 0 );
3541 }
3542 }
3543
3544 # Add a frame parameter, and pass the arguments as an array
3545 $allArgs[] = $frame;
3546 $allArgs[] = $funcArgs;
3547 } else {
3548 # Convert arguments to plain text and append to $allArgs
3549 foreach ( $args as $k => $v ) {
3550 if ( $v instanceof PPNode ) {
3551 $allArgs[] = trim( $frame->expand( $v ) );
3552 } elseif ( is_int( $k ) && $k >= 0 ) {
3553 $allArgs[] = trim( $v );
3554 } else {
3555 $allArgs[] = trim( "$k=$v" );
3556 }
3557 }
3558 }
3559
3560 $result = call_user_func_array( $callback, $allArgs );
3561
3562 # The interface for function hooks allows them to return a wikitext
3563 # string or an array containing the string and any flags. This mungs
3564 # things around to match what this method should return.
3565 if ( !is_array( $result ) ) {
3566 $result = array(
3567 'found' => true,
3568 'text' => $result,
3569 );
3570 } else {
3571 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3572 $result['text'] = $result[0];
3573 }
3574 unset( $result[0] );
3575 $result += array(
3576 'found' => true,
3577 );
3578 }
3579
3580 $noparse = true;
3581 $preprocessFlags = 0;
3582 if ( isset( $result['noparse'] ) ) {
3583 $noparse = $result['noparse'];
3584 }
3585 if ( isset( $result['preprocessFlags'] ) ) {
3586 $preprocessFlags = $result['preprocessFlags'];
3587 }
3588
3589 if ( !$noparse ) {
3590 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3591 $result['isChildObj'] = true;
3592 }
3593 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3594 wfProfileOut( __METHOD__ );
3595
3596 return $result;
3597 }
3598
3599 /**
3600 * Get the semi-parsed DOM representation of a template with a given title,
3601 * and its redirect destination title. Cached.
3602 *
3603 * @param $title Title
3604 *
3605 * @return array
3606 */
3607 function getTemplateDom( $title ) {
3608 $cacheTitle = $title;
3609 $titleText = $title->getPrefixedDBkey();
3610
3611 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3612 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3613 $title = Title::makeTitle( $ns, $dbk );
3614 $titleText = $title->getPrefixedDBkey();
3615 }
3616 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3617 return array( $this->mTplDomCache[$titleText], $title );
3618 }
3619
3620 # Cache miss, go to the database
3621 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3622
3623 if ( $text === false ) {
3624 $this->mTplDomCache[$titleText] = false;
3625 return array( false, $title );
3626 }
3627
3628 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3629 $this->mTplDomCache[$titleText] = $dom;
3630
3631 if ( !$title->equals( $cacheTitle ) ) {
3632 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3633 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3634 }
3635
3636 return array( $dom, $title );
3637 }
3638
3639 /**
3640 * Fetch the unparsed text of a template and register a reference to it.
3641 * @param Title $title
3642 * @return Array ( string or false, Title )
3643 */
3644 function fetchTemplateAndTitle( $title ) {
3645 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3646 $stuff = call_user_func( $templateCb, $title, $this );
3647 $text = $stuff['text'];
3648 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3649 if ( isset( $stuff['deps'] ) ) {
3650 foreach ( $stuff['deps'] as $dep ) {
3651 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3652 if ( $dep['title']->equals( $this->getTitle() ) ) {
3653 // If we transclude ourselves, the final result
3654 // will change based on the new version of the page
3655 $this->mOutput->setFlag( 'vary-revision' );
3656 }
3657 }
3658 }
3659 return array( $text, $finalTitle );
3660 }
3661
3662 /**
3663 * Fetch the unparsed text of a template and register a reference to it.
3664 * @param Title $title
3665 * @return mixed string or false
3666 */
3667 function fetchTemplate( $title ) {
3668 $rv = $this->fetchTemplateAndTitle( $title );
3669 return $rv[0];
3670 }
3671
3672 /**
3673 * Static function to get a template
3674 * Can be overridden via ParserOptions::setTemplateCallback().
3675 *
3676 * @param $title Title
3677 * @param $parser Parser
3678 *
3679 * @return array
3680 */
3681 static function statelessFetchTemplate( $title, $parser = false ) {
3682 $text = $skip = false;
3683 $finalTitle = $title;
3684 $deps = array();
3685
3686 # Loop to fetch the article, with up to 1 redirect
3687 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3688 # Give extensions a chance to select the revision instead
3689 $id = false; # Assume current
3690 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3691 array( $parser, $title, &$skip, &$id ) );
3692
3693 if ( $skip ) {
3694 $text = false;
3695 $deps[] = array(
3696 'title' => $title,
3697 'page_id' => $title->getArticleID(),
3698 'rev_id' => null
3699 );
3700 break;
3701 }
3702 # Get the revision
3703 $rev = $id
3704 ? Revision::newFromId( $id )
3705 : Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
3706 $rev_id = $rev ? $rev->getId() : 0;
3707 # If there is no current revision, there is no page
3708 if ( $id === false && !$rev ) {
3709 $linkCache = LinkCache::singleton();
3710 $linkCache->addBadLinkObj( $title );
3711 }
3712
3713 $deps[] = array(
3714 'title' => $title,
3715 'page_id' => $title->getArticleID(),
3716 'rev_id' => $rev_id );
3717 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3718 # We fetched a rev from a different title; register it too...
3719 $deps[] = array(
3720 'title' => $rev->getTitle(),
3721 'page_id' => $rev->getPage(),
3722 'rev_id' => $rev_id );
3723 }
3724
3725 if ( $rev ) {
3726 $content = $rev->getContent();
3727 $text = $content ? $content->getWikitextForTransclusion() : null;
3728
3729 if ( $text === false || $text === null ) {
3730 $text = false;
3731 break;
3732 }
3733 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3734 global $wgContLang;
3735 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3736 if ( !$message->exists() ) {
3737 $text = false;
3738 break;
3739 }
3740 $content = $message->content();
3741 $text = $message->plain();
3742 } else {
3743 break;
3744 }
3745 if ( !$content ) {
3746 break;
3747 }
3748 # Redirect?
3749 $finalTitle = $title;
3750 $title = $content->getRedirectTarget();
3751 }
3752 return array(
3753 'text' => $text,
3754 'finalTitle' => $finalTitle,
3755 'deps' => $deps );
3756 }
3757
3758 /**
3759 * Fetch a file and its title and register a reference to it.
3760 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3761 * @param Title $title
3762 * @param array $options Array of options to RepoGroup::findFile
3763 * @return File|bool
3764 */
3765 function fetchFile( $title, $options = array() ) {
3766 $res = $this->fetchFileAndTitle( $title, $options );
3767 return $res[0];
3768 }
3769
3770 /**
3771 * Fetch a file and its title and register a reference to it.
3772 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3773 * @param Title $title
3774 * @param array $options Array of options to RepoGroup::findFile
3775 * @return Array ( File or false, Title of file )
3776 */
3777 function fetchFileAndTitle( $title, $options = array() ) {
3778 if ( isset( $options['broken'] ) ) {
3779 $file = false; // broken thumbnail forced by hook
3780 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3781 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3782 } else { // get by (name,timestamp)
3783 $file = wfFindFile( $title, $options );
3784 }
3785 $time = $file ? $file->getTimestamp() : false;
3786 $sha1 = $file ? $file->getSha1() : false;
3787 # Register the file as a dependency...
3788 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3789 if ( $file && !$title->equals( $file->getTitle() ) ) {
3790 # Update fetched file title
3791 $title = $file->getTitle();
3792 if ( is_null( $file->getRedirectedTitle() ) ) {
3793 # This file was not a redirect, but the title does not match.
3794 # Register under the new name because otherwise the link will
3795 # get lost.
3796 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3797 }
3798 }
3799 return array( $file, $title );
3800 }
3801
3802 /**
3803 * Transclude an interwiki link.
3804 *
3805 * @param $title Title
3806 * @param $action
3807 *
3808 * @return string
3809 */
3810 function interwikiTransclude( $title, $action ) {
3811 global $wgEnableScaryTranscluding;
3812
3813 if ( !$wgEnableScaryTranscluding ) {
3814 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3815 }
3816
3817 $url = $title->getFullURL( array( 'action' => $action ) );
3818
3819 if ( strlen( $url ) > 255 ) {
3820 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3821 }
3822 return $this->fetchScaryTemplateMaybeFromCache( $url );
3823 }
3824
3825 /**
3826 * @param $url string
3827 * @return Mixed|String
3828 */
3829 function fetchScaryTemplateMaybeFromCache( $url ) {
3830 global $wgTranscludeCacheExpiry;
3831 $dbr = wfGetDB( DB_SLAVE );
3832 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3833 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3834 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3835 if ( $obj ) {
3836 return $obj->tc_contents;
3837 }
3838
3839 $req = MWHttpRequest::factory( $url );
3840 $status = $req->execute(); // Status object
3841 if ( $status->isOK() ) {
3842 $text = $req->getContent();
3843 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3844 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3845 } else {
3846 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3847 }
3848
3849 $dbw = wfGetDB( DB_MASTER );
3850 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3851 'tc_url' => $url,
3852 'tc_time' => $dbw->timestamp( time() ),
3853 'tc_contents' => $text
3854 ) );
3855 return $text;
3856 }
3857
3858 /**
3859 * Triple brace replacement -- used for template arguments
3860 * @private
3861 *
3862 * @param $piece array
3863 * @param $frame PPFrame
3864 *
3865 * @return array
3866 */
3867 function argSubstitution( $piece, $frame ) {
3868 wfProfileIn( __METHOD__ );
3869
3870 $error = false;
3871 $parts = $piece['parts'];
3872 $nameWithSpaces = $frame->expand( $piece['title'] );
3873 $argName = trim( $nameWithSpaces );
3874 $object = false;
3875 $text = $frame->getArgument( $argName );
3876 if ( $text === false && $parts->getLength() > 0
3877 && (
3878 $this->ot['html']
3879 || $this->ot['pre']
3880 || ( $this->ot['wiki'] && $frame->isTemplate() )
3881 )
3882 ) {
3883 # No match in frame, use the supplied default
3884 $object = $parts->item( 0 )->getChildren();
3885 }
3886 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3887 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3888 $this->limitationWarn( 'post-expand-template-argument' );
3889 }
3890
3891 if ( $text === false && $object === false ) {
3892 # No match anywhere
3893 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3894 }
3895 if ( $error !== false ) {
3896 $text .= $error;
3897 }
3898 if ( $object !== false ) {
3899 $ret = array( 'object' => $object );
3900 } else {
3901 $ret = array( 'text' => $text );
3902 }
3903
3904 wfProfileOut( __METHOD__ );
3905 return $ret;
3906 }
3907
3908 /**
3909 * Return the text to be used for a given extension tag.
3910 * This is the ghost of strip().
3911 *
3912 * @param array $params Associative array of parameters:
3913 * name PPNode for the tag name
3914 * attr PPNode for unparsed text where tag attributes are thought to be
3915 * attributes Optional associative array of parsed attributes
3916 * inner Contents of extension element
3917 * noClose Original text did not have a close tag
3918 * @param $frame PPFrame
3919 *
3920 * @throws MWException
3921 * @return string
3922 */
3923 function extensionSubstitution( $params, $frame ) {
3924 $name = $frame->expand( $params['name'] );
3925 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3926 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3927 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3928
3929 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
3930 ( $this->ot['html'] || $this->ot['pre'] );
3931 if ( $isFunctionTag ) {
3932 $markerType = 'none';
3933 } else {
3934 $markerType = 'general';
3935 }
3936 if ( $this->ot['html'] || $isFunctionTag ) {
3937 $name = strtolower( $name );
3938 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3939 if ( isset( $params['attributes'] ) ) {
3940 $attributes = $attributes + $params['attributes'];
3941 }
3942
3943 if ( isset( $this->mTagHooks[$name] ) ) {
3944 # Workaround for PHP bug 35229 and similar
3945 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3946 throw new MWException( "Tag hook for $name is not callable\n" );
3947 }
3948 $output = call_user_func_array( $this->mTagHooks[$name],
3949 array( $content, $attributes, $this, $frame ) );
3950 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3951 list( $callback, ) = $this->mFunctionTagHooks[$name];
3952 if ( !is_callable( $callback ) ) {
3953 throw new MWException( "Tag hook for $name is not callable\n" );
3954 }
3955
3956 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3957 } else {
3958 $output = '<span class="error">Invalid tag extension name: ' .
3959 htmlspecialchars( $name ) . '</span>';
3960 }
3961
3962 if ( is_array( $output ) ) {
3963 # Extract flags to local scope (to override $markerType)
3964 $flags = $output;
3965 $output = $flags[0];
3966 unset( $flags[0] );
3967 extract( $flags );
3968 }
3969 } else {
3970 if ( is_null( $attrText ) ) {
3971 $attrText = '';
3972 }
3973 if ( isset( $params['attributes'] ) ) {
3974 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3975 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3976 htmlspecialchars( $attrValue ) . '"';
3977 }
3978 }
3979 if ( $content === null ) {
3980 $output = "<$name$attrText/>";
3981 } else {
3982 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3983 $output = "<$name$attrText>$content$close";
3984 }
3985 }
3986
3987 if ( $markerType === 'none' ) {
3988 return $output;
3989 } elseif ( $markerType === 'nowiki' ) {
3990 $this->mStripState->addNoWiki( $marker, $output );
3991 } elseif ( $markerType === 'general' ) {
3992 $this->mStripState->addGeneral( $marker, $output );
3993 } else {
3994 throw new MWException( __METHOD__ . ': invalid marker type' );
3995 }
3996 return $marker;
3997 }
3998
3999 /**
4000 * Increment an include size counter
4001 *
4002 * @param string $type the type of expansion
4003 * @param $size Integer: the size of the text
4004 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
4005 */
4006 function incrementIncludeSize( $type, $size ) {
4007 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
4008 return false;
4009 } else {
4010 $this->mIncludeSizes[$type] += $size;
4011 return true;
4012 }
4013 }
4014
4015 /**
4016 * Increment the expensive function count
4017 *
4018 * @return Boolean: false if the limit has been exceeded
4019 */
4020 function incrementExpensiveFunctionCount() {
4021 $this->mExpensiveFunctionCount++;
4022 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
4023 }
4024
4025 /**
4026 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4027 * Fills $this->mDoubleUnderscores, returns the modified text
4028 *
4029 * @param $text string
4030 *
4031 * @return string
4032 */
4033 function doDoubleUnderscore( $text ) {
4034 wfProfileIn( __METHOD__ );
4035
4036 # The position of __TOC__ needs to be recorded
4037 $mw = MagicWord::get( 'toc' );
4038 if ( $mw->match( $text ) ) {
4039 $this->mShowToc = true;
4040 $this->mForceTocPosition = true;
4041
4042 # Set a placeholder. At the end we'll fill it in with the TOC.
4043 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4044
4045 # Only keep the first one.
4046 $text = $mw->replace( '', $text );
4047 }
4048
4049 # Now match and remove the rest of them
4050 $mwa = MagicWord::getDoubleUnderscoreArray();
4051 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
4052
4053 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
4054 $this->mOutput->mNoGallery = true;
4055 }
4056 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
4057 $this->mShowToc = false;
4058 }
4059 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
4060 $this->addTrackingCategory( 'hidden-category-category' );
4061 }
4062 # (bug 8068) Allow control over whether robots index a page.
4063 #
4064 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4065 # is not desirable, the last one on the page should win.
4066 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
4067 $this->mOutput->setIndexPolicy( 'noindex' );
4068 $this->addTrackingCategory( 'noindex-category' );
4069 }
4070 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4071 $this->mOutput->setIndexPolicy( 'index' );
4072 $this->addTrackingCategory( 'index-category' );
4073 }
4074
4075 # Cache all double underscores in the database
4076 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4077 $this->mOutput->setProperty( $key, '' );
4078 }
4079
4080 wfProfileOut( __METHOD__ );
4081 return $text;
4082 }
4083
4084 /**
4085 * Add a tracking category, getting the title from a system message,
4086 * or print a debug message if the title is invalid.
4087 *
4088 * @param string $msg message key
4089 * @return Boolean: whether the addition was successful
4090 */
4091 public function addTrackingCategory( $msg ) {
4092 if ( $this->mTitle->getNamespace() === NS_SPECIAL ) {
4093 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
4094 return false;
4095 }
4096 // Important to parse with correct title (bug 31469)
4097 $cat = wfMessage( $msg )
4098 ->title( $this->getTitle() )
4099 ->inContentLanguage()
4100 ->text();
4101
4102 # Allow tracking categories to be disabled by setting them to "-"
4103 if ( $cat === '-' ) {
4104 return false;
4105 }
4106
4107 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
4108 if ( $containerCategory ) {
4109 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4110 return true;
4111 } else {
4112 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
4113 return false;
4114 }
4115 }
4116
4117 /**
4118 * This function accomplishes several tasks:
4119 * 1) Auto-number headings if that option is enabled
4120 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4121 * 3) Add a Table of contents on the top for users who have enabled the option
4122 * 4) Auto-anchor headings
4123 *
4124 * It loops through all headlines, collects the necessary data, then splits up the
4125 * string and re-inserts the newly formatted headlines.
4126 *
4127 * @param $text String
4128 * @param string $origText original, untouched wikitext
4129 * @param $isMain Boolean
4130 * @return mixed|string
4131 * @private
4132 */
4133 function formatHeadings( $text, $origText, $isMain = true ) {
4134 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4135
4136 # Inhibit editsection links if requested in the page
4137 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4138 $maybeShowEditLink = $showEditLink = false;
4139 } else {
4140 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4141 $showEditLink = $this->mOptions->getEditSection();
4142 }
4143 if ( $showEditLink ) {
4144 $this->mOutput->setEditSectionTokens( true );
4145 }
4146
4147 # Get all headlines for numbering them and adding funky stuff like [edit]
4148 # links - this is for later, but we need the number of headlines right now
4149 $matches = array();
4150 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4151
4152 # if there are fewer than 4 headlines in the article, do not show TOC
4153 # unless it's been explicitly enabled.
4154 $enoughToc = $this->mShowToc &&
4155 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4156
4157 # Allow user to stipulate that a page should have a "new section"
4158 # link added via __NEWSECTIONLINK__
4159 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4160 $this->mOutput->setNewSection( true );
4161 }
4162
4163 # Allow user to remove the "new section"
4164 # link via __NONEWSECTIONLINK__
4165 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4166 $this->mOutput->hideNewSection( true );
4167 }
4168
4169 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4170 # override above conditions and always show TOC above first header
4171 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4172 $this->mShowToc = true;
4173 $enoughToc = true;
4174 }
4175
4176 # headline counter
4177 $headlineCount = 0;
4178 $numVisible = 0;
4179
4180 # Ugh .. the TOC should have neat indentation levels which can be
4181 # passed to the skin functions. These are determined here
4182 $toc = '';
4183 $full = '';
4184 $head = array();
4185 $sublevelCount = array();
4186 $levelCount = array();
4187 $level = 0;
4188 $prevlevel = 0;
4189 $toclevel = 0;
4190 $prevtoclevel = 0;
4191 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
4192 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4193 $oldType = $this->mOutputType;
4194 $this->setOutputType( self::OT_WIKI );
4195 $frame = $this->getPreprocessor()->newFrame();
4196 $root = $this->preprocessToDom( $origText );
4197 $node = $root->getFirstChild();
4198 $byteOffset = 0;
4199 $tocraw = array();
4200 $refers = array();
4201
4202 foreach ( $matches[3] as $headline ) {
4203 $isTemplate = false;
4204 $titleText = false;
4205 $sectionIndex = false;
4206 $numbering = '';
4207 $markerMatches = array();
4208 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4209 $serial = $markerMatches[1];
4210 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4211 $isTemplate = ( $titleText != $baseTitleText );
4212 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4213 }
4214
4215 if ( $toclevel ) {
4216 $prevlevel = $level;
4217 }
4218 $level = $matches[1][$headlineCount];
4219
4220 if ( $level > $prevlevel ) {
4221 # Increase TOC level
4222 $toclevel++;
4223 $sublevelCount[$toclevel] = 0;
4224 if ( $toclevel < $wgMaxTocLevel ) {
4225 $prevtoclevel = $toclevel;
4226 $toc .= Linker::tocIndent();
4227 $numVisible++;
4228 }
4229 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4230 # Decrease TOC level, find level to jump to
4231
4232 for ( $i = $toclevel; $i > 0; $i-- ) {
4233 if ( $levelCount[$i] == $level ) {
4234 # Found last matching level
4235 $toclevel = $i;
4236 break;
4237 } elseif ( $levelCount[$i] < $level ) {
4238 # Found first matching level below current level
4239 $toclevel = $i + 1;
4240 break;
4241 }
4242 }
4243 if ( $i == 0 ) {
4244 $toclevel = 1;
4245 }
4246 if ( $toclevel < $wgMaxTocLevel ) {
4247 if ( $prevtoclevel < $wgMaxTocLevel ) {
4248 # Unindent only if the previous toc level was shown :p
4249 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4250 $prevtoclevel = $toclevel;
4251 } else {
4252 $toc .= Linker::tocLineEnd();
4253 }
4254 }
4255 } else {
4256 # No change in level, end TOC line
4257 if ( $toclevel < $wgMaxTocLevel ) {
4258 $toc .= Linker::tocLineEnd();
4259 }
4260 }
4261
4262 $levelCount[$toclevel] = $level;
4263
4264 # count number of headlines for each level
4265 $sublevelCount[$toclevel]++;
4266 $dot = 0;
4267 for ( $i = 1; $i <= $toclevel; $i++ ) {
4268 if ( !empty( $sublevelCount[$i] ) ) {
4269 if ( $dot ) {
4270 $numbering .= '.';
4271 }
4272 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4273 $dot = 1;
4274 }
4275 }
4276
4277 # The safe header is a version of the header text safe to use for links
4278
4279 # Remove link placeholders by the link text.
4280 # <!--LINK number-->
4281 # turns into
4282 # link text with suffix
4283 # Do this before unstrip since link text can contain strip markers
4284 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4285
4286 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4287 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4288
4289 # Strip out HTML (first regex removes any tag not allowed)
4290 # Allowed tags are:
4291 # * <sup> and <sub> (bug 8393)
4292 # * <i> (bug 26375)
4293 # * <b> (r105284)
4294 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4295 #
4296 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4297 # to allow setting directionality in toc items.
4298 $tocline = preg_replace(
4299 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4300 array( '', '<$1>' ),
4301 $safeHeadline
4302 );
4303 $tocline = trim( $tocline );
4304
4305 # For the anchor, strip out HTML-y stuff period
4306 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4307 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4308
4309 # Save headline for section edit hint before it's escaped
4310 $headlineHint = $safeHeadline;
4311
4312 if ( $wgExperimentalHtmlIds ) {
4313 # For reverse compatibility, provide an id that's
4314 # HTML4-compatible, like we used to.
4315 #
4316 # It may be worth noting, academically, that it's possible for
4317 # the legacy anchor to conflict with a non-legacy headline
4318 # anchor on the page. In this case likely the "correct" thing
4319 # would be to either drop the legacy anchors or make sure
4320 # they're numbered first. However, this would require people
4321 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4322 # manually, so let's not bother worrying about it.
4323 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4324 array( 'noninitial', 'legacy' ) );
4325 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4326
4327 if ( $legacyHeadline == $safeHeadline ) {
4328 # No reason to have both (in fact, we can't)
4329 $legacyHeadline = false;
4330 }
4331 } else {
4332 $legacyHeadline = false;
4333 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4334 'noninitial' );
4335 }
4336
4337 # HTML names must be case-insensitively unique (bug 10721).
4338 # This does not apply to Unicode characters per
4339 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4340 # @todo FIXME: We may be changing them depending on the current locale.
4341 $arrayKey = strtolower( $safeHeadline );
4342 if ( $legacyHeadline === false ) {
4343 $legacyArrayKey = false;
4344 } else {
4345 $legacyArrayKey = strtolower( $legacyHeadline );
4346 }
4347
4348 # count how many in assoc. array so we can track dupes in anchors
4349 if ( isset( $refers[$arrayKey] ) ) {
4350 $refers[$arrayKey]++;
4351 } else {
4352 $refers[$arrayKey] = 1;
4353 }
4354 if ( isset( $refers[$legacyArrayKey] ) ) {
4355 $refers[$legacyArrayKey]++;
4356 } else {
4357 $refers[$legacyArrayKey] = 1;
4358 }
4359
4360 # Don't number the heading if it is the only one (looks silly)
4361 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4362 # the two are different if the line contains a link
4363 $headline = Html::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4364 }
4365
4366 # Create the anchor for linking from the TOC to the section
4367 $anchor = $safeHeadline;
4368 $legacyAnchor = $legacyHeadline;
4369 if ( $refers[$arrayKey] > 1 ) {
4370 $anchor .= '_' . $refers[$arrayKey];
4371 }
4372 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4373 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4374 }
4375 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4376 $toc .= Linker::tocLine( $anchor, $tocline,
4377 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4378 }
4379
4380 # Add the section to the section tree
4381 # Find the DOM node for this header
4382 while ( $node && !$isTemplate ) {
4383 if ( $node->getName() === 'h' ) {
4384 $bits = $node->splitHeading();
4385 if ( $bits['i'] == $sectionIndex ) {
4386 break;
4387 }
4388 }
4389 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4390 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4391 $node = $node->getNextSibling();
4392 }
4393 $tocraw[] = array(
4394 'toclevel' => $toclevel,
4395 'level' => $level,
4396 'line' => $tocline,
4397 'number' => $numbering,
4398 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4399 'fromtitle' => $titleText,
4400 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
4401 'anchor' => $anchor,
4402 );
4403
4404 # give headline the correct <h#> tag
4405 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4406 // Output edit section links as markers with styles that can be customized by skins
4407 if ( $isTemplate ) {
4408 # Put a T flag in the section identifier, to indicate to extractSections()
4409 # that sections inside <includeonly> should be counted.
4410 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4411 } else {
4412 $editlinkArgs = array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint );
4413 }
4414 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4415 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4416 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4417 // so we don't have to worry about a user trying to input one of these markers directly.
4418 // We use a page and section attribute to stop the language converter from converting these important bits
4419 // of data, but put the headline hint inside a content block because the language converter is supposed to
4420 // be able to convert that piece of data.
4421 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4422 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4423 if ( isset( $editlinkArgs[2] ) ) {
4424 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4425 } else {
4426 $editlink .= '/>';
4427 }
4428 } else {
4429 $editlink = '';
4430 }
4431 $head[$headlineCount] = Linker::makeHeadline( $level,
4432 $matches['attrib'][$headlineCount], $anchor, $headline,
4433 $editlink, $legacyAnchor );
4434
4435 $headlineCount++;
4436 }
4437
4438 $this->setOutputType( $oldType );
4439
4440 # Never ever show TOC if no headers
4441 if ( $numVisible < 1 ) {
4442 $enoughToc = false;
4443 }
4444
4445 if ( $enoughToc ) {
4446 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4447 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4448 }
4449 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4450 $this->mOutput->setTOCHTML( $toc );
4451 }
4452
4453 if ( $isMain ) {
4454 $this->mOutput->setSections( $tocraw );
4455 }
4456
4457 # split up and insert constructed headlines
4458 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4459 $i = 0;
4460
4461 // build an array of document sections
4462 $sections = array();
4463 foreach ( $blocks as $block ) {
4464 // $head is zero-based, sections aren't.
4465 if ( empty( $head[$i - 1] ) ) {
4466 $sections[$i] = $block;
4467 } else {
4468 $sections[$i] = $head[$i - 1] . $block;
4469 }
4470
4471 /**
4472 * Send a hook, one per section.
4473 * The idea here is to be able to make section-level DIVs, but to do so in a
4474 * lower-impact, more correct way than r50769
4475 *
4476 * $this : caller
4477 * $section : the section number
4478 * &$sectionContent : ref to the content of the section
4479 * $showEditLinks : boolean describing whether this section has an edit link
4480 */
4481 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4482
4483 $i++;
4484 }
4485
4486 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4487 // append the TOC at the beginning
4488 // Top anchor now in skin
4489 $sections[0] = $sections[0] . $toc . "\n";
4490 }
4491
4492 $full .= join( '', $sections );
4493
4494 if ( $this->mForceTocPosition ) {
4495 return str_replace( '<!--MWTOC-->', $toc, $full );
4496 } else {
4497 return $full;
4498 }
4499 }
4500
4501 /**
4502 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4503 * conversion, substitting signatures, {{subst:}} templates, etc.
4504 *
4505 * @param string $text the text to transform
4506 * @param $title Title: the Title object for the current article
4507 * @param $user User: the User object describing the current user
4508 * @param $options ParserOptions: parsing options
4509 * @param $clearState Boolean: whether to clear the parser state first
4510 * @return String: the altered wiki markup
4511 */
4512 public function preSaveTransform( $text, Title $title, User $user, ParserOptions $options, $clearState = true ) {
4513 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4514 $this->setUser( $user );
4515
4516 $pairs = array(
4517 "\r\n" => "\n",
4518 );
4519 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4520 if ( $options->getPreSaveTransform() ) {
4521 $text = $this->pstPass2( $text, $user );
4522 }
4523 $text = $this->mStripState->unstripBoth( $text );
4524
4525 $this->setUser( null ); #Reset
4526
4527 return $text;
4528 }
4529
4530 /**
4531 * Pre-save transform helper function
4532 * @private
4533 *
4534 * @param $text string
4535 * @param $user User
4536 *
4537 * @return string
4538 */
4539 function pstPass2( $text, $user ) {
4540 global $wgContLang, $wgLocaltimezone;
4541
4542 # Note: This is the timestamp saved as hardcoded wikitext to
4543 # the database, we use $wgContLang here in order to give
4544 # everyone the same signature and use the default one rather
4545 # than the one selected in each user's preferences.
4546 # (see also bug 12815)
4547 $ts = $this->mOptions->getTimestamp();
4548 if ( isset( $wgLocaltimezone ) ) {
4549 $tz = $wgLocaltimezone;
4550 } else {
4551 $tz = date_default_timezone_get();
4552 }
4553
4554 $unixts = wfTimestamp( TS_UNIX, $ts );
4555 $oldtz = date_default_timezone_get();
4556 date_default_timezone_set( $tz );
4557 $ts = date( 'YmdHis', $unixts );
4558 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4559
4560 # Allow translation of timezones through wiki. date() can return
4561 # whatever crap the system uses, localised or not, so we cannot
4562 # ship premade translations.
4563 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4564 $msg = wfMessage( $key )->inContentLanguage();
4565 if ( $msg->exists() ) {
4566 $tzMsg = $msg->text();
4567 }
4568
4569 date_default_timezone_set( $oldtz );
4570
4571 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4572
4573 # Variable replacement
4574 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4575 $text = $this->replaceVariables( $text );
4576
4577 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4578 # which may corrupt this parser instance via its wfMessage()->text() call-
4579
4580 # Signatures
4581 $sigText = $this->getUserSig( $user );
4582 $text = strtr( $text, array(
4583 '~~~~~' => $d,
4584 '~~~~' => "$sigText $d",
4585 '~~~' => $sigText
4586 ) );
4587
4588 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4589 $tc = '[' . Title::legalChars() . ']';
4590 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4591
4592 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4593 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4594 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4595 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4596
4597 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4598 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4599 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4600 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4601
4602 $t = $this->mTitle->getText();
4603 $m = array();
4604 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4605 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4606 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4607 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4608 } else {
4609 # if there's no context, don't bother duplicating the title
4610 $text = preg_replace( $p2, '[[\\1]]', $text );
4611 }
4612
4613 # Trim trailing whitespace
4614 $text = rtrim( $text );
4615
4616 return $text;
4617 }
4618
4619 /**
4620 * Fetch the user's signature text, if any, and normalize to
4621 * validated, ready-to-insert wikitext.
4622 * If you have pre-fetched the nickname or the fancySig option, you can
4623 * specify them here to save a database query.
4624 * Do not reuse this parser instance after calling getUserSig(),
4625 * as it may have changed if it's the $wgParser.
4626 *
4627 * @param $user User
4628 * @param string|bool $nickname nickname to use or false to use user's default nickname
4629 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4630 * or null to use default value
4631 * @return string
4632 */
4633 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4634 global $wgMaxSigChars;
4635
4636 $username = $user->getName();
4637
4638 # If not given, retrieve from the user object.
4639 if ( $nickname === false ) {
4640 $nickname = $user->getOption( 'nickname' );
4641 }
4642
4643 if ( is_null( $fancySig ) ) {
4644 $fancySig = $user->getBoolOption( 'fancysig' );
4645 }
4646
4647 $nickname = $nickname == null ? $username : $nickname;
4648
4649 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4650 $nickname = $username;
4651 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4652 } elseif ( $fancySig !== false ) {
4653 # Sig. might contain markup; validate this
4654 if ( $this->validateSig( $nickname ) !== false ) {
4655 # Validated; clean up (if needed) and return it
4656 return $this->cleanSig( $nickname, true );
4657 } else {
4658 # Failed to validate; fall back to the default
4659 $nickname = $username;
4660 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4661 }
4662 }
4663
4664 # Make sure nickname doesnt get a sig in a sig
4665 $nickname = self::cleanSigInSig( $nickname );
4666
4667 # If we're still here, make it a link to the user page
4668 $userText = wfEscapeWikiText( $username );
4669 $nickText = wfEscapeWikiText( $nickname );
4670 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4671
4672 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4673 }
4674
4675 /**
4676 * Check that the user's signature contains no bad XML
4677 *
4678 * @param $text String
4679 * @return mixed An expanded string, or false if invalid.
4680 */
4681 function validateSig( $text ) {
4682 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4683 }
4684
4685 /**
4686 * Clean up signature text
4687 *
4688 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4689 * 2) Substitute all transclusions
4690 *
4691 * @param $text String
4692 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4693 * @return String: signature text
4694 */
4695 public function cleanSig( $text, $parsing = false ) {
4696 if ( !$parsing ) {
4697 global $wgTitle;
4698 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4699 }
4700
4701 # Option to disable this feature
4702 if ( !$this->mOptions->getCleanSignatures() ) {
4703 return $text;
4704 }
4705
4706 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4707 # => Move this logic to braceSubstitution()
4708 $substWord = MagicWord::get( 'subst' );
4709 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4710 $substText = '{{' . $substWord->getSynonym( 0 );
4711
4712 $text = preg_replace( $substRegex, $substText, $text );
4713 $text = self::cleanSigInSig( $text );
4714 $dom = $this->preprocessToDom( $text );
4715 $frame = $this->getPreprocessor()->newFrame();
4716 $text = $frame->expand( $dom );
4717
4718 if ( !$parsing ) {
4719 $text = $this->mStripState->unstripBoth( $text );
4720 }
4721
4722 return $text;
4723 }
4724
4725 /**
4726 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4727 *
4728 * @param $text String
4729 * @return String: signature text with /~{3,5}/ removed
4730 */
4731 public static function cleanSigInSig( $text ) {
4732 $text = preg_replace( '/~{3,5}/', '', $text );
4733 return $text;
4734 }
4735
4736 /**
4737 * Set up some variables which are usually set up in parse()
4738 * so that an external function can call some class members with confidence
4739 *
4740 * @param $title Title|null
4741 * @param $options ParserOptions
4742 * @param $outputType
4743 * @param $clearState bool
4744 */
4745 public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4746 $this->startParse( $title, $options, $outputType, $clearState );
4747 }
4748
4749 /**
4750 * @param $title Title|null
4751 * @param $options ParserOptions
4752 * @param $outputType
4753 * @param $clearState bool
4754 */
4755 private function startParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4756 $this->setTitle( $title );
4757 $this->mOptions = $options;
4758 $this->setOutputType( $outputType );
4759 if ( $clearState ) {
4760 $this->clearState();
4761 }
4762 }
4763
4764 /**
4765 * Wrapper for preprocess()
4766 *
4767 * @param string $text the text to preprocess
4768 * @param $options ParserOptions: options
4769 * @param $title Title object or null to use $wgTitle
4770 * @return String
4771 */
4772 public function transformMsg( $text, $options, $title = null ) {
4773 static $executing = false;
4774
4775 # Guard against infinite recursion
4776 if ( $executing ) {
4777 return $text;
4778 }
4779 $executing = true;
4780
4781 wfProfileIn( __METHOD__ );
4782 if ( !$title ) {
4783 global $wgTitle;
4784 $title = $wgTitle;
4785 }
4786
4787 $text = $this->preprocess( $text, $title, $options );
4788
4789 $executing = false;
4790 wfProfileOut( __METHOD__ );
4791 return $text;
4792 }
4793
4794 /**
4795 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4796 * The callback should have the following form:
4797 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4798 *
4799 * Transform and return $text. Use $parser for any required context, e.g. use
4800 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4801 *
4802 * Hooks may return extended information by returning an array, of which the
4803 * first numbered element (index 0) must be the return string, and all other
4804 * entries are extracted into local variables within an internal function
4805 * in the Parser class.
4806 *
4807 * This interface (introduced r61913) appears to be undocumented, but
4808 * 'markerName' is used by some core tag hooks to override which strip
4809 * array their results are placed in. **Use great caution if attempting
4810 * this interface, as it is not documented and injudicious use could smash
4811 * private variables.**
4812 *
4813 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4814 * @param $callback Mixed: the callback function (and object) to use for the tag
4815 * @throws MWException
4816 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4817 */
4818 public function setHook( $tag, $callback ) {
4819 $tag = strtolower( $tag );
4820 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4821 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4822 }
4823 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4824 $this->mTagHooks[$tag] = $callback;
4825 if ( !in_array( $tag, $this->mStripList ) ) {
4826 $this->mStripList[] = $tag;
4827 }
4828
4829 return $oldVal;
4830 }
4831
4832 /**
4833 * As setHook(), but letting the contents be parsed.
4834 *
4835 * Transparent tag hooks are like regular XML-style tag hooks, except they
4836 * operate late in the transformation sequence, on HTML instead of wikitext.
4837 *
4838 * This is probably obsoleted by things dealing with parser frames?
4839 * The only extension currently using it is geoserver.
4840 *
4841 * @since 1.10
4842 * @todo better document or deprecate this
4843 *
4844 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4845 * @param $callback Mixed: the callback function (and object) to use for the tag
4846 * @throws MWException
4847 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4848 */
4849 function setTransparentTagHook( $tag, $callback ) {
4850 $tag = strtolower( $tag );
4851 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4852 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4853 }
4854 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4855 $this->mTransparentTagHooks[$tag] = $callback;
4856
4857 return $oldVal;
4858 }
4859
4860 /**
4861 * Remove all tag hooks
4862 */
4863 function clearTagHooks() {
4864 $this->mTagHooks = array();
4865 $this->mFunctionTagHooks = array();
4866 $this->mStripList = $this->mDefaultStripList;
4867 }
4868
4869 /**
4870 * Create a function, e.g. {{sum:1|2|3}}
4871 * The callback function should have the form:
4872 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4873 *
4874 * Or with SFH_OBJECT_ARGS:
4875 * function myParserFunction( $parser, $frame, $args ) { ... }
4876 *
4877 * The callback may either return the text result of the function, or an array with the text
4878 * in element 0, and a number of flags in the other elements. The names of the flags are
4879 * specified in the keys. Valid flags are:
4880 * found The text returned is valid, stop processing the template. This
4881 * is on by default.
4882 * nowiki Wiki markup in the return value should be escaped
4883 * isHTML The returned text is HTML, armour it against wikitext transformation
4884 *
4885 * @param string $id The magic word ID
4886 * @param $callback Mixed: the callback function (and object) to use
4887 * @param $flags Integer: a combination of the following flags:
4888 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4889 *
4890 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4891 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4892 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4893 * the arguments, and to control the way they are expanded.
4894 *
4895 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4896 * arguments, for instance:
4897 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4898 *
4899 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4900 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4901 * working if/when this is changed.
4902 *
4903 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4904 * expansion.
4905 *
4906 * Please read the documentation in includes/parser/Preprocessor.php for more information
4907 * about the methods available in PPFrame and PPNode.
4908 *
4909 * @throws MWException
4910 * @return string|callback The old callback function for this name, if any
4911 */
4912 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4913 global $wgContLang;
4914
4915 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4916 $this->mFunctionHooks[$id] = array( $callback, $flags );
4917
4918 # Add to function cache
4919 $mw = MagicWord::get( $id );
4920 if ( !$mw ) {
4921 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
4922 }
4923
4924 $synonyms = $mw->getSynonyms();
4925 $sensitive = intval( $mw->isCaseSensitive() );
4926
4927 foreach ( $synonyms as $syn ) {
4928 # Case
4929 if ( !$sensitive ) {
4930 $syn = $wgContLang->lc( $syn );
4931 }
4932 # Add leading hash
4933 if ( !( $flags & SFH_NO_HASH ) ) {
4934 $syn = '#' . $syn;
4935 }
4936 # Remove trailing colon
4937 if ( substr( $syn, -1, 1 ) === ':' ) {
4938 $syn = substr( $syn, 0, -1 );
4939 }
4940 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4941 }
4942 return $oldVal;
4943 }
4944
4945 /**
4946 * Get all registered function hook identifiers
4947 *
4948 * @return Array
4949 */
4950 function getFunctionHooks() {
4951 return array_keys( $this->mFunctionHooks );
4952 }
4953
4954 /**
4955 * Create a tag function, e.g. "<test>some stuff</test>".
4956 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4957 * Unlike parser functions, their content is not preprocessed.
4958 * @param $tag
4959 * @param $callback
4960 * @param $flags
4961 * @throws MWException
4962 * @return null
4963 */
4964 function setFunctionTagHook( $tag, $callback, $flags ) {
4965 $tag = strtolower( $tag );
4966 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4967 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4968 }
4969 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4970 $this->mFunctionTagHooks[$tag] : null;
4971 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
4972
4973 if ( !in_array( $tag, $this->mStripList ) ) {
4974 $this->mStripList[] = $tag;
4975 }
4976
4977 return $old;
4978 }
4979
4980 /**
4981 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4982 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4983 * Placeholders created in Skin::makeLinkObj()
4984 *
4985 * @param $text string
4986 * @param $options int
4987 *
4988 * @return array of link CSS classes, indexed by PDBK.
4989 */
4990 function replaceLinkHolders( &$text, $options = 0 ) {
4991 return $this->mLinkHolders->replace( $text );
4992 }
4993
4994 /**
4995 * Replace "<!--LINK-->" link placeholders with plain text of links
4996 * (not HTML-formatted).
4997 *
4998 * @param $text String
4999 * @return String
5000 */
5001 function replaceLinkHoldersText( $text ) {
5002 return $this->mLinkHolders->replaceText( $text );
5003 }
5004
5005 /**
5006 * Renders an image gallery from a text with one line per image.
5007 * text labels may be given by using |-style alternative text. E.g.
5008 * Image:one.jpg|The number "1"
5009 * Image:tree.jpg|A tree
5010 * given as text will return the HTML of a gallery with two images,
5011 * labeled 'The number "1"' and
5012 * 'A tree'.
5013 *
5014 * @param string $text
5015 * @param array $params
5016 * @return string HTML
5017 */
5018 function renderImageGallery( $text, $params ) {
5019 $ig = new ImageGallery();
5020 $ig->setContextTitle( $this->mTitle );
5021 $ig->setShowBytes( false );
5022 $ig->setShowFilename( false );
5023 $ig->setParser( $this );
5024 $ig->setHideBadImages();
5025 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
5026
5027 if ( isset( $params['showfilename'] ) ) {
5028 $ig->setShowFilename( true );
5029 } else {
5030 $ig->setShowFilename( false );
5031 }
5032 if ( isset( $params['caption'] ) ) {
5033 $caption = $params['caption'];
5034 $caption = htmlspecialchars( $caption );
5035 $caption = $this->replaceInternalLinks( $caption );
5036 $ig->setCaptionHtml( $caption );
5037 }
5038 if ( isset( $params['perrow'] ) ) {
5039 $ig->setPerRow( $params['perrow'] );
5040 }
5041 if ( isset( $params['widths'] ) ) {
5042 $ig->setWidths( $params['widths'] );
5043 }
5044 if ( isset( $params['heights'] ) ) {
5045 $ig->setHeights( $params['heights'] );
5046 }
5047
5048 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5049
5050 $lines = StringUtils::explode( "\n", $text );
5051 foreach ( $lines as $line ) {
5052 # match lines like these:
5053 # Image:someimage.jpg|This is some image
5054 $matches = array();
5055 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5056 # Skip empty lines
5057 if ( count( $matches ) == 0 ) {
5058 continue;
5059 }
5060
5061 if ( strpos( $matches[0], '%' ) !== false ) {
5062 $matches[1] = rawurldecode( $matches[1] );
5063 }
5064 $title = Title::newFromText( $matches[1], NS_FILE );
5065 if ( is_null( $title ) ) {
5066 # Bogus title. Ignore these so we don't bomb out later.
5067 continue;
5068 }
5069
5070 $label = '';
5071 $alt = '';
5072 $link = '';
5073 if ( isset( $matches[3] ) ) {
5074 // look for an |alt= definition while trying not to break existing
5075 // captions with multiple pipes (|) in it, until a more sensible grammar
5076 // is defined for images in galleries
5077
5078 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5079 $parameterMatches = StringUtils::explode( '|', $matches[3] );
5080 $magicWordAlt = MagicWord::get( 'img_alt' );
5081 $magicWordLink = MagicWord::get( 'img_link' );
5082
5083 foreach ( $parameterMatches as $parameterMatch ) {
5084 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
5085 $alt = $this->stripAltText( $match, false );
5086 }
5087 elseif ( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ) {
5088 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5089 $chars = self::EXT_LINK_URL_CLASS;
5090 $prots = $this->mUrlProtocols;
5091 //check to see if link matches an absolute url, if not then it must be a wiki link.
5092 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5093 $link = $linkValue;
5094 } else {
5095 $localLinkTitle = Title::newFromText( $linkValue );
5096 if ( $localLinkTitle !== null ) {
5097 $link = $localLinkTitle->getLocalURL();
5098 }
5099 }
5100 }
5101 else {
5102 // concatenate all other pipes
5103 $label .= '|' . $parameterMatch;
5104 }
5105 }
5106 // remove the first pipe
5107 $label = substr( $label, 1 );
5108 }
5109
5110 $ig->add( $title, $label, $alt, $link );
5111 }
5112 return $ig->toHTML();
5113 }
5114
5115 /**
5116 * @param $handler
5117 * @return array
5118 */
5119 function getImageParams( $handler ) {
5120 if ( $handler ) {
5121 $handlerClass = get_class( $handler );
5122 } else {
5123 $handlerClass = '';
5124 }
5125 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5126 # Initialise static lists
5127 static $internalParamNames = array(
5128 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5129 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5130 'bottom', 'text-bottom' ),
5131 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5132 'upright', 'border', 'link', 'alt', 'class' ),
5133 );
5134 static $internalParamMap;
5135 if ( !$internalParamMap ) {
5136 $internalParamMap = array();
5137 foreach ( $internalParamNames as $type => $names ) {
5138 foreach ( $names as $name ) {
5139 $magicName = str_replace( '-', '_', "img_$name" );
5140 $internalParamMap[$magicName] = array( $type, $name );
5141 }
5142 }
5143 }
5144
5145 # Add handler params
5146 $paramMap = $internalParamMap;
5147 if ( $handler ) {
5148 $handlerParamMap = $handler->getParamMap();
5149 foreach ( $handlerParamMap as $magic => $paramName ) {
5150 $paramMap[$magic] = array( 'handler', $paramName );
5151 }
5152 }
5153 $this->mImageParams[$handlerClass] = $paramMap;
5154 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5155 }
5156 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
5157 }
5158
5159 /**
5160 * Parse image options text and use it to make an image
5161 *
5162 * @param $title Title
5163 * @param $options String
5164 * @param $holders LinkHolderArray|bool
5165 * @return string HTML
5166 */
5167 function makeImage( $title, $options, $holders = false ) {
5168 # Check if the options text is of the form "options|alt text"
5169 # Options are:
5170 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5171 # * left no resizing, just left align. label is used for alt= only
5172 # * right same, but right aligned
5173 # * none same, but not aligned
5174 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5175 # * center center the image
5176 # * frame Keep original image size, no magnify-button.
5177 # * framed Same as "frame"
5178 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5179 # * upright reduce width for upright images, rounded to full __0 px
5180 # * border draw a 1px border around the image
5181 # * alt Text for HTML alt attribute (defaults to empty)
5182 # * class Set a class for img node
5183 # * link Set the target of the image link. Can be external, interwiki, or local
5184 # vertical-align values (no % or length right now):
5185 # * baseline
5186 # * sub
5187 # * super
5188 # * top
5189 # * text-top
5190 # * middle
5191 # * bottom
5192 # * text-bottom
5193
5194 $parts = StringUtils::explode( "|", $options );
5195
5196 # Give extensions a chance to select the file revision for us
5197 $options = array();
5198 $descQuery = false;
5199 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5200 array( $this, $title, &$options, &$descQuery ) );
5201 # Fetch and register the file (file title may be different via hooks)
5202 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5203
5204 # Get parameter map
5205 $handler = $file ? $file->getHandler() : false;
5206
5207 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5208
5209 if ( !$file ) {
5210 $this->addTrackingCategory( 'broken-file-category' );
5211 }
5212
5213 # Process the input parameters
5214 $caption = '';
5215 $params = array( 'frame' => array(), 'handler' => array(),
5216 'horizAlign' => array(), 'vertAlign' => array() );
5217 foreach ( $parts as $part ) {
5218 $part = trim( $part );
5219 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5220 $validated = false;
5221 if ( isset( $paramMap[$magicName] ) ) {
5222 list( $type, $paramName ) = $paramMap[$magicName];
5223
5224 # Special case; width and height come in one variable together
5225 if ( $type === 'handler' && $paramName === 'width' ) {
5226 $parsedWidthParam = $this->parseWidthParam( $value );
5227 if ( isset( $parsedWidthParam['width'] ) ) {
5228 $width = $parsedWidthParam['width'];
5229 if ( $handler->validateParam( 'width', $width ) ) {
5230 $params[$type]['width'] = $width;
5231 $validated = true;
5232 }
5233 }
5234 if ( isset( $parsedWidthParam['height'] ) ) {
5235 $height = $parsedWidthParam['height'];
5236 if ( $handler->validateParam( 'height', $height ) ) {
5237 $params[$type]['height'] = $height;
5238 $validated = true;
5239 }
5240 }
5241 # else no validation -- bug 13436
5242 } else {
5243 if ( $type === 'handler' ) {
5244 # Validate handler parameter
5245 $validated = $handler->validateParam( $paramName, $value );
5246 } else {
5247 # Validate internal parameters
5248 switch ( $paramName ) {
5249 case 'manualthumb':
5250 case 'alt':
5251 case 'class':
5252 # @todo FIXME: Possibly check validity here for
5253 # manualthumb? downstream behavior seems odd with
5254 # missing manual thumbs.
5255 $validated = true;
5256 $value = $this->stripAltText( $value, $holders );
5257 break;
5258 case 'link':
5259 $chars = self::EXT_LINK_URL_CLASS;
5260 $prots = $this->mUrlProtocols;
5261 if ( $value === '' ) {
5262 $paramName = 'no-link';
5263 $value = true;
5264 $validated = true;
5265 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5266 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5267 $paramName = 'link-url';
5268 $this->mOutput->addExternalLink( $value );
5269 if ( $this->mOptions->getExternalLinkTarget() ) {
5270 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5271 }
5272 $validated = true;
5273 }
5274 } else {
5275 $linkTitle = Title::newFromText( $value );
5276 if ( $linkTitle ) {
5277 $paramName = 'link-title';
5278 $value = $linkTitle;
5279 $this->mOutput->addLink( $linkTitle );
5280 $validated = true;
5281 }
5282 }
5283 break;
5284 default:
5285 # Most other things appear to be empty or numeric...
5286 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5287 }
5288 }
5289
5290 if ( $validated ) {
5291 $params[$type][$paramName] = $value;
5292 }
5293 }
5294 }
5295 if ( !$validated ) {
5296 $caption = $part;
5297 }
5298 }
5299
5300 # Process alignment parameters
5301 if ( $params['horizAlign'] ) {
5302 $params['frame']['align'] = key( $params['horizAlign'] );
5303 }
5304 if ( $params['vertAlign'] ) {
5305 $params['frame']['valign'] = key( $params['vertAlign'] );
5306 }
5307
5308 $params['frame']['caption'] = $caption;
5309
5310 # Will the image be presented in a frame, with the caption below?
5311 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5312 isset( $params['frame']['framed'] ) ||
5313 isset( $params['frame']['thumbnail'] ) ||
5314 isset( $params['frame']['manualthumb'] );
5315
5316 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5317 # came to also set the caption, ordinary text after the image -- which
5318 # makes no sense, because that just repeats the text multiple times in
5319 # screen readers. It *also* came to set the title attribute.
5320 #
5321 # Now that we have an alt attribute, we should not set the alt text to
5322 # equal the caption: that's worse than useless, it just repeats the
5323 # text. This is the framed/thumbnail case. If there's no caption, we
5324 # use the unnamed parameter for alt text as well, just for the time be-
5325 # ing, if the unnamed param is set and the alt param is not.
5326 #
5327 # For the future, we need to figure out if we want to tweak this more,
5328 # e.g., introducing a title= parameter for the title; ignoring the un-
5329 # named parameter entirely for images without a caption; adding an ex-
5330 # plicit caption= parameter and preserving the old magic unnamed para-
5331 # meter for BC; ...
5332 if ( $imageIsFramed ) { # Framed image
5333 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5334 # No caption or alt text, add the filename as the alt text so
5335 # that screen readers at least get some description of the image
5336 $params['frame']['alt'] = $title->getText();
5337 }
5338 # Do not set $params['frame']['title'] because tooltips don't make sense
5339 # for framed images
5340 } else { # Inline image
5341 if ( !isset( $params['frame']['alt'] ) ) {
5342 # No alt text, use the "caption" for the alt text
5343 if ( $caption !== '' ) {
5344 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5345 } else {
5346 # No caption, fall back to using the filename for the
5347 # alt text
5348 $params['frame']['alt'] = $title->getText();
5349 }
5350 }
5351 # Use the "caption" for the tooltip text
5352 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5353 }
5354
5355 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5356
5357 # Linker does the rest
5358 $time = isset( $options['time'] ) ? $options['time'] : false;
5359 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5360 $time, $descQuery, $this->mOptions->getThumbSize() );
5361
5362 # Give the handler a chance to modify the parser object
5363 if ( $handler ) {
5364 $handler->parserTransformHook( $this, $file );
5365 }
5366
5367 return $ret;
5368 }
5369
5370 /**
5371 * @param $caption
5372 * @param $holders LinkHolderArray
5373 * @return mixed|String
5374 */
5375 protected function stripAltText( $caption, $holders ) {
5376 # Strip bad stuff out of the title (tooltip). We can't just use
5377 # replaceLinkHoldersText() here, because if this function is called
5378 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5379 if ( $holders ) {
5380 $tooltip = $holders->replaceText( $caption );
5381 } else {
5382 $tooltip = $this->replaceLinkHoldersText( $caption );
5383 }
5384
5385 # make sure there are no placeholders in thumbnail attributes
5386 # that are later expanded to html- so expand them now and
5387 # remove the tags
5388 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5389 $tooltip = Sanitizer::stripAllTags( $tooltip );
5390
5391 return $tooltip;
5392 }
5393
5394 /**
5395 * Set a flag in the output object indicating that the content is dynamic and
5396 * shouldn't be cached.
5397 */
5398 function disableCache() {
5399 wfDebug( "Parser output marked as uncacheable.\n" );
5400 if ( !$this->mOutput ) {
5401 throw new MWException( __METHOD__ .
5402 " can only be called when actually parsing something" );
5403 }
5404 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
5405 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5406 }
5407
5408 /**
5409 * Callback from the Sanitizer for expanding items found in HTML attribute
5410 * values, so they can be safely tested and escaped.
5411 *
5412 * @param $text String
5413 * @param $frame PPFrame
5414 * @return String
5415 */
5416 function attributeStripCallback( &$text, $frame = false ) {
5417 $text = $this->replaceVariables( $text, $frame );
5418 $text = $this->mStripState->unstripBoth( $text );
5419 return $text;
5420 }
5421
5422 /**
5423 * Accessor
5424 *
5425 * @return array
5426 */
5427 function getTags() {
5428 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ), array_keys( $this->mFunctionTagHooks ) );
5429 }
5430
5431 /**
5432 * Replace transparent tags in $text with the values given by the callbacks.
5433 *
5434 * Transparent tag hooks are like regular XML-style tag hooks, except they
5435 * operate late in the transformation sequence, on HTML instead of wikitext.
5436 *
5437 * @param $text string
5438 *
5439 * @return string
5440 */
5441 function replaceTransparentTags( $text ) {
5442 $matches = array();
5443 $elements = array_keys( $this->mTransparentTagHooks );
5444 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
5445 $replacements = array();
5446
5447 foreach ( $matches as $marker => $data ) {
5448 list( $element, $content, $params, $tag ) = $data;
5449 $tagName = strtolower( $element );
5450 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5451 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) );
5452 } else {
5453 $output = $tag;
5454 }
5455 $replacements[$marker] = $output;
5456 }
5457 return strtr( $text, $replacements );
5458 }
5459
5460 /**
5461 * Break wikitext input into sections, and either pull or replace
5462 * some particular section's text.
5463 *
5464 * External callers should use the getSection and replaceSection methods.
5465 *
5466 * @param string $text Page wikitext
5467 * @param string $section a section identifier string of the form:
5468 * "<flag1> - <flag2> - ... - <section number>"
5469 *
5470 * Currently the only recognised flag is "T", which means the target section number
5471 * was derived during a template inclusion parse, in other words this is a template
5472 * section edit link. If no flags are given, it was an ordinary section edit link.
5473 * This flag is required to avoid a section numbering mismatch when a section is
5474 * enclosed by "<includeonly>" (bug 6563).
5475 *
5476 * The section number 0 pulls the text before the first heading; other numbers will
5477 * pull the given section along with its lower-level subsections. If the section is
5478 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5479 *
5480 * Section 0 is always considered to exist, even if it only contains the empty
5481 * string. If $text is the empty string and section 0 is replaced, $newText is
5482 * returned.
5483 *
5484 * @param string $mode one of "get" or "replace"
5485 * @param string $newText replacement text for section data.
5486 * @return String: for "get", the extracted section text.
5487 * for "replace", the whole page with the section replaced.
5488 */
5489 private function extractSections( $text, $section, $mode, $newText = '' ) {
5490 global $wgTitle; # not generally used but removes an ugly failure mode
5491 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5492 $outText = '';
5493 $frame = $this->getPreprocessor()->newFrame();
5494
5495 # Process section extraction flags
5496 $flags = 0;
5497 $sectionParts = explode( '-', $section );
5498 $sectionIndex = array_pop( $sectionParts );
5499 foreach ( $sectionParts as $part ) {
5500 if ( $part === 'T' ) {
5501 $flags |= self::PTD_FOR_INCLUSION;
5502 }
5503 }
5504
5505 # Check for empty input
5506 if ( strval( $text ) === '' ) {
5507 # Only sections 0 and T-0 exist in an empty document
5508 if ( $sectionIndex == 0 ) {
5509 if ( $mode === 'get' ) {
5510 return '';
5511 } else {
5512 return $newText;
5513 }
5514 } else {
5515 if ( $mode === 'get' ) {
5516 return $newText;
5517 } else {
5518 return $text;
5519 }
5520 }
5521 }
5522
5523 # Preprocess the text
5524 $root = $this->preprocessToDom( $text, $flags );
5525
5526 # <h> nodes indicate section breaks
5527 # They can only occur at the top level, so we can find them by iterating the root's children
5528 $node = $root->getFirstChild();
5529
5530 # Find the target section
5531 if ( $sectionIndex == 0 ) {
5532 # Section zero doesn't nest, level=big
5533 $targetLevel = 1000;
5534 } else {
5535 while ( $node ) {
5536 if ( $node->getName() === 'h' ) {
5537 $bits = $node->splitHeading();
5538 if ( $bits['i'] == $sectionIndex ) {
5539 $targetLevel = $bits['level'];
5540 break;
5541 }
5542 }
5543 if ( $mode === 'replace' ) {
5544 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5545 }
5546 $node = $node->getNextSibling();
5547 }
5548 }
5549
5550 if ( !$node ) {
5551 # Not found
5552 if ( $mode === 'get' ) {
5553 return $newText;
5554 } else {
5555 return $text;
5556 }
5557 }
5558
5559 # Find the end of the section, including nested sections
5560 do {
5561 if ( $node->getName() === 'h' ) {
5562 $bits = $node->splitHeading();
5563 $curLevel = $bits['level'];
5564 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5565 break;
5566 }
5567 }
5568 if ( $mode === 'get' ) {
5569 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5570 }
5571 $node = $node->getNextSibling();
5572 } while ( $node );
5573
5574 # Write out the remainder (in replace mode only)
5575 if ( $mode === 'replace' ) {
5576 # Output the replacement text
5577 # Add two newlines on -- trailing whitespace in $newText is conventionally
5578 # stripped by the editor, so we need both newlines to restore the paragraph gap
5579 # Only add trailing whitespace if there is newText
5580 if ( $newText != "" ) {
5581 $outText .= $newText . "\n\n";
5582 }
5583
5584 while ( $node ) {
5585 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5586 $node = $node->getNextSibling();
5587 }
5588 }
5589
5590 if ( is_string( $outText ) ) {
5591 # Re-insert stripped tags
5592 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5593 }
5594
5595 return $outText;
5596 }
5597
5598 /**
5599 * This function returns the text of a section, specified by a number ($section).
5600 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5601 * the first section before any such heading (section 0).
5602 *
5603 * If a section contains subsections, these are also returned.
5604 *
5605 * @param string $text text to look in
5606 * @param string $section section identifier
5607 * @param string $deftext default to return if section is not found
5608 * @return string text of the requested section
5609 */
5610 public function getSection( $text, $section, $deftext = '' ) {
5611 return $this->extractSections( $text, $section, "get", $deftext );
5612 }
5613
5614 /**
5615 * This function returns $oldtext after the content of the section
5616 * specified by $section has been replaced with $text. If the target
5617 * section does not exist, $oldtext is returned unchanged.
5618 *
5619 * @param string $oldtext former text of the article
5620 * @param int $section section identifier
5621 * @param string $text replacing text
5622 * @return String: modified text
5623 */
5624 public function replaceSection( $oldtext, $section, $text ) {
5625 return $this->extractSections( $oldtext, $section, "replace", $text );
5626 }
5627
5628 /**
5629 * Get the ID of the revision we are parsing
5630 *
5631 * @return Mixed: integer or null
5632 */
5633 function getRevisionId() {
5634 return $this->mRevisionId;
5635 }
5636
5637 /**
5638 * Get the revision object for $this->mRevisionId
5639 *
5640 * @return Revision|null either a Revision object or null
5641 */
5642 protected function getRevisionObject() {
5643 if ( !is_null( $this->mRevisionObject ) ) {
5644 return $this->mRevisionObject;
5645 }
5646 if ( is_null( $this->mRevisionId ) ) {
5647 return null;
5648 }
5649
5650 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
5651 return $this->mRevisionObject;
5652 }
5653
5654 /**
5655 * Get the timestamp associated with the current revision, adjusted for
5656 * the default server-local timestamp
5657 */
5658 function getRevisionTimestamp() {
5659 if ( is_null( $this->mRevisionTimestamp ) ) {
5660 wfProfileIn( __METHOD__ );
5661
5662 global $wgContLang;
5663
5664 $revObject = $this->getRevisionObject();
5665 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5666
5667 # The cryptic '' timezone parameter tells to use the site-default
5668 # timezone offset instead of the user settings.
5669 #
5670 # Since this value will be saved into the parser cache, served
5671 # to other users, and potentially even used inside links and such,
5672 # it needs to be consistent for all visitors.
5673 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5674
5675 wfProfileOut( __METHOD__ );
5676 }
5677 return $this->mRevisionTimestamp;
5678 }
5679
5680 /**
5681 * Get the name of the user that edited the last revision
5682 *
5683 * @return String: user name
5684 */
5685 function getRevisionUser() {
5686 if ( is_null( $this->mRevisionUser ) ) {
5687 $revObject = $this->getRevisionObject();
5688
5689 # if this template is subst: the revision id will be blank,
5690 # so just use the current user's name
5691 if ( $revObject ) {
5692 $this->mRevisionUser = $revObject->getUserText();
5693 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5694 $this->mRevisionUser = $this->getUser()->getName();
5695 }
5696 }
5697 return $this->mRevisionUser;
5698 }
5699
5700 /**
5701 * Mutator for $mDefaultSort
5702 *
5703 * @param string $sort New value
5704 */
5705 public function setDefaultSort( $sort ) {
5706 $this->mDefaultSort = $sort;
5707 $this->mOutput->setProperty( 'defaultsort', $sort );
5708 }
5709
5710 /**
5711 * Accessor for $mDefaultSort
5712 * Will use the empty string if none is set.
5713 *
5714 * This value is treated as a prefix, so the
5715 * empty string is equivalent to sorting by
5716 * page name.
5717 *
5718 * @return string
5719 */
5720 public function getDefaultSort() {
5721 if ( $this->mDefaultSort !== false ) {
5722 return $this->mDefaultSort;
5723 } else {
5724 return '';
5725 }
5726 }
5727
5728 /**
5729 * Accessor for $mDefaultSort
5730 * Unlike getDefaultSort(), will return false if none is set
5731 *
5732 * @return string or false
5733 */
5734 public function getCustomDefaultSort() {
5735 return $this->mDefaultSort;
5736 }
5737
5738 /**
5739 * Try to guess the section anchor name based on a wikitext fragment
5740 * presumably extracted from a heading, for example "Header" from
5741 * "== Header ==".
5742 *
5743 * @param $text string
5744 *
5745 * @return string
5746 */
5747 public function guessSectionNameFromWikiText( $text ) {
5748 # Strip out wikitext links(they break the anchor)
5749 $text = $this->stripSectionName( $text );
5750 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5751 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
5752 }
5753
5754 /**
5755 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5756 * instead. For use in redirects, since IE6 interprets Redirect: headers
5757 * as something other than UTF-8 (apparently?), resulting in breakage.
5758 *
5759 * @param string $text The section name
5760 * @return string An anchor
5761 */
5762 public function guessLegacySectionNameFromWikiText( $text ) {
5763 # Strip out wikitext links(they break the anchor)
5764 $text = $this->stripSectionName( $text );
5765 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5766 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
5767 }
5768
5769 /**
5770 * Strips a text string of wikitext for use in a section anchor
5771 *
5772 * Accepts a text string and then removes all wikitext from the
5773 * string and leaves only the resultant text (i.e. the result of
5774 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5775 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5776 * to create valid section anchors by mimicing the output of the
5777 * parser when headings are parsed.
5778 *
5779 * @param string $text text string to be stripped of wikitext
5780 * for use in a Section anchor
5781 * @return string Filtered text string
5782 */
5783 public function stripSectionName( $text ) {
5784 # Strip internal link markup
5785 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5786 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5787
5788 # Strip external link markup
5789 # @todo FIXME: Not tolerant to blank link text
5790 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5791 # on how many empty links there are on the page - need to figure that out.
5792 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5793
5794 # Parse wikitext quotes (italics & bold)
5795 $text = $this->doQuotes( $text );
5796
5797 # Strip HTML tags
5798 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5799 return $text;
5800 }
5801
5802 /**
5803 * strip/replaceVariables/unstrip for preprocessor regression testing
5804 *
5805 * @param $text string
5806 * @param $title Title
5807 * @param $options ParserOptions
5808 * @param $outputType int
5809 *
5810 * @return string
5811 */
5812 function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
5813 $this->startParse( $title, $options, $outputType, true );
5814
5815 $text = $this->replaceVariables( $text );
5816 $text = $this->mStripState->unstripBoth( $text );
5817 $text = Sanitizer::removeHTMLtags( $text );
5818 return $text;
5819 }
5820
5821 /**
5822 * @param $text string
5823 * @param $title Title
5824 * @param $options ParserOptions
5825 * @return string
5826 */
5827 function testPst( $text, Title $title, ParserOptions $options ) {
5828 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5829 }
5830
5831 /**
5832 * @param $text
5833 * @param $title Title
5834 * @param $options ParserOptions
5835 * @return string
5836 */
5837 function testPreprocess( $text, Title $title, ParserOptions $options ) {
5838 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5839 }
5840
5841 /**
5842 * Call a callback function on all regions of the given text that are not
5843 * inside strip markers, and replace those regions with the return value
5844 * of the callback. For example, with input:
5845 *
5846 * aaa<MARKER>bbb
5847 *
5848 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5849 * two strings will be replaced with the value returned by the callback in
5850 * each case.
5851 *
5852 * @param $s string
5853 * @param $callback
5854 *
5855 * @return string
5856 */
5857 function markerSkipCallback( $s, $callback ) {
5858 $i = 0;
5859 $out = '';
5860 while ( $i < strlen( $s ) ) {
5861 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
5862 if ( $markerStart === false ) {
5863 $out .= call_user_func( $callback, substr( $s, $i ) );
5864 break;
5865 } else {
5866 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5867 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5868 if ( $markerEnd === false ) {
5869 $out .= substr( $s, $markerStart );
5870 break;
5871 } else {
5872 $markerEnd += strlen( self::MARKER_SUFFIX );
5873 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5874 $i = $markerEnd;
5875 }
5876 }
5877 }
5878 return $out;
5879 }
5880
5881 /**
5882 * Remove any strip markers found in the given text.
5883 *
5884 * @param $text Input string
5885 * @return string
5886 */
5887 function killMarkers( $text ) {
5888 return $this->mStripState->killMarkers( $text );
5889 }
5890
5891 /**
5892 * Save the parser state required to convert the given half-parsed text to
5893 * HTML. "Half-parsed" in this context means the output of
5894 * recursiveTagParse() or internalParse(). This output has strip markers
5895 * from replaceVariables (extensionSubstitution() etc.), and link
5896 * placeholders from replaceLinkHolders().
5897 *
5898 * Returns an array which can be serialized and stored persistently. This
5899 * array can later be loaded into another parser instance with
5900 * unserializeHalfParsedText(). The text can then be safely incorporated into
5901 * the return value of a parser hook.
5902 *
5903 * @param $text string
5904 *
5905 * @return array
5906 */
5907 function serializeHalfParsedText( $text ) {
5908 wfProfileIn( __METHOD__ );
5909 $data = array(
5910 'text' => $text,
5911 'version' => self::HALF_PARSED_VERSION,
5912 'stripState' => $this->mStripState->getSubState( $text ),
5913 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
5914 );
5915 wfProfileOut( __METHOD__ );
5916 return $data;
5917 }
5918
5919 /**
5920 * Load the parser state given in the $data array, which is assumed to
5921 * have been generated by serializeHalfParsedText(). The text contents is
5922 * extracted from the array, and its markers are transformed into markers
5923 * appropriate for the current Parser instance. This transformed text is
5924 * returned, and can be safely included in the return value of a parser
5925 * hook.
5926 *
5927 * If the $data array has been stored persistently, the caller should first
5928 * check whether it is still valid, by calling isValidHalfParsedText().
5929 *
5930 * @param array $data Serialized data
5931 * @throws MWException
5932 * @return String
5933 */
5934 function unserializeHalfParsedText( $data ) {
5935 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
5936 throw new MWException( __METHOD__ . ': invalid version' );
5937 }
5938
5939 # First, extract the strip state.
5940 $texts = array( $data['text'] );
5941 $texts = $this->mStripState->merge( $data['stripState'], $texts );
5942
5943 # Now renumber links
5944 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
5945
5946 # Should be good to go.
5947 return $texts[0];
5948 }
5949
5950 /**
5951 * Returns true if the given array, presumed to be generated by
5952 * serializeHalfParsedText(), is compatible with the current version of the
5953 * parser.
5954 *
5955 * @param $data Array
5956 *
5957 * @return bool
5958 */
5959 function isValidHalfParsedText( $data ) {
5960 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
5961 }
5962
5963 /**
5964 * Parsed a width param of imagelink like 300px or 200x300px
5965 *
5966 * @param $value String
5967 *
5968 * @return array
5969 * @since 1.20
5970 */
5971 public function parseWidthParam( $value ) {
5972 $parsedWidthParam = array();
5973 if ( $value === '' ) {
5974 return $parsedWidthParam;
5975 }
5976 $m = array();
5977 # (bug 13500) In both cases (width/height and width only),
5978 # permit trailing "px" for backward compatibility.
5979 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5980 $width = intval( $m[1] );
5981 $height = intval( $m[2] );
5982 $parsedWidthParam['width'] = $width;
5983 $parsedWidthParam['height'] = $height;
5984 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5985 $width = intval( $value );
5986 $parsedWidthParam['width'] = $width;
5987 }
5988 return $parsedWidthParam;
5989 }
5990 }