Debian Codegraph @

extensions/Math/src/MathRestbaseInterface.php

raw symbols SCIP
1 <?php
2 /**
3 * MediaWiki math extension
4 *
5 * @copyright 2002-2015 various MediaWiki contributors
6 * @license GPL-2.0-or-later
7 */
8
9 namespace MediaWiki\Extension\Math;
10
11 use Exception;
12 use MediaWiki\Logger\LoggerFactory;
13 use MediaWiki\MediaWikiServices;
14 use Psr\Log\LoggerInterface;
15 use stdClass;
16 use Wikimedia\Http\MultiHttpClient;
17
18 class MathRestbaseInterface {
19 /** @var string|false */
20 private $hash = false;
21 /** @var string */
22 private $tex;
23 /** @var string */
24 private $type;
25 private ?string $checkedTex = null;
26 /** @var bool|null */
27 private $success;
28 /** @var array */
29 private $identifiers;
30 /** @var stdClass|null */
31 private $error;
32 /** @var string|null */
33 private $mathoidStyle;
34 /** @var string|null */
35 private $mml;
36 /** @var array */
37 private $warnings = [];
38 /** @var bool is there a request to purge the existing mathematical content */
39 private $purge = false;
40 /** @var LoggerInterface */
41 private $logger;
42
43 /**
44 * @param string $tex
45 * @param string $type
46 */
47 public function __construct( $tex = '', $type = 'tex' ) {
48 $this->tex = $tex;
49 $this->type = $type;
50 $this->logger = LoggerFactory::getInstance( 'Math' );
51 }
52
53 /**
54 * Bundles several requests for fetching MathML.
55 * Does not send requests, if the input TeX is invalid.
56 * @param MathRestbaseInterface[] $rbis
57 * @param MultiHttpClient $multiHttpClient
58 */
59 private static function batchGetMathML( array $rbis, MultiHttpClient $multiHttpClient ) {
60 $requests = [];
61 $skips = [];
62 $i = 0;
63 foreach ( $rbis as $rbi ) {
64 /** @var MathRestbaseInterface $rbi */
65 if ( $rbi->getSuccess() ) {
66 $requests[] = $rbi->getContentRequest( 'mml' );
67 } else {
68 $skips[] = $i;
69 }
70 $i++;
71 }
72 $results = $multiHttpClient->runMulti( $requests );
73 $lenRbis = count( $rbis );
74 $j = 0;
75 for ( $i = 0; $i < $lenRbis; $i++ ) {
76 if ( !in_array( $i, $skips, true ) ) {
77 /** @var MathRestbaseInterface $rbi */
78 $rbi = $rbis[$i];
79 try {
80 $response = $results[ $j ][ 'response' ];
81 $mml = $rbi->evaluateContentResponse( 'mml', $response, $requests[$j] );
82 $rbi->mml = $mml;
83 } catch ( MathRestbaseException $e ) {
84 // FIXME: Why is this silenced? Doesn't this leave invalid data behind?
85 }
86 $j++;
87 }
88 }
89 }
90
91 /**
92 * Lets this instance know if this is a purge request. When set to true,
93 * it will cause the object to issue the first content request with a
94 * 'Cache-Control: no-cache' header to prompt the regeneration of the
95 * renders.
96 *
97 * @param bool $purge whether this is a purge request
98 */
99 public function setPurge( $purge = true ) {
100 $this->purge = $purge;
101 }
102
103 /**
104 * @return string MathML code
105 * @throws MathRestbaseException
106 */
107 public function getMathML() {
108 if ( !$this->mml ) {
109 $this->mml = $this->getContent( 'mml' );
110 }
111 return $this->mml;
112 }
113
114 /**
115 * @param string $type
116 * @return string
117 * @throws MathRestbaseException
118 */
119 private function getContent( $type ) {
120 $request = $this->getContentRequest( $type );
121 $multiHttpClient = $this->getMultiHttpClient();
122 $response = $multiHttpClient->run( $request );
123 return $this->evaluateContentResponse( $type, $response, $request );
124 }
125
126 /**
127 * @throws InvalidTeXException
128 */
129 private function calculateHash() {
130 if ( !$this->hash ) {
131 if ( !$this->checkTeX() ) {
132 throw new InvalidTeXException( "TeX input is invalid." );
133 }
134 }
135 }
136
137 public function checkTeX() {
138 $request = $this->getCheckRequest();
139 $requestResult = $this->executeRestbaseCheckRequest( $request );
140 return $this->evaluateRestbaseCheckResponse( $requestResult );
141 }
142
143 /**
144 * Performs a service request
145 * Generates error messages on failure
146 * @see MediaWiki\Http\HttpRequestFactory::post()
147 *
148 * @param array $request
149 * @return array
150 */
151 private function executeRestbaseCheckRequest( $request ) {
152 $multiHttpClient = $this->getMultiHttpClient();
153 $response = $multiHttpClient->run( $request );
154 if ( $response['code'] !== 200 ) {
155 $this->logger->info( 'Tex check failed', [
156 'post' => $request['body'],
157 'error' => $response['error'],
158 'urlparams' => $request['url']
159 ] );
160 }
161 return $response;
162 }
163
164 /**
165 * @param MathRestbaseInterface[] $rbis
166 */
167 public static function batchEvaluate( array $rbis ) {
168 if ( count( $rbis ) == 0 ) {
169 return;
170 }
171 $requests = [];
172 /** @var MathRestbaseInterface $first */
173 $first = $rbis[0];
174 $multiHttpClient = $first->getMultiHttpClient();
175 foreach ( $rbis as $rbi ) {
176 /** @var MathRestbaseInterface $rbi */
177 $requests[] = $rbi->getCheckRequest();
178 }
179 $results = $multiHttpClient->runMulti( $requests );
180 $i = 0;
181 foreach ( $results as $requestResponse ) {
182 /** @var MathRestbaseInterface $rbi */
183 $rbi = $rbis[$i++];
184 try {
185 $response = $requestResponse[ 'response' ];
186 $rbi->evaluateRestbaseCheckResponse( $response );
187 } catch ( Exception $e ) {
188 }
189 }
190 self::batchGetMathML( $rbis, $multiHttpClient );
191 }
192
193 private function getMultiHttpClient(): MultiHttpClient {
194 global $wgMathHTTPProxy, $wgMathConcurrentReqs;
195 $multiHttpClient = MediaWikiServices::getInstance()->getHttpRequestFactory()->createMultiClient(
196 [ 'maxConnsPerHost' => $wgMathConcurrentReqs, 'proxy' => $wgMathHTTPProxy ] );
197
198 return $multiHttpClient;
199 }
200
201 /**
202 * The URL is generated according to the following logic:
203 *
204 * Case A: <code>$internal = false</code>, which means one needs a URL that is accessible from
205 * outside:
206 *
207 * --> Use <code>$wgMathFullRestbaseURL</code>. It must always be configured.
208 *
209 * Case B: <code>$internal = true</code>, which means one needs to access content from Restbase
210 * which does not need to be accessible from outside:
211 *
212 * --> Use the mount point when it is available and <code>$wgMathUseInternalRestbasePath =
213 * true</code>. If not, use <code>$wgMathFullRestbaseURL</code>.
214 *
215 * @param string $path
216 * @param bool|true $internal
217 * @return string
218 */
219 public function getUrl( $path, $internal = true ) {
220 global $wgMathInternalRestbaseURL, $wgMathFullRestbaseURL;
221 if ( $internal ) {
222 return "{$wgMathInternalRestbaseURL}v1/$path";
223 } else {
224 return "{$wgMathFullRestbaseURL}v1/$path";
225 }
226 }
227
228 /**
229 * @return string
230 * @throws MathRestbaseException
231 */
232 public function getSvg() {
233 return $this->getContent( 'svg' );
234 }
235
236 /**
237 * Generates a unique TeX string, renders it and gets it via a public URL.
238 * The method fails, if the public URL does not point to the same server, who did render
239 * the unique TeX input in the first place.
240 * @return bool
241 */
242 private function checkConfig() {
243 // Generates a TeX string that probably has not been generated before
244 $uniqueTeX = uniqid( 't=', true );
245 $testInterface = new MathRestbaseInterface( $uniqueTeX );
246 if ( !$testInterface->checkTeX() ) {
247 $this->logger->warning( 'Config check failed, since test expression was considered as invalid.',
248 [ 'uniqueTeX' => $uniqueTeX ] );
249 return false;
250 }
251
252 try {
253 $url = $testInterface->getFullSvgUrl();
254 $req = MediaWikiServices::getInstance()->getHttpRequestFactory()->create( $url, [], __METHOD__ );
255 $status = $req->execute();
256 if ( $status->isOK() ) {
257 return true;
258 }
259
260 $this->logger->warning( 'Config check failed, due to an invalid response code.',
261 [ 'responseCode' => $status ] );
262 } catch ( Exception $e ) {
263 $this->logger->warning( 'Config check failed, due to an exception.', [ $e ] );
264 }
265
266 return false;
267 }
268
269 /**
270 * Gets a publicly accessible link to the generated SVG image.
271 * @return string
272 * @throws InvalidTeXException
273 */
274 public function getFullSvgUrl() {
275 $this->calculateHash();
276 return $this->getUrl( "media/math/render/svg/{$this->hash}", false );
277 }
278
279 public function getCheckedTex(): ?string {
280 return $this->checkedTex;
281 }
282
283 public function getSuccess(): bool {
284 if ( $this->success === null ) {
285 $this->checkTeX();
286 }
287 return $this->success;
288 }
289
290 public function getIdentifiers(): ?array {
291 return $this->identifiers;
292 }
293
294 public function getError(): ?stdClass {
295 return $this->error;
296 }
297
298 public function getTex(): string {
299 return $this->tex;
300 }
301
302 public function getType(): string {
303 return $this->type;
304 }
305
306 private function setErrorMessage( string $msg ) {
307 $this->error = (object)[ 'error' => (object)[ 'message' => $msg ] ];
308 }
309
310 public function getWarnings(): array {
311 return $this->warnings;
312 }
313
314 public function getCheckRequest(): array {
315 return [
316 'method' => 'POST',
317 'body' => [
318 'type' => $this->type,
319 'q' => $this->tex
320 ],
321 'url' => $this->getUrl( "media/math/check/{$this->type}" )
322 ];
323 }
324
325 public function evaluateRestbaseCheckResponse( array $response ): bool {
326 $json = json_decode( $response['body'] );
327 if ( $response['code'] === 200 &&
328 isset( $json->success ) &&
329 isset( $json->checked ) &&
330 isset( $json->identifiers ) ) {
331 $headers = $response['headers'];
332 $this->hash = $headers['x-resource-location'];
333 $this->success = $json->success;
334 $this->checkedTex = $json->checked;
335 $this->identifiers = $json->identifiers;
336 if ( isset( $json->warnings ) ) {
337 $this->warnings = $json->warnings;
338 }
339 return true;
340 }
341 if ( isset( $json->detail->success ) ) {
342 $this->success = $json->detail->success;
343 $this->error = $json->detail;
344 return false;
345 }
346 $this->success = false;
347 $this->setErrorMessage( 'Math extension cannot connect to Restbase.' );
348 $this->logger->error( 'Received invalid response from restbase.', [
349 'body' => $response['body'],
350 'code' => $response['code'] ] );
351 return false;
352 }
353
354 public function getMathoidStyle(): ?string {
355 return $this->mathoidStyle;
356 }
357
358 /**
359 * @param string $type
360 * @return array
361 * @throws InvalidTeXException
362 */
363 private function getContentRequest( $type ) {
364 $this->calculateHash();
365 $request = [
366 'method' => 'GET',
367 'url' => $this->getUrl( "media/math/render/$type/{$this->hash}" )
368 ];
369 if ( $this->purge ) {
370 $request['headers'] = [
371 'Cache-Control' => 'no-cache'
372 ];
373 $this->purge = false;
374 }
375 return $request;
376 }
377
378 /**
379 * @param string $type
380 * @param array $response
381 * @param array $request
382 * @return string
383 * @throws MathRestbaseException
384 */
385 private function evaluateContentResponse( $type, array $response, array $request ) {
386 if ( $response['code'] === 200 ) {
387 if ( array_key_exists( 'x-mathoid-style', $response['headers'] ) ) {
388 $this->mathoidStyle = $response['headers']['x-mathoid-style'];
389 }
390 return $response['body'];
391 }
392 // Remove "convenience" duplicate keys put in place by MultiHttpClient
393 unset( $response[0], $response[1], $response[2], $response[3], $response[4] );
394 $this->logger->error( 'Restbase math server problem', [
395 'urlparams' => $request['url'],
396 'response' => [ 'code' => $response['code'], 'body' => $response['body'] ],
397 'math_type' => $type,
398 'tex' => $this->tex
399 ] );
400 self::throwContentError( $type, $response['body'] );
401 }
402
403 /**
404 * @param string $type
405 * @param string $body
406 * @throws MathRestbaseException
407 * @return never
408 */
409 public static function throwContentError( $type, $body ) {
410 $detail = 'Server problem.';
411 $json = json_decode( $body );
412 if ( isset( $json->detail ) ) {
413 if ( is_array( $json->detail ) ) {
414 $detail = $json->detail[0];
415 } elseif ( is_string( $json->detail ) ) {
416 $detail = $json->detail;
417 }
418 }
419 throw new MathRestbaseException( "Cannot get $type. $detail" );
420 }
421 }