Merge "Rewrite pref cleanup script"
[lhc/web/wiklou.git] / includes / tidy / RemexCompatMunger.php
1 <?php
2
3 namespace MediaWiki\Tidy;
4
5 use RemexHtml\HTMLData;
6 use RemexHtml\Serializer\Serializer;
7 use RemexHtml\Serializer\SerializerNode;
8 use RemexHtml\Tokenizer\Attributes;
9 use RemexHtml\Tokenizer\PlainAttributes;
10 use RemexHtml\TreeBuilder\TreeBuilder;
11 use RemexHtml\TreeBuilder\TreeHandler;
12 use RemexHtml\TreeBuilder\Element;
13
14 /**
15 * @internal
16 */
17 class RemexCompatMunger implements TreeHandler {
18 private static $onlyInlineElements = [
19 "a" => true,
20 "abbr" => true,
21 "acronym" => true,
22 "applet" => true,
23 "b" => true,
24 "basefont" => true,
25 "bdo" => true,
26 "big" => true,
27 "br" => true,
28 "button" => true,
29 "cite" => true,
30 "code" => true,
31 "dfn" => true,
32 "em" => true,
33 "font" => true,
34 "i" => true,
35 "iframe" => true,
36 "img" => true,
37 "input" => true,
38 "kbd" => true,
39 "label" => true,
40 "legend" => true,
41 "map" => true,
42 "object" => true,
43 "param" => true,
44 "q" => true,
45 "rb" => true,
46 "rbc" => true,
47 "rp" => true,
48 "rt" => true,
49 "rtc" => true,
50 "ruby" => true,
51 "s" => true,
52 "samp" => true,
53 "select" => true,
54 "small" => true,
55 "span" => true,
56 "strike" => true,
57 "strong" => true,
58 "sub" => true,
59 "sup" => true,
60 "textarea" => true,
61 "tt" => true,
62 "u" => true,
63 "var" => true,
64 ];
65
66 private static $formattingElements = [
67 'a' => true,
68 'b' => true,
69 'big' => true,
70 'code' => true,
71 'em' => true,
72 'font' => true,
73 'i' => true,
74 'nobr' => true,
75 's' => true,
76 'small' => true,
77 'strike' => true,
78 'strong' => true,
79 'tt' => true,
80 'u' => true,
81 ];
82
83 /**
84 * @param Serializer $serializer
85 */
86 public function __construct( Serializer $serializer ) {
87 $this->serializer = $serializer;
88 }
89
90 public function startDocument( $fragmentNamespace, $fragmentName ) {
91 $this->serializer->startDocument( $fragmentNamespace, $fragmentName );
92 $root = $this->serializer->getRootNode();
93 $root->snData = new RemexMungerData;
94 $root->snData->needsPWrapping = true;
95 }
96
97 public function endDocument( $pos ) {
98 $this->serializer->endDocument( $pos );
99 }
100
101 private function getParentForInsert( $preposition, $refElement ) {
102 if ( $preposition === TreeBuilder::ROOT ) {
103 return [ $this->serializer->getRootNode(), null ];
104 } elseif ( $preposition === TreeBuilder::BEFORE ) {
105 $refNode = $refElement->userData;
106 return [ $this->serializer->getParentNode( $refNode ), $refNode ];
107 } else {
108 $refNode = $refElement->userData;
109 $refData = $refNode->snData;
110 if ( $refData->currentCloneElement ) {
111 // Follow a chain of clone links if necessary
112 $origRefData = $refData;
113 while ( $refData->currentCloneElement ) {
114 $refElement = $refData->currentCloneElement;
115 $refNode = $refElement->userData;
116 $refData = $refNode->snData;
117 }
118 // Cache the end of the chain in the requested element
119 $origRefData->currentCloneElement = $refElement;
120 } elseif ( $refData->childPElement ) {
121 $refElement = $refData->childPElement;
122 $refNode = $refElement->userData;
123 }
124 return [ $refNode, $refNode ];
125 }
126 }
127
128 /**
129 * Insert a p-wrapper
130 *
131 * @param SerializerNode $parent
132 * @param int $sourceStart
133 * @return SerializerNode
134 */
135 private function insertPWrapper( SerializerNode $parent, $sourceStart ) {
136 $pWrap = new Element( HTMLData::NS_HTML, 'mw:p-wrap', new PlainAttributes );
137 $this->serializer->insertElement( TreeBuilder::UNDER, $parent, $pWrap, false,
138 $sourceStart, 0 );
139 $data = new RemexMungerData;
140 $data->isPWrapper = true;
141 $data->wrapBaseNode = $parent;
142 $pWrap->userData->snData = $data;
143 $parent->snData->childPElement = $pWrap;
144 return $pWrap->userData;
145 }
146
147 public function characters( $preposition, $refElement, $text, $start, $length,
148 $sourceStart, $sourceLength
149 ) {
150 $isBlank = strspn( $text, "\t\n\f\r ", $start, $length ) === $length;
151
152 list( $parent, $refNode ) = $this->getParentForInsert( $preposition, $refElement );
153 $parentData = $parent->snData;
154
155 if ( $preposition === TreeBuilder::UNDER ) {
156 if ( $parentData->needsPWrapping && !$isBlank ) {
157 // Add a p-wrapper for bare text under body/blockquote
158 $refNode = $this->insertPWrapper( $refNode, $sourceStart );
159 $parent = $refNode;
160 $parentData = $parent->snData;
161 } elseif ( $parentData->isSplittable && !$parentData->ancestorPNode ) {
162 // The parent is splittable and in block mode, so split the tag stack
163 $refNode = $this->splitTagStack( $refNode, true, $sourceStart );
164 $parent = $refNode;
165 $parentData = $parent->snData;
166 }
167 }
168
169 if ( !$isBlank ) {
170 // Non-whitespace characters detected
171 $parentData->nonblankNodeCount++;
172 }
173 $this->serializer->characters( $preposition, $refNode, $text, $start,
174 $length, $sourceStart, $sourceLength );
175 }
176
177 private function trace( $msg ) {
178 // echo "[RCM] $msg\n";
179 }
180
181 /**
182 * Insert or reparent an element. Create p-wrappers or split the tag stack
183 * as necessary.
184 *
185 * Consider the following insertion locations. The parent may be:
186 *
187 * - A: A body or blockquote (!!needsPWrapping)
188 * - B: A p-wrapper (!!isPWrapper)
189 * - C: A descendant of a p-wrapper (!!ancestorPNode)
190 * - CS: With splittable formatting elements in the stack region up to
191 * the p-wrapper
192 * - CU: With one or more unsplittable elements in the stack region up
193 * to the p-wrapper
194 * - D: Not a descendant of a p-wrapper (!ancestorNode)
195 * - DS: With splittable formatting elements in the stack region up to
196 * the body or blockquote
197 * - DU: With one or more unsplittable elements in the stack region up
198 * to the body or blockquote
199 *
200 * And consider that we may insert two types of element:
201 * - b: block
202 * - i: inline
203 *
204 * We handle the insertion as follows:
205 *
206 * - A/i: Create a p-wrapper, insert under it
207 * - A/b: Insert as normal
208 * - B/i: Insert as normal
209 * - B/b: Close the p-wrapper, insert under the body/blockquote (wrap
210 * base) instead)
211 * - C/i: Insert as normal
212 * - CS/b: Split the tag stack, insert the block under cloned formatting
213 * elements which have the wrap base (the parent of the p-wrap) as
214 * their ultimate parent.
215 * - CU/b: Disable the p-wrap, by reparenting the currently open child
216 * of the p-wrap under the p-wrap's parent. Then insert the block as
217 * normal.
218 * - D/b: Insert as normal
219 * - DS/i: Split the tag stack, creating a new p-wrapper as the ultimate
220 * parent of the formatting elements thus cloned. The parent of the
221 * p-wrapper is the body or blockquote.
222 * - DU/i: Insert as normal
223 *
224 * FIXME: fostering ($preposition == BEFORE) is mostly done by inserting as
225 * normal, the full algorithm is not followed.
226 *
227 * @param int $preposition
228 * @param Element|SerializerNode|null $refElement
229 * @param Element $element
230 * @param bool $void
231 * @param int $sourceStart
232 * @param int $sourceLength
233 */
234 public function insertElement( $preposition, $refElement, Element $element, $void,
235 $sourceStart, $sourceLength
236 ) {
237 list( $parent, $newRef ) = $this->getParentForInsert( $preposition, $refElement );
238 $parentData = $parent->snData;
239 $parentNs = $parent->namespace;
240 $parentName = $parent->name;
241 $elementName = $element->htmlName;
242
243 $inline = isset( self::$onlyInlineElements[$elementName] );
244 $under = $preposition === TreeBuilder::UNDER;
245
246 if ( $under && $parentData->isPWrapper && !$inline ) {
247 // [B/b] The element is non-inline and the parent is a p-wrapper,
248 // close the parent and insert into its parent instead
249 $this->trace( 'insert B/b' );
250 $newParent = $this->serializer->getParentNode( $parent );
251 $parent = $newParent;
252 $parentData = $parent->snData;
253 $pElement = $parentData->childPElement;
254 $parentData->childPElement = null;
255 $newRef = $refElement->userData;
256 $this->endTag( $pElement, $sourceStart, 0 );
257 } elseif ( $under && $parentData->isSplittable
258 && (bool)$parentData->ancestorPNode !== $inline
259 ) {
260 // [CS/b, DS/i] The parent is splittable and the current element is
261 // inline in block context, or if the current element is a block
262 // under a p-wrapper, split the tag stack.
263 $this->trace( $inline ? 'insert DS/i' : 'insert CS/b' );
264 $newRef = $this->splitTagStack( $newRef, $inline, $sourceStart );
265 $parent = $newRef;
266 $parentData = $parent->snData;
267 } elseif ( $under && $parentData->needsPWrapping && $inline ) {
268 // [A/i] If the element is inline and we are in body/blockquote,
269 // we need to create a p-wrapper
270 $this->trace( 'insert A/i' );
271 $newRef = $this->insertPWrapper( $newRef, $sourceStart );
272 $parent = $newRef;
273 $parentData = $parent->snData;
274 } elseif ( $parentData->ancestorPNode && !$inline ) {
275 // [CU/b] If the element is non-inline and (despite attempting to
276 // split above) there is still an ancestor p-wrap, disable that
277 // p-wrap
278 $this->trace( 'insert CU/b' );
279 $this->disablePWrapper( $parent, $sourceStart );
280 } else {
281 // [A/b, B/i, C/i, D/b, DU/i] insert as normal
282 $this->trace( 'insert normal' );
283 }
284
285 // An element with element children is a non-blank element
286 $parentData->nonblankNodeCount++;
287
288 // Insert the element downstream and so initialise its userData
289 $this->serializer->insertElement( $preposition, $newRef,
290 $element, $void, $sourceStart, $sourceLength );
291
292 // Initialise snData
293 if ( !$element->userData->snData ) {
294 $elementData = $element->userData->snData = new RemexMungerData;
295 } else {
296 $elementData = $element->userData->snData;
297 }
298 if ( ( $parentData->isPWrapper || $parentData->isSplittable )
299 && isset( self::$formattingElements[$elementName] )
300 ) {
301 $elementData->isSplittable = true;
302 }
303 if ( $parentData->isPWrapper ) {
304 $elementData->ancestorPNode = $parent;
305 } elseif ( $parentData->ancestorPNode ) {
306 $elementData->ancestorPNode = $parentData->ancestorPNode;
307 }
308 if ( $parentData->wrapBaseNode ) {
309 $elementData->wrapBaseNode = $parentData->wrapBaseNode;
310 } elseif ( $parentData->needsPWrapping ) {
311 $elementData->wrapBaseNode = $parent;
312 }
313 if ( $elementName === 'body'
314 || $elementName === 'blockquote'
315 || $elementName === 'html'
316 ) {
317 $elementData->needsPWrapping = true;
318 }
319 }
320
321 /**
322 * Clone nodes in a stack range and return the new parent
323 *
324 * @param SerializerNode $parentNode
325 * @param bool $inline
326 * @param int $pos The source position
327 * @return SerializerNode
328 */
329 private function splitTagStack( SerializerNode $parentNode, $inline, $pos ) {
330 $parentData = $parentNode->snData;
331 $wrapBase = $parentData->wrapBaseNode;
332 $pWrap = $parentData->ancestorPNode;
333 if ( !$pWrap ) {
334 $cloneEnd = $wrapBase;
335 } else {
336 $cloneEnd = $parentData->ancestorPNode;
337 }
338
339 $serializer = $this->serializer;
340 $node = $parentNode;
341 $root = $serializer->getRootNode();
342 $nodes = [];
343 $removableNodes = [];
344 $haveContent = false;
345 while ( $node !== $cloneEnd ) {
346 $nextParent = $serializer->getParentNode( $node );
347 if ( $nextParent === $root ) {
348 throw new \Exception( 'Did not find end of clone range' );
349 }
350 $nodes[] = $node;
351 if ( $node->snData->nonblankNodeCount === 0 ) {
352 $removableNodes[] = $node;
353 $nextParent->snData->nonblankNodeCount--;
354 }
355 $node = $nextParent;
356 }
357
358 if ( $inline ) {
359 $pWrap = $this->insertPWrapper( $wrapBase, $pos );
360 $node = $pWrap;
361 } else {
362 if ( $pWrap ) {
363 // End the p-wrap which was open, cancel the diversion
364 $wrapBase->snData->childPElement = null;
365 }
366 $pWrap = null;
367 $node = $wrapBase;
368 }
369
370 for ( $i = count( $nodes ) - 1; $i >= 0; $i-- ) {
371 $oldNode = $nodes[$i];
372 $oldData = $oldNode->snData;
373 $nodeParent = $node;
374 $element = new Element( $oldNode->namespace, $oldNode->name, $oldNode->attrs );
375 $this->serializer->insertElement( TreeBuilder::UNDER, $nodeParent,
376 $element, false, $pos, 0 );
377 $oldData->currentCloneElement = $element;
378
379 $newNode = $element->userData;
380 $newData = $newNode->snData = new RemexMungerData;
381 if ( $pWrap ) {
382 $newData->ancestorPNode = $pWrap;
383 }
384 $newData->isSplittable = true;
385 $newData->wrapBaseNode = $wrapBase;
386 $newData->isPWrapper = $oldData->isPWrapper;
387
388 $nodeParent->snData->nonblankNodeCount++;
389
390 $node = $newNode;
391 }
392 foreach ( $removableNodes as $rNode ) {
393 $fakeElement = new Element( $rNode->namespace, $rNode->name, $rNode->attrs );
394 $fakeElement->userData = $rNode;
395 $this->serializer->removeNode( $fakeElement, $pos );
396 }
397 return $node;
398 }
399
400 /**
401 * Find the ancestor of $node which is a child of a p-wrapper, and
402 * reparent that node so that it is placed after the end of the p-wrapper
403 */
404 private function disablePWrapper( SerializerNode $node, $sourceStart ) {
405 $nodeData = $node->snData;
406 $pWrapNode = $nodeData->ancestorPNode;
407 $newParent = $this->serializer->getParentNode( $pWrapNode );
408 if ( $pWrapNode !== $this->serializer->getLastChild( $newParent ) ) {
409 // Fostering or something? Abort!
410 return;
411 }
412
413 $nextParent = $node;
414 do {
415 $victim = $nextParent;
416 $victim->snData->ancestorPNode = null;
417 $nextParent = $this->serializer->getParentNode( $victim );
418 } while ( $nextParent !== $pWrapNode );
419
420 // Make a fake Element to use in a reparenting operation
421 $victimElement = new Element( $victim->namespace, $victim->name, $victim->attrs );
422 $victimElement->userData = $victim;
423
424 // Reparent
425 $this->serializer->insertElement( TreeBuilder::UNDER, $newParent, $victimElement,
426 false, $sourceStart, 0 );
427
428 // Decrement nonblank node count
429 $pWrapNode->snData->nonblankNodeCount--;
430
431 // Cancel the diversion so that no more elements are inserted under this p-wrap
432 $newParent->snData->childPElement = null;
433 }
434
435 public function endTag( Element $element, $sourceStart, $sourceLength ) {
436 $data = $element->userData->snData;
437 if ( $data->childPElement ) {
438 $this->endTag( $data->childPElement, $sourceStart, 0 );
439 }
440 $this->serializer->endTag( $element, $sourceStart, $sourceLength );
441 $element->userData->snData = null;
442 $element->userData = null;
443 }
444
445 public function doctype( $name, $public, $system, $quirks, $sourceStart, $sourceLength ) {
446 $this->serializer->doctype( $name, $public, $system, $quirks,
447 $sourceStart, $sourceLength );
448 }
449
450 public function comment( $preposition, $refElement, $text, $sourceStart, $sourceLength ) {
451 list( $parent, $refNode ) = $this->getParentForInsert( $preposition, $refElement );
452 $this->serializer->comment( $preposition, $refNode, $text,
453 $sourceStart, $sourceLength );
454 }
455
456 public function error( $text, $pos ) {
457 $this->serializer->error( $text, $pos );
458 }
459
460 public function mergeAttributes( Element $element, Attributes $attrs, $sourceStart ) {
461 $this->serializer->mergeAttributes( $element, $attrs, $sourceStart );
462 }
463
464 public function removeNode( Element $element, $sourceStart ) {
465 $this->serializer->removeNode( $element, $sourceStart );
466 }
467
468 public function reparentChildren( Element $element, Element $newParent, $sourceStart ) {
469 $self = $element->userData;
470 if ( $self->snData->childPElement ) {
471 // Reparent under the p-wrapper instead, so that e.g.
472 // <blockquote><mw:p-wrap>...</mw:p-wrap></blockquote>
473 // becomes
474 // <blockquote><mw:p-wrap><i>...</i></mw:p-wrap></blockquote>
475
476 // The formatting element should not be the parent of the p-wrap.
477 // Without this special case, the insertElement() of the <i> below
478 // would be diverted into the p-wrapper, causing infinite recursion
479 // (T178632)
480 $this->reparentChildren( $self->snData->childPElement, $newParent, $sourceStart );
481 return;
482 }
483
484 $children = $self->children;
485 $self->children = [];
486 $this->insertElement( TreeBuilder::UNDER, $element, $newParent, false, $sourceStart, 0 );
487 $newParentNode = $newParent->userData;
488 $newParentId = $newParentNode->id;
489 foreach ( $children as $child ) {
490 if ( is_object( $child ) ) {
491 $this->trace( "reparent <{$child->name}>" );
492 $child->parentId = $newParentId;
493 }
494 }
495 $newParentNode->children = $children;
496 }
497 }