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