Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
94.70% |
268 / 283 |
|
81.48% |
22 / 27 |
CRAP | |
0.00% |
0 / 1 |
CommentUtils | |
94.70% |
268 / 283 |
|
81.48% |
22 / 27 |
165.91 | |
0.00% |
0 / 1 |
__construct | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
isBlockElement | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
isRenderingTransparentNode | |
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |
11 | |||
isOurGeneratedNode | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
4 | |||
cantHaveElementChildren | |
100.00% |
18 / 18 |
|
100.00% |
1 / 1 |
7 | |||
isCommentSeparator | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
13 | |||
isCommentContent | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
3 | |||
childIndexOf | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
contains | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
closestElement | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
closestElementWithSibling | |
0.00% |
0 / 7 |
|
0.00% |
0 / 1 |
72 | |||
getTranscludedFromElement | |
100.00% |
14 / 14 |
|
100.00% |
1 / 1 |
10 | |||
getHeadlineNode | |
66.67% |
6 / 9 |
|
0.00% |
0 / 1 |
5.93 | |||
htmlTrim | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getIndentLevel | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
6 | |||
getCoveredSiblings | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
5 | |||
getFullyCoveredSiblings | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
5 | |||
unwrapParsoidSections | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
getTitleFromUrl | |
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |
6 | |||
linearWalk | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
5 | |||
linearWalkBackwards | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
5 | |||
getRangeFirstNode | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
getRangeLastNode | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
compareRanges | |
88.00% |
22 / 25 |
|
0.00% |
0 / 1 |
23.91 | |||
compareRangesAlmostEqualBoundaries | |
100.00% |
28 / 28 |
|
100.00% |
1 / 1 |
15 | |||
isSingleCommentSignedBy | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
9 | |||
getNewTopicsSubscriptionId | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 |
1 | <?php |
2 | |
3 | namespace MediaWiki\Extension\DiscussionTools; |
4 | |
5 | use LogicException; |
6 | use MediaWiki\Config\Config; |
7 | use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentCommentItem; |
8 | use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentThreadItem; |
9 | use MediaWiki\MainConfigNames; |
10 | use MediaWiki\Title\Title; |
11 | use Wikimedia\Assert\Assert; |
12 | use Wikimedia\Parsoid\DOM\Comment; |
13 | use Wikimedia\Parsoid\DOM\Element; |
14 | use Wikimedia\Parsoid\DOM\Node; |
15 | use Wikimedia\Parsoid\DOM\Text; |
16 | use Wikimedia\Parsoid\Utils\DOMCompat; |
17 | use Wikimedia\Parsoid\Utils\DOMUtils; |
18 | |
19 | class CommentUtils { |
20 | |
21 | private function __construct() { |
22 | } |
23 | |
24 | private const BLOCK_ELEMENT_TYPES = [ |
25 | 'div', 'p', |
26 | // Tables |
27 | 'table', 'tbody', 'thead', 'tfoot', 'caption', 'th', 'tr', 'td', |
28 | // Lists |
29 | 'ul', 'ol', 'li', 'dl', 'dt', 'dd', |
30 | // HTML5 heading content |
31 | 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', |
32 | // HTML5 sectioning content |
33 | 'article', 'aside', 'body', 'nav', 'section', 'footer', 'header', 'figure', |
34 | 'figcaption', 'fieldset', 'details', 'blockquote', |
35 | // Other |
36 | 'hr', 'button', 'canvas', 'center', 'col', 'colgroup', 'embed', |
37 | 'map', 'object', 'pre', 'progress', 'video' |
38 | ]; |
39 | |
40 | /** |
41 | * @param Node $node |
42 | * @return bool Node is a block element |
43 | */ |
44 | public static function isBlockElement( Node $node ): bool { |
45 | return $node instanceof Element && |
46 | in_array( strtolower( $node->tagName ), static::BLOCK_ELEMENT_TYPES, true ); |
47 | } |
48 | |
49 | private const SOL_TRANSPARENT_LINK_REGEX = |
50 | '/(?:^|\s)mw:PageProp\/(?:Category|redirect|Language)(?=$|\s)/D'; |
51 | |
52 | /** |
53 | * @param Node $node |
54 | * @return bool Node is considered a rendering-transparent node in Parsoid |
55 | */ |
56 | public static function isRenderingTransparentNode( Node $node ): bool { |
57 | $nextSibling = $node->nextSibling; |
58 | return ( |
59 | $node instanceof Comment || |
60 | ( $node instanceof Element && ( |
61 | strtolower( $node->tagName ) === 'meta' || |
62 | ( |
63 | strtolower( $node->tagName ) === 'link' && |
64 | preg_match( static::SOL_TRANSPARENT_LINK_REGEX, $node->getAttribute( 'rel' ) ?? '' ) |
65 | ) || |
66 | // Empty inline templates, e.g. tracking templates. (T269036) |
67 | // But not empty nodes that are just the start of a non-empty template about-group. (T290940) |
68 | ( |
69 | strtolower( $node->tagName ) === 'span' && |
70 | in_array( 'mw:Transclusion', explode( ' ', $node->getAttribute( 'typeof' ) ?? '' ), true ) && |
71 | !static::htmlTrim( DOMCompat::getInnerHTML( $node ) ) && |
72 | ( |
73 | !$nextSibling || !( $nextSibling instanceof Element ) || |
74 | // Maybe we should be checking all of the about-grouped nodes to see if they're empty, |
75 | // but that's prooobably not needed in practice, and it leads to a quadratic worst case. |
76 | $nextSibling->getAttribute( 'about' ) !== $node->getAttribute( 'about' ) |
77 | ) |
78 | ) |
79 | ) ) |
80 | ); |
81 | } |
82 | |
83 | /** |
84 | * @param Node $node |
85 | * @return bool Node was added to the page by DiscussionTools |
86 | */ |
87 | public static function isOurGeneratedNode( Node $node ): bool { |
88 | return $node instanceof Element && ( |
89 | DOMUtils::hasClass( $node, 'ext-discussiontools-init-replylink-buttons' ) || |
90 | $node->hasAttribute( 'data-mw-comment-start' ) || |
91 | $node->hasAttribute( 'data-mw-comment-end' ) |
92 | ); |
93 | } |
94 | |
95 | /** |
96 | * Elements which can't have element children (but some may have text content). |
97 | */ |
98 | private const NO_ELEMENT_CHILDREN_ELEMENT_TYPES = [ |
99 | // https://html.spec.whatwg.org/multipage/syntax.html#elements-2 |
100 | // Void elements |
101 | 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', |
102 | 'link', 'meta', 'param', 'source', 'track', 'wbr', |
103 | // Raw text elements |
104 | 'script', 'style', |
105 | // Escapable raw text elements |
106 | 'textarea', 'title', |
107 | // Foreign elements |
108 | 'math', 'svg', |
109 | // Treated like text when scripting is enabled in the parser |
110 | // https://html.spec.whatwg.org/#the-noscript-element |
111 | 'noscript', |
112 | // Replaced elements (that aren't already included above) |
113 | // https://html.spec.whatwg.org/multipage/rendering.html#replaced-elements |
114 | // They might allow element children, but they aren't rendered on the page. |
115 | 'audio', 'canvas', 'iframe', 'object', 'video', |
116 | ]; |
117 | |
118 | /** |
119 | * @param Node $node |
120 | * @return bool If true, node can't have element children. If false, it's complicated. |
121 | */ |
122 | public static function cantHaveElementChildren( Node $node ): bool { |
123 | return ( |
124 | $node instanceof Comment || |
125 | ( $node instanceof Element && ( |
126 | in_array( strtolower( $node->tagName ), static::NO_ELEMENT_CHILDREN_ELEMENT_TYPES, true ) || |
127 | // Thumbnail wrappers generated by MediaTransformOutput::linkWrap (T301427), |
128 | // for compatibility with TimedMediaHandler. |
129 | // There is no better way to detect them, and we can't insert markers here, |
130 | // because the media DOM CSS depends on specific tag names and their order :( |
131 | // TODO See if we can remove this condition when wgParserEnableLegacyMediaDOM=false |
132 | // is enabled everywhere. |
133 | ( |
134 | in_array( strtolower( $node->tagName ), [ 'a', 'span' ], true ) && |
135 | $node->firstChild && |
136 | // We always step inside a child node so this can't be infinite, silly Phan |
137 | // @phan-suppress-next-line PhanInfiniteRecursion |
138 | static::cantHaveElementChildren( $node->firstChild ) |
139 | ) || |
140 | // Do not insert anything inside figures when using wgParserEnableLegacyMediaDOM=false, |
141 | // because their CSS can't handle it (T320285). |
142 | strtolower( $node->tagName ) === 'figure' |
143 | ) ) |
144 | ); |
145 | } |
146 | |
147 | /** |
148 | * Check whether the node is a comment separator (instead of a part of the comment). |
149 | */ |
150 | public static function isCommentSeparator( Node $node ): bool { |
151 | if ( !( $node instanceof Element ) ) { |
152 | return false; |
153 | } |
154 | |
155 | $tagName = strtolower( $node->tagName ); |
156 | if ( $tagName === 'br' || $tagName === 'hr' ) { |
157 | return true; |
158 | } |
159 | |
160 | // TemplateStyles followed by any of the others |
161 | if ( $node->nextSibling && |
162 | ( $tagName === 'link' || $tagName === 'style' ) && |
163 | self::isCommentSeparator( $node->nextSibling ) |
164 | ) { |
165 | return true; |
166 | } |
167 | |
168 | // Anything marked as not containing comments |
169 | // {{outdent}} templates |
170 | // {{tracked}} templates (T313097) |
171 | if ( DOMUtils::hasClass( $node, 'mw-notalk|outdent-template|mw-trackedTemplate' ) ) { |
172 | return true; |
173 | } |
174 | |
175 | // Wikitext definition list term markup (`;`) when used as a fake heading (T265964) |
176 | if ( $tagName === 'dl' && |
177 | count( $node->childNodes ) === 1 && |
178 | $node->firstChild instanceof Element && |
179 | strtolower( $node->firstChild->nodeName ) === 'dt' |
180 | ) { |
181 | return true; |
182 | } |
183 | |
184 | return false; |
185 | } |
186 | |
187 | /** |
188 | * Check whether the node is a comment content. It's a little vague what this means… |
189 | * |
190 | * @param Node $node Node, should be a leaf node (a node with no children) |
191 | * @return bool |
192 | */ |
193 | public static function isCommentContent( Node $node ): bool { |
194 | return ( |
195 | $node instanceof Text && |
196 | static::htmlTrim( $node->nodeValue ?? '' ) !== '' |
197 | ) || |
198 | ( |
199 | static::cantHaveElementChildren( $node ) |
200 | ); |
201 | } |
202 | |
203 | /** |
204 | * Get the index of $child in its parent |
205 | */ |
206 | public static function childIndexOf( Node $child ): int { |
207 | $i = 0; |
208 | while ( ( $child = $child->previousSibling ) ) { |
209 | $i++; |
210 | } |
211 | return $i; |
212 | } |
213 | |
214 | /** |
215 | * Check whether a Node contains (is an ancestor of) another Node (or is the same node) |
216 | */ |
217 | public static function contains( Node $ancestor, Node $descendant ): bool { |
218 | // TODO can we use Node->compareDocumentPosition() here maybe? |
219 | $node = $descendant; |
220 | while ( $node && $node !== $ancestor ) { |
221 | $node = $node->parentNode; |
222 | } |
223 | return $node === $ancestor; |
224 | } |
225 | |
226 | /** |
227 | * Find closest ancestor element using one of the given tag names. |
228 | * |
229 | * @param Node $node |
230 | * @param string[] $tagNames |
231 | * @return Element|null |
232 | */ |
233 | public static function closestElement( Node $node, array $tagNames ): ?Element { |
234 | do { |
235 | if ( |
236 | $node instanceof Element && |
237 | in_array( strtolower( $node->tagName ), $tagNames, true ) |
238 | ) { |
239 | return $node; |
240 | } |
241 | $node = $node->parentNode; |
242 | } while ( $node ); |
243 | return null; |
244 | } |
245 | |
246 | /** |
247 | * Find closest ancestor element that has sibling nodes |
248 | * |
249 | * @param Node $node |
250 | * @param string $direction Can be 'next', 'previous', or 'either' |
251 | * @return Element|null |
252 | */ |
253 | public static function closestElementWithSibling( Node $node, string $direction ): ?Element { |
254 | do { |
255 | if ( |
256 | $node instanceof Element && ( |
257 | ( $node->nextSibling && ( $direction === 'next' || $direction === 'either' ) ) || |
258 | ( $node->previousSibling && ( $direction === 'previous' || $direction === 'either' ) ) |
259 | ) |
260 | ) { |
261 | return $node; |
262 | } |
263 | $node = $node->parentNode; |
264 | } while ( $node ); |
265 | return null; |
266 | } |
267 | |
268 | /** |
269 | * Find the transclusion node which rendered the current node, if it exists. |
270 | * |
271 | * 1. Find the closest ancestor with an 'about' attribute |
272 | * 2. Find the main node of the about-group (first sibling with the same 'about' attribute) |
273 | * 3. If this is an mw:Transclusion node, return it; otherwise, go to step 1 |
274 | * |
275 | * @param Node $node |
276 | * @return Element|null Transclusion node, null if not found |
277 | */ |
278 | public static function getTranscludedFromElement( Node $node ): ?Element { |
279 | while ( $node ) { |
280 | // 1. |
281 | if ( |
282 | $node instanceof Element && |
283 | $node->getAttribute( 'about' ) && |
284 | preg_match( '/^#mwt\d+$/', $node->getAttribute( 'about' ) ?? '' ) |
285 | ) { |
286 | $about = $node->getAttribute( 'about' ); |
287 | |
288 | // 2. |
289 | while ( |
290 | ( $previousSibling = $node->previousSibling ) && |
291 | $previousSibling instanceof Element && |
292 | $previousSibling->getAttribute( 'about' ) === $about |
293 | ) { |
294 | $node = $previousSibling; |
295 | } |
296 | |
297 | // 3. |
298 | if ( |
299 | $node->getAttribute( 'typeof' ) && |
300 | in_array( 'mw:Transclusion', explode( ' ', $node->getAttribute( 'typeof' ) ?? '' ), true ) |
301 | ) { |
302 | break; |
303 | } |
304 | } |
305 | |
306 | $node = $node->parentNode; |
307 | } |
308 | return $node; |
309 | } |
310 | |
311 | /** |
312 | * Given a heading node, return the node on which the ID attribute is set. |
313 | * |
314 | * @param Element $heading Heading node (`<h1>`-`<h6>`) |
315 | * @return Element Headline node, normally also a `<h1>`-`<h6>` element. |
316 | * In integration tests and in JS, it can be a `<span class="mw-headline">` (see T363031). |
317 | */ |
318 | public static function getHeadlineNode( Element $heading ): Element { |
319 | // This code assumes that $wgFragmentMode is [ 'html5', 'legacy' ] or [ 'html5' ] |
320 | $headline = $heading; |
321 | |
322 | if ( $headline->hasAttribute( 'data-mw-comment-start' ) ) { |
323 | // HACK: For contaminated integration tests only (see T363031) |
324 | $headline = $headline->parentNode; |
325 | Assert::precondition( $headline !== null, 'data-mw-comment-start was attached to a heading' ); |
326 | } |
327 | |
328 | if ( !$headline->getAttribute( 'id' ) && !$headline->getAttribute( 'data-mw-anchor' ) ) { |
329 | // HACK: For outdated integration tests only (see T363031) |
330 | $headline = DOMCompat::querySelector( $headline, '.mw-headline' ); |
331 | if ( !$headline ) { |
332 | $headline = $heading; |
333 | } |
334 | } |
335 | |
336 | return $headline; |
337 | } |
338 | |
339 | /** |
340 | * Trim ASCII whitespace, as defined in the HTML spec. |
341 | */ |
342 | public static function htmlTrim( string $str ): string { |
343 | // https://infra.spec.whatwg.org/#ascii-whitespace |
344 | return trim( $str, "\t\n\f\r " ); |
345 | } |
346 | |
347 | /** |
348 | * Get the indent level of $node, relative to $rootNode. |
349 | * |
350 | * The indent level is the number of lists inside of which it is nested. |
351 | */ |
352 | public static function getIndentLevel( Node $node, Element $rootNode ): int { |
353 | $indent = 0; |
354 | while ( $node ) { |
355 | if ( $node === $rootNode ) { |
356 | break; |
357 | } |
358 | $tagName = $node instanceof Element ? strtolower( $node->tagName ) : null; |
359 | if ( $tagName === 'li' || $tagName === 'dd' ) { |
360 | $indent++; |
361 | } |
362 | $node = $node->parentNode; |
363 | } |
364 | return $indent; |
365 | } |
366 | |
367 | /** |
368 | * Get an array of sibling nodes that contain parts of the given range. |
369 | * |
370 | * @param ImmutableRange $range |
371 | * @return Node[] |
372 | */ |
373 | public static function getCoveredSiblings( ImmutableRange $range ): array { |
374 | $ancestor = $range->commonAncestorContainer; |
375 | |
376 | // Convert to array early because apparently NodeList acts like a linked list |
377 | // and accessing items by index is slow |
378 | $siblings = iterator_to_array( $ancestor->childNodes ); |
379 | $start = 0; |
380 | $end = count( $siblings ) - 1; |
381 | |
382 | // Find first of the siblings that contains the item |
383 | if ( $ancestor === $range->startContainer ) { |
384 | $start = $range->startOffset; |
385 | } else { |
386 | while ( !static::contains( $siblings[ $start ], $range->startContainer ) ) { |
387 | $start++; |
388 | } |
389 | } |
390 | |
391 | // Find last of the siblings that contains the item |
392 | if ( $ancestor === $range->endContainer ) { |
393 | $end = $range->endOffset - 1; |
394 | } else { |
395 | while ( !static::contains( $siblings[ $end ], $range->endContainer ) ) { |
396 | $end--; |
397 | } |
398 | } |
399 | |
400 | return array_slice( $siblings, $start, $end - $start + 1 ); |
401 | } |
402 | |
403 | /** |
404 | * Get the nodes (if any) that contain the given thread item, and nothing else. |
405 | * |
406 | * @param ContentThreadItem $item |
407 | * @param ?Node $excludedAncestorNode Node that shouldn't be included in the result, even if it |
408 | * contains the item and nothing else. This is intended to avoid traversing outside of a node |
409 | * which is a container for all the thread items. |
410 | * @return Node[]|null |
411 | */ |
412 | public static function getFullyCoveredSiblings( |
413 | ContentThreadItem $item, ?Node $excludedAncestorNode = null |
414 | ): ?array { |
415 | $siblings = static::getCoveredSiblings( $item->getRange() ); |
416 | |
417 | $makeRange = static function ( $siblings ) { |
418 | return new ImmutableRange( |
419 | $siblings[0]->parentNode, |
420 | CommentUtils::childIndexOf( $siblings[0] ), |
421 | end( $siblings )->parentNode, |
422 | CommentUtils::childIndexOf( end( $siblings ) ) + 1 |
423 | ); |
424 | }; |
425 | |
426 | $matches = static::compareRanges( $makeRange( $siblings ), $item->getRange() ) === 'equal'; |
427 | |
428 | if ( $matches ) { |
429 | // If these are all of the children (or the only child), go up one more level |
430 | while ( |
431 | ( $parent = $siblings[ 0 ]->parentNode ) && |
432 | $parent !== $excludedAncestorNode && |
433 | static::compareRanges( $makeRange( [ $parent ] ), $item->getRange() ) === 'equal' |
434 | ) { |
435 | $siblings = [ $parent ]; |
436 | } |
437 | return $siblings; |
438 | } |
439 | return null; |
440 | } |
441 | |
442 | /** |
443 | * Unwrap Parsoid sections |
444 | * |
445 | * @param Element $element Parent element, e.g. document body |
446 | */ |
447 | public static function unwrapParsoidSections( Element $element ): void { |
448 | $sections = DOMCompat::querySelectorAll( $element, 'section[data-mw-section-id]' ); |
449 | foreach ( $sections as $section ) { |
450 | $parent = $section->parentNode; |
451 | while ( $section->firstChild ) { |
452 | $parent->insertBefore( $section->firstChild, $section ); |
453 | } |
454 | $parent->removeChild( $section ); |
455 | } |
456 | } |
457 | |
458 | /** |
459 | * Get a MediaWiki page title from a URL |
460 | * |
461 | * @param string $url Relative URL (from a `href` attribute) |
462 | * @param Config $config Config settings needed to resolve the relative URL |
463 | * @return string|null |
464 | */ |
465 | public static function getTitleFromUrl( string $url, Config $config ): ?string { |
466 | // Protocol-relative URLs are handled really badly by parse_url() |
467 | if ( str_starts_with( $url, '//' ) ) { |
468 | $url = "http:$url"; |
469 | } |
470 | |
471 | $bits = parse_url( $url ); |
472 | $query = wfCgiToArray( $bits['query'] ?? '' ); |
473 | if ( isset( $query['title'] ) ) { |
474 | return $query['title']; |
475 | } |
476 | |
477 | // TODO: Set the correct base in the document? |
478 | $articlePath = $config->get( MainConfigNames::ArticlePath ); |
479 | if ( str_starts_with( $url, './' ) ) { |
480 | // Assume this is URL in the format used by Parsoid documents |
481 | $url = substr( $url, 2 ); |
482 | $path = str_replace( '$1', $url, $articlePath ); |
483 | } elseif ( !str_contains( $url, '://' ) ) { |
484 | // Assume this is URL in the format used by legacy parser documents |
485 | $path = $url; |
486 | } else { |
487 | // External link |
488 | $path = $bits['path'] ?? ''; |
489 | } |
490 | |
491 | $articlePathRegexp = '/^' . str_replace( |
492 | '\\$1', |
493 | '([^?]*)', |
494 | preg_quote( $articlePath, '/' ) |
495 | ) . '/'; |
496 | $matches = null; |
497 | if ( preg_match( $articlePathRegexp, $path, $matches ) ) { |
498 | return rawurldecode( $matches[1] ); |
499 | } |
500 | return null; |
501 | } |
502 | |
503 | /** |
504 | * Traverse the document in depth-first order, calling the callback whenever entering and leaving |
505 | * a node. The walk starts before the given node and ends when callback returns a truthy value, or |
506 | * after reaching the end of the document. |
507 | * |
508 | * You might also think about this as processing XML token stream linearly (rather than XML |
509 | * nodes), as if we were parsing the document. |
510 | * |
511 | * @param Node $node Node to start at |
512 | * @param callable $callback Function accepting two arguments: $event ('enter' or 'leave') and |
513 | * $node (Node) |
514 | * @return mixed Final return value of the callback |
515 | */ |
516 | public static function linearWalk( Node $node, callable $callback ) { |
517 | $result = null; |
518 | [ $withinNode, $beforeNode ] = [ $node->parentNode, $node ]; |
519 | |
520 | while ( $beforeNode || $withinNode ) { |
521 | if ( $beforeNode ) { |
522 | $result = $callback( 'enter', $beforeNode ); |
523 | [ $withinNode, $beforeNode ] = [ $beforeNode, $beforeNode->firstChild ]; |
524 | } else { |
525 | $result = $callback( 'leave', $withinNode ); |
526 | [ $withinNode, $beforeNode ] = [ $withinNode->parentNode, $withinNode->nextSibling ]; |
527 | } |
528 | |
529 | if ( $result ) { |
530 | return $result; |
531 | } |
532 | } |
533 | return $result; |
534 | } |
535 | |
536 | /** |
537 | * Like #linearWalk, but it goes backwards. |
538 | * |
539 | * @inheritDoc ::linearWalk() |
540 | */ |
541 | public static function linearWalkBackwards( Node $node, callable $callback ) { |
542 | $result = null; |
543 | [ $withinNode, $beforeNode ] = [ $node->parentNode, $node ]; |
544 | |
545 | while ( $beforeNode || $withinNode ) { |
546 | if ( $beforeNode ) { |
547 | $result = $callback( 'enter', $beforeNode ); |
548 | [ $withinNode, $beforeNode ] = [ $beforeNode, $beforeNode->lastChild ]; |
549 | } else { |
550 | $result = $callback( 'leave', $withinNode ); |
551 | [ $withinNode, $beforeNode ] = [ $withinNode->parentNode, $withinNode->previousSibling ]; |
552 | } |
553 | |
554 | if ( $result ) { |
555 | return $result; |
556 | } |
557 | } |
558 | return $result; |
559 | } |
560 | |
561 | /** |
562 | * @param ImmutableRange $range (must not be collapsed) |
563 | * @return Node |
564 | */ |
565 | public static function getRangeFirstNode( ImmutableRange $range ): Node { |
566 | Assert::precondition( !$range->collapsed, 'Range is not collapsed' ); |
567 | // PHP bug: childNodes can be null |
568 | return $range->startContainer->childNodes && $range->startContainer->childNodes->length ? |
569 | $range->startContainer->childNodes[ $range->startOffset ] : |
570 | $range->startContainer; |
571 | } |
572 | |
573 | /** |
574 | * @param ImmutableRange $range (must not be collapsed) |
575 | * @return Node |
576 | */ |
577 | public static function getRangeLastNode( ImmutableRange $range ): Node { |
578 | Assert::precondition( !$range->collapsed, 'Range is not collapsed' ); |
579 | // PHP bug: childNodes can be null |
580 | return $range->endContainer->childNodes && $range->endContainer->childNodes->length ? |
581 | $range->endContainer->childNodes[ $range->endOffset - 1 ] : |
582 | $range->endContainer; |
583 | } |
584 | |
585 | /** |
586 | * Check whether two ranges overlap, and how. |
587 | * |
588 | * Includes a hack to check for "almost equal" ranges (whose start/end boundaries only differ by |
589 | * "uninteresting" nodes that we ignore when detecting comments), and treat them as equal. |
590 | * |
591 | * Illustration of return values: |
592 | * [ equal ] |
593 | * |[ contained ]| |
594 | * [ | contains | ] |
595 | * [overlap|start] | |
596 | * | [overlap|end] |
597 | * [before] | | |
598 | * | | [after] |
599 | * |
600 | * @param ImmutableRange $a |
601 | * @param ImmutableRange $b |
602 | * @return string One of: |
603 | * - 'equal': Ranges A and B are equal |
604 | * - 'contains': Range A contains range B |
605 | * - 'contained': Range A is contained within range B |
606 | * - 'after': Range A is before range B |
607 | * - 'before': Range A is after range B |
608 | * - 'overlapstart': Start of range A overlaps range B |
609 | * - 'overlapend': End of range A overlaps range B |
610 | */ |
611 | public static function compareRanges( ImmutableRange $a, ImmutableRange $b ): string { |
612 | // Compare the positions of: start of A to start of B, start of A to end of B, and so on. |
613 | // Watch out, the constant names are the opposite of what they should be. |
614 | $startToStart = $a->compareBoundaryPoints( ImmutableRange::START_TO_START, $b ); |
615 | $startToEnd = $a->compareBoundaryPoints( ImmutableRange::END_TO_START, $b ); |
616 | $endToStart = $a->compareBoundaryPoints( ImmutableRange::START_TO_END, $b ); |
617 | $endToEnd = $a->compareBoundaryPoints( ImmutableRange::END_TO_END, $b ); |
618 | |
619 | // Handle almost equal ranges: When start or end boundary points of the two ranges are different, |
620 | // but only differ by "uninteresting" nodes, treat them as equal instead. |
621 | if ( |
622 | ( $startToStart < 0 && static::compareRangesAlmostEqualBoundaries( $a, $b, 'start' ) ) || |
623 | ( $startToStart > 0 && static::compareRangesAlmostEqualBoundaries( $b, $a, 'start' ) ) |
624 | ) { |
625 | $startToStart = 0; |
626 | } |
627 | if ( |
628 | ( $endToEnd < 0 && static::compareRangesAlmostEqualBoundaries( $a, $b, 'end' ) ) || |
629 | ( $endToEnd > 0 && static::compareRangesAlmostEqualBoundaries( $b, $a, 'end' ) ) |
630 | ) { |
631 | $endToEnd = 0; |
632 | } |
633 | |
634 | if ( $startToStart === 0 && $endToEnd === 0 ) { |
635 | return 'equal'; |
636 | } |
637 | if ( $startToStart <= 0 && $endToEnd >= 0 ) { |
638 | return 'contains'; |
639 | } |
640 | if ( $startToStart >= 0 && $endToEnd <= 0 ) { |
641 | return 'contained'; |
642 | } |
643 | if ( $startToEnd >= 0 ) { |
644 | return 'after'; |
645 | } |
646 | if ( $endToStart <= 0 ) { |
647 | return 'before'; |
648 | } |
649 | if ( $startToStart > 0 && $startToEnd < 0 && $endToEnd >= 0 ) { |
650 | return 'overlapstart'; |
651 | } |
652 | if ( $endToEnd < 0 && $endToStart > 0 && $startToStart <= 0 ) { |
653 | return 'overlapend'; |
654 | } |
655 | |
656 | throw new LogicException( 'Unreachable' ); |
657 | } |
658 | |
659 | /** |
660 | * Check if the given boundary points of ranges A and B are almost equal (only differing by |
661 | * uninteresting nodes). |
662 | * |
663 | * Boundary of A must be before the boundary of B in the tree. |
664 | * |
665 | * @param ImmutableRange $a |
666 | * @param ImmutableRange $b |
667 | * @param string $boundary 'start' or 'end' |
668 | * @return bool |
669 | */ |
670 | private static function compareRangesAlmostEqualBoundaries( |
671 | ImmutableRange $a, ImmutableRange $b, string $boundary |
672 | ): bool { |
673 | // This code is awful, but several attempts to rewrite it made it even worse. |
674 | // You're welcome to give it a try. |
675 | |
676 | $from = $boundary === 'end' ? static::getRangeLastNode( $a ) : static::getRangeFirstNode( $a ); |
677 | $to = $boundary === 'end' ? static::getRangeLastNode( $b ) : static::getRangeFirstNode( $b ); |
678 | |
679 | $skipNode = null; |
680 | if ( $boundary === 'end' ) { |
681 | $skipNode = $from; |
682 | } |
683 | |
684 | $foundContent = false; |
685 | static::linearWalk( |
686 | $from, |
687 | static function ( string $event, Node $n ) use ( |
688 | $from, $to, $boundary, &$skipNode, &$foundContent |
689 | ) { |
690 | if ( $n === $to && $event === ( $boundary === 'end' ? 'leave' : 'enter' ) ) { |
691 | return true; |
692 | } |
693 | if ( $skipNode ) { |
694 | if ( $n === $skipNode && $event === 'leave' ) { |
695 | $skipNode = null; |
696 | } |
697 | return; |
698 | } |
699 | |
700 | if ( $event === 'enter' ) { |
701 | if ( |
702 | CommentUtils::isCommentSeparator( $n ) || |
703 | CommentUtils::isRenderingTransparentNode( $n ) || |
704 | CommentUtils::isOurGeneratedNode( $n ) |
705 | ) { |
706 | $skipNode = $n; |
707 | |
708 | } elseif ( |
709 | CommentUtils::isCommentContent( $n ) |
710 | ) { |
711 | $foundContent = true; |
712 | return true; |
713 | } |
714 | } |
715 | } |
716 | ); |
717 | |
718 | return !$foundContent; |
719 | } |
720 | |
721 | /** |
722 | * Check whether the last item in the thread item set is a properly signed comment by |
723 | * the expected author (that is: there is a signature, and either there's nothing following the |
724 | * signature, or there's some text within the same paragraph that was detected as part of the same |
725 | * comment). |
726 | */ |
727 | public static function isSingleCommentSignedBy( |
728 | ContentThreadItemSet $itemSet, |
729 | string $author, |
730 | Element $rootNode |
731 | ): bool { |
732 | $items = $itemSet->getThreadItems(); |
733 | |
734 | if ( $items ) { |
735 | $lastItem = end( $items ); |
736 | // Check that we've detected a comment first, not just headings (T304377) |
737 | if ( !( $lastItem instanceof ContentCommentItem && $lastItem->getAuthor() === $author ) ) { |
738 | return false; |
739 | } |
740 | |
741 | $commentRange = $lastItem->getRange(); |
742 | $bodyRange = new ImmutableRange( |
743 | $rootNode, 0, $rootNode, count( $rootNode->childNodes ) |
744 | ); |
745 | |
746 | // Only check that the end of the comment range is at the end of the body range. |
747 | // We don't care about preceding headings, comments, or other content (T363285). |
748 | // This is a simplified fragment of static::compareRanges(). |
749 | $cmp = $commentRange->compareBoundaryPoints( ImmutableRange::END_TO_END, $bodyRange ); |
750 | if ( |
751 | $cmp === 0 || |
752 | ( $cmp < 0 && static::compareRangesAlmostEqualBoundaries( $commentRange, $bodyRange, 'end' ) ) || |
753 | ( $cmp > 0 && static::compareRangesAlmostEqualBoundaries( $bodyRange, $commentRange, 'end' ) ) |
754 | ) { |
755 | // New comment includes a signature in the proper place |
756 | return true; |
757 | } |
758 | } |
759 | |
760 | return false; |
761 | } |
762 | |
763 | /** |
764 | * Get the ID for a new topics subscription from a page title |
765 | * |
766 | * @param Title $title Page title |
767 | * @return string ID for a new topics subscription |
768 | */ |
769 | public static function getNewTopicsSubscriptionId( Title $title ) { |
770 | return "p-topics-{$title->getNamespace()}:{$title->getDBkey()}"; |
771 | } |
772 | } |