Merge "mediawiki.page.startup: Code cleanup"
[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 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3300 if ( $part1 !== $relative ) {
3301 $part1 = $relative;
3302 $ns = $this->mTitle->getNamespace();
3303 }
3304 $title = Title::newFromText( $part1, $ns );
3305 if ( $title ) {
3306 $titleText = $title->getPrefixedText();
3307 # Check for language variants if the template is not found
3308 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3309 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3310 }
3311 # Do recursion depth check
3312 $limit = $this->mOptions->getMaxTemplateDepth();
3313 if ( $frame->depth >= $limit ) {
3314 $found = true;
3315 $text = '<span class="error">'
3316 . wfMessage( 'parser-template-recursion-depth-warning' )
3317 ->numParams( $limit )->inContentLanguage()->text()
3318 . '</span>';
3319 }
3320 }
3321 }
3322
3323 # Load from database
3324 if ( !$found && $title ) {
3325 if ( !Profiler::instance()->isPersistent() ) {
3326 # Too many unique items can kill profiling DBs/collectors
3327 $titleProfileIn = __METHOD__ . "-title-" . $title->getPrefixedDBkey();
3328 wfProfileIn( $titleProfileIn ); // template in
3329 }
3330 wfProfileIn( __METHOD__ . '-loadtpl' );
3331 if ( !$title->isExternal() ) {
3332 if ( $title->isSpecialPage()
3333 && $this->mOptions->getAllowSpecialInclusion()
3334 && $this->ot['html'] )
3335 {
3336 // Pass the template arguments as URL parameters.
3337 // "uselang" will have no effect since the Language object
3338 // is forced to the one defined in ParserOptions.
3339 $pageArgs = array();
3340 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3341 $bits = $args->item( $i )->splitArg();
3342 if ( strval( $bits['index'] ) === '' ) {
3343 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3344 $value = trim( $frame->expand( $bits['value'] ) );
3345 $pageArgs[$name] = $value;
3346 }
3347 }
3348
3349 // Create a new context to execute the special page
3350 $context = new RequestContext;
3351 $context->setTitle( $title );
3352 $context->setRequest( new FauxRequest( $pageArgs ) );
3353 $context->setUser( $this->getUser() );
3354 $context->setLanguage( $this->mOptions->getUserLangObj() );
3355 $ret = SpecialPageFactory::capturePath( $title, $context );
3356 if ( $ret ) {
3357 $text = $context->getOutput()->getHTML();
3358 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3359 $found = true;
3360 $isHTML = true;
3361 $this->disableCache();
3362 }
3363 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3364 $found = false; # access denied
3365 wfDebug( __METHOD__ . ": template inclusion denied for " . $title->getPrefixedDBkey() );
3366 } else {
3367 list( $text, $title ) = $this->getTemplateDom( $title );
3368 if ( $text !== false ) {
3369 $found = true;
3370 $isChildObj = true;
3371 }
3372 }
3373
3374 # If the title is valid but undisplayable, make a link to it
3375 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3376 $text = "[[:$titleText]]";
3377 $found = true;
3378 }
3379 } elseif ( $title->isTrans() ) {
3380 # Interwiki transclusion
3381 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3382 $text = $this->interwikiTransclude( $title, 'render' );
3383 $isHTML = true;
3384 } else {
3385 $text = $this->interwikiTransclude( $title, 'raw' );
3386 # Preprocess it like a template
3387 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3388 $isChildObj = true;
3389 }
3390 $found = true;
3391 }
3392
3393 # Do infinite loop check
3394 # This has to be done after redirect resolution to avoid infinite loops via redirects
3395 if ( !$frame->loopCheck( $title ) ) {
3396 $found = true;
3397 $text = '<span class="error">'
3398 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3399 . '</span>';
3400 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3401 }
3402 wfProfileOut( __METHOD__ . '-loadtpl' );
3403 }
3404
3405 # If we haven't found text to substitute by now, we're done
3406 # Recover the source wikitext and return it
3407 if ( !$found ) {
3408 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3409 if ( $titleProfileIn ) {
3410 wfProfileOut( $titleProfileIn ); // template out
3411 }
3412 wfProfileOut( __METHOD__ );
3413 return array( 'object' => $text );
3414 }
3415
3416 # Expand DOM-style return values in a child frame
3417 if ( $isChildObj ) {
3418 # Clean up argument array
3419 $newFrame = $frame->newChild( $args, $title );
3420
3421 if ( $nowiki ) {
3422 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3423 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3424 # Expansion is eligible for the empty-frame cache
3425 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3426 $text = $this->mTplExpandCache[$titleText];
3427 } else {
3428 $text = $newFrame->expand( $text );
3429 $this->mTplExpandCache[$titleText] = $text;
3430 }
3431 } else {
3432 # Uncached expansion
3433 $text = $newFrame->expand( $text );
3434 }
3435 }
3436 if ( $isLocalObj && $nowiki ) {
3437 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3438 $isLocalObj = false;
3439 }
3440
3441 if ( $titleProfileIn ) {
3442 wfProfileOut( $titleProfileIn ); // template out
3443 }
3444
3445 # Replace raw HTML by a placeholder
3446 if ( $isHTML ) {
3447 $text = $this->insertStripItem( $text );
3448 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3449 # Escape nowiki-style return values
3450 $text = wfEscapeWikiText( $text );
3451 } elseif ( is_string( $text )
3452 && !$piece['lineStart']
3453 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3454 {
3455 # Bug 529: if the template begins with a table or block-level
3456 # element, it should be treated as beginning a new line.
3457 # This behavior is somewhat controversial.
3458 $text = "\n" . $text;
3459 }
3460
3461 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3462 # Error, oversize inclusion
3463 if ( $titleText !== false ) {
3464 # Make a working, properly escaped link if possible (bug 23588)
3465 $text = "[[:$titleText]]";
3466 } else {
3467 # This will probably not be a working link, but at least it may
3468 # provide some hint of where the problem is
3469 preg_replace( '/^:/', '', $originalTitle );
3470 $text = "[[:$originalTitle]]";
3471 }
3472 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3473 $this->limitationWarn( 'post-expand-template-inclusion' );
3474 }
3475
3476 if ( $isLocalObj ) {
3477 $ret = array( 'object' => $text );
3478 } else {
3479 $ret = array( 'text' => $text );
3480 }
3481
3482 wfProfileOut( __METHOD__ );
3483 return $ret;
3484 }
3485
3486 /**
3487 * Call a parser function and return an array with text and flags.
3488 *
3489 * The returned array will always contain a boolean 'found', indicating
3490 * whether the parser function was found or not. It may also contain the
3491 * following:
3492 * text: string|object, resulting wikitext or PP DOM object
3493 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3494 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3495 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3496 * nowiki: bool, wiki markup in $text should be escaped
3497 *
3498 * @since 1.21
3499 * @param $frame PPFrame The current frame, contains template arguments
3500 * @param $function string Function name
3501 * @param $args array Arguments to the function
3502 * @return array
3503 */
3504 public function callParserFunction( $frame, $function, array $args = array() ) {
3505 global $wgContLang;
3506
3507 wfProfileIn( __METHOD__ );
3508
3509 # Case sensitive functions
3510 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3511 $function = $this->mFunctionSynonyms[1][$function];
3512 } else {
3513 # Case insensitive functions
3514 $function = $wgContLang->lc( $function );
3515 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3516 $function = $this->mFunctionSynonyms[0][$function];
3517 } else {
3518 wfProfileOut( __METHOD__ );
3519 return array( 'found' => false );
3520 }
3521 }
3522
3523 wfProfileIn( __METHOD__ . '-pfunc-' . $function );
3524 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3525
3526 # Workaround for PHP bug 35229 and similar
3527 if ( !is_callable( $callback ) ) {
3528 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3529 wfProfileOut( __METHOD__ );
3530 throw new MWException( "Tag hook for $function is not callable\n" );
3531 }
3532
3533 $allArgs = array( &$this );
3534 if ( $flags & SFH_OBJECT_ARGS ) {
3535 # Convert arguments to PPNodes and collect for appending to $allArgs
3536 $funcArgs = array();
3537 foreach ( $args as $k => $v ) {
3538 if ( $v instanceof PPNode || $k === 0 ) {
3539 $funcArgs[] = $v;
3540 } else {
3541 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( array( $k => $v ) )->item( 0 );
3542 }
3543 }
3544
3545 # Add a frame parameter, and pass the arguments as an array
3546 $allArgs[] = $frame;
3547 $allArgs[] = $funcArgs;
3548 } else {
3549 # Convert arguments to plain text and append to $allArgs
3550 foreach ( $args as $k => $v ) {
3551 if ( $v instanceof PPNode ) {
3552 $allArgs[] = trim( $frame->expand( $v ) );
3553 } elseif ( is_int( $k ) && $k >= 0 ) {
3554 $allArgs[] = trim( $v );
3555 } else {
3556 $allArgs[] = trim( "$k=$v" );
3557 }
3558 }
3559 }
3560
3561 $result = call_user_func_array( $callback, $allArgs );
3562
3563 # The interface for function hooks allows them to return a wikitext
3564 # string or an array containing the string and any flags. This mungs
3565 # things around to match what this method should return.
3566 if ( !is_array( $result ) ) {
3567 $result = array(
3568 'found' => true,
3569 'text' => $result,
3570 );
3571 } else {
3572 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3573 $result['text'] = $result[0];
3574 }
3575 unset( $result[0] );
3576 $result += array(
3577 'found' => true,
3578 );
3579 }
3580
3581 $noparse = true;
3582 $preprocessFlags = 0;
3583 if ( isset( $result['noparse'] ) ) {
3584 $noparse = $result['noparse'];
3585 }
3586 if ( isset( $result['preprocessFlags'] ) ) {
3587 $preprocessFlags = $result['preprocessFlags'];
3588 }
3589
3590 if ( !$noparse ) {
3591 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3592 $result['isChildObj'] = true;
3593 }
3594 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3595 wfProfileOut( __METHOD__ );
3596
3597 return $result;
3598 }
3599
3600 /**
3601 * Get the semi-parsed DOM representation of a template with a given title,
3602 * and its redirect destination title. Cached.
3603 *
3604 * @param $title Title
3605 *
3606 * @return array
3607 */
3608 function getTemplateDom( $title ) {
3609 $cacheTitle = $title;
3610 $titleText = $title->getPrefixedDBkey();
3611
3612 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3613 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3614 $title = Title::makeTitle( $ns, $dbk );
3615 $titleText = $title->getPrefixedDBkey();
3616 }
3617 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3618 return array( $this->mTplDomCache[$titleText], $title );
3619 }
3620
3621 # Cache miss, go to the database
3622 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3623
3624 if ( $text === false ) {
3625 $this->mTplDomCache[$titleText] = false;
3626 return array( false, $title );
3627 }
3628
3629 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3630 $this->mTplDomCache[$titleText] = $dom;
3631
3632 if ( !$title->equals( $cacheTitle ) ) {
3633 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3634 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3635 }
3636
3637 return array( $dom, $title );
3638 }
3639
3640 /**
3641 * Fetch the unparsed text of a template and register a reference to it.
3642 * @param Title $title
3643 * @return Array ( string or false, Title )
3644 */
3645 function fetchTemplateAndTitle( $title ) {
3646 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3647 $stuff = call_user_func( $templateCb, $title, $this );
3648 $text = $stuff['text'];
3649 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3650 if ( isset( $stuff['deps'] ) ) {
3651 foreach ( $stuff['deps'] as $dep ) {
3652 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3653 if ( $dep['title']->equals( $this->getTitle() ) ) {
3654 // If we transclude ourselves, the final result
3655 // will change based on the new version of the page
3656 $this->mOutput->setFlag( 'vary-revision' );
3657 }
3658 }
3659 }
3660 return array( $text, $finalTitle );
3661 }
3662
3663 /**
3664 * Fetch the unparsed text of a template and register a reference to it.
3665 * @param Title $title
3666 * @return mixed string or false
3667 */
3668 function fetchTemplate( $title ) {
3669 $rv = $this->fetchTemplateAndTitle( $title );
3670 return $rv[0];
3671 }
3672
3673 /**
3674 * Static function to get a template
3675 * Can be overridden via ParserOptions::setTemplateCallback().
3676 *
3677 * @param $title Title
3678 * @param $parser Parser
3679 *
3680 * @return array
3681 */
3682 static function statelessFetchTemplate( $title, $parser = false ) {
3683 $text = $skip = false;
3684 $finalTitle = $title;
3685 $deps = array();
3686
3687 # Loop to fetch the article, with up to 1 redirect
3688 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3689 # Give extensions a chance to select the revision instead
3690 $id = false; # Assume current
3691 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3692 array( $parser, $title, &$skip, &$id ) );
3693
3694 if ( $skip ) {
3695 $text = false;
3696 $deps[] = array(
3697 'title' => $title,
3698 'page_id' => $title->getArticleID(),
3699 'rev_id' => null
3700 );
3701 break;
3702 }
3703 # Get the revision
3704 $rev = $id
3705 ? Revision::newFromId( $id )
3706 : Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
3707 $rev_id = $rev ? $rev->getId() : 0;
3708 # If there is no current revision, there is no page
3709 if ( $id === false && !$rev ) {
3710 $linkCache = LinkCache::singleton();
3711 $linkCache->addBadLinkObj( $title );
3712 }
3713
3714 $deps[] = array(
3715 'title' => $title,
3716 'page_id' => $title->getArticleID(),
3717 'rev_id' => $rev_id );
3718 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3719 # We fetched a rev from a different title; register it too...
3720 $deps[] = array(
3721 'title' => $rev->getTitle(),
3722 'page_id' => $rev->getPage(),
3723 'rev_id' => $rev_id );
3724 }
3725
3726 if ( $rev ) {
3727 $content = $rev->getContent();
3728 $text = $content ? $content->getWikitextForTransclusion() : null;
3729
3730 if ( $text === false || $text === null ) {
3731 $text = false;
3732 break;
3733 }
3734 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3735 global $wgContLang;
3736 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3737 if ( !$message->exists() ) {
3738 $text = false;
3739 break;
3740 }
3741 $content = $message->content();
3742 $text = $message->plain();
3743 } else {
3744 break;
3745 }
3746 if ( !$content ) {
3747 break;
3748 }
3749 # Redirect?
3750 $finalTitle = $title;
3751 $title = $content->getRedirectTarget();
3752 }
3753 return array(
3754 'text' => $text,
3755 'finalTitle' => $finalTitle,
3756 'deps' => $deps );
3757 }
3758
3759 /**
3760 * Fetch a file and its title and register a reference to it.
3761 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3762 * @param Title $title
3763 * @param array $options Array of options to RepoGroup::findFile
3764 * @return File|bool
3765 */
3766 function fetchFile( $title, $options = array() ) {
3767 $res = $this->fetchFileAndTitle( $title, $options );
3768 return $res[0];
3769 }
3770
3771 /**
3772 * Fetch a file and its title and register a reference to it.
3773 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3774 * @param Title $title
3775 * @param array $options Array of options to RepoGroup::findFile
3776 * @return Array ( File or false, Title of file )
3777 */
3778 function fetchFileAndTitle( $title, $options = array() ) {
3779 $file = $this->fetchFileNoRegister( $title, $options );
3780
3781 $time = $file ? $file->getTimestamp() : false;
3782 $sha1 = $file ? $file->getSha1() : false;
3783 # Register the file as a dependency...
3784 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3785 if ( $file && !$title->equals( $file->getTitle() ) ) {
3786 # Update fetched file title
3787 $title = $file->getTitle();
3788 if ( is_null( $file->getRedirectedTitle() ) ) {
3789 # This file was not a redirect, but the title does not match.
3790 # Register under the new name because otherwise the link will
3791 # get lost.
3792 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3793 }
3794 }
3795 return array( $file, $title );
3796 }
3797
3798 /**
3799 * Helper function for fetchFileAndTitle.
3800 *
3801 * Also useful if you need to fetch a file but not use it yet,
3802 * for example to get the file's handler.
3803 *
3804 * @param Title $title
3805 * @param array $options Array of options to RepoGroup::findFile
3806 * @return File or false
3807 */
3808 protected function fetchFileNoRegister( $title, $options = array() ) {
3809 if ( isset( $options['broken'] ) ) {
3810 $file = false; // broken thumbnail forced by hook
3811 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3812 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3813 } else { // get by (name,timestamp)
3814 $file = wfFindFile( $title, $options );
3815 }
3816 return $file;
3817 }
3818
3819 /**
3820 * Transclude an interwiki link.
3821 *
3822 * @param $title Title
3823 * @param $action
3824 *
3825 * @return string
3826 */
3827 function interwikiTransclude( $title, $action ) {
3828 global $wgEnableScaryTranscluding;
3829
3830 if ( !$wgEnableScaryTranscluding ) {
3831 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3832 }
3833
3834 $url = $title->getFullURL( array( 'action' => $action ) );
3835
3836 if ( strlen( $url ) > 255 ) {
3837 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3838 }
3839 return $this->fetchScaryTemplateMaybeFromCache( $url );
3840 }
3841
3842 /**
3843 * @param $url string
3844 * @return Mixed|String
3845 */
3846 function fetchScaryTemplateMaybeFromCache( $url ) {
3847 global $wgTranscludeCacheExpiry;
3848 $dbr = wfGetDB( DB_SLAVE );
3849 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3850 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3851 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3852 if ( $obj ) {
3853 return $obj->tc_contents;
3854 }
3855
3856 $req = MWHttpRequest::factory( $url );
3857 $status = $req->execute(); // Status object
3858 if ( $status->isOK() ) {
3859 $text = $req->getContent();
3860 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3861 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3862 } else {
3863 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3864 }
3865
3866 $dbw = wfGetDB( DB_MASTER );
3867 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3868 'tc_url' => $url,
3869 'tc_time' => $dbw->timestamp( time() ),
3870 'tc_contents' => $text
3871 ) );
3872 return $text;
3873 }
3874
3875 /**
3876 * Triple brace replacement -- used for template arguments
3877 * @private
3878 *
3879 * @param $piece array
3880 * @param $frame PPFrame
3881 *
3882 * @return array
3883 */
3884 function argSubstitution( $piece, $frame ) {
3885 wfProfileIn( __METHOD__ );
3886
3887 $error = false;
3888 $parts = $piece['parts'];
3889 $nameWithSpaces = $frame->expand( $piece['title'] );
3890 $argName = trim( $nameWithSpaces );
3891 $object = false;
3892 $text = $frame->getArgument( $argName );
3893 if ( $text === false && $parts->getLength() > 0
3894 && (
3895 $this->ot['html']
3896 || $this->ot['pre']
3897 || ( $this->ot['wiki'] && $frame->isTemplate() )
3898 )
3899 ) {
3900 # No match in frame, use the supplied default
3901 $object = $parts->item( 0 )->getChildren();
3902 }
3903 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3904 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3905 $this->limitationWarn( 'post-expand-template-argument' );
3906 }
3907
3908 if ( $text === false && $object === false ) {
3909 # No match anywhere
3910 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3911 }
3912 if ( $error !== false ) {
3913 $text .= $error;
3914 }
3915 if ( $object !== false ) {
3916 $ret = array( 'object' => $object );
3917 } else {
3918 $ret = array( 'text' => $text );
3919 }
3920
3921 wfProfileOut( __METHOD__ );
3922 return $ret;
3923 }
3924
3925 /**
3926 * Return the text to be used for a given extension tag.
3927 * This is the ghost of strip().
3928 *
3929 * @param array $params Associative array of parameters:
3930 * name PPNode for the tag name
3931 * attr PPNode for unparsed text where tag attributes are thought to be
3932 * attributes Optional associative array of parsed attributes
3933 * inner Contents of extension element
3934 * noClose Original text did not have a close tag
3935 * @param $frame PPFrame
3936 *
3937 * @throws MWException
3938 * @return string
3939 */
3940 function extensionSubstitution( $params, $frame ) {
3941 $name = $frame->expand( $params['name'] );
3942 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3943 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3944 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3945
3946 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
3947 ( $this->ot['html'] || $this->ot['pre'] );
3948 if ( $isFunctionTag ) {
3949 $markerType = 'none';
3950 } else {
3951 $markerType = 'general';
3952 }
3953 if ( $this->ot['html'] || $isFunctionTag ) {
3954 $name = strtolower( $name );
3955 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3956 if ( isset( $params['attributes'] ) ) {
3957 $attributes = $attributes + $params['attributes'];
3958 }
3959
3960 if ( isset( $this->mTagHooks[$name] ) ) {
3961 # Workaround for PHP bug 35229 and similar
3962 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3963 throw new MWException( "Tag hook for $name is not callable\n" );
3964 }
3965 $output = call_user_func_array( $this->mTagHooks[$name],
3966 array( $content, $attributes, $this, $frame ) );
3967 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3968 list( $callback, ) = $this->mFunctionTagHooks[$name];
3969 if ( !is_callable( $callback ) ) {
3970 throw new MWException( "Tag hook for $name is not callable\n" );
3971 }
3972
3973 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3974 } else {
3975 $output = '<span class="error">Invalid tag extension name: ' .
3976 htmlspecialchars( $name ) . '</span>';
3977 }
3978
3979 if ( is_array( $output ) ) {
3980 # Extract flags to local scope (to override $markerType)
3981 $flags = $output;
3982 $output = $flags[0];
3983 unset( $flags[0] );
3984 extract( $flags );
3985 }
3986 } else {
3987 if ( is_null( $attrText ) ) {
3988 $attrText = '';
3989 }
3990 if ( isset( $params['attributes'] ) ) {
3991 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3992 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3993 htmlspecialchars( $attrValue ) . '"';
3994 }
3995 }
3996 if ( $content === null ) {
3997 $output = "<$name$attrText/>";
3998 } else {
3999 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
4000 $output = "<$name$attrText>$content$close";
4001 }
4002 }
4003
4004 if ( $markerType === 'none' ) {
4005 return $output;
4006 } elseif ( $markerType === 'nowiki' ) {
4007 $this->mStripState->addNoWiki( $marker, $output );
4008 } elseif ( $markerType === 'general' ) {
4009 $this->mStripState->addGeneral( $marker, $output );
4010 } else {
4011 throw new MWException( __METHOD__ . ': invalid marker type' );
4012 }
4013 return $marker;
4014 }
4015
4016 /**
4017 * Increment an include size counter
4018 *
4019 * @param string $type the type of expansion
4020 * @param $size Integer: the size of the text
4021 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
4022 */
4023 function incrementIncludeSize( $type, $size ) {
4024 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
4025 return false;
4026 } else {
4027 $this->mIncludeSizes[$type] += $size;
4028 return true;
4029 }
4030 }
4031
4032 /**
4033 * Increment the expensive function count
4034 *
4035 * @return Boolean: false if the limit has been exceeded
4036 */
4037 function incrementExpensiveFunctionCount() {
4038 $this->mExpensiveFunctionCount++;
4039 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
4040 }
4041
4042 /**
4043 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4044 * Fills $this->mDoubleUnderscores, returns the modified text
4045 *
4046 * @param $text string
4047 *
4048 * @return string
4049 */
4050 function doDoubleUnderscore( $text ) {
4051 wfProfileIn( __METHOD__ );
4052
4053 # The position of __TOC__ needs to be recorded
4054 $mw = MagicWord::get( 'toc' );
4055 if ( $mw->match( $text ) ) {
4056 $this->mShowToc = true;
4057 $this->mForceTocPosition = true;
4058
4059 # Set a placeholder. At the end we'll fill it in with the TOC.
4060 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4061
4062 # Only keep the first one.
4063 $text = $mw->replace( '', $text );
4064 }
4065
4066 # Now match and remove the rest of them
4067 $mwa = MagicWord::getDoubleUnderscoreArray();
4068 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
4069
4070 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
4071 $this->mOutput->mNoGallery = true;
4072 }
4073 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
4074 $this->mShowToc = false;
4075 }
4076 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
4077 $this->addTrackingCategory( 'hidden-category-category' );
4078 }
4079 # (bug 8068) Allow control over whether robots index a page.
4080 #
4081 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4082 # is not desirable, the last one on the page should win.
4083 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
4084 $this->mOutput->setIndexPolicy( 'noindex' );
4085 $this->addTrackingCategory( 'noindex-category' );
4086 }
4087 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4088 $this->mOutput->setIndexPolicy( 'index' );
4089 $this->addTrackingCategory( 'index-category' );
4090 }
4091
4092 # Cache all double underscores in the database
4093 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4094 $this->mOutput->setProperty( $key, '' );
4095 }
4096
4097 wfProfileOut( __METHOD__ );
4098 return $text;
4099 }
4100
4101 /**
4102 * Add a tracking category, getting the title from a system message,
4103 * or print a debug message if the title is invalid.
4104 *
4105 * @param string $msg message key
4106 * @return Boolean: whether the addition was successful
4107 */
4108 public function addTrackingCategory( $msg ) {
4109 if ( $this->mTitle->getNamespace() === NS_SPECIAL ) {
4110 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
4111 return false;
4112 }
4113 // Important to parse with correct title (bug 31469)
4114 $cat = wfMessage( $msg )
4115 ->title( $this->getTitle() )
4116 ->inContentLanguage()
4117 ->text();
4118
4119 # Allow tracking categories to be disabled by setting them to "-"
4120 if ( $cat === '-' ) {
4121 return false;
4122 }
4123
4124 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
4125 if ( $containerCategory ) {
4126 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4127 return true;
4128 } else {
4129 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
4130 return false;
4131 }
4132 }
4133
4134 /**
4135 * This function accomplishes several tasks:
4136 * 1) Auto-number headings if that option is enabled
4137 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4138 * 3) Add a Table of contents on the top for users who have enabled the option
4139 * 4) Auto-anchor headings
4140 *
4141 * It loops through all headlines, collects the necessary data, then splits up the
4142 * string and re-inserts the newly formatted headlines.
4143 *
4144 * @param $text String
4145 * @param string $origText original, untouched wikitext
4146 * @param $isMain Boolean
4147 * @return mixed|string
4148 * @private
4149 */
4150 function formatHeadings( $text, $origText, $isMain = true ) {
4151 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4152
4153 # Inhibit editsection links if requested in the page
4154 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4155 $maybeShowEditLink = $showEditLink = false;
4156 } else {
4157 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4158 $showEditLink = $this->mOptions->getEditSection();
4159 }
4160 if ( $showEditLink ) {
4161 $this->mOutput->setEditSectionTokens( true );
4162 }
4163
4164 # Get all headlines for numbering them and adding funky stuff like [edit]
4165 # links - this is for later, but we need the number of headlines right now
4166 $matches = array();
4167 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4168
4169 # if there are fewer than 4 headlines in the article, do not show TOC
4170 # unless it's been explicitly enabled.
4171 $enoughToc = $this->mShowToc &&
4172 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4173
4174 # Allow user to stipulate that a page should have a "new section"
4175 # link added via __NEWSECTIONLINK__
4176 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4177 $this->mOutput->setNewSection( true );
4178 }
4179
4180 # Allow user to remove the "new section"
4181 # link via __NONEWSECTIONLINK__
4182 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4183 $this->mOutput->hideNewSection( true );
4184 }
4185
4186 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4187 # override above conditions and always show TOC above first header
4188 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4189 $this->mShowToc = true;
4190 $enoughToc = true;
4191 }
4192
4193 # headline counter
4194 $headlineCount = 0;
4195 $numVisible = 0;
4196
4197 # Ugh .. the TOC should have neat indentation levels which can be
4198 # passed to the skin functions. These are determined here
4199 $toc = '';
4200 $full = '';
4201 $head = array();
4202 $sublevelCount = array();
4203 $levelCount = array();
4204 $level = 0;
4205 $prevlevel = 0;
4206 $toclevel = 0;
4207 $prevtoclevel = 0;
4208 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
4209 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4210 $oldType = $this->mOutputType;
4211 $this->setOutputType( self::OT_WIKI );
4212 $frame = $this->getPreprocessor()->newFrame();
4213 $root = $this->preprocessToDom( $origText );
4214 $node = $root->getFirstChild();
4215 $byteOffset = 0;
4216 $tocraw = array();
4217 $refers = array();
4218
4219 foreach ( $matches[3] as $headline ) {
4220 $isTemplate = false;
4221 $titleText = false;
4222 $sectionIndex = false;
4223 $numbering = '';
4224 $markerMatches = array();
4225 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4226 $serial = $markerMatches[1];
4227 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4228 $isTemplate = ( $titleText != $baseTitleText );
4229 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4230 }
4231
4232 if ( $toclevel ) {
4233 $prevlevel = $level;
4234 }
4235 $level = $matches[1][$headlineCount];
4236
4237 if ( $level > $prevlevel ) {
4238 # Increase TOC level
4239 $toclevel++;
4240 $sublevelCount[$toclevel] = 0;
4241 if ( $toclevel < $wgMaxTocLevel ) {
4242 $prevtoclevel = $toclevel;
4243 $toc .= Linker::tocIndent();
4244 $numVisible++;
4245 }
4246 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4247 # Decrease TOC level, find level to jump to
4248
4249 for ( $i = $toclevel; $i > 0; $i-- ) {
4250 if ( $levelCount[$i] == $level ) {
4251 # Found last matching level
4252 $toclevel = $i;
4253 break;
4254 } elseif ( $levelCount[$i] < $level ) {
4255 # Found first matching level below current level
4256 $toclevel = $i + 1;
4257 break;
4258 }
4259 }
4260 if ( $i == 0 ) {
4261 $toclevel = 1;
4262 }
4263 if ( $toclevel < $wgMaxTocLevel ) {
4264 if ( $prevtoclevel < $wgMaxTocLevel ) {
4265 # Unindent only if the previous toc level was shown :p
4266 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4267 $prevtoclevel = $toclevel;
4268 } else {
4269 $toc .= Linker::tocLineEnd();
4270 }
4271 }
4272 } else {
4273 # No change in level, end TOC line
4274 if ( $toclevel < $wgMaxTocLevel ) {
4275 $toc .= Linker::tocLineEnd();
4276 }
4277 }
4278
4279 $levelCount[$toclevel] = $level;
4280
4281 # count number of headlines for each level
4282 $sublevelCount[$toclevel]++;
4283 $dot = 0;
4284 for ( $i = 1; $i <= $toclevel; $i++ ) {
4285 if ( !empty( $sublevelCount[$i] ) ) {
4286 if ( $dot ) {
4287 $numbering .= '.';
4288 }
4289 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4290 $dot = 1;
4291 }
4292 }
4293
4294 # The safe header is a version of the header text safe to use for links
4295
4296 # Remove link placeholders by the link text.
4297 # <!--LINK number-->
4298 # turns into
4299 # link text with suffix
4300 # Do this before unstrip since link text can contain strip markers
4301 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4302
4303 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4304 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4305
4306 # Strip out HTML (first regex removes any tag not allowed)
4307 # Allowed tags are:
4308 # * <sup> and <sub> (bug 8393)
4309 # * <i> (bug 26375)
4310 # * <b> (r105284)
4311 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4312 #
4313 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4314 # to allow setting directionality in toc items.
4315 $tocline = preg_replace(
4316 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4317 array( '', '<$1>' ),
4318 $safeHeadline
4319 );
4320 $tocline = trim( $tocline );
4321
4322 # For the anchor, strip out HTML-y stuff period
4323 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4324 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4325
4326 # Save headline for section edit hint before it's escaped
4327 $headlineHint = $safeHeadline;
4328
4329 if ( $wgExperimentalHtmlIds ) {
4330 # For reverse compatibility, provide an id that's
4331 # HTML4-compatible, like we used to.
4332 #
4333 # It may be worth noting, academically, that it's possible for
4334 # the legacy anchor to conflict with a non-legacy headline
4335 # anchor on the page. In this case likely the "correct" thing
4336 # would be to either drop the legacy anchors or make sure
4337 # they're numbered first. However, this would require people
4338 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4339 # manually, so let's not bother worrying about it.
4340 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4341 array( 'noninitial', 'legacy' ) );
4342 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4343
4344 if ( $legacyHeadline == $safeHeadline ) {
4345 # No reason to have both (in fact, we can't)
4346 $legacyHeadline = false;
4347 }
4348 } else {
4349 $legacyHeadline = false;
4350 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4351 'noninitial' );
4352 }
4353
4354 # HTML names must be case-insensitively unique (bug 10721).
4355 # This does not apply to Unicode characters per
4356 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4357 # @todo FIXME: We may be changing them depending on the current locale.
4358 $arrayKey = strtolower( $safeHeadline );
4359 if ( $legacyHeadline === false ) {
4360 $legacyArrayKey = false;
4361 } else {
4362 $legacyArrayKey = strtolower( $legacyHeadline );
4363 }
4364
4365 # count how many in assoc. array so we can track dupes in anchors
4366 if ( isset( $refers[$arrayKey] ) ) {
4367 $refers[$arrayKey]++;
4368 } else {
4369 $refers[$arrayKey] = 1;
4370 }
4371 if ( isset( $refers[$legacyArrayKey] ) ) {
4372 $refers[$legacyArrayKey]++;
4373 } else {
4374 $refers[$legacyArrayKey] = 1;
4375 }
4376
4377 # Don't number the heading if it is the only one (looks silly)
4378 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4379 # the two are different if the line contains a link
4380 $headline = Html::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4381 }
4382
4383 # Create the anchor for linking from the TOC to the section
4384 $anchor = $safeHeadline;
4385 $legacyAnchor = $legacyHeadline;
4386 if ( $refers[$arrayKey] > 1 ) {
4387 $anchor .= '_' . $refers[$arrayKey];
4388 }
4389 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4390 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4391 }
4392 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4393 $toc .= Linker::tocLine( $anchor, $tocline,
4394 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4395 }
4396
4397 # Add the section to the section tree
4398 # Find the DOM node for this header
4399 while ( $node && !$isTemplate ) {
4400 if ( $node->getName() === 'h' ) {
4401 $bits = $node->splitHeading();
4402 if ( $bits['i'] == $sectionIndex ) {
4403 break;
4404 }
4405 }
4406 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4407 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4408 $node = $node->getNextSibling();
4409 }
4410 $tocraw[] = array(
4411 'toclevel' => $toclevel,
4412 'level' => $level,
4413 'line' => $tocline,
4414 'number' => $numbering,
4415 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4416 'fromtitle' => $titleText,
4417 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
4418 'anchor' => $anchor,
4419 );
4420
4421 # give headline the correct <h#> tag
4422 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4423 // Output edit section links as markers with styles that can be customized by skins
4424 if ( $isTemplate ) {
4425 # Put a T flag in the section identifier, to indicate to extractSections()
4426 # that sections inside <includeonly> should be counted.
4427 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4428 } else {
4429 $editlinkArgs = array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint );
4430 }
4431 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4432 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4433 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4434 // so we don't have to worry about a user trying to input one of these markers directly.
4435 // We use a page and section attribute to stop the language converter from converting these important bits
4436 // of data, but put the headline hint inside a content block because the language converter is supposed to
4437 // be able to convert that piece of data.
4438 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4439 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4440 if ( isset( $editlinkArgs[2] ) ) {
4441 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4442 } else {
4443 $editlink .= '/>';
4444 }
4445 } else {
4446 $editlink = '';
4447 }
4448 $head[$headlineCount] = Linker::makeHeadline( $level,
4449 $matches['attrib'][$headlineCount], $anchor, $headline,
4450 $editlink, $legacyAnchor );
4451
4452 $headlineCount++;
4453 }
4454
4455 $this->setOutputType( $oldType );
4456
4457 # Never ever show TOC if no headers
4458 if ( $numVisible < 1 ) {
4459 $enoughToc = false;
4460 }
4461
4462 if ( $enoughToc ) {
4463 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4464 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4465 }
4466 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4467 $this->mOutput->setTOCHTML( $toc );
4468 }
4469
4470 if ( $isMain ) {
4471 $this->mOutput->setSections( $tocraw );
4472 }
4473
4474 # split up and insert constructed headlines
4475 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4476 $i = 0;
4477
4478 // build an array of document sections
4479 $sections = array();
4480 foreach ( $blocks as $block ) {
4481 // $head is zero-based, sections aren't.
4482 if ( empty( $head[$i - 1] ) ) {
4483 $sections[$i] = $block;
4484 } else {
4485 $sections[$i] = $head[$i - 1] . $block;
4486 }
4487
4488 /**
4489 * Send a hook, one per section.
4490 * The idea here is to be able to make section-level DIVs, but to do so in a
4491 * lower-impact, more correct way than r50769
4492 *
4493 * $this : caller
4494 * $section : the section number
4495 * &$sectionContent : ref to the content of the section
4496 * $showEditLinks : boolean describing whether this section has an edit link
4497 */
4498 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4499
4500 $i++;
4501 }
4502
4503 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4504 // append the TOC at the beginning
4505 // Top anchor now in skin
4506 $sections[0] = $sections[0] . $toc . "\n";
4507 }
4508
4509 $full .= join( '', $sections );
4510
4511 if ( $this->mForceTocPosition ) {
4512 return str_replace( '<!--MWTOC-->', $toc, $full );
4513 } else {
4514 return $full;
4515 }
4516 }
4517
4518 /**
4519 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4520 * conversion, substitting signatures, {{subst:}} templates, etc.
4521 *
4522 * @param string $text the text to transform
4523 * @param $title Title: the Title object for the current article
4524 * @param $user User: the User object describing the current user
4525 * @param $options ParserOptions: parsing options
4526 * @param $clearState Boolean: whether to clear the parser state first
4527 * @return String: the altered wiki markup
4528 */
4529 public function preSaveTransform( $text, Title $title, User $user, ParserOptions $options, $clearState = true ) {
4530 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4531 $this->setUser( $user );
4532
4533 $pairs = array(
4534 "\r\n" => "\n",
4535 );
4536 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4537 if ( $options->getPreSaveTransform() ) {
4538 $text = $this->pstPass2( $text, $user );
4539 }
4540 $text = $this->mStripState->unstripBoth( $text );
4541
4542 $this->setUser( null ); #Reset
4543
4544 return $text;
4545 }
4546
4547 /**
4548 * Pre-save transform helper function
4549 * @private
4550 *
4551 * @param $text string
4552 * @param $user User
4553 *
4554 * @return string
4555 */
4556 function pstPass2( $text, $user ) {
4557 global $wgContLang, $wgLocaltimezone;
4558
4559 # Note: This is the timestamp saved as hardcoded wikitext to
4560 # the database, we use $wgContLang here in order to give
4561 # everyone the same signature and use the default one rather
4562 # than the one selected in each user's preferences.
4563 # (see also bug 12815)
4564 $ts = $this->mOptions->getTimestamp();
4565 if ( isset( $wgLocaltimezone ) ) {
4566 $tz = $wgLocaltimezone;
4567 } else {
4568 $tz = date_default_timezone_get();
4569 }
4570
4571 $unixts = wfTimestamp( TS_UNIX, $ts );
4572 $oldtz = date_default_timezone_get();
4573 date_default_timezone_set( $tz );
4574 $ts = date( 'YmdHis', $unixts );
4575 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4576
4577 # Allow translation of timezones through wiki. date() can return
4578 # whatever crap the system uses, localised or not, so we cannot
4579 # ship premade translations.
4580 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4581 $msg = wfMessage( $key )->inContentLanguage();
4582 if ( $msg->exists() ) {
4583 $tzMsg = $msg->text();
4584 }
4585
4586 date_default_timezone_set( $oldtz );
4587
4588 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4589
4590 # Variable replacement
4591 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4592 $text = $this->replaceVariables( $text );
4593
4594 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4595 # which may corrupt this parser instance via its wfMessage()->text() call-
4596
4597 # Signatures
4598 $sigText = $this->getUserSig( $user );
4599 $text = strtr( $text, array(
4600 '~~~~~' => $d,
4601 '~~~~' => "$sigText $d",
4602 '~~~' => $sigText
4603 ) );
4604
4605 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4606 $tc = '[' . Title::legalChars() . ']';
4607 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4608
4609 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4610 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4611 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4612 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4613
4614 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4615 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4616 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4617 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4618
4619 $t = $this->mTitle->getText();
4620 $m = array();
4621 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4622 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4623 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4624 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4625 } else {
4626 # if there's no context, don't bother duplicating the title
4627 $text = preg_replace( $p2, '[[\\1]]', $text );
4628 }
4629
4630 # Trim trailing whitespace
4631 $text = rtrim( $text );
4632
4633 return $text;
4634 }
4635
4636 /**
4637 * Fetch the user's signature text, if any, and normalize to
4638 * validated, ready-to-insert wikitext.
4639 * If you have pre-fetched the nickname or the fancySig option, you can
4640 * specify them here to save a database query.
4641 * Do not reuse this parser instance after calling getUserSig(),
4642 * as it may have changed if it's the $wgParser.
4643 *
4644 * @param $user User
4645 * @param string|bool $nickname nickname to use or false to use user's default nickname
4646 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4647 * or null to use default value
4648 * @return string
4649 */
4650 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4651 global $wgMaxSigChars;
4652
4653 $username = $user->getName();
4654
4655 # If not given, retrieve from the user object.
4656 if ( $nickname === false ) {
4657 $nickname = $user->getOption( 'nickname' );
4658 }
4659
4660 if ( is_null( $fancySig ) ) {
4661 $fancySig = $user->getBoolOption( 'fancysig' );
4662 }
4663
4664 $nickname = $nickname == null ? $username : $nickname;
4665
4666 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4667 $nickname = $username;
4668 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4669 } elseif ( $fancySig !== false ) {
4670 # Sig. might contain markup; validate this
4671 if ( $this->validateSig( $nickname ) !== false ) {
4672 # Validated; clean up (if needed) and return it
4673 return $this->cleanSig( $nickname, true );
4674 } else {
4675 # Failed to validate; fall back to the default
4676 $nickname = $username;
4677 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4678 }
4679 }
4680
4681 # Make sure nickname doesnt get a sig in a sig
4682 $nickname = self::cleanSigInSig( $nickname );
4683
4684 # If we're still here, make it a link to the user page
4685 $userText = wfEscapeWikiText( $username );
4686 $nickText = wfEscapeWikiText( $nickname );
4687 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4688
4689 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4690 }
4691
4692 /**
4693 * Check that the user's signature contains no bad XML
4694 *
4695 * @param $text String
4696 * @return mixed An expanded string, or false if invalid.
4697 */
4698 function validateSig( $text ) {
4699 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4700 }
4701
4702 /**
4703 * Clean up signature text
4704 *
4705 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4706 * 2) Substitute all transclusions
4707 *
4708 * @param $text String
4709 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4710 * @return String: signature text
4711 */
4712 public function cleanSig( $text, $parsing = false ) {
4713 if ( !$parsing ) {
4714 global $wgTitle;
4715 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4716 }
4717
4718 # Option to disable this feature
4719 if ( !$this->mOptions->getCleanSignatures() ) {
4720 return $text;
4721 }
4722
4723 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4724 # => Move this logic to braceSubstitution()
4725 $substWord = MagicWord::get( 'subst' );
4726 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4727 $substText = '{{' . $substWord->getSynonym( 0 );
4728
4729 $text = preg_replace( $substRegex, $substText, $text );
4730 $text = self::cleanSigInSig( $text );
4731 $dom = $this->preprocessToDom( $text );
4732 $frame = $this->getPreprocessor()->newFrame();
4733 $text = $frame->expand( $dom );
4734
4735 if ( !$parsing ) {
4736 $text = $this->mStripState->unstripBoth( $text );
4737 }
4738
4739 return $text;
4740 }
4741
4742 /**
4743 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4744 *
4745 * @param $text String
4746 * @return String: signature text with /~{3,5}/ removed
4747 */
4748 public static function cleanSigInSig( $text ) {
4749 $text = preg_replace( '/~{3,5}/', '', $text );
4750 return $text;
4751 }
4752
4753 /**
4754 * Set up some variables which are usually set up in parse()
4755 * so that an external function can call some class members with confidence
4756 *
4757 * @param $title Title|null
4758 * @param $options ParserOptions
4759 * @param $outputType
4760 * @param $clearState bool
4761 */
4762 public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4763 $this->startParse( $title, $options, $outputType, $clearState );
4764 }
4765
4766 /**
4767 * @param $title Title|null
4768 * @param $options ParserOptions
4769 * @param $outputType
4770 * @param $clearState bool
4771 */
4772 private function startParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4773 $this->setTitle( $title );
4774 $this->mOptions = $options;
4775 $this->setOutputType( $outputType );
4776 if ( $clearState ) {
4777 $this->clearState();
4778 }
4779 }
4780
4781 /**
4782 * Wrapper for preprocess()
4783 *
4784 * @param string $text the text to preprocess
4785 * @param $options ParserOptions: options
4786 * @param $title Title object or null to use $wgTitle
4787 * @return String
4788 */
4789 public function transformMsg( $text, $options, $title = null ) {
4790 static $executing = false;
4791
4792 # Guard against infinite recursion
4793 if ( $executing ) {
4794 return $text;
4795 }
4796 $executing = true;
4797
4798 wfProfileIn( __METHOD__ );
4799 if ( !$title ) {
4800 global $wgTitle;
4801 $title = $wgTitle;
4802 }
4803
4804 $text = $this->preprocess( $text, $title, $options );
4805
4806 $executing = false;
4807 wfProfileOut( __METHOD__ );
4808 return $text;
4809 }
4810
4811 /**
4812 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4813 * The callback should have the following form:
4814 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4815 *
4816 * Transform and return $text. Use $parser for any required context, e.g. use
4817 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4818 *
4819 * Hooks may return extended information by returning an array, of which the
4820 * first numbered element (index 0) must be the return string, and all other
4821 * entries are extracted into local variables within an internal function
4822 * in the Parser class.
4823 *
4824 * This interface (introduced r61913) appears to be undocumented, but
4825 * 'markerName' is used by some core tag hooks to override which strip
4826 * array their results are placed in. **Use great caution if attempting
4827 * this interface, as it is not documented and injudicious use could smash
4828 * private variables.**
4829 *
4830 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4831 * @param $callback Mixed: the callback function (and object) to use for the tag
4832 * @throws MWException
4833 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4834 */
4835 public function setHook( $tag, $callback ) {
4836 $tag = strtolower( $tag );
4837 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4838 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4839 }
4840 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4841 $this->mTagHooks[$tag] = $callback;
4842 if ( !in_array( $tag, $this->mStripList ) ) {
4843 $this->mStripList[] = $tag;
4844 }
4845
4846 return $oldVal;
4847 }
4848
4849 /**
4850 * As setHook(), but letting the contents be parsed.
4851 *
4852 * Transparent tag hooks are like regular XML-style tag hooks, except they
4853 * operate late in the transformation sequence, on HTML instead of wikitext.
4854 *
4855 * This is probably obsoleted by things dealing with parser frames?
4856 * The only extension currently using it is geoserver.
4857 *
4858 * @since 1.10
4859 * @todo better document or deprecate this
4860 *
4861 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4862 * @param $callback Mixed: the callback function (and object) to use for the tag
4863 * @throws MWException
4864 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4865 */
4866 function setTransparentTagHook( $tag, $callback ) {
4867 $tag = strtolower( $tag );
4868 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4869 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4870 }
4871 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4872 $this->mTransparentTagHooks[$tag] = $callback;
4873
4874 return $oldVal;
4875 }
4876
4877 /**
4878 * Remove all tag hooks
4879 */
4880 function clearTagHooks() {
4881 $this->mTagHooks = array();
4882 $this->mFunctionTagHooks = array();
4883 $this->mStripList = $this->mDefaultStripList;
4884 }
4885
4886 /**
4887 * Create a function, e.g. {{sum:1|2|3}}
4888 * The callback function should have the form:
4889 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4890 *
4891 * Or with SFH_OBJECT_ARGS:
4892 * function myParserFunction( $parser, $frame, $args ) { ... }
4893 *
4894 * The callback may either return the text result of the function, or an array with the text
4895 * in element 0, and a number of flags in the other elements. The names of the flags are
4896 * specified in the keys. Valid flags are:
4897 * found The text returned is valid, stop processing the template. This
4898 * is on by default.
4899 * nowiki Wiki markup in the return value should be escaped
4900 * isHTML The returned text is HTML, armour it against wikitext transformation
4901 *
4902 * @param string $id The magic word ID
4903 * @param $callback Mixed: the callback function (and object) to use
4904 * @param $flags Integer: a combination of the following flags:
4905 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4906 *
4907 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4908 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4909 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4910 * the arguments, and to control the way they are expanded.
4911 *
4912 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4913 * arguments, for instance:
4914 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4915 *
4916 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4917 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4918 * working if/when this is changed.
4919 *
4920 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4921 * expansion.
4922 *
4923 * Please read the documentation in includes/parser/Preprocessor.php for more information
4924 * about the methods available in PPFrame and PPNode.
4925 *
4926 * @throws MWException
4927 * @return string|callback The old callback function for this name, if any
4928 */
4929 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4930 global $wgContLang;
4931
4932 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4933 $this->mFunctionHooks[$id] = array( $callback, $flags );
4934
4935 # Add to function cache
4936 $mw = MagicWord::get( $id );
4937 if ( !$mw ) {
4938 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
4939 }
4940
4941 $synonyms = $mw->getSynonyms();
4942 $sensitive = intval( $mw->isCaseSensitive() );
4943
4944 foreach ( $synonyms as $syn ) {
4945 # Case
4946 if ( !$sensitive ) {
4947 $syn = $wgContLang->lc( $syn );
4948 }
4949 # Add leading hash
4950 if ( !( $flags & SFH_NO_HASH ) ) {
4951 $syn = '#' . $syn;
4952 }
4953 # Remove trailing colon
4954 if ( substr( $syn, -1, 1 ) === ':' ) {
4955 $syn = substr( $syn, 0, -1 );
4956 }
4957 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4958 }
4959 return $oldVal;
4960 }
4961
4962 /**
4963 * Get all registered function hook identifiers
4964 *
4965 * @return Array
4966 */
4967 function getFunctionHooks() {
4968 return array_keys( $this->mFunctionHooks );
4969 }
4970
4971 /**
4972 * Create a tag function, e.g. "<test>some stuff</test>".
4973 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4974 * Unlike parser functions, their content is not preprocessed.
4975 * @param $tag
4976 * @param $callback
4977 * @param $flags
4978 * @throws MWException
4979 * @return null
4980 */
4981 function setFunctionTagHook( $tag, $callback, $flags ) {
4982 $tag = strtolower( $tag );
4983 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4984 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4985 }
4986 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4987 $this->mFunctionTagHooks[$tag] : null;
4988 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
4989
4990 if ( !in_array( $tag, $this->mStripList ) ) {
4991 $this->mStripList[] = $tag;
4992 }
4993
4994 return $old;
4995 }
4996
4997 /**
4998 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4999 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5000 * Placeholders created in Skin::makeLinkObj()
5001 *
5002 * @param $text string
5003 * @param $options int
5004 *
5005 * @return array of link CSS classes, indexed by PDBK.
5006 */
5007 function replaceLinkHolders( &$text, $options = 0 ) {
5008 return $this->mLinkHolders->replace( $text );
5009 }
5010
5011 /**
5012 * Replace "<!--LINK-->" link placeholders with plain text of links
5013 * (not HTML-formatted).
5014 *
5015 * @param $text String
5016 * @return String
5017 */
5018 function replaceLinkHoldersText( $text ) {
5019 return $this->mLinkHolders->replaceText( $text );
5020 }
5021
5022 /**
5023 * Renders an image gallery from a text with one line per image.
5024 * text labels may be given by using |-style alternative text. E.g.
5025 * Image:one.jpg|The number "1"
5026 * Image:tree.jpg|A tree
5027 * given as text will return the HTML of a gallery with two images,
5028 * labeled 'The number "1"' and
5029 * 'A tree'.
5030 *
5031 * @param string $text
5032 * @param array $params
5033 * @return string HTML
5034 */
5035 function renderImageGallery( $text, $params ) {
5036 wfProfileIn( __METHOD__ );
5037 $ig = new ImageGallery();
5038 $ig->setContextTitle( $this->mTitle );
5039 $ig->setShowBytes( false );
5040 $ig->setShowFilename( false );
5041 $ig->setParser( $this );
5042 $ig->setHideBadImages();
5043 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
5044
5045 if ( isset( $params['showfilename'] ) ) {
5046 $ig->setShowFilename( true );
5047 } else {
5048 $ig->setShowFilename( false );
5049 }
5050 if ( isset( $params['caption'] ) ) {
5051 $caption = $params['caption'];
5052 $caption = htmlspecialchars( $caption );
5053 $caption = $this->replaceInternalLinks( $caption );
5054 $ig->setCaptionHtml( $caption );
5055 }
5056 if ( isset( $params['perrow'] ) ) {
5057 $ig->setPerRow( $params['perrow'] );
5058 }
5059 if ( isset( $params['widths'] ) ) {
5060 $ig->setWidths( $params['widths'] );
5061 }
5062 if ( isset( $params['heights'] ) ) {
5063 $ig->setHeights( $params['heights'] );
5064 }
5065
5066 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5067
5068 $lines = StringUtils::explode( "\n", $text );
5069 foreach ( $lines as $line ) {
5070 # match lines like these:
5071 # Image:someimage.jpg|This is some image
5072 $matches = array();
5073 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5074 # Skip empty lines
5075 if ( count( $matches ) == 0 ) {
5076 continue;
5077 }
5078
5079 if ( strpos( $matches[0], '%' ) !== false ) {
5080 $matches[1] = rawurldecode( $matches[1] );
5081 }
5082 $title = Title::newFromText( $matches[1], NS_FILE );
5083 if ( is_null( $title ) ) {
5084 # Bogus title. Ignore these so we don't bomb out later.
5085 continue;
5086 }
5087
5088 # We need to get what handler the file uses, to figure out parameters.
5089 # Note, a hook can overide the file name, and chose an entirely different
5090 # file (which potentially could be of a different type and have different handler).
5091 $options = array();
5092 $descQuery = false;
5093 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5094 array( $this, $title, &$options, &$descQuery ) );
5095 # Don't register it now, as ImageGallery does that later.
5096 $file = $this->fetchFileNoRegister( $title, $options );
5097 $handler = $file ? $file->getHandler() : false;
5098
5099 wfProfileIn( __METHOD__ . '-getMagicWord' );
5100 $paramMap = array(
5101 'img_alt' => 'gallery-internal-alt',
5102 'img_link' => 'gallery-internal-link',
5103 );
5104 if ( $handler ) {
5105 $paramMap = $paramMap + $handler->getParamMap();
5106 // We don't want people to specify per-image widths.
5107 // Additionally the width parameter would need special casing anyhow.
5108 unset( $paramMap['img_width'] );
5109 }
5110
5111 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5112 wfProfileOut( __METHOD__ . '-getMagicWord' );
5113
5114 $label = '';
5115 $alt = '';
5116 $link = '';
5117 $handlerOptions = array();
5118 if ( isset( $matches[3] ) ) {
5119 // look for an |alt= definition while trying not to break existing
5120 // captions with multiple pipes (|) in it, until a more sensible grammar
5121 // is defined for images in galleries
5122
5123 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5124 // splitting on '|' is a bit odd, and different from makeImage.
5125 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5126 $parameterMatches = StringUtils::explode( '|', $matches[3] );
5127
5128 foreach ( $parameterMatches as $parameterMatch ) {
5129 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5130 if ( $magicName ) {
5131 $paramName = $paramMap[$magicName];
5132
5133 switch( $paramName ) {
5134 case 'gallery-internal-alt':
5135 $alt = $this->stripAltText( $match, false );
5136 break;
5137 case 'gallery-internal-link':
5138 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5139 $chars = self::EXT_LINK_URL_CLASS;
5140 $prots = $this->mUrlProtocols;
5141 //check to see if link matches an absolute url, if not then it must be a wiki link.
5142 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5143 $link = $linkValue;
5144 } else {
5145 $localLinkTitle = Title::newFromText( $linkValue );
5146 if ( $localLinkTitle !== null ) {
5147 $link = $localLinkTitle->getLocalURL();
5148 }
5149 }
5150 break;
5151 default:
5152 // Must be a handler specific parameter.
5153 if ( $handler->validateParam( $paramName, $match ) ) {
5154 $handlerOptions[$paramName] = $match;
5155 } else {
5156 // Guess not. Append it to the caption.
5157 wfDebug( "$parameterMatch failed parameter validation" );
5158 $label .= '|' . $parameterMatch;
5159 }
5160 }
5161
5162 } else {
5163 // concatenate all other pipes
5164 $label .= '|' . $parameterMatch;
5165 }
5166 }
5167 // remove the first pipe
5168 $label = substr( $label, 1 );
5169 }
5170
5171 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5172 }
5173 $html = $ig->toHTML();
5174 wfProfileOut( __METHOD__ );
5175 return $html;
5176 }
5177
5178 /**
5179 * @param $handler
5180 * @return array
5181 */
5182 function getImageParams( $handler ) {
5183 if ( $handler ) {
5184 $handlerClass = get_class( $handler );
5185 } else {
5186 $handlerClass = '';
5187 }
5188 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5189 # Initialise static lists
5190 static $internalParamNames = array(
5191 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5192 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5193 'bottom', 'text-bottom' ),
5194 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5195 'upright', 'border', 'link', 'alt', 'class' ),
5196 );
5197 static $internalParamMap;
5198 if ( !$internalParamMap ) {
5199 $internalParamMap = array();
5200 foreach ( $internalParamNames as $type => $names ) {
5201 foreach ( $names as $name ) {
5202 $magicName = str_replace( '-', '_', "img_$name" );
5203 $internalParamMap[$magicName] = array( $type, $name );
5204 }
5205 }
5206 }
5207
5208 # Add handler params
5209 $paramMap = $internalParamMap;
5210 if ( $handler ) {
5211 $handlerParamMap = $handler->getParamMap();
5212 foreach ( $handlerParamMap as $magic => $paramName ) {
5213 $paramMap[$magic] = array( 'handler', $paramName );
5214 }
5215 }
5216 $this->mImageParams[$handlerClass] = $paramMap;
5217 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5218 }
5219 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
5220 }
5221
5222 /**
5223 * Parse image options text and use it to make an image
5224 *
5225 * @param $title Title
5226 * @param $options String
5227 * @param $holders LinkHolderArray|bool
5228 * @return string HTML
5229 */
5230 function makeImage( $title, $options, $holders = false ) {
5231 # Check if the options text is of the form "options|alt text"
5232 # Options are:
5233 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5234 # * left no resizing, just left align. label is used for alt= only
5235 # * right same, but right aligned
5236 # * none same, but not aligned
5237 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5238 # * center center the image
5239 # * frame Keep original image size, no magnify-button.
5240 # * framed Same as "frame"
5241 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5242 # * upright reduce width for upright images, rounded to full __0 px
5243 # * border draw a 1px border around the image
5244 # * alt Text for HTML alt attribute (defaults to empty)
5245 # * class Set a class for img node
5246 # * link Set the target of the image link. Can be external, interwiki, or local
5247 # vertical-align values (no % or length right now):
5248 # * baseline
5249 # * sub
5250 # * super
5251 # * top
5252 # * text-top
5253 # * middle
5254 # * bottom
5255 # * text-bottom
5256
5257 $parts = StringUtils::explode( "|", $options );
5258
5259 # Give extensions a chance to select the file revision for us
5260 $options = array();
5261 $descQuery = false;
5262 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5263 array( $this, $title, &$options, &$descQuery ) );
5264 # Fetch and register the file (file title may be different via hooks)
5265 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5266
5267 # Get parameter map
5268 $handler = $file ? $file->getHandler() : false;
5269
5270 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5271
5272 if ( !$file ) {
5273 $this->addTrackingCategory( 'broken-file-category' );
5274 }
5275
5276 # Process the input parameters
5277 $caption = '';
5278 $params = array( 'frame' => array(), 'handler' => array(),
5279 'horizAlign' => array(), 'vertAlign' => array() );
5280 foreach ( $parts as $part ) {
5281 $part = trim( $part );
5282 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5283 $validated = false;
5284 if ( isset( $paramMap[$magicName] ) ) {
5285 list( $type, $paramName ) = $paramMap[$magicName];
5286
5287 # Special case; width and height come in one variable together
5288 if ( $type === 'handler' && $paramName === 'width' ) {
5289 $parsedWidthParam = $this->parseWidthParam( $value );
5290 if ( isset( $parsedWidthParam['width'] ) ) {
5291 $width = $parsedWidthParam['width'];
5292 if ( $handler->validateParam( 'width', $width ) ) {
5293 $params[$type]['width'] = $width;
5294 $validated = true;
5295 }
5296 }
5297 if ( isset( $parsedWidthParam['height'] ) ) {
5298 $height = $parsedWidthParam['height'];
5299 if ( $handler->validateParam( 'height', $height ) ) {
5300 $params[$type]['height'] = $height;
5301 $validated = true;
5302 }
5303 }
5304 # else no validation -- bug 13436
5305 } else {
5306 if ( $type === 'handler' ) {
5307 # Validate handler parameter
5308 $validated = $handler->validateParam( $paramName, $value );
5309 } else {
5310 # Validate internal parameters
5311 switch ( $paramName ) {
5312 case 'manualthumb':
5313 case 'alt':
5314 case 'class':
5315 # @todo FIXME: Possibly check validity here for
5316 # manualthumb? downstream behavior seems odd with
5317 # missing manual thumbs.
5318 $validated = true;
5319 $value = $this->stripAltText( $value, $holders );
5320 break;
5321 case 'link':
5322 $chars = self::EXT_LINK_URL_CLASS;
5323 $prots = $this->mUrlProtocols;
5324 if ( $value === '' ) {
5325 $paramName = 'no-link';
5326 $value = true;
5327 $validated = true;
5328 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5329 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5330 $paramName = 'link-url';
5331 $this->mOutput->addExternalLink( $value );
5332 if ( $this->mOptions->getExternalLinkTarget() ) {
5333 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5334 }
5335 $validated = true;
5336 }
5337 } else {
5338 $linkTitle = Title::newFromText( $value );
5339 if ( $linkTitle ) {
5340 $paramName = 'link-title';
5341 $value = $linkTitle;
5342 $this->mOutput->addLink( $linkTitle );
5343 $validated = true;
5344 }
5345 }
5346 break;
5347 default:
5348 # Most other things appear to be empty or numeric...
5349 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5350 }
5351 }
5352
5353 if ( $validated ) {
5354 $params[$type][$paramName] = $value;
5355 }
5356 }
5357 }
5358 if ( !$validated ) {
5359 $caption = $part;
5360 }
5361 }
5362
5363 # Process alignment parameters
5364 if ( $params['horizAlign'] ) {
5365 $params['frame']['align'] = key( $params['horizAlign'] );
5366 }
5367 if ( $params['vertAlign'] ) {
5368 $params['frame']['valign'] = key( $params['vertAlign'] );
5369 }
5370
5371 $params['frame']['caption'] = $caption;
5372
5373 # Will the image be presented in a frame, with the caption below?
5374 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5375 isset( $params['frame']['framed'] ) ||
5376 isset( $params['frame']['thumbnail'] ) ||
5377 isset( $params['frame']['manualthumb'] );
5378
5379 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5380 # came to also set the caption, ordinary text after the image -- which
5381 # makes no sense, because that just repeats the text multiple times in
5382 # screen readers. It *also* came to set the title attribute.
5383 #
5384 # Now that we have an alt attribute, we should not set the alt text to
5385 # equal the caption: that's worse than useless, it just repeats the
5386 # text. This is the framed/thumbnail case. If there's no caption, we
5387 # use the unnamed parameter for alt text as well, just for the time be-
5388 # ing, if the unnamed param is set and the alt param is not.
5389 #
5390 # For the future, we need to figure out if we want to tweak this more,
5391 # e.g., introducing a title= parameter for the title; ignoring the un-
5392 # named parameter entirely for images without a caption; adding an ex-
5393 # plicit caption= parameter and preserving the old magic unnamed para-
5394 # meter for BC; ...
5395 if ( $imageIsFramed ) { # Framed image
5396 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5397 # No caption or alt text, add the filename as the alt text so
5398 # that screen readers at least get some description of the image
5399 $params['frame']['alt'] = $title->getText();
5400 }
5401 # Do not set $params['frame']['title'] because tooltips don't make sense
5402 # for framed images
5403 } else { # Inline image
5404 if ( !isset( $params['frame']['alt'] ) ) {
5405 # No alt text, use the "caption" for the alt text
5406 if ( $caption !== '' ) {
5407 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5408 } else {
5409 # No caption, fall back to using the filename for the
5410 # alt text
5411 $params['frame']['alt'] = $title->getText();
5412 }
5413 }
5414 # Use the "caption" for the tooltip text
5415 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5416 }
5417
5418 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5419
5420 # Linker does the rest
5421 $time = isset( $options['time'] ) ? $options['time'] : false;
5422 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5423 $time, $descQuery, $this->mOptions->getThumbSize() );
5424
5425 # Give the handler a chance to modify the parser object
5426 if ( $handler ) {
5427 $handler->parserTransformHook( $this, $file );
5428 }
5429
5430 return $ret;
5431 }
5432
5433 /**
5434 * @param $caption
5435 * @param $holders LinkHolderArray
5436 * @return mixed|String
5437 */
5438 protected function stripAltText( $caption, $holders ) {
5439 # Strip bad stuff out of the title (tooltip). We can't just use
5440 # replaceLinkHoldersText() here, because if this function is called
5441 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5442 if ( $holders ) {
5443 $tooltip = $holders->replaceText( $caption );
5444 } else {
5445 $tooltip = $this->replaceLinkHoldersText( $caption );
5446 }
5447
5448 # make sure there are no placeholders in thumbnail attributes
5449 # that are later expanded to html- so expand them now and
5450 # remove the tags
5451 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5452 $tooltip = Sanitizer::stripAllTags( $tooltip );
5453
5454 return $tooltip;
5455 }
5456
5457 /**
5458 * Set a flag in the output object indicating that the content is dynamic and
5459 * shouldn't be cached.
5460 */
5461 function disableCache() {
5462 wfDebug( "Parser output marked as uncacheable.\n" );
5463 if ( !$this->mOutput ) {
5464 throw new MWException( __METHOD__ .
5465 " can only be called when actually parsing something" );
5466 }
5467 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
5468 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5469 }
5470
5471 /**
5472 * Callback from the Sanitizer for expanding items found in HTML attribute
5473 * values, so they can be safely tested and escaped.
5474 *
5475 * @param $text String
5476 * @param $frame PPFrame
5477 * @return String
5478 */
5479 function attributeStripCallback( &$text, $frame = false ) {
5480 $text = $this->replaceVariables( $text, $frame );
5481 $text = $this->mStripState->unstripBoth( $text );
5482 return $text;
5483 }
5484
5485 /**
5486 * Accessor
5487 *
5488 * @return array
5489 */
5490 function getTags() {
5491 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ), array_keys( $this->mFunctionTagHooks ) );
5492 }
5493
5494 /**
5495 * Replace transparent tags in $text with the values given by the callbacks.
5496 *
5497 * Transparent tag hooks are like regular XML-style tag hooks, except they
5498 * operate late in the transformation sequence, on HTML instead of wikitext.
5499 *
5500 * @param $text string
5501 *
5502 * @return string
5503 */
5504 function replaceTransparentTags( $text ) {
5505 $matches = array();
5506 $elements = array_keys( $this->mTransparentTagHooks );
5507 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
5508 $replacements = array();
5509
5510 foreach ( $matches as $marker => $data ) {
5511 list( $element, $content, $params, $tag ) = $data;
5512 $tagName = strtolower( $element );
5513 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5514 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) );
5515 } else {
5516 $output = $tag;
5517 }
5518 $replacements[$marker] = $output;
5519 }
5520 return strtr( $text, $replacements );
5521 }
5522
5523 /**
5524 * Break wikitext input into sections, and either pull or replace
5525 * some particular section's text.
5526 *
5527 * External callers should use the getSection and replaceSection methods.
5528 *
5529 * @param string $text Page wikitext
5530 * @param string $section a section identifier string of the form:
5531 * "<flag1> - <flag2> - ... - <section number>"
5532 *
5533 * Currently the only recognised flag is "T", which means the target section number
5534 * was derived during a template inclusion parse, in other words this is a template
5535 * section edit link. If no flags are given, it was an ordinary section edit link.
5536 * This flag is required to avoid a section numbering mismatch when a section is
5537 * enclosed by "<includeonly>" (bug 6563).
5538 *
5539 * The section number 0 pulls the text before the first heading; other numbers will
5540 * pull the given section along with its lower-level subsections. If the section is
5541 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5542 *
5543 * Section 0 is always considered to exist, even if it only contains the empty
5544 * string. If $text is the empty string and section 0 is replaced, $newText is
5545 * returned.
5546 *
5547 * @param string $mode one of "get" or "replace"
5548 * @param string $newText replacement text for section data.
5549 * @return String: for "get", the extracted section text.
5550 * for "replace", the whole page with the section replaced.
5551 */
5552 private function extractSections( $text, $section, $mode, $newText = '' ) {
5553 global $wgTitle; # not generally used but removes an ugly failure mode
5554 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5555 $outText = '';
5556 $frame = $this->getPreprocessor()->newFrame();
5557
5558 # Process section extraction flags
5559 $flags = 0;
5560 $sectionParts = explode( '-', $section );
5561 $sectionIndex = array_pop( $sectionParts );
5562 foreach ( $sectionParts as $part ) {
5563 if ( $part === 'T' ) {
5564 $flags |= self::PTD_FOR_INCLUSION;
5565 }
5566 }
5567
5568 # Check for empty input
5569 if ( strval( $text ) === '' ) {
5570 # Only sections 0 and T-0 exist in an empty document
5571 if ( $sectionIndex == 0 ) {
5572 if ( $mode === 'get' ) {
5573 return '';
5574 } else {
5575 return $newText;
5576 }
5577 } else {
5578 if ( $mode === 'get' ) {
5579 return $newText;
5580 } else {
5581 return $text;
5582 }
5583 }
5584 }
5585
5586 # Preprocess the text
5587 $root = $this->preprocessToDom( $text, $flags );
5588
5589 # <h> nodes indicate section breaks
5590 # They can only occur at the top level, so we can find them by iterating the root's children
5591 $node = $root->getFirstChild();
5592
5593 # Find the target section
5594 if ( $sectionIndex == 0 ) {
5595 # Section zero doesn't nest, level=big
5596 $targetLevel = 1000;
5597 } else {
5598 while ( $node ) {
5599 if ( $node->getName() === 'h' ) {
5600 $bits = $node->splitHeading();
5601 if ( $bits['i'] == $sectionIndex ) {
5602 $targetLevel = $bits['level'];
5603 break;
5604 }
5605 }
5606 if ( $mode === 'replace' ) {
5607 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5608 }
5609 $node = $node->getNextSibling();
5610 }
5611 }
5612
5613 if ( !$node ) {
5614 # Not found
5615 if ( $mode === 'get' ) {
5616 return $newText;
5617 } else {
5618 return $text;
5619 }
5620 }
5621
5622 # Find the end of the section, including nested sections
5623 do {
5624 if ( $node->getName() === 'h' ) {
5625 $bits = $node->splitHeading();
5626 $curLevel = $bits['level'];
5627 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5628 break;
5629 }
5630 }
5631 if ( $mode === 'get' ) {
5632 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5633 }
5634 $node = $node->getNextSibling();
5635 } while ( $node );
5636
5637 # Write out the remainder (in replace mode only)
5638 if ( $mode === 'replace' ) {
5639 # Output the replacement text
5640 # Add two newlines on -- trailing whitespace in $newText is conventionally
5641 # stripped by the editor, so we need both newlines to restore the paragraph gap
5642 # Only add trailing whitespace if there is newText
5643 if ( $newText != "" ) {
5644 $outText .= $newText . "\n\n";
5645 }
5646
5647 while ( $node ) {
5648 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5649 $node = $node->getNextSibling();
5650 }
5651 }
5652
5653 if ( is_string( $outText ) ) {
5654 # Re-insert stripped tags
5655 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5656 }
5657
5658 return $outText;
5659 }
5660
5661 /**
5662 * This function returns the text of a section, specified by a number ($section).
5663 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5664 * the first section before any such heading (section 0).
5665 *
5666 * If a section contains subsections, these are also returned.
5667 *
5668 * @param string $text text to look in
5669 * @param string $section section identifier
5670 * @param string $deftext default to return if section is not found
5671 * @return string text of the requested section
5672 */
5673 public function getSection( $text, $section, $deftext = '' ) {
5674 return $this->extractSections( $text, $section, "get", $deftext );
5675 }
5676
5677 /**
5678 * This function returns $oldtext after the content of the section
5679 * specified by $section has been replaced with $text. If the target
5680 * section does not exist, $oldtext is returned unchanged.
5681 *
5682 * @param string $oldtext former text of the article
5683 * @param int $section section identifier
5684 * @param string $text replacing text
5685 * @return String: modified text
5686 */
5687 public function replaceSection( $oldtext, $section, $text ) {
5688 return $this->extractSections( $oldtext, $section, "replace", $text );
5689 }
5690
5691 /**
5692 * Get the ID of the revision we are parsing
5693 *
5694 * @return Mixed: integer or null
5695 */
5696 function getRevisionId() {
5697 return $this->mRevisionId;
5698 }
5699
5700 /**
5701 * Get the revision object for $this->mRevisionId
5702 *
5703 * @return Revision|null either a Revision object or null
5704 */
5705 protected function getRevisionObject() {
5706 if ( !is_null( $this->mRevisionObject ) ) {
5707 return $this->mRevisionObject;
5708 }
5709 if ( is_null( $this->mRevisionId ) ) {
5710 return null;
5711 }
5712
5713 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
5714 return $this->mRevisionObject;
5715 }
5716
5717 /**
5718 * Get the timestamp associated with the current revision, adjusted for
5719 * the default server-local timestamp
5720 */
5721 function getRevisionTimestamp() {
5722 if ( is_null( $this->mRevisionTimestamp ) ) {
5723 wfProfileIn( __METHOD__ );
5724
5725 global $wgContLang;
5726
5727 $revObject = $this->getRevisionObject();
5728 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5729
5730 # The cryptic '' timezone parameter tells to use the site-default
5731 # timezone offset instead of the user settings.
5732 #
5733 # Since this value will be saved into the parser cache, served
5734 # to other users, and potentially even used inside links and such,
5735 # it needs to be consistent for all visitors.
5736 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5737
5738 wfProfileOut( __METHOD__ );
5739 }
5740 return $this->mRevisionTimestamp;
5741 }
5742
5743 /**
5744 * Get the name of the user that edited the last revision
5745 *
5746 * @return String: user name
5747 */
5748 function getRevisionUser() {
5749 if ( is_null( $this->mRevisionUser ) ) {
5750 $revObject = $this->getRevisionObject();
5751
5752 # if this template is subst: the revision id will be blank,
5753 # so just use the current user's name
5754 if ( $revObject ) {
5755 $this->mRevisionUser = $revObject->getUserText();
5756 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5757 $this->mRevisionUser = $this->getUser()->getName();
5758 }
5759 }
5760 return $this->mRevisionUser;
5761 }
5762
5763 /**
5764 * Mutator for $mDefaultSort
5765 *
5766 * @param string $sort New value
5767 */
5768 public function setDefaultSort( $sort ) {
5769 $this->mDefaultSort = $sort;
5770 $this->mOutput->setProperty( 'defaultsort', $sort );
5771 }
5772
5773 /**
5774 * Accessor for $mDefaultSort
5775 * Will use the empty string if none is set.
5776 *
5777 * This value is treated as a prefix, so the
5778 * empty string is equivalent to sorting by
5779 * page name.
5780 *
5781 * @return string
5782 */
5783 public function getDefaultSort() {
5784 if ( $this->mDefaultSort !== false ) {
5785 return $this->mDefaultSort;
5786 } else {
5787 return '';
5788 }
5789 }
5790
5791 /**
5792 * Accessor for $mDefaultSort
5793 * Unlike getDefaultSort(), will return false if none is set
5794 *
5795 * @return string or false
5796 */
5797 public function getCustomDefaultSort() {
5798 return $this->mDefaultSort;
5799 }
5800
5801 /**
5802 * Try to guess the section anchor name based on a wikitext fragment
5803 * presumably extracted from a heading, for example "Header" from
5804 * "== Header ==".
5805 *
5806 * @param $text string
5807 *
5808 * @return string
5809 */
5810 public function guessSectionNameFromWikiText( $text ) {
5811 # Strip out wikitext links(they break the anchor)
5812 $text = $this->stripSectionName( $text );
5813 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5814 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
5815 }
5816
5817 /**
5818 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5819 * instead. For use in redirects, since IE6 interprets Redirect: headers
5820 * as something other than UTF-8 (apparently?), resulting in breakage.
5821 *
5822 * @param string $text The section name
5823 * @return string An anchor
5824 */
5825 public function guessLegacySectionNameFromWikiText( $text ) {
5826 # Strip out wikitext links(they break the anchor)
5827 $text = $this->stripSectionName( $text );
5828 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5829 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
5830 }
5831
5832 /**
5833 * Strips a text string of wikitext for use in a section anchor
5834 *
5835 * Accepts a text string and then removes all wikitext from the
5836 * string and leaves only the resultant text (i.e. the result of
5837 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5838 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5839 * to create valid section anchors by mimicing the output of the
5840 * parser when headings are parsed.
5841 *
5842 * @param string $text text string to be stripped of wikitext
5843 * for use in a Section anchor
5844 * @return string Filtered text string
5845 */
5846 public function stripSectionName( $text ) {
5847 # Strip internal link markup
5848 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5849 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5850
5851 # Strip external link markup
5852 # @todo FIXME: Not tolerant to blank link text
5853 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5854 # on how many empty links there are on the page - need to figure that out.
5855 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5856
5857 # Parse wikitext quotes (italics & bold)
5858 $text = $this->doQuotes( $text );
5859
5860 # Strip HTML tags
5861 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5862 return $text;
5863 }
5864
5865 /**
5866 * strip/replaceVariables/unstrip for preprocessor regression testing
5867 *
5868 * @param $text string
5869 * @param $title Title
5870 * @param $options ParserOptions
5871 * @param $outputType int
5872 *
5873 * @return string
5874 */
5875 function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
5876 $this->startParse( $title, $options, $outputType, true );
5877
5878 $text = $this->replaceVariables( $text );
5879 $text = $this->mStripState->unstripBoth( $text );
5880 $text = Sanitizer::removeHTMLtags( $text );
5881 return $text;
5882 }
5883
5884 /**
5885 * @param $text string
5886 * @param $title Title
5887 * @param $options ParserOptions
5888 * @return string
5889 */
5890 function testPst( $text, Title $title, ParserOptions $options ) {
5891 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5892 }
5893
5894 /**
5895 * @param $text
5896 * @param $title Title
5897 * @param $options ParserOptions
5898 * @return string
5899 */
5900 function testPreprocess( $text, Title $title, ParserOptions $options ) {
5901 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5902 }
5903
5904 /**
5905 * Call a callback function on all regions of the given text that are not
5906 * inside strip markers, and replace those regions with the return value
5907 * of the callback. For example, with input:
5908 *
5909 * aaa<MARKER>bbb
5910 *
5911 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5912 * two strings will be replaced with the value returned by the callback in
5913 * each case.
5914 *
5915 * @param $s string
5916 * @param $callback
5917 *
5918 * @return string
5919 */
5920 function markerSkipCallback( $s, $callback ) {
5921 $i = 0;
5922 $out = '';
5923 while ( $i < strlen( $s ) ) {
5924 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
5925 if ( $markerStart === false ) {
5926 $out .= call_user_func( $callback, substr( $s, $i ) );
5927 break;
5928 } else {
5929 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5930 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5931 if ( $markerEnd === false ) {
5932 $out .= substr( $s, $markerStart );
5933 break;
5934 } else {
5935 $markerEnd += strlen( self::MARKER_SUFFIX );
5936 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5937 $i = $markerEnd;
5938 }
5939 }
5940 }
5941 return $out;
5942 }
5943
5944 /**
5945 * Remove any strip markers found in the given text.
5946 *
5947 * @param $text Input string
5948 * @return string
5949 */
5950 function killMarkers( $text ) {
5951 return $this->mStripState->killMarkers( $text );
5952 }
5953
5954 /**
5955 * Save the parser state required to convert the given half-parsed text to
5956 * HTML. "Half-parsed" in this context means the output of
5957 * recursiveTagParse() or internalParse(). This output has strip markers
5958 * from replaceVariables (extensionSubstitution() etc.), and link
5959 * placeholders from replaceLinkHolders().
5960 *
5961 * Returns an array which can be serialized and stored persistently. This
5962 * array can later be loaded into another parser instance with
5963 * unserializeHalfParsedText(). The text can then be safely incorporated into
5964 * the return value of a parser hook.
5965 *
5966 * @param $text string
5967 *
5968 * @return array
5969 */
5970 function serializeHalfParsedText( $text ) {
5971 wfProfileIn( __METHOD__ );
5972 $data = array(
5973 'text' => $text,
5974 'version' => self::HALF_PARSED_VERSION,
5975 'stripState' => $this->mStripState->getSubState( $text ),
5976 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
5977 );
5978 wfProfileOut( __METHOD__ );
5979 return $data;
5980 }
5981
5982 /**
5983 * Load the parser state given in the $data array, which is assumed to
5984 * have been generated by serializeHalfParsedText(). The text contents is
5985 * extracted from the array, and its markers are transformed into markers
5986 * appropriate for the current Parser instance. This transformed text is
5987 * returned, and can be safely included in the return value of a parser
5988 * hook.
5989 *
5990 * If the $data array has been stored persistently, the caller should first
5991 * check whether it is still valid, by calling isValidHalfParsedText().
5992 *
5993 * @param array $data Serialized data
5994 * @throws MWException
5995 * @return String
5996 */
5997 function unserializeHalfParsedText( $data ) {
5998 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
5999 throw new MWException( __METHOD__ . ': invalid version' );
6000 }
6001
6002 # First, extract the strip state.
6003 $texts = array( $data['text'] );
6004 $texts = $this->mStripState->merge( $data['stripState'], $texts );
6005
6006 # Now renumber links
6007 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
6008
6009 # Should be good to go.
6010 return $texts[0];
6011 }
6012
6013 /**
6014 * Returns true if the given array, presumed to be generated by
6015 * serializeHalfParsedText(), is compatible with the current version of the
6016 * parser.
6017 *
6018 * @param $data Array
6019 *
6020 * @return bool
6021 */
6022 function isValidHalfParsedText( $data ) {
6023 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
6024 }
6025
6026 /**
6027 * Parsed a width param of imagelink like 300px or 200x300px
6028 *
6029 * @param $value String
6030 *
6031 * @return array
6032 * @since 1.20
6033 */
6034 public function parseWidthParam( $value ) {
6035 $parsedWidthParam = array();
6036 if ( $value === '' ) {
6037 return $parsedWidthParam;
6038 }
6039 $m = array();
6040 # (bug 13500) In both cases (width/height and width only),
6041 # permit trailing "px" for backward compatibility.
6042 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6043 $width = intval( $m[1] );
6044 $height = intval( $m[2] );
6045 $parsedWidthParam['width'] = $width;
6046 $parsedWidthParam['height'] = $height;
6047 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6048 $width = intval( $value );
6049 $parsedWidthParam['width'] = $width;
6050 }
6051 return $parsedWidthParam;
6052 }
6053 }