forked from wikimedia/mediawiki-extensions-Math
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMathRenderer.php
More file actions
717 lines (663 loc) · 19.2 KB
/
MathRenderer.php
File metadata and controls
717 lines (663 loc) · 19.2 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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
<?php
/**
* MediaWiki math extension
*
* (c) 2002-2012 Tomasz Wegrzanowski, Brion Vibber, Moritz Schubotz,
* and other MediaWiki contributors
* GPLv2 license; info in main package.
*
* @file
*/
use MediaWiki\Logger\LoggerFactory;
/**
* Abstract base class with static methods for rendering the <math> tags using
* different technologies. These static methods create a new instance of the
* extending classes and render the math tags based on the mode setting of the user.
* Furthermore this class handles the caching of the rendered output.
*
* @author Tomasz Wegrzanowski
* @author Brion Vibber
* @author Moritz Schubotz
*/
abstract class MathRenderer {
// REPRESENTATIONS OF THE MATHEMATICAL CONTENT
/** @var string tex representation */
protected $tex = '';
/** @var string MathML content and presentation */
protected $mathml = '';
/** @var string SVG layout only (no semantics) */
protected $svg = '';
/** @var string the original user input string (which was used to calculate the inputhash) */
protected $userInputTex = '';
// FURTHER PROPERTIES OF THE MATHEMATICAL CONTENT
/** @var ('inlineDisplaystyle'|'display'|'inline'|'linebreak') the rendering style */
protected $mathStyle = 'inlineDisplaystyle';
/** @var array with userdefined parameters passed to the extension (not used) */
protected $params = [];
/** @var string a userdefined identifier to link to the equation. */
protected $id = '';
// STATE OF THE CLASS INSTANCE
/** @var boolean has variable tex been security-checked */
protected $texSecure = false;
/** @var boolean has the mathematical content changed */
protected $changed = false;
/** @var boolean is there a database entry for the mathematical content */
protected $storedInDatabase = null;
/** @var boolean is there a request to purge the existing mathematical content */
protected $purge = false;
/** @var string with last occurred error */
protected $lastError = '';
/** @var string md5 value from userInputTex */
protected $md5 = '';
/** @var string binary packed inputhash */
protected $inputHash = '';
/** @var string rendering mode */
protected $mode = 'png';
/** @var string input type */
protected $inputType = 'tex';
/** @var MathRestbaseInterface used for checking */
protected $rbi;
/**
* Constructs a base MathRenderer
*
* @param string $tex (optional) LaTeX markup
* @param array $params (optional) HTML attributes
*/
public function __construct( $tex = '', $params = [] ) {
$this->params = $params;
if ( isset( $params['id'] ) ) {
$this->id = $params['id'];
}
if ( isset( $params['display'] ) ) {
$layoutMode = $params['display'];
if ( $layoutMode == 'block' ) {
$this->mathStyle = 'display';
$tex = '{\displaystyle ' . $tex . '}';
$this->inputType = 'tex';
} elseif ( $layoutMode == 'inline' ) {
$this->mathStyle = 'inline';
$this->inputType = 'inline-tex';
$tex = '{\textstyle ' . $tex . '}';
} elseif ( $layoutMode == 'linebreak' ) {
$this->mathStyle = 'linebreak';
$tex = '\[ ' . $tex . ' \]';
}
}
// TODO: Implement caching for attributes of the math tag
// Currently the key for the database entry relating to an equation
// is md5($tex) the new option to determine if the tex input
// is rendered in displaystyle or textstyle would require a database
// layout change to use a composite key e.g. (md5($tex),$mathStyle).
// As a workaround we use the prefix \displaystyle so that the key becomes
// md5((\{\\displaystyle|\{\\textstyle)?\s?$tex\}?)
// The new value of $tex string describes now how the rendering should look like.
// The variable MathRenderer::mathStyle determines if the rendered equation should
// be centered in a new line, or just in be displayed in the current line.
$this->userInputTex = $tex;
$this->tex = $tex;
}
/**
* Static method for rendering math tag
*
* @param string $tex LaTeX markup
* @param array $params HTML attributes
* @param string $mode constant indicating rendering mode
* @return string HTML for math tag
*/
public static function renderMath( $tex, $params = [], $mode = 'png' ) {
$renderer = self::getRenderer( $tex, $params, $mode );
if ( $renderer->render() ) {
return $renderer->getHtmlOutput();
} else {
return $renderer->getLastError();
}
}
/**
*
* @param string $md5
* @return MathRenderer the MathRenderer generated from md5
*/
public static function newFromMd5( $md5 ) {
$class = get_called_class();
/** @var MathRenderer $instance */
$instance = new $class;
$instance->setMd5( $md5 );
$instance->readFromDatabase();
return $instance;
}
/**
* Static factory method for getting a renderer based on mode
*
* @param string $tex LaTeX markup
* @param array $params HTML attributes
* @param string $mode indicating rendering mode
* @return MathRenderer appropriate renderer for mode
*/
public static function getRenderer( $tex, $params = [], $mode = 'png' ) {
global $wgDefaultUserOptions, $wgMathEnableExperimentalInputFormats, $wgLatexOnWindows;
if ( isset( $params['forcemathmode'] ) ) {
$mode = $params['forcemathmode'];
}
if ( !in_array( $mode, self::getValidModes() ) ) {
$mode = $wgDefaultUserOptions['math'];
}
if ( $wgMathEnableExperimentalInputFormats === true && $mode == 'mathml' &&
isset( $params['type'] ) ) {
// Support of MathML input (experimental)
// Currently support for mode 'mathml' only
if ( !in_array( $params['type'], [ 'pmml', 'ascii' ] ) ) {
unset( $params['type'] );
}
}
if ( isset( $params['chem'] ) ) {
$mode = 'mathml';
$params['type'] = 'chem';
}
switch ( $mode ) {
case 'source':
$renderer = new MathSource( $tex, $params );
break;
case 'png':
if(wgLatexOnWindows)
{
$renderer = new MathLatexRender($tex, $params);
}
else
{
$renderer = new MathTexvc( $tex, $params );
}
break;
case 'latexml':
$renderer = new MathLaTeXML( $tex, $params );
break;
case 'mathml':
default:
$renderer = new MathMathML($tex, $params);
}
LoggerFactory::getInstance( 'Math' )->debug( 'Start rendering $' . $renderer->tex .
'$ in mode ' . $mode );
return $renderer;
}
/**
* Performs the rendering
*
* @return boolean if rendering was successful.
*/
abstract public function render();
/**
* @return string Html output that is embedded in the page
*/
abstract public function getHtmlOutput();
/**
* texvc error messages
* TODO: update to MathML
* Returns an internationalized HTML error string
*
* @param string $msg message key for specific error
* @internal param \Varargs $parameters (optional) zero
* or more message parameters for specific error
*
* @return string HTML error string
*/
public function getError( $msg /*, ... */ ) {
$mf = wfMessage( 'math_failure' )->inContentLanguage()->escaped();
$parameters = func_get_args();
array_shift( $parameters );
$errmsg = wfMessage( $msg, $parameters )->inContentLanguage()->escaped();
$source = htmlspecialchars( str_replace( "\n", ' ', $this->tex ) );
return "<strong class='error texerror'>$mf ($errmsg): $source</strong>\n";
}
/**
* Return hash of input
*
* @return string hash
*/
public function getMd5() {
if ( ! $this->md5 ) {
$this->md5 = md5( $this->userInputTex );
}
return $this->md5;
}
/**
* Set the input hash (if user input tex is not available)
* @param $md5
* @return string hash
*/
public function setMd5( $md5 ) {
$this->md5 = $md5;
}
/**
* Return hash of input
*
* @return string hash
*/
public function getInputHash() {
// TODO: What happens if $tex is empty?
if ( !$this->inputHash ) {
$dbr = wfGetDB( DB_SLAVE );
return $dbr->encodeBlob( pack( "H32", $this->getMd5() ) ); # Binary packed, not hex
}
return $this->inputHash;
}
/**
* Decode binary packed hash from the database to md5 of input_tex
* @param string $hash (binary)
* @return string md5
*/
private static function dbHash2md5( $hash ) {
$dbr = wfGetDB( DB_SLAVE );
$xhash = unpack( 'H32md5', $dbr->decodeBlob( $hash ) . " " );
return $xhash['md5'];
}
/**
* Reads rendering data from database
*
* @return boolean true if read successfully, false otherwise
*/
public function readFromDatabase() {
$dbr = wfGetDB( DB_SLAVE );
$rpage = $dbr->selectRow( $this->getMathTableName(),
$this->dbInArray(),
[ 'math_inputhash' => $this->getInputHash() ],
__METHOD__ );
if ( $rpage !== false ) {
$this->initializeFromDatabaseRow( $rpage );
$this->storedInDatabase = true;
return true;
} else {
# Missing from the database and/or the render cache
$this->storedInDatabase = false;
return false;
}
}
/**
* @return array with the database column names
*/
protected function dbInArray() {
$in = [ 'math_inputhash',
'math_mathml',
'math_inputtex',
'math_tex',
'math_svg'
];
return $in;
}
/**
* Reads the values from the database but does not overwrite set values with empty values
* @param stdClass $rpage (a database row)
*/
protected function initializeFromDatabaseRow( $rpage ) {
$this->inputHash = $rpage->math_inputhash; // MUST NOT BE NULL
$this->md5 = self::dbHash2md5( $this->inputHash );
if ( ! empty( $rpage->math_mathml ) ) {
$this->mathml = utf8_decode( $rpage->math_mathml );
}
if ( ! empty( $rpage->math_inputtex ) ) {
// in the current database the field is probably not set.
$this->userInputTex = $rpage->math_inputtex;
}
if ( ! empty( $rpage->math_tex ) ) {
$this->tex = $rpage->math_tex;
}
if ( ! empty( $rpage->math_svg ) ) {
$this->svg = $rpage->math_svg;
}
$this->changed = false;
}
/**
* Writes rendering entry to database.
*
* WARNING: Use writeCache() instead of this method to be sure that all
* renderer specific (such as squid caching) are taken into account.
* This function stores the values that are currently present in the class
* to the database even if they are empty.
*
* This function can be seen as protected function.
* @param DatabaseBase $dbw
*/
public function writeToDatabase( $dbw = null ) {
# Now save it back to the DB:
if ( !wfReadOnly() ) {
LoggerFactory::getInstance( 'Math' )->debug( 'Store entry for $' . $this->tex .
'$ in database (hash:' . $this->getMd5() . ')' );
$outArray = $this->dbOutArray();
$mathTableName = $this->getMathTableName();
if ( $this->isInDatabase() ) {
$inputHash = $this->getInputHash();
DeferredUpdates::addCallableUpdate( function () use (
$dbw, $outArray, $inputHash, $mathTableName
) {
$dbw = $dbw ?: wfGetDB( DB_MASTER );
$dbw->update( $mathTableName, $outArray,
[ 'math_inputhash' => $inputHash ], __METHOD__ );
LoggerFactory::getInstance( 'Math' )->debug(
'Row updated after db transaction was idle: ' .
var_export( $outArray, true ) . " to database" );
} );
} else {
DeferredUpdates::addCallableUpdate( function () use (
$dbw, $outArray, $mathTableName
) {
$dbw = $dbw ?: wfGetDB( DB_MASTER );
$dbw->insert( $mathTableName, $outArray, __METHOD__, [ 'IGNORE' ] );
LoggerFactory::getInstance( 'Math' )->debug(
'Row inserted after db transaction was idle ' .
var_export( $outArray, true ) . " to database" );
if ( $dbw->affectedRows() == 0 ) {
// That's the price for the delayed update.
LoggerFactory::getInstance( 'Math' )->warning(
'Entry could not be written. Might be changed in between.' );
}
} );
}
}
}
/**
* Gets an array that matches the variables of the class to the database columns
* @return array
*/
protected function dbOutArray() {
$out = [
'math_inputhash' => $this->getInputHash(),
'math_mathml' => utf8_encode( $this->mathml ),
'math_inputtex' => $this->userInputTex,
'math_tex' => $this->tex,
'math_svg' => $this->svg
];
return $out;
}
/**
* @param MathRestbaseInterface $param
*/
public function setRestbaseInterface( $param ) {
$this->rbi = $param;
$this->rbi->setPurge( $this->isPurge() );
}
/**
* Returns sanitized attributes
*
* @param string $tag element name
* @param array $defaults default attributes
* @param array $overrides attributes to override defaults
* @return array HTML attributes
*/
protected function getAttributes( $tag, $defaults = [], $overrides = [] ) {
$attribs = Sanitizer::validateTagAttributes( $this->params, $tag );
$attribs = Sanitizer::mergeAttributes( $defaults, $attribs );
$attribs = Sanitizer::mergeAttributes( $attribs, $overrides );
return $attribs;
}
/**
* Writes cache. Writes the database entry if values were changed
*/
public function writeCache() {
$logger = LoggerFactory::getInstance( 'Math' );
$logger->debug( 'Writing of cache requested.' );
if ( $this->isChanged() ) {
$logger->debug( 'Change detected. Perform writing.' );
$this->writeToDatabase();
return true;
} else {
$logger->debug( "Nothing was changed. Don't write to database." );
return false;
}
}
/**
* Gets TeX markup
*
* @return string TeX markup
*/
public function getTex() {
return $this->tex;
}
/**
* Gets the rendering mode
*
* @return string
*/
public function getMode() {
return $this->mode;
}
/**
* Sets the rendering mode
* @param string $newMode element of the array $wgMathValidModes
* @return bool
*/
public function setMode( $newMode ) {
if ( in_array( $newMode, self::getValidModes() ) ) {
$this->mode = $newMode;
return true;
} else {
return false;
}
}
/**
* Sets the TeX code
*
* @param string $tex
*/
public function setTex( $tex ) {
if ( $this->tex != $tex ) {
$this->changed = true;
$this->tex = $tex;
}
}
/**
* Gets the MathML XML element
* @return string in UTF-8 encoding
*/
public function getMathml() {
if ( !StringUtils::isUtf8( $this->mathml ) ) {
$this->setMathml( '' );
}
return $this->mathml;
}
/**
* @param string $mathml use UTF-8 encoding
*/
public function setMathml( $mathml ) {
$this->changed = true;
$this->mathml = $mathml;
}
/**
* Get the attributes of the math tag
*
* @return []
*/
public function getParams() {
return $this->params;
}
/**
* @param [] $params
*/
public function setParams( $params ) {
// $changed is not set to true here, because the attributes do not affect
// the rendering in the current implementation.
// If this behavior will change in the future $this->tex is no longer a
// primary key and the input hash cannot be calculate form $this->tex
// only. See the discussion 'Tag extensions in Block mode' on wikitech-l.
$this->params = $params;
}
/**
* Checks if the instance was modified i.e., because math was rendered
*
* @return boolean true if something was changed false otherwise
*/
public function isChanged() {
return $this->changed;
}
/**
* Checks if there is an explicit user request to rerender the math-tag.
* @return boolean
*/
function isPurge() {
if ( $this->purge ) {
return true;
}
$request = RequestContext::getMain()->getRequest();
// TODO: Figure out if ?action=purge
// $action = $request->getText('action'); //always returns ''
// until this issue is resolved we use ?mathpurge=true instead
$mathpurge = $request->getBool( 'mathpurge', false );
if ( $mathpurge ) {
LoggerFactory::getInstance( 'Math' )->debug( 'Re-Rendering on user request' );
return true;
} else {
return false;
}
}
/**
* Sets purge. If set to true the render is forced to rerender and must not
* use a cached version.
* @param bool $purge
* @return boolean
*/
function setPurge( $purge = true ) {
$this->changed = true;
$this->purge = $purge;
}
function getLastError() {
return $this->lastError;
}
/**
*
* @param string $mathStyle ('inlineDisplaystyle'|'display'|'inline')
*/
public function setMathStyle( $mathStyle = 'display' ) {
if ( $this->mathStyle !== $mathStyle ){
$this->changed = true;
}
$this->mathStyle = $mathStyle;
if ( $mathStyle == 'inline' ){
$this->inputType = 'inline-tex';
} else {
$this->inputType = 'tex';
}
}
/**
* Returns the value of the DisplayStyle attribute
* @return string ('inlineDisplaystyle'|'display'|'inline'|'linebreak') the DisplayStyle
*/
public function getMathStyle() {
return $this->mathStyle;
}
/**
* Get if the input tex was marked as secure
* @return boolean
*/
public function isTexSecure() {
return $this->texSecure;
}
/**
* @global $wgMathDisableTexFilter
* @return bool
*/
public function checkTeX() {
if ( $this->texSecure || self::getDisableTexFilter() == 'always' ) {
// equation was already checked or checking is disabled
return true;
} else {
if ( self::getDisableTexFilter() == 'new' && $this->mode != 'source' ){
if ( $this->readFromDatabase() ) {
return true;
}
}
return $this->doCheck();
}
}
public function isInDatabase() {
if ( $this->storedInDatabase === null ) {
$this->readFromDatabase();
}
return $this->storedInDatabase;
}
/**
*
* @return string TeX the original tex string specified by the user
*/
public function getUserInputTex() {
return $this->userInputTex;
}
/**
* @return string user defined ID
*/
public function getID() {
return $this->id;
}
/**
* @param string user defined ID
*/
public function setID( $id ) {
// Changes in the ID affect the container for the math element on the current page
// only. Therefore an id change does not affect the $this->changed variable, which
// indicates if database relevant fields have been changed.
$this->id = $id;
}
/**
*
* @param string $svg
*/
public function setSvg( $svg ) {
$this->changed = true;
$this->svg = trim( $svg );
}
/**
* 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( /** @noinspection PhpUnusedParameterInspection */ $render = 'render' ) {
// Spaces will prevent the image from being displayed correctly in the browser
if ( !$this->svg && $this->rbi ){
$this->svg = $this->rbi->getSvg();
}
return trim( $this->svg );
}
abstract protected function getMathTableName();
public function getModeStr() {
$names = MathHooks::getMathNames();
return $names[ $this->getMode() ];
}
public static function getValidModes() {
global $wgMathValidModes;
return array_map( "MathHooks::mathModeToString", $wgMathValidModes );
}
public static function getDisableTexFilter() {
global $wgMathDisableTexFilter;
return MathHooks::mathCheckToString( $wgMathDisableTexFilter );
}
/**
* @param string $inputType
*/
public function setInputType( $inputType ) {
$this->inputType = $inputType;
}
/**
* @return string
*/
public function getInputType() {
return $this->inputType;
}
/**
* @return bool
*/
protected function doCheck() {
$checker = new MathInputCheckRestbase( $this->tex, $this->getInputType(), $this->rbi );
try {
if ( $checker->isValid() ) {
$this->setTex( $checker->getValidTex() );
$this->texSecure = true;
return true;
}
}
catch ( MWException $e ) {
}
$this->lastError = $checker->getError();
return false;
}
}