Debian Codegraph @

extensions/Math/src/MathMathML.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 MediaWiki\Extension\Math\Hooks\HookRunner;
12 use MediaWiki\Html\Html;
13 use MediaWiki\Logger\LoggerFactory;
14 use MediaWiki\MediaWikiServices;
15 use MediaWiki\SpecialPage\SpecialPage;
16 use MediaWiki\Title\Title;
17 use Psr\Log\LoggerInterface;
18 use StatusValue;
19 use stdClass;
20 use Throwable;
21 use Wikimedia\Mime\XmlTypeCheck;
22
23 /**
24 * Converts LaTeX to MathML using the mathoid-server
25 */
26 class MathMathML extends MathRenderer {
27
28 /** @var string[] */
29 protected $defaultAllowedRootElements = [ 'math' ];
30 /** @var string[] */
31 protected $restbaseInputTypes = [ 'tex', 'inline-tex', 'chem' ];
32 /** @var string[] */
33 protected $restbaseRenderingModes = [ MathConfig::MODE_MATHML ];
34 /** @var string[] */
35 protected $allowedRootElements = [];
36 /** @var string */
37 protected $host;
38
39 /** @var LoggerInterface */
40 protected $logger;
41
42 /** @var bool if false MathML output is not validated */
43 private $XMLValidation = true;
44
45 /**
46 * @var string|bool
47 */
48 private $svgPath = false;
49
50 /** @var string|null */
51 private $mathoidStyle;
52
53 /** @inheritDoc */
54 public function __construct( string $tex = '', array $params = [], $cache = null, $mathConfig = null ) {
55 global $wgMathMathMLUrl;
56 parent::__construct( $tex, $params, $cache, $mathConfig );
57 $this->setMode( MathConfig::MODE_MATHML );
58 $this->host = $wgMathMathMLUrl;
59 if ( isset( $params['type'] ) ) {
60 $allowedTypes = [ 'pmml', 'ascii', 'chem' ];
61 if ( in_array( $params['type'], $allowedTypes, true ) ) {
62 $this->inputType = $params['type'];
63 }
64 if ( $params['type'] == 'pmml' ) {
65 $this->setMathml( '<math>' . $tex . '</math>' );
66 }
67 }
68 if ( !isset( $params['display'] ) && $this->getMathStyle() == 'inlineDisplaystyle' ) {
69 // default preserve the (broken) layout as it was
70 $this->tex = '{\\displaystyle ' . $tex . '}';
71 }
72 $this->logger = LoggerFactory::getInstance( 'Math' );
73 }
74
75 /**
76 * @inheritDoc
77 */
78 public function addTrackingCategories( $parser ) {
79 parent::addTrackingCategories( $parser );
80 if ( $this->hasWarnings() ) {
81 foreach ( $this->warnings as $warning ) {
82 if ( isset( $warning->type ) ) {
83 switch ( $warning->type ) {
84 case 'mhchem-deprecation':
85 $parser->addTrackingCategory( 'math-tracking-category-mhchem-deprecation' );
86 break;
87 case 'texvc-deprecation':
88 $parser->addTrackingCategory( 'math-tracking-category-texvc-deprecation' );
89 }
90 }
91 }
92 }
93 }
94
95 /**
96 * @param MathRenderer[] $renderers
97 */
98 public static function batchEvaluate( array $renderers ) {
99 $rbis = [];
100 foreach ( $renderers as $renderer ) {
101 $rbi = new MathRestbaseInterface( $renderer->getTex(), $renderer->getInputType() );
102 $renderer->setRestbaseInterface( $rbi );
103 $rbis[] = $rbi;
104 }
105 MathRestbaseInterface::batchEvaluate( $rbis );
106 }
107
108 /**
109 * Gets the allowed root elements the rendered math tag might have.
110 *
111 * @return string[]
112 */
113 public function getAllowedRootElements() {
114 return $this->allowedRootElements ?: $this->defaultAllowedRootElements;
115 }
116
117 /**
118 * Sets the XML validation.
119 * If set to false the output of MathML is not validated.
120 * @param bool $validation
121 */
122 public function setXMLValidation( $validation = true ) {
123 $this->XMLValidation = $validation;
124 }
125
126 /**
127 * Sets the allowed root elements the rendered math tag might have.
128 * An empty value indicates to use the default settings.
129 * @param string[] $settings
130 */
131 public function setAllowedRootElements( $settings ) {
132 $this->allowedRootElements = $settings;
133 }
134
135 public function render() {
136 global $wgMathFullRestbaseURL, $wgMathSvgRenderer;
137 try {
138 if ( $wgMathSvgRenderer === 'restbase' &&
139 in_array( $this->inputType, $this->restbaseInputTypes, true ) &&
140 in_array( $this->mode, $this->restbaseRenderingModes, true )
141 ) {
142 if ( !$this->rbi ) {
143 $this->rbi =
144 new MathRestbaseInterface( $this->getTex(), $this->getInputType() );
145 $this->rbi->setPurge( $this->isPurge() );
146 }
147 $rbi = $this->rbi;
148 if ( $rbi->getSuccess() ) {
149 $this->mathml = $rbi->getMathML();
150 $this->mathoidStyle = $rbi->getMathoidStyle();
151 $this->svgPath = $rbi->getFullSvgUrl();
152 $this->warnings = $rbi->getWarnings();
153 } elseif ( $this->lastError === '' ) {
154 $this->doCheck();
155 }
156 $this->changed = false;
157 return $rbi->getSuccess();
158 }
159 if ( $this->renderingRequired() ) {
160 $renderResult = $this->doRender();
161 if ( !$renderResult->isGood() ) {
162 // TODO: this is a hacky hack, lastError will not exist soon.
163 $renderError = $renderResult->getErrors()[0];
164 $this->lastError = $this->getError( $renderError['message'], ...$renderError['params'] );
165 }
166 return $renderResult->isGood();
167 }
168 return true;
169 } catch ( Throwable $e ) {
170 $this->lastError = $this->getError( 'math_mathoid_error',
171 $wgMathFullRestbaseURL, $e->getMessage() );
172 $this->logger->error( $e->getMessage(), [ $e, $this ] );
173 return false;
174 }
175 }
176
177 /**
178 * Helper function to checks if the math tag must be rendered.
179 * @return bool
180 */
181 private function renderingRequired() {
182 if ( $this->isPurge() ) {
183 $this->logger->debug( 'Rerendering was requested.' );
184 return true;
185 }
186
187 $dbres = $this->isInDatabase();
188 if ( $dbres ) {
189 if ( $this->isValidMathML( $this->getMathml() ) ) {
190 $this->logger->debug( 'Valid MathML entry found in database.' );
191 if ( $this->getSvg( 'cached' ) ) {
192 $this->logger->debug( 'SVG-fallback found in database.' );
193 return false;
194 } else {
195 $this->logger->debug( 'SVG-fallback missing.' );
196 return true;
197 }
198 } else {
199 $this->logger->debug( 'Malformatted entry found in database' );
200 return true;
201 }
202 } else {
203 $this->logger->debug( 'No entry found in database.' );
204 return true;
205 }
206 }
207
208 /**
209 * Performs a HTTP Post request to the given host.
210 * Uses $wgMathLaTeXMLTimeout as timeout.
211 *
212 * @return StatusValue result with response body as a value
213 */
214 public function makeRequest() {
215 // TODO: Change the timeout mechanism.
216 global $wgMathLaTeXMLTimeout;
217 $post = $this->getPostData();
218 $options = [ 'method' => 'POST', 'postData' => $post, 'timeout' => $wgMathLaTeXMLTimeout ];
219 $req = MediaWikiServices::getInstance()->getHttpRequestFactory()->create( $this->host, $options, __METHOD__ );
220 $status = $req->execute();
221 if ( $status->isGood() ) {
222 return StatusValue::newGood( $req->getContent() );
223 } else {
224 if ( $status->hasMessage( 'http-timed-out' ) ) {
225 $this->logger->warning( 'Math service request timeout', [
226 'post' => $post,
227 'host' => $this->host,
228 'timeout' => $wgMathLaTeXMLTimeout
229 ] );
230 return StatusValue::newFatal( 'math_timeout', $this->getModeName(), $this->host );
231 } else {
232 $errormsg = $req->getContent();
233 $this->logger->warning( 'Math service request failed', [
234 'post' => $post,
235 'host' => $this->host,
236 'errormsg' => $errormsg
237 ] );
238 return StatusValue::newFatal(
239 'math_invalidresponse',
240 $this->getModeName(),
241 $this->host,
242 $errormsg,
243 $this->getModeName()
244 );
245 }
246 }
247 }
248
249 /**
250 * Calculates the HTTP POST Data for the request. Depends on the settings
251 * and the input string only.
252 * @return string HTTP POST data
253 */
254 public function getPostData() {
255 $input = $this->getTex();
256 if ( $this->inputType == 'pmml' ||
257 ( $this->getMode() == MathConfig::MODE_LATEXML && $this->getMathml() )
258 ) {
259 $out = 'type=mml&q=' . rawurlencode( $this->getMathml() );
260 } elseif ( $this->inputType == 'ascii' ) {
261 $out = 'type=asciimath&q=' . rawurlencode( $input );
262 } else {
263 if ( $this->getMathStyle() === 'inlineDisplaystyle' ) {
264 // default preserve the (broken) layout as it was
265 $out = 'type=inline-TeX&q=' . rawurlencode( '{\\displaystyle ' . $input . '}' );
266 } elseif ( $this->getMathStyle() === 'inline' ) {
267 $out = 'type=inline-TeX&q=' . rawurlencode( $input );
268 } else {
269 $out = 'type=tex&q=' . rawurlencode( $input );
270 }
271 }
272 $this->logger->debug( 'Get post data: ' . $out );
273 return $out;
274 }
275
276 /**
277 * Does the actual web request to convert TeX to MathML.
278 *
279 * @return StatusValue
280 */
281 protected function doRender(): StatusValue {
282 if ( $this->isEmpty() ) {
283 $this->logger->debug( 'Rendering was requested, but no TeX string is specified.' );
284 return StatusValue::newFatal( 'math_empty_tex' );
285 }
286 $requestStatus = $this->makeRequest();
287 if ( $requestStatus->isGood() ) {
288 $jsonResult = json_decode( $requestStatus->getValue() );
289 if ( $jsonResult && json_last_error() === JSON_ERROR_NONE ) {
290 if ( $jsonResult->success ) {
291 return $this->processJsonResult( $jsonResult, $this->host );
292 } else {
293 $serviceLog = $jsonResult->log ?? wfMessage( 'math_unknown_error' )
294 ->inContentLanguage()
295 ->escaped();
296 $this->logger->warning( 'Mathoid conversion error', [
297 'post' => $this->getPostData(),
298 'host' => $this->host,
299 'result' => $requestStatus->getValue(),
300 'service_log' => $serviceLog
301 ] );
302 return StatusValue::newFatal( 'math_mathoid_error', $this->host, $serviceLog );
303 }
304 } else {
305 $this->logger->error( 'MathML invalid JSON', [
306 'post' => $this->getPostData(),
307 'host' => $this->host,
308 'res' => $requestStatus->getValue(),
309 ] );
310 return StatusValue::newFatal( 'math_invalidjson', $this->host );
311 }
312 } else {
313 return $requestStatus;
314 }
315 }
316
317 /**
318 * Checks if the input is valid MathML,
319 * and if the root element has the name math
320 * @param string $XML
321 * @return bool
322 */
323 public function isValidMathML( $XML ) {
324 $out = false;
325 if ( !$this->XMLValidation ) {
326 return true;
327 }
328
329 $xmlObject = new XmlTypeCheck( $XML, null, false );
330 if ( !$xmlObject->wellFormed ) {
331 $this->logger->error(
332 'XML validation error: ' . var_export( $XML, true ) );
333 } else {
334 $name = $xmlObject->getRootElement();
335 $elementSplit = explode( ':', $name );
336 $localName = end( $elementSplit );
337 if ( in_array( $localName, $this->getAllowedRootElements(), true ) ) {
338 $out = true;
339 } else {
340 $this->logger->error( "Got wrong root element: $name" );
341 }
342 }
343 return $out;
344 }
345
346 /**
347 * @param bool $noRender
348 * @return Title|string
349 */
350 private function getFallbackImageUrl( $noRender = false ) {
351 if ( $this->svgPath ) {
352 return $this->svgPath;
353 }
354 return SpecialPage::getTitleFor( 'MathShowImage' )->getLocalURL( [
355 'hash' => $this->getInputHash(),
356 'mode' => $this->getMode(),
357 'noRender' => $noRender
358 ]
359 );
360 }
361
362 /**
363 * Helper function to correct the style information for a
364 * linked SVG image.
365 * @param string &$style current style information to be updated
366 */
367 public function correctSvgStyle( &$style ) {
368 if ( preg_match( '/style="([^"]*)"/', $this->getSvg(), $styles ) ) {
369 $style .= ' ' . $styles[1]; // merge styles
370 if ( $this->getMathStyle() === 'display' ) {
371 // TODO: Improve style cleaning
372 $style = preg_replace(
373 '/margin\-(left|right)\:\s*\d+(\%|in|cm|mm|em|ex|pt|pc|px)\;/', '', $style
374 );
375 }
376 $style = trim( preg_replace( '/position:\s*absolute;\s*left:\s*0px;/', '', $style ),
377 "; \t\n\r\0\x0B" ) . '; ';
378
379 }
380 // TODO: Figure out if there is a way to construct
381 // a SVGReader from a string that represents the SVG
382 // content
383 if ( preg_match( "/height=\"(.*?)\"/", $this->getSvg(), $matches ) ) {
384 $style .= 'height: ' . $matches[1] . '; ';
385 }
386 if ( preg_match( "/width=\"(.*?)\"/", $this->getSvg(), $matches ) ) {
387 $style .= 'width: ' . $matches[1] . ';';
388 }
389 }
390
391 /**
392 * Gets img tag for math image
393 * @param bool $noRender if true no rendering will be performed
394 * if the image is not stored in the database
395 * @param false|string $classOverride if classOverride
396 * is false the class name will be calculated by getClassName
397 * @return string XML the image html tag
398 */
399 protected function getFallbackImage( $noRender = false, $classOverride = false ) {
400 $attribs = [
401 'src' => $this->getFallbackImageUrl( $noRender ),
402 'class' => $classOverride === false ? $this->getClassName( true ) : $classOverride,
403 ];
404 if ( !$this->mathoidStyle ) {
405 $this->correctSvgStyle( $this->mathoidStyle );
406 }
407
408 return Html::element( 'img', $this->getAttributes( 'span', $attribs, [
409 'aria-hidden' => 'true',
410 'style' => $this->mathoidStyle,
411 'alt' => $this->tex
412 ] ) );
413 }
414
415 /**
416 * @return string
417 */
418 protected function getMathTableName() {
419 return 'mathoid';
420 }
421
422 /**
423 * Calculates the default class name for a math element
424 * @param bool $fallback
425 * @return string the class name
426 */
427 private function getClassName( $fallback = false ) {
428 $class = 'mwe-math-';
429 if ( $fallback ) {
430 $class .= 'fallback-image-';
431 } else {
432 $class .= 'mathml-';
433 }
434 if ( $this->getMathStyle() == 'display' ) {
435 $class .= 'display';
436 } else {
437 $class .= 'inline';
438 }
439 if ( $fallback ) {
440 // Support 3rd party gadgets and extensions.
441 $class .= ' mw-invert';
442 // Support skins with night theme.
443 $class .= ' skin-invert';
444 } else {
445 $class .= ' mwe-math-mathml-a11y';
446 }
447 return $class;
448 }
449
450 /**
451 * @param bool $svg
452 * @return string Html output that is embedded in the page
453 */
454 public function getHtmlOutput( bool $svg = true ): string {
455 $config = MediaWikiServices::getInstance()->getMainConfig();
456 $enableLinks = $config->get( "MathEnableFormulaLinks" );
457 if ( $this->getMathStyle() === 'display' ) {
458 $mml_class = 'mwe-math-mathml-display';
459 } else {
460 $mml_class = 'mwe-math-mathml-inline';
461 }
462 $attribs = [ 'class' => 'mwe-math-element' ];
463 if ( $this->getID() !== '' ) {
464 $attribs['id'] = $this->getID();
465 }
466 $hyperlink = null;
467 if ( isset( $this->params['qid'] ) && preg_match( '/Q\d+/', $this->params['qid'] ) ) {
468 $attribs['data-qid'] = $this->params['qid'];
469 $titleObj = SpecialPage::getTitleFor( 'MathWikibase' );
470 $hyperlink = $titleObj->getLocalURL( [ 'qid' => $this->params['qid'] ] );
471 }
472 $output = '';
473 // MathML has to be wrapped into a div or span in order to be able to hide it.
474 // Remove displayStyle attributes set by the MathML converter
475 // (Beginning from Mathoid 0.2.5 block is the default layout.)
476 $mml = preg_replace(
477 '/(<math[^>]*)(display|mode)=["\'](inline|block)["\']/', '$1', $this->getMathml()
478 );
479 if ( $this->getMathStyle() == 'display' ) {
480 $mml = preg_replace( '/<math/', '<math display="block"', $mml );
481 }
482
483 if ( $svg ) {
484 $mml_attribs = [
485 'class' => $this->getClassName(),
486 'style' => 'display: none;'
487 ];
488 } else {
489 $mml_attribs = [
490 'class' => $mml_class,
491 ];
492 }
493 $output .= Html::rawElement( 'span', $mml_attribs, $mml );
494 if ( $svg ) {
495 $output .= $this->getFallbackImage();
496 }
497
498 if ( $hyperlink && $enableLinks ) {
499 $output = Html::rawElement( 'a',
500 [ 'href' => $hyperlink, 'style' => 'color:inherit;' ],
501 $output
502 );
503 }
504
505 return Html::rawElement( 'span', $attribs, $output );
506 }
507
508 protected function dbOutArray() {
509 $out = parent::dbOutArray();
510 if ( $this->getMathTableName() === 'mathoid' ) {
511 $out['math_input'] = $out['math_inputtex'];
512 unset( $out['math_inputtex'] );
513 }
514 return $out;
515 }
516
517 protected function dbInArray() {
518 $out = parent::dbInArray();
519 if ( $this->getMathTableName() === 'mathoid' ) {
520 $out = array_diff( $out, [ 'math_inputtex' ] );
521 $out[] = 'math_input';
522 }
523 return $out;
524 }
525
526 /** @inheritDoc */
527 public function initializeFromCache( $rpage ) {
528 // mathoid allows different input formats
529 // therefore the column name math_inputtex was changed to math_input
530 if ( $this->getMathTableName() === 'mathoid' && isset( $rpage['math_input'] ) ) {
531 $this->userInputTex = $rpage['math_input'];
532 }
533 parent::initializeFromCache( $rpage );
534 }
535
536 /**
537 * @param stdClass $jsonResult
538 * @param string $host name
539 *
540 * @return StatusValue
541 */
542 protected function processJsonResult( $jsonResult, $host ): StatusValue {
543 if ( $this->getMode() == MathConfig::MODE_LATEXML || $this->inputType == 'pmml' ||
544 $this->isValidMathML( $jsonResult->mml )
545 ) {
546 if ( isset( $jsonResult->svg ) ) {
547 $xmlObject = new XmlTypeCheck( $jsonResult->svg, null, false );
548 if ( !$xmlObject->wellFormed ) {
549 return StatusValue::newFatal( 'math_invalidxml', $host );
550 } else {
551 $this->setSvg( $jsonResult->svg );
552 }
553 } else {
554 $this->logger->error( 'Missing SVG property in JSON result.' );
555 }
556 if ( $this->getMode() != MathConfig::MODE_LATEXML && $this->inputType != 'pmml' ) {
557 $this->setMathml( $jsonResult->mml );
558 }
559 // Avoid PHP 7.1 warning from passing $this by reference
560 $renderer = $this;
561 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onMathRenderingResultRetrieved(
562 $renderer, $jsonResult
563 ); // Enables debugging of server results
564 return StatusValue::newGood(); // FIXME: empty?
565 } else {
566 return StatusValue::newFatal( 'math_unknown_error', $host );
567 }
568 }
569
570 /**
571 * @return bool
572 */
573 protected function isEmpty() {
574 return $this->userInputTex === '';
575 }
576
577 }