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