Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / parser / BlockLevelPass.php
blob24285efbf67c9bc47507af3d1a1608a7ccfd05f7
1 <?php
3 /**
4 * This is the part of the wikitext parser which handles automatic paragraphs
5 * and conversion of start-of-line prefixes to HTML lists.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
22 * @file
23 * @ingroup Parser
24 * @internal
27 namespace MediaWiki\Parser;
29 use LogicException;
30 use StringUtils;
32 class BlockLevelPass {
33 /** @var bool */
34 private $DTopen = false;
35 /** @var bool */
36 private $inPre = false;
37 /** @var string */
38 private $lastParagraph = '';
39 /** @var bool */
40 private $lineStart;
41 /** @var string */
42 private $text;
44 # State constants for the definition list colon extraction
45 private const COLON_STATE_TEXT = 0;
46 private const COLON_STATE_TAG = 1;
47 private const COLON_STATE_TAGSTART = 2;
48 private const COLON_STATE_CLOSETAG = 3;
49 private const COLON_STATE_TAGSLASH = 4;
50 private const COLON_STATE_COMMENT = 5;
51 private const COLON_STATE_COMMENTDASH = 6;
52 private const COLON_STATE_COMMENTDASHDASH = 7;
53 private const COLON_STATE_LC = 8;
55 /**
56 * Make lists from lines starting with ':', '*', '#', etc.
58 * @param string $text
59 * @param bool $lineStart Whether or not this is at the start of a line.
60 * @return string The lists rendered as HTML
61 * @internal
63 public static function doBlockLevels( $text, $lineStart ) {
64 $pass = new self( $text, $lineStart );
65 return $pass->execute();
68 /**
69 * @param string $text
70 * @param bool $lineStart
72 private function __construct( $text, $lineStart ) {
73 $this->text = $text;
74 $this->lineStart = $lineStart;
77 /**
78 * @return bool
80 private function hasOpenParagraph() {
81 return $this->lastParagraph !== '';
84 /**
85 * If a pre or p is open, return the corresponding close tag and update
86 * the state. If no tag is open, return an empty string.
87 * @param bool $atTheEnd Omit trailing newline if we've reached the end.
88 * @return string
90 private function closeParagraph( $atTheEnd = false ) {
91 $result = '';
92 if ( $this->hasOpenParagraph() ) {
93 $result = '</' . $this->lastParagraph . '>';
94 if ( !$atTheEnd ) {
95 $result .= "\n";
98 $this->inPre = false;
99 $this->lastParagraph = '';
100 return $result;
104 * getCommon() returns the length of the longest common substring
105 * of both arguments, starting at the beginning of both.
107 * @param string $st1
108 * @param string $st2
110 * @return int
112 private function getCommon( $st1, $st2 ) {
113 $shorter = min( strlen( $st1 ), strlen( $st2 ) );
115 for ( $i = 0; $i < $shorter; ++$i ) {
116 if ( $st1[$i] !== $st2[$i] ) {
117 break;
120 return $i;
124 * Open the list item element identified by the prefix character.
126 * @param string $char
128 * @return string
130 private function openList( $char ) {
131 $result = $this->closeParagraph();
133 if ( $char === '*' ) {
134 $result .= "<ul><li>";
135 } elseif ( $char === '#' ) {
136 $result .= "<ol><li>";
137 } elseif ( $char === ':' ) {
138 $result .= "<dl><dd>";
139 } elseif ( $char === ';' ) {
140 $result .= "<dl><dt>";
141 $this->DTopen = true;
142 } else {
143 $result = '<!-- ERR 1 -->';
146 return $result;
150 * Close the current list item and open the next one.
151 * @param string $char
153 * @return string
155 private function nextItem( $char ) {
156 if ( $char === '*' || $char === '#' ) {
157 return "</li>\n<li>";
158 } elseif ( $char === ':' || $char === ';' ) {
159 $close = "</dd>\n";
160 if ( $this->DTopen ) {
161 $close = "</dt>\n";
163 if ( $char === ';' ) {
164 $this->DTopen = true;
165 return $close . '<dt>';
166 } else {
167 $this->DTopen = false;
168 return $close . '<dd>';
171 return '<!-- ERR 2 -->';
175 * Close the current list item identified by the prefix character.
176 * @param string $char
178 * @return string
180 private function closeList( $char ) {
181 if ( $char === '*' ) {
182 $text = "</li></ul>";
183 } elseif ( $char === '#' ) {
184 $text = "</li></ol>";
185 } elseif ( $char === ':' ) {
186 if ( $this->DTopen ) {
187 $this->DTopen = false;
188 $text = "</dt></dl>";
189 } else {
190 $text = "</dd></dl>";
192 } else {
193 return '<!-- ERR 3 -->';
195 return $text;
199 * Execute the pass.
200 * @return string
202 private function execute() {
203 $text = $this->text;
204 # Parsing through the text line by line. The main thing
205 # happening here is handling of block-level elements p, pre,
206 # and making lists from lines starting with * # : etc.
207 $textLines = StringUtils::explode( "\n", $text );
209 $lastPrefix = $output = '';
210 $this->DTopen = $inBlockElem = false;
211 $prefixLength = 0;
212 $pendingPTag = false;
213 $inBlockquote = false;
215 for ( $textLines->rewind(); $textLines->valid(); ) {
216 $inputLine = $textLines->current();
217 $textLines->next();
218 $notLastLine = $textLines->valid();
220 # Fix up $lineStart
221 if ( !$this->lineStart ) {
222 $output .= $inputLine;
223 $this->lineStart = true;
224 continue;
226 # * = ul
227 # # = ol
228 # ; = dt
229 # : = dd
231 $lastPrefixLength = strlen( $lastPrefix );
232 $preCloseMatch = preg_match( '/<\\/pre/i', $inputLine );
233 $preOpenMatch = preg_match( '/<pre/i', $inputLine );
234 # If not in a <pre> element, scan for and figure out what prefixes are there.
235 if ( !$this->inPre ) {
236 # Multiple prefixes may abut each other for nested lists.
237 $prefixLength = strspn( $inputLine, '*#:;' );
238 $prefix = substr( $inputLine, 0, $prefixLength );
240 # eh?
241 # ; and : are both from definition-lists, so they're equivalent
242 # for the purposes of determining whether or not we need to open/close
243 # elements.
244 $prefix2 = str_replace( ';', ':', $prefix );
245 $t = substr( $inputLine, $prefixLength );
246 $this->inPre = (bool)$preOpenMatch;
247 } else {
248 # Don't interpret any other prefixes in preformatted text
249 $prefixLength = 0;
250 $prefix = $prefix2 = '';
251 $t = $inputLine;
254 # List generation
255 if ( $prefixLength && $lastPrefix === $prefix2 ) {
256 # Same as the last item, so no need to deal with nesting or opening stuff
257 $output .= $this->nextItem( substr( $prefix, -1 ) );
258 $pendingPTag = false;
260 if ( substr( $prefix, -1 ) === ';' ) {
261 # The one nasty exception: definition lists work like this:
262 # ; title : definition text
263 # So we check for : in the remainder text to split up the
264 # title and definition, without b0rking links.
265 $term = $t2 = '';
266 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
267 $t = $t2;
268 // Trim whitespace in list items
269 $output .= trim( $term ) . $this->nextItem( ':' );
272 } elseif ( $prefixLength || $lastPrefixLength ) {
273 # We need to open or close prefixes, or both.
275 # Either open or close a level...
276 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
277 $pendingPTag = false;
279 # Close all the prefixes which aren't shared.
280 while ( $commonPrefixLength < $lastPrefixLength ) {
281 // @phan-suppress-next-line PhanTypeInvalidDimOffset
282 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
283 --$lastPrefixLength;
286 # Continue the current prefix if appropriate.
287 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
288 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
291 # Close an open <dt> if we have a <dd> (":") starting on this line
292 if ( $this->DTopen && $commonPrefixLength > 0 && $prefix[$commonPrefixLength - 1] === ':' ) {
293 $output .= $this->nextItem( ':' );
296 # Open prefixes where appropriate.
297 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
298 $output .= "\n";
300 while ( $prefixLength > $commonPrefixLength ) {
301 $char = $prefix[$commonPrefixLength];
302 $output .= $this->openList( $char );
304 if ( $char === ';' ) {
305 # @todo FIXME: This is dupe of code above
306 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
307 $t = $t2;
308 // Trim whitespace in list items
309 $output .= trim( $term ) . $this->nextItem( ':' );
312 ++$commonPrefixLength;
314 if ( !$prefixLength && $lastPrefix ) {
315 $output .= "\n";
317 $lastPrefix = $prefix2;
320 # If we have no prefixes, go to paragraph mode.
321 if ( $prefixLength == 0 ) {
322 # No prefix (not in list)--go to paragraph mode
323 # @todo consider using a stack for nestable elements like span, table and div
325 // P-wrapping and indent-pre are suppressed inside, not outside
326 $blockElems = 'table|h1|h2|h3|h4|h5|h6|pre|p|ul|ol|dl';
327 // P-wrapping and indent-pre are suppressed outside, not inside
328 $antiBlockElems = 'td|th';
330 $openMatch = preg_match(
331 '/<('
332 . "({$blockElems})|\\/({$antiBlockElems})|"
333 // Always suppresses
334 . '\\/?(tr|caption|dt|dd|li)'
335 . ')\\b/iS',
338 $closeMatch = preg_match(
339 '/<('
340 . "\\/({$blockElems})|({$antiBlockElems})|"
341 // Never suppresses
342 . '\\/?(center|blockquote|div|hr|mw:|aside|figure)|'
343 // Used as Parser::TOC_PLACEHOLDER
344 . 'meta property="mw:'
345 . ')\\b/iS',
349 // Any match closes the paragraph, but only when `!$closeMatch`
350 // do we enter block mode. The oddities with table rows and
351 // cells are to avoid paragraph wrapping in interstitial spaces
352 // leading to fostered content.
354 if ( $openMatch || $closeMatch ) {
355 $pendingPTag = false;
356 // Only close the paragraph if we're not inside a <pre> tag, or if
357 // that <pre> tag has just been opened
358 if ( !$this->inPre || $preOpenMatch ) {
359 // @todo T7718: paragraph closed
360 $output .= $this->closeParagraph();
362 if ( $preOpenMatch && !$preCloseMatch ) {
363 $this->inPre = true;
365 $bqOffset = 0;
366 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t,
367 $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset )
369 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
370 $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] );
372 $inBlockElem = !$closeMatch;
373 } elseif ( !$inBlockElem && !$this->inPre ) {
374 if ( substr( $t, 0, 1 ) == ' '
375 && ( $this->lastParagraph === 'pre' || trim( $t ) != '' )
376 && !$inBlockquote
378 # pre
379 if ( $this->lastParagraph !== 'pre' ) {
380 $pendingPTag = false;
381 $output .= $this->closeParagraph() . '<pre>';
382 $this->lastParagraph = 'pre';
384 $t = substr( $t, 1 );
385 } elseif ( preg_match( '/^(?:<style\\b[^>]*>.*?<\\/style>\s*|<link\\b[^>]*>\s*)+$/iS', $t ) ) {
386 # T186965: <style> or <link> by itself on a line shouldn't open or close paragraphs.
387 # But it should clear $pendingPTag.
388 if ( $pendingPTag ) {
389 $output .= $this->closeParagraph();
390 $pendingPTag = false;
392 } else {
393 # paragraph
394 if ( trim( $t ) === '' ) {
395 if ( $pendingPTag ) {
396 $output .= $pendingPTag . '<br />';
397 $pendingPTag = false;
398 $this->lastParagraph = 'p';
399 } elseif ( $this->lastParagraph !== 'p' ) {
400 $output .= $this->closeParagraph();
401 $pendingPTag = '<p>';
402 } else {
403 $pendingPTag = '</p><p>';
405 } elseif ( $pendingPTag ) {
406 $output .= $pendingPTag;
407 $pendingPTag = false;
408 $this->lastParagraph = 'p';
409 } elseif ( $this->lastParagraph !== 'p' ) {
410 $output .= $this->closeParagraph() . '<p>';
411 $this->lastParagraph = 'p';
416 # somewhere above we forget to get out of pre block (T2785)
417 if ( $preCloseMatch && $this->inPre ) {
418 $this->inPre = false;
420 if ( $pendingPTag === false ) {
421 if ( $prefixLength === 0 ) {
422 $output .= $t;
423 // Add a newline if there's an open paragraph
424 // or we've yet to reach the last line.
425 if ( $notLastLine || $this->hasOpenParagraph() ) {
426 $output .= "\n";
428 } else {
429 // Trim whitespace in list items
430 $output .= trim( $t );
434 while ( $prefixLength ) {
435 // @phan-suppress-next-line PhanTypeArraySuspicious $prefix set if $prefixLength is set
436 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
437 --$prefixLength;
438 // Note that a paragraph is only ever opened when `prefixLength`
439 // is zero, but we'll choose to be overly cautious.
440 if ( !$prefixLength && $this->hasOpenParagraph() ) {
441 $output .= "\n";
444 $output .= $this->closeParagraph( true );
445 return $output;
449 * Split up a string on ':', ignoring any occurrences inside tags
450 * to prevent illegal overlapping.
452 * @param string $str The string to split
453 * @param string &$before Set to everything before the ':'
454 * @param string &$after Set to everything after the ':'
455 * @return int|false The position of the ':', or false if none found
457 private function findColonNoLinks( $str, &$before, &$after ) {
458 if ( !preg_match( '/:|<|-\{/', $str, $m, PREG_OFFSET_CAPTURE ) ) {
459 # Nothing to find!
460 return false;
463 if ( $m[0][0] === ':' ) {
464 # Easy; no tag nesting to worry about
465 $colonPos = $m[0][1];
466 $before = substr( $str, 0, $colonPos );
467 $after = substr( $str, $colonPos + 1 );
468 return $colonPos;
471 # Ugly state machine to walk through avoiding tags.
472 $state = self::COLON_STATE_TEXT;
473 $ltLevel = 0;
474 $lcLevel = 0;
475 $len = strlen( $str );
476 for ( $i = $m[0][1]; $i < $len; $i++ ) {
477 $c = $str[$i];
479 switch ( $state ) {
480 case self::COLON_STATE_TEXT:
481 switch ( $c ) {
482 case "<":
483 # Could be either a <start> tag or an </end> tag
484 $state = self::COLON_STATE_TAGSTART;
485 break;
486 case ":":
487 if ( $ltLevel === 0 ) {
488 # We found it!
489 $before = substr( $str, 0, $i );
490 $after = substr( $str, $i + 1 );
491 return $i;
493 # Embedded in a tag; don't break it.
494 break;
495 default:
496 # Skip ahead looking for something interesting
497 if ( !preg_match( '/:|<|-\{/', $str, $m, PREG_OFFSET_CAPTURE, $i ) ) {
498 # Nothing else interesting
499 return false;
501 if ( $m[0][0] === '-{' ) {
502 $state = self::COLON_STATE_LC;
503 $lcLevel++;
504 $i = $m[0][1] + 1;
505 } else {
506 # Skip ahead to next interesting character.
507 $i = $m[0][1] - 1;
509 break;
511 break;
512 case self::COLON_STATE_LC:
513 # In language converter markup -{ ... }-
514 if ( !preg_match( '/-\{|\}-/', $str, $m, PREG_OFFSET_CAPTURE, $i ) ) {
515 # Nothing else interesting to find; abort!
516 # We're nested in language converter markup, but there
517 # are no close tags left. Abort!
518 break 2;
520 if ( $m[0][0] === '-{' ) {
521 $i = $m[0][1] + 1;
522 $lcLevel++;
523 } elseif ( $m[0][0] === '}-' ) {
524 $i = $m[0][1] + 1;
525 $lcLevel--;
526 if ( $lcLevel === 0 ) {
527 $state = self::COLON_STATE_TEXT;
530 break;
531 case self::COLON_STATE_TAG:
532 # In a <tag>
533 switch ( $c ) {
534 case ">":
535 $ltLevel++;
536 $state = self::COLON_STATE_TEXT;
537 break;
538 case "/":
539 # Slash may be followed by >?
540 $state = self::COLON_STATE_TAGSLASH;
541 break;
542 default:
543 # ignore
545 break;
546 case self::COLON_STATE_TAGSTART:
547 switch ( $c ) {
548 case "/":
549 $state = self::COLON_STATE_CLOSETAG;
550 break;
551 case "!":
552 $state = self::COLON_STATE_COMMENT;
553 break;
554 case ">":
555 # Illegal early close? This shouldn't happen D:
556 $state = self::COLON_STATE_TEXT;
557 break;
558 default:
559 $state = self::COLON_STATE_TAG;
561 break;
562 case self::COLON_STATE_CLOSETAG:
563 # In a </tag>
564 if ( $c === ">" ) {
565 if ( $ltLevel > 0 ) {
566 $ltLevel--;
567 } else {
568 # ignore the excess close tag, but keep looking for
569 # colons. (This matches Parsoid behavior.)
570 wfDebug( __METHOD__ . ": Invalid input; too many close tags" );
572 $state = self::COLON_STATE_TEXT;
574 break;
575 case self::COLON_STATE_TAGSLASH:
576 if ( $c === ">" ) {
577 # Yes, a self-closed tag <blah/>
578 $state = self::COLON_STATE_TEXT;
579 } else {
580 # Probably we're jumping the gun, and this is an attribute
581 $state = self::COLON_STATE_TAG;
583 break;
584 case self::COLON_STATE_COMMENT:
585 if ( $c === "-" ) {
586 $state = self::COLON_STATE_COMMENTDASH;
588 break;
589 case self::COLON_STATE_COMMENTDASH:
590 if ( $c === "-" ) {
591 $state = self::COLON_STATE_COMMENTDASHDASH;
592 } else {
593 $state = self::COLON_STATE_COMMENT;
595 break;
596 case self::COLON_STATE_COMMENTDASHDASH:
597 if ( $c === ">" ) {
598 $state = self::COLON_STATE_TEXT;
599 } else {
600 $state = self::COLON_STATE_COMMENT;
602 break;
603 default:
604 throw new LogicException( "State machine error in " . __METHOD__ );
607 if ( $ltLevel > 0 || $lcLevel > 0 ) {
608 wfDebug(
609 __METHOD__ . ": Invalid input; not enough close tags " .
610 "(level $ltLevel/$lcLevel, state $state)"
613 return false;
617 /** @deprecated class alias since 1.43 */
618 class_alias( BlockLevelPass::class, 'BlockLevelPass' );