MediaWiki master
BlockLevelPass.php
Go to the documentation of this file.
1<?php
2
14
15use LogicException;
16use Wikimedia\RemexHtml\HTMLData;
18
21 private $DTopen = false;
23 private $inPre = false;
25 private $lastParagraph = '';
27 private $lineStart;
29 private $text;
30
31 # State constants for the definition list colon extraction
32 private const COLON_STATE_TEXT = 0;
33 private const COLON_STATE_TAG = 1;
34 private const COLON_STATE_TAGSTART = 2;
35 private const COLON_STATE_CLOSETAG = 3;
36 private const COLON_STATE_TAGSLASH = 4;
37 private const COLON_STATE_COMMENT = 5;
38 private const COLON_STATE_COMMENTDASH = 6;
39 private const COLON_STATE_COMMENTDASHDASH = 7;
40 private const COLON_STATE_LC = 8;
41
50 public static function doBlockLevels( $text, $lineStart ) {
51 $pass = new self( $text, $lineStart );
52 return $pass->execute();
53 }
54
59 private function __construct( $text, $lineStart ) {
60 $this->text = $text;
61 $this->lineStart = $lineStart;
62 }
63
67 private function hasOpenParagraph() {
68 return $this->lastParagraph !== '';
69 }
70
77 private function closeParagraph( $atTheEnd = false ) {
78 $result = '';
79 if ( $this->hasOpenParagraph() ) {
80 $result = '</' . $this->lastParagraph . '>';
81 if ( !$atTheEnd ) {
82 $result .= "\n";
83 }
84 }
85 $this->inPre = false;
86 $this->lastParagraph = '';
87 return $result;
88 }
89
99 private function getCommon( $st1, $st2 ) {
100 $shorter = min( strlen( $st1 ), strlen( $st2 ) );
101
102 for ( $i = 0; $i < $shorter; ++$i ) {
103 if ( $st1[$i] !== $st2[$i] ) {
104 break;
105 }
106 }
107 return $i;
108 }
109
117 private function openList( $char ) {
118 $result = $this->closeParagraph();
119
120 if ( $char === '*' ) {
121 $result .= "<ul><li>";
122 } elseif ( $char === '#' ) {
123 $result .= "<ol><li>";
124 } elseif ( $char === ':' ) {
125 $result .= "<dl><dd>";
126 } elseif ( $char === ';' ) {
127 $result .= "<dl><dt>";
128 $this->DTopen = true;
129 } else {
130 $result = '<!-- ERR 1 -->';
131 }
132
133 return $result;
134 }
135
142 private function nextItem( $char ) {
143 if ( $char === '*' || $char === '#' ) {
144 return "</li>\n<li>";
145 } elseif ( $char === ':' || $char === ';' ) {
146 $close = "</dd>\n";
147 if ( $this->DTopen ) {
148 $close = "</dt>\n";
149 }
150 if ( $char === ';' ) {
151 $this->DTopen = true;
152 return $close . '<dt>';
153 } else {
154 $this->DTopen = false;
155 return $close . '<dd>';
156 }
157 }
158 return '<!-- ERR 2 -->';
159 }
160
167 private function closeList( $char ) {
168 if ( $char === '*' ) {
169 $text = "</li></ul>";
170 } elseif ( $char === '#' ) {
171 $text = "</li></ol>";
172 } elseif ( $char === ':' ) {
173 if ( $this->DTopen ) {
174 $this->DTopen = false;
175 $text = "</dt></dl>";
176 } else {
177 $text = "</dd></dl>";
178 }
179 } else {
180 return '<!-- ERR 3 -->';
181 }
182 return $text;
183 }
184
189 private function execute() {
190 $text = $this->text;
191 # Parsing through the text line by line. The main thing
192 # happening here is handling of block-level elements p, pre,
193 # and making lists from lines starting with * # : etc.
194 $textLines = StringUtils::explode( "\n", $text );
195
196 $lastPrefix = $output = '';
197 $this->DTopen = $inBlockElem = false;
198 $prefixLength = 0;
199 $pendingPTag = false;
200 $inBlockquote = false;
201
202 for ( $textLines->rewind(); $textLines->valid(); ) {
203 $inputLine = $textLines->current();
204 $textLines->next();
205 $notLastLine = $textLines->valid();
206
207 # Fix up $lineStart
208 if ( !$this->lineStart ) {
209 $output .= $inputLine;
210 $this->lineStart = true;
211 continue;
212 }
213 # * = ul
214 # # = ol
215 # ; = dt
216 # : = dd
217
218 $lastPrefixLength = strlen( $lastPrefix );
219 $preCloseMatch = preg_match( '/<\\/pre/i', $inputLine );
220 $preOpenMatch = preg_match( '/<pre/i', $inputLine );
221 # If not in a <pre> element, scan for and figure out what prefixes are there.
222 if ( !$this->inPre ) {
223 # Multiple prefixes may abut each other for nested lists.
224 $prefixLength = strspn( $inputLine, '*#:;' );
225 $prefix = substr( $inputLine, 0, $prefixLength );
226
227 # eh?
228 # ; and : are both from definition-lists, so they're equivalent
229 # for the purposes of determining whether or not we need to open/close
230 # elements.
231 $prefix2 = str_replace( ';', ':', $prefix );
232 $t = substr( $inputLine, $prefixLength );
233 $this->inPre = (bool)$preOpenMatch;
234 } else {
235 # Don't interpret any other prefixes in preformatted text
236 $prefixLength = 0;
237 $prefix = $prefix2 = '';
238 $t = $inputLine;
239 }
240
241 # List generation
242 if ( $prefixLength && $lastPrefix === $prefix2 ) {
243 # Same as the last item, so no need to deal with nesting or opening stuff
244 $output .= $this->nextItem( substr( $prefix, -1 ) );
245 $pendingPTag = false;
246
247 if ( substr( $prefix, -1 ) === ';' ) {
248 # The one nasty exception: definition lists work like this:
249 # ; title : definition text
250 # So we check for : in the remainder text to split up the
251 # title and definition, without b0rking links.
252 $term = $t2 = '';
253 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
254 $t = $t2;
255 // Trim whitespace in list items
256 $output .= trim( $term ) . $this->nextItem( ':' );
257 }
258 }
259 } elseif ( $prefixLength || $lastPrefixLength ) {
260 # We need to open or close prefixes, or both.
261
262 # Either open or close a level...
263 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
264 $pendingPTag = false;
265
266 # Close all the prefixes which aren't shared.
267 while ( $commonPrefixLength < $lastPrefixLength ) {
268 // @phan-suppress-next-line PhanTypeInvalidDimOffset
269 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
270 --$lastPrefixLength;
271 }
272
273 # Continue the current prefix if appropriate.
274 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
275 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
276 }
277
278 # Close an open <dt> if we have a <dd> (":") starting on this line
279 if ( $this->DTopen && $commonPrefixLength > 0 && $prefix[$commonPrefixLength - 1] === ':' ) {
280 $output .= $this->nextItem( ':' );
281 }
282
283 # Open prefixes where appropriate.
284 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
285 $output .= "\n";
286 }
287 while ( $prefixLength > $commonPrefixLength ) {
288 $char = $prefix[$commonPrefixLength];
289 $output .= $this->openList( $char );
290
291 if ( $char === ';' ) {
292 # @todo FIXME: This is dupe of code above
293 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
294 $t = $t2;
295 // Trim whitespace in list items
296 $output .= trim( $term ) . $this->nextItem( ':' );
297 }
298 }
299 ++$commonPrefixLength;
300 }
301 if ( !$prefixLength && $lastPrefix ) {
302 $output .= "\n";
303 }
304 $lastPrefix = $prefix2;
305 }
306
307 # If we have no prefixes, go to paragraph mode.
308 if ( $prefixLength == 0 ) {
309 # No prefix (not in list)--go to paragraph mode
310 # @todo consider using a stack for nestable elements like span, table and div
311
312 // P-wrapping and indent-pre are suppressed inside, not outside
313 $blockElems = 'table|h1|h2|h3|h4|h5|h6|pre|p|ul|ol|dl';
314 // P-wrapping and indent-pre are suppressed outside, not inside
315 $antiBlockElems = 'td|th';
316
317 $openMatch = preg_match(
318 '/<('
319 . "({$blockElems})|\\/({$antiBlockElems})|"
320 // Always suppresses
321 . '\\/?(tr|caption|dt|dd|li)'
322 . ')\\b/iS',
323 $t
324 );
325 $closeMatch = preg_match(
326 '/<('
327 . "\\/({$blockElems})|({$antiBlockElems})|"
328 // Never suppresses
329 . '\\/?(center|blockquote|div|hr|mw:|aside|figure)|'
330 // Used as Parser::TOC_PLACEHOLDER
331 . 'meta property="mw:'
332 . ')\\b/iS',
333 $t
334 );
335
336 // Any match closes the paragraph, but only when `!$closeMatch`
337 // do we enter block mode. The oddities with table rows and
338 // cells are to avoid paragraph wrapping in interstitial spaces
339 // leading to fostered content.
340
341 if ( $openMatch || $closeMatch ) {
342 $pendingPTag = false;
343 // Only close the paragraph if we're not inside a <pre> tag, or if
344 // that <pre> tag has just been opened
345 if ( !$this->inPre || $preOpenMatch ) {
346 // @todo T7718: paragraph closed
347 $output .= $this->closeParagraph();
348 }
349 if ( $preOpenMatch && !$preCloseMatch ) {
350 $this->inPre = true;
351 }
352 $bqOffset = 0;
353 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t,
354 $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset )
355 ) {
356 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
357 $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] );
358 }
359 $inBlockElem = !$closeMatch;
360 } elseif ( !$inBlockElem && !$this->inPre ) {
361 if ( substr( $t, 0, 1 ) == ' '
362 && ( $this->lastParagraph === 'pre' || trim( $t ) != '' )
363 && !$inBlockquote
364 ) {
365 # pre
366 if ( $this->lastParagraph !== 'pre' ) {
367 $pendingPTag = false;
368 $output .= $this->closeParagraph() . '<pre>';
369 $this->lastParagraph = 'pre';
370 }
371 $t = substr( $t, 1 );
372 } elseif ( preg_match( '/^(?:<style\\b[^>]*>.*?<\\/style>\s*|<link\\b[^>]*>\s*)+$/iS', $t ) ) {
373 # T186965: <style> or <link> by itself on a line shouldn't open or close paragraphs.
374 # But it should clear $pendingPTag.
375 if ( $pendingPTag ) {
376 $output .= $this->closeParagraph();
377 $pendingPTag = false;
378 }
379 } else {
380 # paragraph
381 if ( trim( $t ) === '' ) {
382 if ( $pendingPTag ) {
383 $output .= $pendingPTag . '<br />';
384 $pendingPTag = false;
385 $this->lastParagraph = 'p';
386 } elseif ( $this->lastParagraph !== 'p' ) {
387 $output .= $this->closeParagraph();
388 $pendingPTag = '<p>';
389 } else {
390 $pendingPTag = '</p><p>';
391 }
392 } elseif ( $pendingPTag ) {
393 $output .= $pendingPTag;
394 $pendingPTag = false;
395 $this->lastParagraph = 'p';
396 } elseif ( $this->lastParagraph !== 'p' ) {
397 $output .= $this->closeParagraph() . '<p>';
398 $this->lastParagraph = 'p';
399 }
400 }
401 }
402 }
403 # somewhere above we forget to get out of pre block (T2785)
404 if ( $preCloseMatch && $this->inPre ) {
405 $this->inPre = false;
406 }
407 if ( $pendingPTag === false ) {
408 if ( $prefixLength === 0 ) {
409 $output .= $t;
410 // Add a newline if there's an open paragraph
411 // or we've yet to reach the last line.
412 if ( $notLastLine || $this->hasOpenParagraph() ) {
413 $output .= "\n";
414 }
415 } else {
416 // Trim whitespace in list items
417 $output .= trim( $t );
418 }
419 }
420 }
421 while ( $prefixLength ) {
422 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
423 --$prefixLength;
424 // Note that a paragraph is only ever opened when `prefixLength`
425 // is zero, but we'll choose to be overly cautious.
426 if ( !$prefixLength && $this->hasOpenParagraph() ) {
427 $output .= "\n";
428 }
429 }
430 $output .= $this->closeParagraph( true );
431 return $output;
432 }
433
443 private function findColonNoLinks( $str, &$before, &$after ) {
444 if ( !preg_match( '/:|<|-\{/', $str, $m, PREG_OFFSET_CAPTURE ) ) {
445 # Nothing to find!
446 return false;
447 }
448
449 if ( $m[0][0] === ':' ) {
450 # Easy; no tag nesting to worry about
451 $colonPos = $m[0][1];
452 $before = substr( $str, 0, $colonPos );
453 $after = substr( $str, $colonPos + 1 );
454 return $colonPos;
455 }
456
457 # Ugly state machine to walk through avoiding tags.
458 $state = self::COLON_STATE_TEXT;
459 $ltLevel = 0;
460 $lcLevel = 0;
461 $captureName = false;
462 $tagName = '';
463 $len = strlen( $str );
464 for ( $i = $m[0][1]; $i < $len; $i++ ) {
465 $c = $str[$i];
466
467 switch ( $state ) {
468 case self::COLON_STATE_TEXT:
469 switch ( $c ) {
470 case "<":
471 # Could be either a <start> tag or an </end> tag
472 $state = self::COLON_STATE_TAGSTART;
473 $captureName = true;
474 $tagName = '';
475 break;
476 case ":":
477 if ( $ltLevel === 0 ) {
478 # We found it!
479 $before = substr( $str, 0, $i );
480 $after = substr( $str, $i + 1 );
481 return $i;
482 }
483 # Embedded in a tag; don't break it.
484 break;
485 default:
486 # Skip ahead looking for something interesting
487 if ( !preg_match( '/:|<|-\{/', $str, $m, PREG_OFFSET_CAPTURE, $i ) ) {
488 # Nothing else interesting
489 return false;
490 }
491 if ( $m[0][0] === '-{' ) {
492 $state = self::COLON_STATE_LC;
493 $lcLevel++;
494 $i = $m[0][1] + 1;
495 } else {
496 # Skip ahead to next interesting character.
497 $i = $m[0][1] - 1;
498 }
499 break;
500 }
501 break;
502 case self::COLON_STATE_LC:
503 # In language converter markup -{ ... }-
504 if ( !preg_match( '/-\{|\}-/', $str, $m, PREG_OFFSET_CAPTURE, $i ) ) {
505 # Nothing else interesting to find; abort!
506 # We're nested in language converter markup, but there
507 # are no close tags left. Abort!
508 break 2;
509 }
510 if ( $m[0][0] === '-{' ) {
511 $i = $m[0][1] + 1;
512 $lcLevel++;
513 } elseif ( $m[0][0] === '}-' ) {
514 $i = $m[0][1] + 1;
515 $lcLevel--;
516 if ( $lcLevel === 0 ) {
517 $state = self::COLON_STATE_TEXT;
518 }
519 }
520 break;
521 case self::COLON_STATE_TAG:
522 # In a <tag>
523 switch ( $c ) {
524 case " ":
525 $captureName = false;
526 break;
527 case ">":
528 if ( !isset( HTMLData::TAGS['void'][strtolower( $tagName )] ) ) {
529 $ltLevel++;
530 }
531 $state = self::COLON_STATE_TEXT;
532 break;
533 case "/":
534 # Slash may be followed by >?
535 $state = self::COLON_STATE_TAGSLASH;
536 break;
537 default:
538 if ( $captureName ) {
539 $tagName .= $c;
540 }
541 # ignore
542 }
543 break;
544 case self::COLON_STATE_TAGSTART:
545 switch ( $c ) {
546 case "/":
547 $state = self::COLON_STATE_CLOSETAG;
548 break;
549 case "!":
550 $state = self::COLON_STATE_COMMENT;
551 break;
552 case ">":
553 # Illegal early close? This shouldn't happen D:
554 $state = self::COLON_STATE_TEXT;
555 break;
556 default:
557 if ( $captureName ) {
558 $tagName .= $c;
559 }
560 $state = self::COLON_STATE_TAG;
561 }
562 break;
563 case self::COLON_STATE_CLOSETAG:
564 # In a </tag>
565 if ( $c === ">" ) {
566 if ( $ltLevel > 0 ) {
567 $ltLevel--;
568 } else {
569 # ignore the excess close tag, but keep looking for
570 # colons. (This matches Parsoid behavior.)
571 wfDebug( __METHOD__ . ": Invalid input; too many close tags" );
572 }
573 $state = self::COLON_STATE_TEXT;
574 }
575 break;
576 case self::COLON_STATE_TAGSLASH:
577 if ( $c === ">" ) {
578 # Yes, a self-closed tag <blah/>
579 $state = self::COLON_STATE_TEXT;
580 } else {
581 # Probably we're jumping the gun, and this is an attribute
582 $state = self::COLON_STATE_TAG;
583 }
584 break;
585 case self::COLON_STATE_COMMENT:
586 if ( $c === "-" ) {
587 $state = self::COLON_STATE_COMMENTDASH;
588 }
589 break;
590 case self::COLON_STATE_COMMENTDASH:
591 if ( $c === "-" ) {
592 $state = self::COLON_STATE_COMMENTDASHDASH;
593 } else {
594 $state = self::COLON_STATE_COMMENT;
595 }
596 break;
597 case self::COLON_STATE_COMMENTDASHDASH:
598 if ( $c === ">" ) {
599 $state = self::COLON_STATE_TEXT;
600 } else {
601 $state = self::COLON_STATE_COMMENT;
602 }
603 break;
604 default:
605 throw new LogicException( "State machine error in " . __METHOD__ );
606 }
607 }
608 if ( $ltLevel > 0 || $lcLevel > 0 ) {
609 wfDebug(
610 __METHOD__ . ": Invalid input; not enough close tags " .
611 "(level $ltLevel/$lcLevel, state $state)"
612 );
613 }
614 return false;
615 }
616}
617
619class_alias( BlockLevelPass::class, 'BlockLevelPass' );
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
static doBlockLevels( $text, $lineStart)
Make lists from lines starting with ':', '*', '#', etc.
A collection of static methods to play with strings.