Remove HWLDFWordAccumulator, deprecated in 1.28
[lhc/web/wiklou.git] / includes / diff / TextSlotDiffRenderer.php
1 <?php
2 /**
3 * Renders a slot diff by doing a text diff on the native representation.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup DifferenceEngine
22 */
23
24 use MediaWiki\Shell\Shell;
25 use Wikimedia\Assert\Assert;
26
27 /**
28 * Renders a slot diff by doing a text diff on the native representation.
29 *
30 * If you want to use this without content objects (to call getTextDiff() on some
31 * non-content-related texts), obtain an instance with
32 * ContentHandler::getForModelID( CONTENT_MODEL_TEXT )
33 * ->getSlotDiffRenderer( RequestContext::getMain() )
34 *
35 * @ingroup DifferenceEngine
36 */
37 class TextSlotDiffRenderer extends SlotDiffRenderer {
38
39 /** Use the PHP diff implementation (DiffEngine). */
40 const ENGINE_PHP = 'php';
41
42 /** Use the wikidiff2 PHP module. */
43 const ENGINE_WIKIDIFF2 = 'wikidiff2';
44
45 /** Use an external executable. */
46 const ENGINE_EXTERNAL = 'external';
47
48 /** @var IBufferingStatsdDataFactory|null */
49 private $statsdDataFactory;
50
51 /** @var Language|null The language this content is in. */
52 private $language;
53
54 /**
55 * Number of paragraph moves the algorithm should attempt to detect.
56 * Only used with the wikidiff2 engine.
57 * @var int
58 * @see $wgWikiDiff2MovedParagraphDetectionCutoff
59 */
60 private $wikiDiff2MovedParagraphDetectionCutoff = 0;
61
62 /** @var string One of the ENGINE_* constants. */
63 private $engine = self::ENGINE_PHP;
64
65 /** @var string Path to an executable to be used as the diff engine. */
66 private $externalEngine;
67
68 /**
69 * Convenience helper to use getTextDiff without an instance.
70 * @param string $oldText
71 * @param string $newText
72 * @return string
73 */
74 public static function diff( $oldText, $newText ) {
75 /** @var TextSlotDiffRenderer $slotDiffRenderer */
76 $slotDiffRenderer = ContentHandler::getForModelID( CONTENT_MODEL_TEXT )
77 ->getSlotDiffRenderer( RequestContext::getMain() );
78 return $slotDiffRenderer->getTextDiff( $oldText, $newText );
79 }
80
81 public function setStatsdDataFactory( IBufferingStatsdDataFactory $statsdDataFactory ) {
82 $this->statsdDataFactory = $statsdDataFactory;
83 }
84
85 public function setLanguage( Language $language ) {
86 $this->language = $language;
87 }
88
89 /**
90 * @param int $cutoff
91 * @see $wgWikiDiff2MovedParagraphDetectionCutoff
92 */
93 public function setWikiDiff2MovedParagraphDetectionCutoff( $cutoff ) {
94 Assert::parameterType( 'integer', $cutoff, '$cutoff' );
95 $this->wikiDiff2MovedParagraphDetectionCutoff = $cutoff;
96 }
97
98 /**
99 * Set which diff engine to use.
100 * @param string $type One of the ENGINE_* constants.
101 * @param string|null $executable Path to an external exectable, only when type is ENGINE_EXTERNAL.
102 */
103 public function setEngine( $type, $executable = null ) {
104 $engines = [ self::ENGINE_PHP, self::ENGINE_WIKIDIFF2, self::ENGINE_EXTERNAL ];
105 Assert::parameter( in_array( $type, $engines, true ), '$type',
106 'must be one of the TextSlotDiffRenderer::ENGINE_* constants' );
107 if ( $type === self::ENGINE_EXTERNAL ) {
108 Assert::parameter( is_string( $executable ) && is_executable( $executable ), '$executable',
109 'must be a path to a valid executable' );
110 } else {
111 Assert::parameter( is_null( $executable ), '$executable',
112 'must not be set unless $type is ENGINE_EXTERNAL' );
113 }
114 $this->engine = $type;
115 $this->externalEngine = $executable;
116 }
117
118 /** @inheritDoc */
119 public function getDiff( Content $oldContent = null, Content $newContent = null ) {
120 $this->normalizeContents( $oldContent, $newContent, TextContent::class );
121
122 $oldText = $oldContent->serialize();
123 $newText = $newContent->serialize();
124
125 return $this->getTextDiff( $oldText, $newText );
126 }
127
128 /**
129 * Diff the text representations of two content objects (or just two pieces of text in general).
130 * @param string $oldText
131 * @param string $newText
132 * @return string
133 */
134 public function getTextDiff( $oldText, $newText ) {
135 Assert::parameterType( 'string', $oldText, '$oldText' );
136 Assert::parameterType( 'string', $newText, '$newText' );
137
138 $diff = function () use ( $oldText, $newText ) {
139 $time = microtime( true );
140
141 $result = $this->getTextDiffInternal( $oldText, $newText );
142
143 $time = intval( ( microtime( true ) - $time ) * 1000 );
144 if ( $this->statsdDataFactory ) {
145 $this->statsdDataFactory->timing( 'diff_time', $time );
146 }
147
148 // TODO reimplement this using T142313
149 /*
150 // Log requests slower than 99th percentile
151 if ( $time > 100 && $this->mOldPage && $this->mNewPage ) {
152 wfDebugLog( 'diff',
153 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
154 }
155 */
156
157 return $result;
158 };
159
160 /**
161 * @param Status $status
162 * @throws FatalError
163 */
164 $error = function ( $status ) {
165 throw new FatalError( $status->getWikiText() );
166 };
167
168 // Use PoolCounter if the diff looks like it can be expensive
169 if ( strlen( $oldText ) + strlen( $newText ) > 20000 ) {
170 $work = new PoolCounterWorkViaCallback( 'diff',
171 md5( $oldText ) . md5( $newText ),
172 [ 'doWork' => $diff, 'error' => $error ]
173 );
174 return $work->execute();
175 }
176
177 return $diff();
178 }
179
180 /**
181 * Diff the text representations of two content objects (or just two pieces of text in general).
182 * This does the actual diffing, getTextDiff() wraps it with logging and resource limiting.
183 * @param string $oldText
184 * @param string $newText
185 * @return string
186 * @throws Exception
187 */
188 protected function getTextDiffInternal( $oldText, $newText ) {
189 // TODO move most of this into three parallel implementations of a text diff generator
190 // class, choose which one to use via dependecy injection
191
192 $oldText = str_replace( "\r\n", "\n", $oldText );
193 $newText = str_replace( "\r\n", "\n", $newText );
194
195 // Better external diff engine, the 2 may some day be dropped
196 // This one does the escaping and segmenting itself
197 if ( $this->engine === self::ENGINE_WIKIDIFF2 ) {
198 $wikidiff2Version = phpversion( 'wikidiff2' );
199 if (
200 $wikidiff2Version !== false &&
201 version_compare( $wikidiff2Version, '1.5.0', '>=' ) &&
202 version_compare( $wikidiff2Version, '1.8.0', '<' )
203 ) {
204 $text = wikidiff2_do_diff(
205 $oldText,
206 $newText,
207 2,
208 $this->wikiDiff2MovedParagraphDetectionCutoff
209 );
210 } else {
211 // Don't pass the 4th parameter introduced in version 1.5.0 and removed in version 1.8.0
212 $text = wikidiff2_do_diff(
213 $oldText,
214 $newText,
215 2
216 );
217 }
218
219 return $text;
220 } elseif ( $this->engine === self::ENGINE_EXTERNAL ) {
221 # Diff via the shell
222 $tmpDir = wfTempDir();
223 $tempName1 = tempnam( $tmpDir, 'diff_' );
224 $tempName2 = tempnam( $tmpDir, 'diff_' );
225
226 $tempFile1 = fopen( $tempName1, "w" );
227 if ( !$tempFile1 ) {
228 return false;
229 }
230 $tempFile2 = fopen( $tempName2, "w" );
231 if ( !$tempFile2 ) {
232 return false;
233 }
234 fwrite( $tempFile1, $oldText );
235 fwrite( $tempFile2, $newText );
236 fclose( $tempFile1 );
237 fclose( $tempFile2 );
238 $cmd = [ $this->externalEngine, $tempName1, $tempName2 ];
239 $result = Shell::command( $cmd )
240 ->execute();
241 $exitCode = $result->getExitCode();
242 if ( $exitCode !== 0 ) {
243 throw new Exception( "External diff command returned code {$exitCode}. Stderr: "
244 . wfEscapeWikiText( $result->getStderr() )
245 );
246 }
247 $difftext = $result->getStdout();
248 unlink( $tempName1 );
249 unlink( $tempName2 );
250
251 return $difftext;
252 } elseif ( $this->engine === self::ENGINE_PHP ) {
253 if ( $this->language ) {
254 $oldText = $this->language->segmentForDiff( $oldText );
255 $newText = $this->language->segmentForDiff( $newText );
256 }
257 $ota = explode( "\n", $oldText );
258 $nta = explode( "\n", $newText );
259 $diffs = new Diff( $ota, $nta );
260 $formatter = new TableDiffFormatter();
261 $difftext = $formatter->format( $diffs );
262 if ( $this->language ) {
263 $difftext = $this->language->unsegmentForDiff( $difftext );
264 }
265
266 return $difftext;
267 }
268 throw new LogicException( 'Invalid engine: ' . $this->engine );
269 }
270
271 }