Update git submodules
[mediawiki.git] / includes / parser / BlockLevelPass.php
blob2c9388a929a14ebc29dec736b6f0eaf608b8925c
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
26 class BlockLevelPass {
27 private $DTopen = false;
28 private $inPre = false;
29 private $lastParagraph = '';
30 private $lineStart;
31 private $text;
33 # State constants for the definition list colon extraction
34 private const COLON_STATE_TEXT = 0;
35 private const COLON_STATE_TAG = 1;
36 private const COLON_STATE_TAGSTART = 2;
37 private const COLON_STATE_CLOSETAG = 3;
38 private const COLON_STATE_TAGSLASH = 4;
39 private const COLON_STATE_COMMENT = 5;
40 private const COLON_STATE_COMMENTDASH = 6;
41 private const COLON_STATE_COMMENTDASHDASH = 7;
42 private const COLON_STATE_LC = 8;
44 /**
45 * Make lists from lines starting with ':', '*', '#', etc.
47 * @param string $text
48 * @param bool $lineStart Whether or not this is at the start of a line.
49 * @return string The lists rendered as HTML
50 * @internal
52 public static function doBlockLevels( $text, $lineStart ) {
53 $pass = new self( $text, $lineStart );
54 return $pass->execute();
57 /**
58 * @param string $text
59 * @param bool $lineStart
61 private function __construct( $text, $lineStart ) {
62 $this->text = $text;
63 $this->lineStart = $lineStart;
66 /**
67 * @return bool
69 private function hasOpenParagraph() {
70 return $this->lastParagraph !== '';
73 /**
74 * If a pre or p is open, return the corresponding close tag and update
75 * the state. If no tag is open, return an empty string.
76 * @param bool $atTheEnd Omit trailing newline if we've reached the end.
77 * @return string
79 private function closeParagraph( $atTheEnd = false ) {
80 $result = '';
81 if ( $this->hasOpenParagraph() ) {
82 $result = '</' . $this->lastParagraph . '>';
83 if ( !$atTheEnd ) {
84 $result .= "\n";
87 $this->inPre = false;
88 $this->lastParagraph = '';
89 return $result;
92 /**
93 * getCommon() returns the length of the longest common substring
94 * of both arguments, starting at the beginning of both.
96 * @param string $st1
97 * @param string $st2
99 * @return int
101 private function getCommon( $st1, $st2 ) {
102 $shorter = min( strlen( $st1 ), strlen( $st2 ) );
104 for ( $i = 0; $i < $shorter; ++$i ) {
105 if ( $st1[$i] !== $st2[$i] ) {
106 break;
109 return $i;
113 * Open the list item element identified by the prefix character.
115 * @param string $char
117 * @return string
119 private function openList( $char ) {
120 $result = $this->closeParagraph();
122 if ( $char === '*' ) {
123 $result .= "<ul><li>";
124 } elseif ( $char === '#' ) {
125 $result .= "<ol><li>";
126 } elseif ( $char === ':' ) {
127 $result .= "<dl><dd>";
128 } elseif ( $char === ';' ) {
129 $result .= "<dl><dt>";
130 $this->DTopen = true;
131 } else {
132 $result = '<!-- ERR 1 -->';
135 return $result;
139 * Close the current list item and open the next one.
140 * @param string $char
142 * @return string
144 private function nextItem( $char ) {
145 if ( $char === '*' || $char === '#' ) {
146 return "</li>\n<li>";
147 } elseif ( $char === ':' || $char === ';' ) {
148 $close = "</dd>\n";
149 if ( $this->DTopen ) {
150 $close = "</dt>\n";
152 if ( $char === ';' ) {
153 $this->DTopen = true;
154 return $close . '<dt>';
155 } else {
156 $this->DTopen = false;
157 return $close . '<dd>';
160 return '<!-- ERR 2 -->';
164 * Close the current list item identified by the prefix character.
165 * @param string $char
167 * @return string
169 private function closeList( $char ) {
170 if ( $char === '*' ) {
171 $text = "</li></ul>";
172 } elseif ( $char === '#' ) {
173 $text = "</li></ol>";
174 } elseif ( $char === ':' ) {
175 if ( $this->DTopen ) {
176 $this->DTopen = false;
177 $text = "</dt></dl>";
178 } else {
179 $text = "</dd></dl>";
181 } else {
182 return '<!-- ERR 3 -->';
184 return $text;
188 * Execute the pass.
189 * @return string
191 private function execute() {
192 $text = $this->text;
193 # Parsing through the text line by line. The main thing
194 # happening here is handling of block-level elements p, pre,
195 # and making lists from lines starting with * # : etc.
196 $textLines = StringUtils::explode( "\n", $text );
198 $lastPrefix = $output = '';
199 $this->DTopen = $inBlockElem = false;
200 $prefixLength = 0;
201 $pendingPTag = false;
202 $inBlockquote = false;
204 for ( $textLines->rewind(); $textLines->valid(); ) {
205 $inputLine = $textLines->current();
206 $textLines->next();
207 $notLastLine = $textLines->valid();
209 # Fix up $lineStart
210 if ( !$this->lineStart ) {
211 $output .= $inputLine;
212 $this->lineStart = true;
213 continue;
215 # * = ul
216 # # = ol
217 # ; = dt
218 # : = dd
220 $lastPrefixLength = strlen( $lastPrefix );
221 $preCloseMatch = preg_match( '/<\\/pre/i', $inputLine );
222 $preOpenMatch = preg_match( '/<pre/i', $inputLine );
223 # If not in a <pre> element, scan for and figure out what prefixes are there.
224 if ( !$this->inPre ) {
225 # Multiple prefixes may abut each other for nested lists.
226 $prefixLength = strspn( $inputLine, '*#:;' );
227 $prefix = substr( $inputLine, 0, $prefixLength );
229 # eh?
230 # ; and : are both from definition-lists, so they're equivalent
231 # for the purposes of determining whether or not we need to open/close
232 # elements.
233 $prefix2 = str_replace( ';', ':', $prefix );
234 $t = substr( $inputLine, $prefixLength );
235 $this->inPre = (bool)$preOpenMatch;
236 } else {
237 # Don't interpret any other prefixes in preformatted text
238 $prefixLength = 0;
239 $prefix = $prefix2 = '';
240 $t = $inputLine;
243 # List generation
244 if ( $prefixLength && $lastPrefix === $prefix2 ) {
245 # Same as the last item, so no need to deal with nesting or opening stuff
246 $output .= $this->nextItem( substr( $prefix, -1 ) );
247 $pendingPTag = false;
249 if ( substr( $prefix, -1 ) === ';' ) {
250 # The one nasty exception: definition lists work like this:
251 # ; title : definition text
252 # So we check for : in the remainder text to split up the
253 # title and definition, without b0rking links.
254 $term = $t2 = '';
255 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
256 $t = $t2;
257 // Trim whitespace in list items
258 $output .= trim( $term ) . $this->nextItem( ':' );
261 } elseif ( $prefixLength || $lastPrefixLength ) {
262 # We need to open or close prefixes, or both.
264 # Either open or close a level...
265 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
266 $pendingPTag = false;
268 # Close all the prefixes which aren't shared.
269 while ( $commonPrefixLength < $lastPrefixLength ) {
270 // @phan-suppress-next-line PhanTypeInvalidDimOffset
271 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
272 --$lastPrefixLength;
275 # Continue the current prefix if appropriate.
276 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
277 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
280 # Close an open <dt> if we have a <dd> (":") starting on this line
281 if ( $this->DTopen && $commonPrefixLength > 0 && $prefix[$commonPrefixLength - 1] === ':' ) {
282 $output .= $this->nextItem( ':' );
285 # Open prefixes where appropriate.
286 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
287 $output .= "\n";
289 while ( $prefixLength > $commonPrefixLength ) {
290 $char = $prefix[$commonPrefixLength];
291 $output .= $this->openList( $char );
293 if ( $char === ';' ) {
294 # @todo FIXME: This is dupe of code above
295 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
296 $t = $t2;
297 // Trim whitespace in list items
298 $output .= trim( $term ) . $this->nextItem( ':' );
301 ++$commonPrefixLength;
303 if ( !$prefixLength && $lastPrefix ) {
304 $output .= "\n";
306 $lastPrefix = $prefix2;
309 # If we have no prefixes, go to paragraph mode.
310 if ( $prefixLength == 0 ) {
311 # No prefix (not in list)--go to paragraph mode
312 # @todo consider using a stack for nestable elements like span, table and div
314 // P-wrapping and indent-pre are suppressed inside, not outside
315 $blockElems = 'table|h1|h2|h3|h4|h5|h6|pre|p|ul|ol|dl';
316 // P-wrapping and indent-pre are suppressed outside, not inside
317 $antiBlockElems = 'td|th';
319 $openMatch = preg_match(
320 '/<('
321 . "({$blockElems})|\\/({$antiBlockElems})|"
322 // Always suppresses
323 . '\\/?(tr|caption|dt|dd|li)'
324 . ')\\b/iS',
327 $closeMatch = preg_match(
328 '/<('
329 . "\\/({$blockElems})|({$antiBlockElems})|"
330 // Never suppresses
331 . '\\/?(center|blockquote|div|hr|mw:|aside|figure)|'
332 // Used as Parser::TOC_PLACEHOLDER
333 . 'meta property="mw:'
334 . ')\\b/iS',
338 // Any match closes the paragraph, but only when `!$closeMatch`
339 // do we enter block mode. The oddities with table rows and
340 // cells are to avoid paragraph wrapping in interstitial spaces
341 // leading to fostered content.
343 if ( $openMatch || $closeMatch ) {
344 $pendingPTag = false;
345 // Only close the paragraph if we're not inside a <pre> tag, or if
346 // that <pre> tag has just been opened
347 if ( !$this->inPre || $preOpenMatch ) {
348 // @todo T7718: paragraph closed
349 $output .= $this->closeParagraph();
351 if ( $preOpenMatch && !$preCloseMatch ) {
352 $this->inPre = true;
354 $bqOffset = 0;
355 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t,
356 $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset )
358 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
359 $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] );
361 $inBlockElem = !$closeMatch;
362 } elseif ( !$inBlockElem && !$this->inPre ) {
363 if ( substr( $t, 0, 1 ) == ' '
364 && ( $this->lastParagraph === 'pre' || trim( $t ) != '' )
365 && !$inBlockquote
367 # pre
368 if ( $this->lastParagraph !== 'pre' ) {
369 $pendingPTag = false;
370 $output .= $this->closeParagraph() . '<pre>';
371 $this->lastParagraph = 'pre';
373 $t = substr( $t, 1 );
374 } elseif ( preg_match( '/^(?:<style\\b[^>]*>.*?<\\/style>\s*|<link\\b[^>]*>\s*)+$/iS', $t ) ) {
375 # T186965: <style> or <link> by itself on a line shouldn't open or close paragraphs.
376 # But it should clear $pendingPTag.
377 if ( $pendingPTag ) {
378 $output .= $this->closeParagraph();
379 $pendingPTag = false;
381 } else {
382 # paragraph
383 if ( trim( $t ) === '' ) {
384 if ( $pendingPTag ) {
385 $output .= $pendingPTag . '<br />';
386 $pendingPTag = false;
387 $this->lastParagraph = 'p';
388 } elseif ( $this->lastParagraph !== 'p' ) {
389 $output .= $this->closeParagraph();
390 $pendingPTag = '<p>';
391 } else {
392 $pendingPTag = '</p><p>';
394 } elseif ( $pendingPTag ) {
395 $output .= $pendingPTag;
396 $pendingPTag = false;
397 $this->lastParagraph = 'p';
398 } elseif ( $this->lastParagraph !== 'p' ) {
399 $output .= $this->closeParagraph() . '<p>';
400 $this->lastParagraph = 'p';
405 # somewhere above we forget to get out of pre block (T2785)
406 if ( $preCloseMatch && $this->inPre ) {
407 $this->inPre = false;
409 if ( $pendingPTag === false ) {
410 if ( $prefixLength === 0 ) {
411 $output .= $t;
412 // Add a newline if there's an open paragraph
413 // or we've yet to reach the last line.
414 if ( $notLastLine || $this->hasOpenParagraph() ) {
415 $output .= "\n";
417 } else {
418 // Trim whitespace in list items
419 $output .= trim( $t );
423 while ( $prefixLength ) {
424 // @phan-suppress-next-line PhanTypeArraySuspicious $prefix set if $prefixLength is set
425 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
426 --$prefixLength;
427 // Note that a paragraph is only ever opened when `prefixLength`
428 // is zero, but we'll choose to be overly cautious.
429 if ( !$prefixLength && $this->hasOpenParagraph() ) {
430 $output .= "\n";
433 $output .= $this->closeParagraph( true );
434 return $output;
438 * Split up a string on ':', ignoring any occurrences inside tags
439 * to prevent illegal overlapping.
441 * @param string $str The string to split
442 * @param string &$before Set to everything before the ':'
443 * @param string &$after Set to everything after the ':'
444 * @return int|false The position of the ':', or false if none found
446 private function findColonNoLinks( $str, &$before, &$after ) {
447 if ( !preg_match( '/:|<|-\{/', $str, $m, PREG_OFFSET_CAPTURE ) ) {
448 # Nothing to find!
449 return false;
452 if ( $m[0][0] === ':' ) {
453 # Easy; no tag nesting to worry about
454 $colonPos = $m[0][1];
455 $before = substr( $str, 0, $colonPos );
456 $after = substr( $str, $colonPos + 1 );
457 return $colonPos;
460 # Ugly state machine to walk through avoiding tags.
461 $state = self::COLON_STATE_TEXT;
462 $ltLevel = 0;
463 $lcLevel = 0;
464 $len = strlen( $str );
465 for ( $i = $m[0][1]; $i < $len; $i++ ) {
466 $c = $str[$i];
468 switch ( $state ) {
469 case self::COLON_STATE_TEXT:
470 switch ( $c ) {
471 case "<":
472 # Could be either a <start> tag or an </end> tag
473 $state = self::COLON_STATE_TAGSTART;
474 break;
475 case ":":
476 if ( $ltLevel === 0 ) {
477 # We found it!
478 $before = substr( $str, 0, $i );
479 $after = substr( $str, $i + 1 );
480 return $i;
482 # Embedded in a tag; don't break it.
483 break;
484 default:
485 # Skip ahead looking for something interesting
486 if ( !preg_match( '/:|<|-\{/', $str, $m, PREG_OFFSET_CAPTURE, $i ) ) {
487 # Nothing else interesting
488 return false;
490 if ( $m[0][0] === '-{' ) {
491 $state = self::COLON_STATE_LC;
492 $lcLevel++;
493 $i = $m[0][1] + 1;
494 } else {
495 # Skip ahead to next interesting character.
496 $i = $m[0][1] - 1;
498 break;
500 break;
501 case self::COLON_STATE_LC:
502 # In language converter markup -{ ... }-
503 if ( !preg_match( '/-\{|\}-/', $str, $m, PREG_OFFSET_CAPTURE, $i ) ) {
504 # Nothing else interesting to find; abort!
505 # We're nested in language converter markup, but there
506 # are no close tags left. Abort!
507 break 2;
509 if ( $m[0][0] === '-{' ) {
510 $i = $m[0][1] + 1;
511 $lcLevel++;
512 } elseif ( $m[0][0] === '}-' ) {
513 $i = $m[0][1] + 1;
514 $lcLevel--;
515 if ( $lcLevel === 0 ) {
516 $state = self::COLON_STATE_TEXT;
519 break;
520 case self::COLON_STATE_TAG:
521 # In a <tag>
522 switch ( $c ) {
523 case ">":
524 $ltLevel++;
525 $state = self::COLON_STATE_TEXT;
526 break;
527 case "/":
528 # Slash may be followed by >?
529 $state = self::COLON_STATE_TAGSLASH;
530 break;
531 default:
532 # ignore
534 break;
535 case self::COLON_STATE_TAGSTART:
536 switch ( $c ) {
537 case "/":
538 $state = self::COLON_STATE_CLOSETAG;
539 break;
540 case "!":
541 $state = self::COLON_STATE_COMMENT;
542 break;
543 case ">":
544 # Illegal early close? This shouldn't happen D:
545 $state = self::COLON_STATE_TEXT;
546 break;
547 default:
548 $state = self::COLON_STATE_TAG;
550 break;
551 case self::COLON_STATE_CLOSETAG:
552 # In a </tag>
553 if ( $c === ">" ) {
554 if ( $ltLevel > 0 ) {
555 $ltLevel--;
556 } else {
557 # ignore the excess close tag, but keep looking for
558 # colons. (This matches Parsoid behavior.)
559 wfDebug( __METHOD__ . ": Invalid input; too many close tags" );
561 $state = self::COLON_STATE_TEXT;
563 break;
564 case self::COLON_STATE_TAGSLASH:
565 if ( $c === ">" ) {
566 # Yes, a self-closed tag <blah/>
567 $state = self::COLON_STATE_TEXT;
568 } else {
569 # Probably we're jumping the gun, and this is an attribute
570 $state = self::COLON_STATE_TAG;
572 break;
573 case self::COLON_STATE_COMMENT:
574 if ( $c === "-" ) {
575 $state = self::COLON_STATE_COMMENTDASH;
577 break;
578 case self::COLON_STATE_COMMENTDASH:
579 if ( $c === "-" ) {
580 $state = self::COLON_STATE_COMMENTDASHDASH;
581 } else {
582 $state = self::COLON_STATE_COMMENT;
584 break;
585 case self::COLON_STATE_COMMENTDASHDASH:
586 if ( $c === ">" ) {
587 $state = self::COLON_STATE_TEXT;
588 } else {
589 $state = self::COLON_STATE_COMMENT;
591 break;
592 default:
593 throw new LogicException( "State machine error in " . __METHOD__ );
596 if ( $ltLevel > 0 || $lcLevel > 0 ) {
597 wfDebug(
598 __METHOD__ . ": Invalid input; not enough close tags " .
599 "(level $ltLevel/$lcLevel, state $state)"
602 return false;