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