forked from wikimedia/mediawiki-extensions-Math
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MathLaTeXML.php
219 lines (207 loc) · 6.83 KB
/
MathLaTeXML.php
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
<?php
use MediaWiki\Logger\LoggerFactory;
/**
* MediaWiki math extension
*
* (c)2012 Moritz Schubotz
* GPLv2 license; info in main package.
*
* Contains the driver function for the LaTeXML daemon
* @file
*/
class MathLaTeXML extends MathMathML {
protected $defaultAllowedRootElements = [ 'math', 'div', 'table', 'query' ];
/** @var String settings for LaTeXML daemon */
private $LaTeXMLSettings = '';
public function __construct( $tex = '', $params = [] ) {
global $wgMathLaTeXMLUrl;
parent::__construct( $tex, $params );
$this->hosts = $wgMathLaTeXMLUrl;
$this->setMode( 'latexml' );
}
/**
* Converts an array with LaTeXML settings to a URL encoded String.
* If the argument is a string the input will be returned.
* Thus the function has projector properties and can be applied a second time safely.
* @param (string|array) $array
* @return string
*/
public function serializeSettings( $array ) {
if ( !is_array( $array ) ) {
return $array;
} else {
// removes the [1] [2]... for the unnamed subarrays since LaTeXML
// assigns multiple values to one key e.g.
// preload=amsmath.sty&preload=amsthm.sty&preload=amstext.sty
$cgi_string = wfArrayToCgi( $array );
$cgi_string = preg_replace( '|\%5B\d+\%5D|', '', $cgi_string );
$cgi_string = preg_replace( '|&\d+=|', '&', $cgi_string );
return $cgi_string;
}
}
/**
* Gets the settings for the LaTeXML daemon.
* @global (array|string) $wgMathDefaultLaTeXMLSetting
* @return string
*/
public function getLaTeXMLSettings() {
global $wgMathDefaultLaTeXMLSetting;
if ( $this->LaTeXMLSettings ) {
return $this->LaTeXMLSettings;
} else {
return $wgMathDefaultLaTeXMLSetting;
}
}
/**
* Sets the settings for the LaTeXML daemon.
* The settings affect only the current instance of the class.
* For a list of possible settings see:
* http://dlmf.nist.gov/LaTeXML/manual/commands/latexmlpost.xhtml
* An empty value indicates to use the default settings.
* @param string|array $settings
*/
public function setLaTeXMLSettings( $settings ) {
$this->LaTeXMLSettings = $settings;
}
/**
* Calculates the HTTP POST Data for the request. Depends on the settings
* and the input string only.
* @return string HTTP POST data
*/
public function getLaTeXMLPostData() {
$tex = $this->getTex();
if ( $this->getMathStyle() == 'inlineDisplaystyle' ) {
// In 'inlineDisplaystyle' the old
// texvc behavior is reproduced:
// The equation is rendered in displaystyle
// (texvc used $$ $tex $$ to render)
// but the equation is not centered.
$tex = '{\displaystyle ' . $tex . '}';
}
$texcmd = rawurlencode( $tex );
$settings = $this->serializeSettings( $this->getLaTeXMLSettings() );
$postData = $settings . '&tex=' . $texcmd;
LoggerFactory::getInstance( 'Math' )->debug( 'Get post data: ' . $postData );
return $postData;
}
/**
* Does the actual web request to convert TeX to MathML.
* @return boolean
*/
protected function doRender() {
if ( trim( $this->getTex() ) === '' ) {
LoggerFactory::getInstance( 'Math' )->warning(
'Rendering was requested, but no TeX string is specified.' );
$this->lastError = $this->getError( 'math_empty_tex' );
return false;
}
$res = '';
$host = $this->pickHost();
$post = $this->getLaTeXMLPostData();
// There is an API-inconsistency between different versions of the LaTeXML daemon
// some versions require the literal prefix other don't allow it.
if ( ! strpos( $host, '/convert' ) ){
$post = preg_replace( '/&tex=/', '&tex=literal:', $post, 1 );
}
$this->lastError = '';
$requestResult = $this->makeRequest( $host, $post, $res, $this->lastError );
if ( $requestResult ) {
$jsonResult = json_decode( $res );
if ( $jsonResult && json_last_error() === JSON_ERROR_NONE ) {
if ( $this->isValidMathML( $jsonResult->result ) ) {
$this->setMathml( $jsonResult->result );
Hooks::run( 'MathRenderingResultRetrieved',
[ &$this, &$jsonResult ] );// Enables debugging of server results
return true;
} else {
// Do not print bad mathml. It's probably too verbose and might
// mess up the browser output.
$this->lastError = $this->getError( 'math_invalidxml', $this->getModeStr(), $host );
LoggerFactory::getInstance( 'Math' )->warning(
'LaTeXML InvalidMathML: ' . var_export( [
'post' => $post,
'host' => $host,
'result' => $res
], true ) );
return false;
}
} else {
$this->lastError = $this->getError( 'math_invalidjson', $this->getModeStr(), $host );
LoggerFactory::getInstance( 'Math' )->warning(
'LaTeXML InvalidJSON:' . var_export( [
'post' => $post,
'host' => $host,
'res' => $res
], true ) );
return false;
}
} else {
// Error message has already been set.
return false;
}
}
/**
* Internal version of @link self::embedMathML
* @return string
* @return html element with rendered math
*/
protected function getMathMLTag() {
return self::embedMathML( $this->getMathml(), urldecode( $this->getTex() ) );
}
/**
* Embeds the MathML-XML element in a HTML span element with class tex
* @param string $mml : the MathML string
* @param string $tagId : optional tagID for references like (pagename#equation2)
* @param bool $attribs
* @return html element with rendered math
*/
public static function embedMathML( $mml, $tagId = '', $attribs = false ) {
$mml = str_replace( "\n", " ", $mml );
if ( ! $attribs ) {
$attribs = [ 'class' => 'tex', 'dir' => 'ltr' ];
if ( $tagId ) {
$attribs['id'] = $tagId;
}
$attribs = Sanitizer::validateTagAttributes( $attribs, 'span' );
}
return Xml::tags( 'span', $attribs, $mml );
}
/**
* Calculates the SVG image based on the MathML input
* No cache is used.
* @return boolean
*/
public function calculateSvg() {
$renderer = new MathMathML( $this->getTex() );
$renderer->setMathml( $this->getMathml() );
$renderer->setMode( 'latexml' );
$res = $renderer->render( true );
if ( $res == true ) {
$this->setSvg( $renderer->getSvg() );
} else {
$lastError = $renderer->getLastError();
LoggerFactory::getInstance( 'Math' )->error(
'Failed to convert LaTeXML-MathML to SVG:' . $lastError );
}
return $res;
}
/**
* Gets the SVG image
*
* @param string $render if set to 'render' (default) and no SVG image exists, the function
* tries to generate it on the fly.
* Otherwise, if set to 'cached', and there is no SVG in the database
* cache, an empty string is returned.
*
* @return string XML-Document of the rendered SVG
*/
public function getSvg( $render = 'render' ) {
if ( $render == 'render' && ( $this->isPurge() || $this->svg == '' ) ) {
$this->calculateSvg();
}
return parent::getSvg( $render );
}
protected function getMathTableName() {
return 'mathlatexml';
}
}