Merge "resourceloader: Remove redundant var-freeing in addScript()"
[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 }
361 } else {
362 # paragraph
363 if ( trim( $t ) === '' ) {
364 if ( $pendingPTag ) {
365 $output .= $pendingPTag . '<br />';
366 $pendingPTag = false;
367 $this->lastSection = 'p';
368 } else {
369 if ( $this->lastSection !== 'p' ) {
370 $output .= $this->closeParagraph();
371 $pendingPTag = '<p>';
372 } else {
373 $pendingPTag = '</p><p>';
374 }
375 }
376 } else {
377 if ( $pendingPTag ) {
378 $output .= $pendingPTag;
379 $pendingPTag = false;
380 $this->lastSection = 'p';
381 } elseif ( $this->lastSection !== 'p' ) {
382 $output .= $this->closeParagraph() . '<p>';
383 $this->lastSection = 'p';
384 }
385 }
386 }
387 }
388 }
389 # somewhere above we forget to get out of pre block (T2785)
390 if ( $preCloseMatch && $this->inPre ) {
391 $this->inPre = false;
392 }
393 if ( $pendingPTag === false ) {
394 if ( $prefixLength === 0 ) {
395 $output .= $t;
396 $output .= "\n";
397 } else {
398 // Trim whitespace in list items
399 $output .= trim( $t );
400 }
401 }
402 }
403 while ( $prefixLength ) {
404 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
405 --$prefixLength;
406 if ( !$prefixLength ) {
407 $output .= "\n";
408 }
409 }
410 if ( $this->lastSection !== '' ) {
411 $output .= '</' . $this->lastSection . '>';
412 $this->lastSection = '';
413 }
414
415 return $output;
416 }
417
418 /**
419 * Split up a string on ':', ignoring any occurrences inside tags
420 * to prevent illegal overlapping.
421 *
422 * @param string $str The string to split
423 * @param string &$before Set to everything before the ':'
424 * @param string &$after Set to everything after the ':'
425 * @throws MWException
426 * @return string The position of the ':', or false if none found
427 */
428 private function findColonNoLinks( $str, &$before, &$after ) {
429 if ( !preg_match( '/:|<|-\{/', $str, $m, PREG_OFFSET_CAPTURE ) ) {
430 # Nothing to find!
431 return false;
432 }
433
434 if ( $m[0][0] === ':' ) {
435 # Easy; no tag nesting to worry about
436 $colonPos = $m[0][1];
437 $before = substr( $str, 0, $colonPos );
438 $after = substr( $str, $colonPos + 1 );
439 return $colonPos;
440 }
441
442 # Ugly state machine to walk through avoiding tags.
443 $state = self::COLON_STATE_TEXT;
444 $ltLevel = 0;
445 $lcLevel = 0;
446 $len = strlen( $str );
447 for ( $i = $m[0][1]; $i < $len; $i++ ) {
448 $c = $str[$i];
449
450 switch ( $state ) {
451 case self::COLON_STATE_TEXT:
452 switch ( $c ) {
453 case "<":
454 # Could be either a <start> tag or an </end> tag
455 $state = self::COLON_STATE_TAGSTART;
456 break;
457 case ":":
458 if ( $ltLevel === 0 ) {
459 # We found it!
460 $before = substr( $str, 0, $i );
461 $after = substr( $str, $i + 1 );
462 return $i;
463 }
464 # Embedded in a tag; don't break it.
465 break;
466 default:
467 # Skip ahead looking for something interesting
468 if ( !preg_match( '/:|<|-\{/', $str, $m, PREG_OFFSET_CAPTURE, $i ) ) {
469 # Nothing else interesting
470 return false;
471 }
472 if ( $m[0][0] === '-{' ) {
473 $state = self::COLON_STATE_LC;
474 $lcLevel++;
475 $i = $m[0][1] + 1;
476 } else {
477 # Skip ahead to next interesting character.
478 $i = $m[0][1] - 1;
479 }
480 break;
481 }
482 break;
483 case self::COLON_STATE_LC:
484 # In language converter markup -{ ... }-
485 if ( !preg_match( '/-\{|\}-/', $str, $m, PREG_OFFSET_CAPTURE, $i ) ) {
486 # Nothing else interesting to find; abort!
487 # We're nested in language converter markup, but there
488 # are no close tags left. Abort!
489 break 2;
490 } elseif ( $m[0][0] === '-{' ) {
491 $i = $m[0][1] + 1;
492 $lcLevel++;
493 } elseif ( $m[0][0] === '}-' ) {
494 $i = $m[0][1] + 1;
495 $lcLevel--;
496 if ( $lcLevel === 0 ) {
497 $state = self::COLON_STATE_TEXT;
498 }
499 }
500 break;
501 case self::COLON_STATE_TAG:
502 # In a <tag>
503 switch ( $c ) {
504 case ">":
505 $ltLevel++;
506 $state = self::COLON_STATE_TEXT;
507 break;
508 case "/":
509 # Slash may be followed by >?
510 $state = self::COLON_STATE_TAGSLASH;
511 break;
512 default:
513 # ignore
514 }
515 break;
516 case self::COLON_STATE_TAGSTART:
517 switch ( $c ) {
518 case "/":
519 $state = self::COLON_STATE_CLOSETAG;
520 break;
521 case "!":
522 $state = self::COLON_STATE_COMMENT;
523 break;
524 case ">":
525 # Illegal early close? This shouldn't happen D:
526 $state = self::COLON_STATE_TEXT;
527 break;
528 default:
529 $state = self::COLON_STATE_TAG;
530 }
531 break;
532 case self::COLON_STATE_CLOSETAG:
533 # In a </tag>
534 if ( $c === ">" ) {
535 if ( $ltLevel > 0 ) {
536 $ltLevel--;
537 } else {
538 # ignore the excess close tag, but keep looking for
539 # colons. (This matches Parsoid behavior.)
540 wfDebug( __METHOD__ . ": Invalid input; too many close tags\n" );
541 }
542 $state = self::COLON_STATE_TEXT;
543 }
544 break;
545 case self::COLON_STATE_TAGSLASH:
546 if ( $c === ">" ) {
547 # Yes, a self-closed tag <blah/>
548 $state = self::COLON_STATE_TEXT;
549 } else {
550 # Probably we're jumping the gun, and this is an attribute
551 $state = self::COLON_STATE_TAG;
552 }
553 break;
554 case self::COLON_STATE_COMMENT:
555 if ( $c === "-" ) {
556 $state = self::COLON_STATE_COMMENTDASH;
557 }
558 break;
559 case self::COLON_STATE_COMMENTDASH:
560 if ( $c === "-" ) {
561 $state = self::COLON_STATE_COMMENTDASHDASH;
562 } else {
563 $state = self::COLON_STATE_COMMENT;
564 }
565 break;
566 case self::COLON_STATE_COMMENTDASHDASH:
567 if ( $c === ">" ) {
568 $state = self::COLON_STATE_TEXT;
569 } else {
570 $state = self::COLON_STATE_COMMENT;
571 }
572 break;
573 default:
574 throw new MWException( "State machine error in " . __METHOD__ );
575 }
576 }
577 if ( $ltLevel > 0 || $lcLevel > 0 ) {
578 wfDebug(
579 __METHOD__ . ": Invalid input; not enough close tags " .
580 "(level $ltLevel/$lcLevel, state $state)\n"
581 );
582 return false;
583 }
584 return false;
585 }
586 }