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