Debian Codegraph @

vendor/wikimedia/parsoid/src/Utils/ComputeSelectiveStats.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Utils;
5
6 use Wikimedia\Parsoid\Config\Env;
7 use Wikimedia\Parsoid\Config\PageConfig;
8 use Wikimedia\Parsoid\Core\PageBundle;
9 use Wikimedia\Parsoid\DOM\Document;
10 use Wikimedia\Parsoid\DOM\Element;
11 use Wikimedia\Parsoid\Html2Wt\DiffUtils;
12 use Wikimedia\Parsoid\Html2Wt\DOMDiff;
13 use Wikimedia\Parsoid\NodeData\TemplateInfo;
14
15 /**
16 * This file contains code to classify opportunities for selective
17 * update and collect statistics.
18 */
19 class ComputeSelectiveStats {
20
21 /** @return array<string,string> */
22 public static function classify(
23 Env $env,
24 ?PageConfig $oldPage, ?PageBundle $oldPb,
25 PageConfig $newPage, PageBundle $newPb
26 ): array {
27 // Default labels (ensure keys are consistent & in consistent order)
28 $labels = [
29 'type' => 'missing-prev',
30 'same-wt' => 'unknown',
31 'rev-diff' => 'unknown',
32 'changed-sections' => 'unknown',
33 'changed-template-sites' => 'unknown',
34 'changed-template-names' => 'unknown',
35 ];
36 if ( $oldPage === null || $oldPb === null ) {
37 return $labels;
38 }
39 $oldWt = self::pc2wt( $oldPage );
40 $newWt = self::pc2wt( $newPage );
41
42 // Compare wikitext in both revisions
43 $labels['same-wt'] = self::bool2str( $oldWt == $newWt );
44
45 // Compare revision IDs
46 $oldRev = $oldPage->getRevisionId();
47 $newRev = $newPage->getRevisionId();
48 if ( $oldRev === $newRev ) {
49 // same revision (template update, most likely)
50 $labels['rev-diff'] = '0';
51 } elseif ( $oldRev === $newPage->getParentRevisionId() ) {
52 // "normal edit": new revision is the one after old revision
53 $labels['rev-diff'] = '1';
54 } elseif ( $newRev === $oldPage->getParentRevisionId() ) {
55 // new revision is the one *before* old revision
56 // This is probably a render triggered from RevisionOutputCache
57 // of the previous revision where the "oldRev" is coming from
58 // the parser cache and is thus the latest. This may happen
59 // during races, vandalism patrol, HTML diffing, etc.
60 $labels['rev-diff'] = 'minus1';
61 }
62
63 // Parse to DOM and diff
64 $oldDoc = self::pb2doc( $env, $oldPb );
65 $newDoc = self::pb2doc( $env, $newPb );
66 $dd = new DOMDiff( $env );
67 // Don't skip over template content!
68 $dd->skipEncapsulatedContent = false;
69 // Ignore differences in data-parsoid 'dsr' and 'tmp'
70 $cleanDP = static function ( $dp ) {
71 $dp = $dp->clone();
72 foreach ( [ 'tmp', 'tsr', 'dsr', 'extTagOffsets', 'extLinkContentOffsets' ] as $prop ) {
73 unset( $dp->$prop );
74 }
75 return $dp;
76 };
77 $dd->specializedAttribHandlers['data-parsoid'] = static function ( $nA, $vA, $nB, $vB ) use ( $cleanDP ) {
78 return $cleanDP( $vA ) == $cleanDP( $vB );
79 };
80 // Ignore differences in 'id' attributes, since these are a side-effect
81 // of data-parsoid/page bundle encapsulation.
82 $dd->specializedAttribHandlers['id'] = static function ( $nA, $vA, $nB, $vB ) {
83 // XXX we can't really tell synthethic ID attributes created by
84 // DOMDataUtils::storeInPageBundle() from "real" ID attributes
85 // in user wikitext. Hackishly ignore differences in any ID
86 // attributes that begin with 'mw' even though technically you
87 // could have a <span id="mw-something'> in wikitext, and change
88 // that to <span id='mw-different-thing'> and with this attribute
89 // handler DOM diff wouldn't flag the change. In theory we should
90 // be using shadow attributes to record when an id was synthetic.
91 if ( str_starts_with( $vA, 'mw' ) && str_starts_with( $vB, 'mw' ) ) {
92 return true; // equal enough
93 }
94 return $vA === $vB;
95 };
96 [ 'isEmpty' => $emptyDiff ] = $dd->diff(
97 DOMCompat::getBody( $oldDoc ),
98 DOMCompat::getBody( $newDoc )
99 );
100 if ( $oldWt === $newWt ) {
101 // old and new wikitext identical. is html also identical?
102 $labels['type'] = $emptyDiff ? 'no-op' : 'template-update';
103 } else {
104 $labels['type'] = 'page-update';
105 }
106
107 // Use a DOMTraverser to count how many sections and templates were
108 // modified. (Skip attribute embedded HTML for now.)
109 $dt = new DOMTraverser( true );
110 $sectionsModified = 0;
111 $dt->addHandler( 'section', static function ( Element $el ) use ( &$sectionsModified ) {
112 if ( WTUtils::isParsoidSectionTag( $el ) && !DiffUtils::subtreeUnchanged( $el ) ) {
113 $sectionsModified++;
114 }
115 return true;
116 } );
117 $templatesModified = 0;
118 $namedTemplates = [];
119 $dt->addHandler( null, static function ( $el, $state ) use ( &$templatesModified, &$namedTemplates ) {
120 if ( !( $el instanceof Element ) ) {
121 return true;
122 }
123 if (
124 $el === ( $state->tplInfo->first ?? null ) &&
125 DOMUtils::hasTypeOf( $el, 'mw:Transclusion' )
126 ) {
127 $changed = false;
128 $about = DOMCompat::getAttribute( $el, 'about' );
129 foreach ( WTUtils::getAboutSiblings( $el, $about ) as $sib ) {
130 // Note that we might miss a change here in a sibling
131 // which is fosterable IEW, since that's !Element.
132 if (
133 $sib instanceof Element &&
134 !DiffUtils::subtreeUnchanged( $sib )
135 ) {
136 $changed = true;
137 break;
138 }
139 }
140
141 // Compute the number of templates modified
142 if ( $changed ) {
143 $templatesModified++;
144 $dataMw = DOMDataUtils::getDataMw( $el );
145 $name = null;
146 foreach ( $dataMw->parts ?? [] as $part ) {
147 if ( $part instanceof TemplateInfo ) {
148 $name ??= $part->href;
149 }
150 }
151 $namedTemplates[$name ?? 'unknown'] = true;
152 }
153 // Don't recurse into templates, just tabulate top-level
154 $state->tplInfo->clear = true;
155 return $state->tplInfo->last->nextSibling;
156 }
157 return true;
158 } );
159 # do the traversal
160 $dt->traverse( null, DOMCompat::getBody( $newDoc ), new DTState( $env ) );
161
162 # report changed sections as '0', '1', or '2+'
163 $labels['changed-sections'] = self::int2str( $sectionsModified, 2 );
164 # report changed templates as '0', '1', or '2+'
165 $labels['changed-template-sites'] = self::int2str( $templatesModified, 2 );
166 # report the count of the *names* of the templates that were updated.
167 $labels['changed-template-names'] = self::int2str( count( $namedTemplates ), 2 );
168
169 // TODO: sum up the time spent on modified (vs unmodified) templates
170
171 return $labels;
172 }
173
174 // ----------- Helper functions ---------------
175
176 /** Convert a page bundle to a DOM Document. */
177 private static function pb2doc( Env $env, PageBundle $pb ): Document {
178 $doc = $pb->toDom();
179 DOMDataUtils::prepareDoc( $doc );
180 $body = DOMCompat::getBody( $doc );
181 '@phan-var Element $body'; // assert non-null
182 DOMDataUtils::visitAndLoadDataAttribs( $body, [ 'markNew' => true ] );
183 return $doc;
184 }
185
186 /** Convert a PageConfig to a wikitext string. */
187 private static function pc2wt( PageConfig $pc ): string {
188 return $pc->getRevisionContent()->getContent( 'main' );
189 }
190
191 /** Convert a boolean to a string for labelling purposes. */
192 private static function bool2str( ?bool $val ): string {
193 return ( $val === true ) ? 'true' : (
194 ( $val === false ) ? 'false' : 'unknown'
195 );
196 }
197
198 /** Convert an integer to a string for labelling purposes. */
199 private static function int2str( ?int $val, ?int $limit = null ): string {
200 if ( $val === null ) {
201 return 'unknown';
202 }
203 if ( $limit !== null && $val >= $limit ) {
204 return "{$limit}plus";
205 }
206 return "$val";
207 }
208 }