MediaWiki master
BlockLevelPass.php
Go to the documentation of this file.
1<?php
2
28
29use LogicException;
30use StringUtils;
31
34 private $DTopen = false;
36 private $inPre = false;
38 private $lastParagraph = '';
40 private $lineStart;
42 private $text;
43
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;
54
63 public static function doBlockLevels( $text, $lineStart ) {
64 $pass = new self( $text, $lineStart );
65 return $pass->execute();
66 }
67
72 private function __construct( $text, $lineStart ) {
73 $this->text = $text;
74 $this->lineStart = $lineStart;
75 }
76
80 private function hasOpenParagraph() {
81 return $this->lastParagraph !== '';
82 }
83
90 private function closeParagraph( $atTheEnd = false ) {
91 $result = '';
92 if ( $this->hasOpenParagraph() ) {
93 $result = '</' . $this->lastParagraph . '>';
94 if ( !$atTheEnd ) {
95 $result .= "\n";
96 }
97 }
98 $this->inPre = false;
99 $this->lastParagraph = '';
100 return $result;
101 }
102
112 private function getCommon( $st1, $st2 ) {
113 $shorter = min( strlen( $st1 ), strlen( $st2 ) );
114
115 for ( $i = 0; $i < $shorter; ++$i ) {
116 if ( $st1[$i] !== $st2[$i] ) {
117 break;
118 }
119 }
120 return $i;
121 }
122
130 private function openList( $char ) {
131 $result = $this->closeParagraph();
132
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 -->';
144 }
145
146 return $result;
147 }
148
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";
162 }
163 if ( $char === ';' ) {
164 $this->DTopen = true;
165 return $close . '<dt>';
166 } else {
167 $this->DTopen = false;
168 return $close . '<dd>';
169 }
170 }
171 return '<!-- ERR 2 -->';
172 }
173
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>";
191 }
192 } else {
193 return '<!-- ERR 3 -->';
194 }
195 return $text;
196 }
197
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 );
208
209 $lastPrefix = $output = '';
210 $this->DTopen = $inBlockElem = false;
211 $prefixLength = 0;
212 $pendingPTag = false;
213 $inBlockquote = false;
214
215 for ( $textLines->rewind(); $textLines->valid(); ) {
216 $inputLine = $textLines->current();
217 $textLines->next();
218 $notLastLine = $textLines->valid();
219
220 # Fix up $lineStart
221 if ( !$this->lineStart ) {
222 $output .= $inputLine;
223 $this->lineStart = true;
224 continue;
225 }
226 # * = ul
227 # # = ol
228 # ; = dt
229 # : = dd
230
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 );
239
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;
252 }
253
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;
259
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( ':' );
270 }
271 }
272 } elseif ( $prefixLength || $lastPrefixLength ) {
273 # We need to open or close prefixes, or both.
274
275 # Either open or close a level...
276 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
277 $pendingPTag = false;
278
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;
284 }
285
286 # Continue the current prefix if appropriate.
287 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
288 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
289 }
290
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( ':' );
294 }
295
296 # Open prefixes where appropriate.
297 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
298 $output .= "\n";
299 }
300 while ( $prefixLength > $commonPrefixLength ) {
301 $char = $prefix[$commonPrefixLength];
302 $output .= $this->openList( $char );
303
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( ':' );
310 }
311 }
312 ++$commonPrefixLength;
313 }
314 if ( !$prefixLength && $lastPrefix ) {
315 $output .= "\n";
316 }
317 $lastPrefix = $prefix2;
318 }
319
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
324
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';
329
330 $openMatch = preg_match(
331 '/<('
332 . "({$blockElems})|\\/({$antiBlockElems})|"
333 // Always suppresses
334 . '\\/?(tr|caption|dt|dd|li)'
335 . ')\\b/iS',
336 $t
337 );
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',
346 $t
347 );
348
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.
353
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();
361 }
362 if ( $preOpenMatch && !$preCloseMatch ) {
363 $this->inPre = true;
364 }
365 $bqOffset = 0;
366 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t,
367 $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset )
368 ) {
369 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
370 $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] );
371 }
372 $inBlockElem = !$closeMatch;
373 } elseif ( !$inBlockElem && !$this->inPre ) {
374 if ( substr( $t, 0, 1 ) == ' '
375 && ( $this->lastParagraph === 'pre' || trim( $t ) != '' )
376 && !$inBlockquote
377 ) {
378 # pre
379 if ( $this->lastParagraph !== 'pre' ) {
380 $pendingPTag = false;
381 $output .= $this->closeParagraph() . '<pre>';
382 $this->lastParagraph = 'pre';
383 }
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;
391 }
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>';
404 }
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';
412 }
413 }
414 }
415 }
416 # somewhere above we forget to get out of pre block (T2785)
417 if ( $preCloseMatch && $this->inPre ) {
418 $this->inPre = false;
419 }
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";
427 }
428 } else {
429 // Trim whitespace in list items
430 $output .= trim( $t );
431 }
432 }
433 }
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";
442 }
443 }
444 $output .= $this->closeParagraph( true );
445 return $output;
446 }
447
457 private function findColonNoLinks( $str, &$before, &$after ) {
458 if ( !preg_match( '/:|<|-\{/', $str, $m, PREG_OFFSET_CAPTURE ) ) {
459 # Nothing to find!
460 return false;
461 }
462
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;
469 }
470
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];
478
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;
492 }
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;
500 }
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;
508 }
509 break;
510 }
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;
519 }
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;
528 }
529 }
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
544 }
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;
560 }
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" );
571 }
572 $state = self::COLON_STATE_TEXT;
573 }
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;
582 }
583 break;
584 case self::COLON_STATE_COMMENT:
585 if ( $c === "-" ) {
586 $state = self::COLON_STATE_COMMENTDASH;
587 }
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;
594 }
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;
601 }
602 break;
603 default:
604 throw new LogicException( "State machine error in " . __METHOD__ );
605 }
606 }
607 if ( $ltLevel > 0 || $lcLevel > 0 ) {
608 wfDebug(
609 __METHOD__ . ": Invalid input; not enough close tags " .
610 "(level $ltLevel/$lcLevel, state $state)"
611 );
612 }
613 return false;
614 }
615}
616
618class_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.
static explode( $separator, $subject)
Workalike for explode() with limited memory usage.