Merge "Enable configuration to supply options for Special:Search form"
[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 /** @var string One of the ENGINE_* constants. */
55 private $engine = self::ENGINE_PHP;
56
57 /** @var string Path to an executable to be used as the diff engine. */
58 private $externalEngine;
59
60 /**
61 * Convenience helper to use getTextDiff without an instance.
62 * @param string $oldText
63 * @param string $newText
64 * @return string
65 */
66 public static function diff( $oldText, $newText ) {
67 /** @var TextSlotDiffRenderer $slotDiffRenderer */
68 $slotDiffRenderer = ContentHandler::getForModelID( CONTENT_MODEL_TEXT )
69 ->getSlotDiffRenderer( RequestContext::getMain() );
70 return $slotDiffRenderer->getTextDiff( $oldText, $newText );
71 }
72
73 public function setStatsdDataFactory( IBufferingStatsdDataFactory $statsdDataFactory ) {
74 $this->statsdDataFactory = $statsdDataFactory;
75 }
76
77 public function setLanguage( Language $language ) {
78 $this->language = $language;
79 }
80
81 /**
82 * Set which diff engine to use.
83 * @param string $type One of the ENGINE_* constants.
84 * @param string|null $executable Path to an external exectable, only when type is ENGINE_EXTERNAL.
85 */
86 public function setEngine( $type, $executable = null ) {
87 $engines = [ self::ENGINE_PHP, self::ENGINE_WIKIDIFF2, self::ENGINE_EXTERNAL ];
88 Assert::parameter( in_array( $type, $engines, true ), '$type',
89 'must be one of the TextSlotDiffRenderer::ENGINE_* constants' );
90 if ( $type === self::ENGINE_EXTERNAL ) {
91 Assert::parameter( is_string( $executable ) && is_executable( $executable ), '$executable',
92 'must be a path to a valid executable' );
93 } else {
94 Assert::parameter( is_null( $executable ), '$executable',
95 'must not be set unless $type is ENGINE_EXTERNAL' );
96 }
97 $this->engine = $type;
98 $this->externalEngine = $executable;
99 }
100
101 /** @inheritDoc */
102 public function getDiff( Content $oldContent = null, Content $newContent = null ) {
103 $this->normalizeContents( $oldContent, $newContent, TextContent::class );
104
105 $oldText = $oldContent->serialize();
106 $newText = $newContent->serialize();
107
108 return $this->getTextDiff( $oldText, $newText );
109 }
110
111 /**
112 * Diff the text representations of two content objects (or just two pieces of text in general).
113 * @param string $oldText
114 * @param string $newText
115 * @return string
116 */
117 public function getTextDiff( $oldText, $newText ) {
118 Assert::parameterType( 'string', $oldText, '$oldText' );
119 Assert::parameterType( 'string', $newText, '$newText' );
120
121 $diff = function () use ( $oldText, $newText ) {
122 $time = microtime( true );
123
124 $result = $this->getTextDiffInternal( $oldText, $newText );
125
126 $time = intval( ( microtime( true ) - $time ) * 1000 );
127 if ( $this->statsdDataFactory ) {
128 $this->statsdDataFactory->timing( 'diff_time', $time );
129 }
130
131 // TODO reimplement this using T142313
132 /*
133 // Log requests slower than 99th percentile
134 if ( $time > 100 && $this->mOldPage && $this->mNewPage ) {
135 wfDebugLog( 'diff',
136 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
137 }
138 */
139
140 return $result;
141 };
142
143 /**
144 * @param Status $status
145 * @throws FatalError
146 */
147 $error = function ( $status ) {
148 throw new FatalError( $status->getWikiText() );
149 };
150
151 // Use PoolCounter if the diff looks like it can be expensive
152 if ( strlen( $oldText ) + strlen( $newText ) > 20000 ) {
153 $work = new PoolCounterWorkViaCallback( 'diff',
154 md5( $oldText ) . md5( $newText ),
155 [ 'doWork' => $diff, 'error' => $error ]
156 );
157 return $work->execute();
158 }
159
160 return $diff();
161 }
162
163 /**
164 * Diff the text representations of two content objects (or just two pieces of text in general).
165 * This does the actual diffing, getTextDiff() wraps it with logging and resource limiting.
166 * @param string $oldText
167 * @param string $newText
168 * @return string
169 * @throws Exception
170 */
171 protected function getTextDiffInternal( $oldText, $newText ) {
172 // TODO move most of this into three parallel implementations of a text diff generator
173 // class, choose which one to use via dependecy injection
174
175 $oldText = str_replace( "\r\n", "\n", $oldText );
176 $newText = str_replace( "\r\n", "\n", $newText );
177
178 // Better external diff engine, the 2 may some day be dropped
179 // This one does the escaping and segmenting itself
180 if ( $this->engine === self::ENGINE_WIKIDIFF2 ) {
181 $wikidiff2Version = phpversion( 'wikidiff2' );
182 if (
183 $wikidiff2Version !== false &&
184 version_compare( $wikidiff2Version, '1.5.0', '>=' ) &&
185 version_compare( $wikidiff2Version, '1.8.0', '<' )
186 ) {
187 $text = wikidiff2_do_diff(
188 $oldText,
189 $newText,
190 2,
191 0
192 );
193 } else {
194 // Don't pass the 4th parameter introduced in version 1.5.0 and removed in version 1.8.0
195 $text = wikidiff2_do_diff(
196 $oldText,
197 $newText,
198 2
199 );
200 }
201
202 return $text;
203 } elseif ( $this->engine === self::ENGINE_EXTERNAL ) {
204 # Diff via the shell
205 $tmpDir = wfTempDir();
206 $tempName1 = tempnam( $tmpDir, 'diff_' );
207 $tempName2 = tempnam( $tmpDir, 'diff_' );
208
209 $tempFile1 = fopen( $tempName1, "w" );
210 if ( !$tempFile1 ) {
211 return false;
212 }
213 $tempFile2 = fopen( $tempName2, "w" );
214 if ( !$tempFile2 ) {
215 return false;
216 }
217 fwrite( $tempFile1, $oldText );
218 fwrite( $tempFile2, $newText );
219 fclose( $tempFile1 );
220 fclose( $tempFile2 );
221 $cmd = [ $this->externalEngine, $tempName1, $tempName2 ];
222 $result = Shell::command( $cmd )
223 ->execute();
224 $exitCode = $result->getExitCode();
225 if ( $exitCode !== 0 ) {
226 throw new Exception( "External diff command returned code {$exitCode}. Stderr: "
227 . wfEscapeWikiText( $result->getStderr() )
228 );
229 }
230 $difftext = $result->getStdout();
231 unlink( $tempName1 );
232 unlink( $tempName2 );
233
234 return $difftext;
235 } elseif ( $this->engine === self::ENGINE_PHP ) {
236 if ( $this->language ) {
237 $oldText = $this->language->segmentForDiff( $oldText );
238 $newText = $this->language->segmentForDiff( $newText );
239 }
240 $ota = explode( "\n", $oldText );
241 $nta = explode( "\n", $newText );
242 $diffs = new Diff( $ota, $nta );
243 $formatter = new TableDiffFormatter();
244 $difftext = $formatter->format( $diffs );
245 if ( $this->language ) {
246 $difftext = $this->language->unsegmentForDiff( $difftext );
247 }
248
249 return $difftext;
250 }
251 throw new LogicException( 'Invalid engine: ' . $this->engine );
252 }
253
254 }