ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
class.ilMathJax.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (c) 1998-2016 ILIAS open source, Extended GPL, see docs/LICENSE */
3 
4 // fau: mathJaxServer - new class for mathjax rendering.
5 
9 class ilMathJax
10 {
11  const PURPOSE_BROWSER = 'browser'; // direct display of page in the browser
12  const PURPOSE_EXPORT = 'export'; // html export of contents
13  const PURPOSE_PDF = 'pdf'; // server-side PDF generation
14  const PURPOSE_DEFERRED_PDF = 'deferred_pdf'; // defer rendering for server-side pdf generation (e.g. for XSL-FO)
15  // this needs a second call with PURPOSE_PDF at the end
16 
17  const ENGINE_SERVER = 'server'; // code is treated by one of the rendering modes below
18  const ENGINE_CLIENT = 'client'; // code delimiters are
19  const ENGINE_MIMETEX = 'mimetex'; // fallback to old mimetex cgi (if configured in ilias.ini.php)
20  const ENGINE_DEFERRED = 'deferred'; // protect code for a deferred rendering
21  const ENGINE_NONE = 'none'; // don't render the code, just show it
22 
23  const RENDER_SVG_AS_XML_EMBED = 'svg_as_xml_embed'; // embed svg code directly in html (default for browser view)
24  const RENDER_SVG_AS_IMG_EMBED = 'svg_as_img_embed'; // embed svg base64 encoded in an img tag (default for HTML export)
25  const RENDER_SVG_AS_IMG_FILE = 'svg_as_img_file'; // refer to an svg file from an img tag (if called with output dir)
26 
27  const RENDER_PNG_AS_IMG_EMBED = 'png_as_img_embed'; // embed png base64 encoded in an img tag (default for PDF generation)
28  const RENDER_PNG_AS_IMG_FILE = 'png_as_img_file'; // refer to a png file from an img tag (if called with output dir)
29  const RENDER_PNG_AS_FO_FILE = 'png_as_fo_file'; // refer to a png file from an fo tag (for PDF generation with XSL-FO)
30 
34  protected static $_instance = null;
35 
39  protected $settings = null;
40 
44  protected $engine = null;
45 
49  protected $mathjax_url = '';
50 
54  protected $start_limiter = '';
55 
59  protected $end_limiter = '';
60 
64  protected $server_address = '';
65 
69  protected $server_timeout = 5;
70 
74  protected $rendering = self::RENDER_SVG_AS_XML_EMBED;
75 
79  protected $output = 'svg';
80 
84  protected $dpi = 150;
85 
89  protected $zoom_factor = 1.0;
90 
91 
97  protected $mimetex_url = URL_TO_LATEX;
98 
102  protected $mimetex_count = 0;
103 
109  protected $use_curl = true;
110 
114  protected $cache_dir = '';
115 
119  protected $default_options = array(
120  "format" => "TeX",
121  "math" => '', // TeX code
122  "svg" => true,
123  "mml" => false,
124  "png" => false,
125  "speakText" => false,
126  "speakRuleset" => "mathspeak",
127  "speakStyle" => "default",
128  "ex" => 6,
129  "width" => 1000000,
130  "linebreaks" => false,
131  );
132 
133 
137  protected function __construct()
138  {
139  // initiate the settings for browser as default
140  include_once "./Services/Administration/classes/class.ilSetting.php";
141  $this->settings = new ilSetting("MathJax");
142  $this->init(self::PURPOSE_BROWSER);
143 
144  // set the connection method
145  $this->use_curl = extension_loaded('cURL');
146 
147  // set the cache directory
148  $this->cache_dir = ilUtil::getWebspaceDir() . '/temp/tex';
149  }
150 
155  public static function getInstance()
156  {
157  if (self::$_instance === null) {
158  self::$_instance = new self;
159  }
160  return self::$_instance;
161  }
162 
169  public function init($a_purpose = self::PURPOSE_BROWSER)
170  {
171  // reset the choice of a former initialisation
172  unset($this->engine);
173 
174  // try server-side rendering first, set this engine, if possible
175  if ($this->settings->get('enable_server')) {
176  $this->server_address = $this->settings->get('server_address');
177  $this->server_timeout = $this->settings->get('server_timeout');
178 
179  if ($a_purpose == self::PURPOSE_BROWSER && $this->settings->get('server_for_browser')) {
180  $this->engine = self::ENGINE_SERVER;
181  // delivering svg directly in page may be faster than loading image files
182  $this->setRendering(self::RENDER_SVG_AS_XML_EMBED);
183  } elseif ($a_purpose == self::PURPOSE_EXPORT && $this->settings->get('server_for_export')) {
184  $this->engine = self::ENGINE_SERVER;
185  // offline pages must always embed the svg as image tags
186  // otherwise the html base tag may conflict with references in svg
187  $this->setRendering(self::RENDER_SVG_AS_IMG_EMBED);
188  } elseif ($a_purpose == self::PURPOSE_PDF && $this->settings->get('server_for_pdf')) {
189  $this->engine = self::ENGINE_SERVER;
190  // embedded png should work in most pdf engines
191  // details can be set by the rendering engine
192  $this->setRendering(self::RENDER_PNG_AS_IMG_EMBED);
193  } elseif ($a_purpose == self::PURPOSE_DEFERRED_PDF && $this->settings->get('server_for_pdf')) {
194  $this->engine = self::ENGINE_DEFERRED;
195  }
196  }
197 
198  // if server is not generally enabled or not activated for the intended purpose
199  // then set engine for client-side rendering, if possible
200  if (!isset($this->engine) && $this->settings->get('enable')) {
201  $this->engine = self::ENGINE_CLIENT;
202  $this->mathjax_url = $this->settings->get('path_to_mathjax');
203  $this->includeMathJax();
204 
205  switch ((int) $this->settings->get("limiter")) {
206  case 1:
207  $this->start_limiter = "[tex]";
208  $this->end_limiter = "[/tex]";
209  break;
210 
211  case 2:
212  $this->start_limiter = '<span class="math">';
213  $this->end_limiter = '</span>';
214  break;
215 
216  default:
217  $this->start_limiter = "\(";
218  $this->end_limiter = "\)";
219  break;
220  }
221  }
222 
223  // neither server nor client side rendering is enabled
224  // the use the older mimetex as fallback, if configured in ilias.ini.php
225  if (!isset($this->engine) && !empty($this->mimetex_url)) {
226  $this->engine = self::ENGINE_MIMETEX;
227  }
228 
229  // no engine available or configured
230  if (!isset($this->engine)) {
231  $this->engine = self::ENGINE_NONE;
232  }
233 
234  return $this;
235  }
236 
237 
243  public function setRendering($a_rendering)
244  {
245  switch ($a_rendering) {
246  case self::RENDER_SVG_AS_XML_EMBED:
247  case self::RENDER_SVG_AS_IMG_EMBED:
248  case self::RENDER_SVG_AS_IMG_FILE:
249  $this->rendering = $a_rendering;
250  $this->output = 'svg';
251  break;
252 
253  case self::RENDER_PNG_AS_IMG_EMBED:
254  case self::RENDER_PNG_AS_IMG_FILE:
255  case self::RENDER_PNG_AS_FO_FILE:
256  $this->rendering = $a_rendering;
257  $this->output = 'png';
258  break;
259  }
260  return $this;
261  }
262 
268  public function setDpi($a_dpi)
269  {
270  $this->dpi = (float) $a_dpi;
271  return $this;
272  }
273 
279  public function setZoomFactor($a_factor)
280  {
281  $this->zoom_factor = (float) $a_factor;
282  return $this;
283  }
284 
290  public function includeMathJax($a_tpl = null)
291  {
292  global $tpl;
293 
294  if ($a_tpl == null) {
295  $a_tpl = $tpl;
296  }
297 
298  if ($this->engine == self::ENGINE_CLIENT) {
299  $a_tpl->addJavaScript($this->mathjax_url);
300  }
301  }
302 
303 
316  public function insertLatexImages($a_text, $a_start = '[tex]', $a_end = '[/tex]', $a_dir = null, $a_path = null)
317  {
318  // is this replacement still needed?
319  // it was defined in the old ilUtil::insertLatexImages function
320  // perhaps it was related to jsmath
321  if ($this->engine != self::ENGINE_MIMETEX) {
322  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{" . "$1" . "}" . "$2", $a_text);
323  }
324 
325  // this is a fix for bug5362
326  $a_start = str_replace("\\", "", $a_start);
327  $a_end = str_replace("\\", "", $a_end);
328 
329  // current position to start the search for delimiters
330  $cpos = 0;
331  // find position of start delimiter
332  while (is_int($spos = ilStr::strIPos($a_text, $a_start, $cpos))) {
333  // find position of end delimiter
334  if (is_int($epos = ilStr::strIPos($a_text, $a_end, $spos + ilStr::strLen($a_start)))) {
335  // extract the tex code inside the delimiters
336  $tex = ilStr::subStr($a_text, $spos + ilStr::strLen($a_start), $epos - $spos - ilStr::strLen($a_start));
337 
338  // undo a code protection done by the deferred engine before
339  if (ilStr::subStr($tex, 0, 7) == 'base64:') {
340  $tex = base64_decode(substr($tex, 7));
341  }
342 
343  // omit the html newlines added by the ILIAS page editor
344  // handle custom newlines in JSMath (still needed?)
345  $tex = str_replace('<br>', '', $tex);
346  $tex = str_replace('<br/>', '', $tex);
347  $tex = str_replace('<br />', '', $tex);
348  $tex = str_replace('\\\\', '\\cr', $tex);
349 
350  // check, if tags go across div borders
351  if (is_int(ilStr::strPos($tex, '<div>')) || is_int(ilStr::strPos($tex, '</div>'))) {
352  // keep the original including delimiters, continue search behind
353  $cpos = $epos + ilStr::strLen($a_end);
354  }
355  else {
356  switch ($this->engine) {
357  case self::ENGINE_CLIENT:
358  // prepare code for processing in the browser
359  // add necessary html encodings
360  // use the configured mathjax delimiters
361  $tex = str_replace('<', '&lt;', $tex);
362  $replacement = $this->start_limiter . $tex . $this->end_limiter;
363  break;
364 
365  case self::ENGINE_SERVER:
366  // apply server-side processing
367  // mathjax-node expects pure tex code
368  // so revert any applied html encoding
369  $tex = html_entity_decode($tex, ENT_QUOTES, 'UTF-8');
370  $replacement = $this->renderMathJax($tex, $a_dir, $a_path);
371  break;
372 
373  case self::ENGINE_MIMETEX:
374  // use mimetex
375  $replacement = $this->renderMimetex($tex, $a_dir, $a_path);
376  break;
377 
378  case self::ENGINE_DEFERRED:
379  // protect code to save it for post production
380  $replacement = '[tex]' . 'base64:' . base64_encode($tex) . '[/tex]';
381  break;
382 
383  case self::ENGINE_NONE:
384  default:
385  // show only the pure tex code
386  $replacement = htmlspecialchars($tex);
387  break;
388  }
389 
390  // replace delimiters and tex code with prepared code or generated image
391  $a_text = ilStr::subStr($a_text, 0, $spos) . $replacement . ilStr::subStr($a_text, $epos + ilStr::strLen($a_end));
392 
393  // continue search behind replacement
394  $cpos = $spos + ilStr::strLen($replacement);
395  }
396  }
397  else {
398  // end delimiter position not found => stop search
399  break;
400  }
401 
402  if ($cpos >= ilStr::strlen($a_text)) {
403  // current position at the end => stop search
404  break;
405  }
406  }
407  return $a_text;
408  }
409 
410 
419  protected function renderMathJax($a_tex, $a_output_dir = null, $a_image_path = null)
420  {
422  $options['math'] = $a_tex;
423  $options['dpi'] = $this->dpi;
424 
425  switch ($this->output) {
426  case 'png':
427  $options['svg'] = false;
428  $options['png'] = true;
429  $suffix = ".png";
430  break;
431 
432  case 'svg':
433  default:
434  $options['svg'] = true;
435  $options['png'] = false;
436  $suffix = ".svg";
437  break;
438  }
439 
440  // store cached rendered image in cascading sub directories
441  $hash = md5($a_tex . '#' . $this->dpi);
442  $file = $this->cache_dir . '/' . substr($hash, 0, 4) . '/' . substr($hash, 4, 4) . '/' . $hash . $suffix;
443 
444  try {
445  if (!is_file($file)) {
446  // file has to be rendered
447  if ($this->use_curl) {
448  $curl = curl_init($this->server_address);
449  curl_setopt($curl, CURLOPT_HEADER, false);
450  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
451  curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
452  curl_setopt($curl, CURLOPT_POST, true);
453  curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($options));
454  curl_setopt($curl, CURLOPT_TIMEOUT, $this->server_timeout);
455 
456  $response = curl_exec($curl);
457  $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
458  curl_close($curl);
459 
460  if ($status != 200) {
461  $lines = explode("\n", $response);
462  return "[TeX rendering failed: " . $lines[1] . " " . htmlspecialchars($a_tex) . "]";
463  }
464  } else {
465  $context = stream_context_create(
466  array(
467  'http' => array(
468  'method' => 'POST',
469  'content' => json_encode($options),
470  'header' => "Content-Type: application/json\r\n",
471  'timeout' => $this->server_timeout,
472  'ignore_errors' => true
473  )
474  )
475  );
476  $response = @file_get_contents($this->server_address, false, $context);
477  if (empty($response)) {
478  return "[TeX rendering failed: " . htmlspecialchars($a_tex) . "]";
479  }
480  }
481 
482  // create the parent directories recursively
483  @mkdir(dirname($file), 0777, true);
484 
485  // save a rendered image to the temp folder
486  file_put_contents($file, $response);
487  }
488 
489  // handle output of images for offline usage without embedding
490  if (isset($a_output_dir) && is_dir($a_output_dir)) {
491  @copy($file, $a_output_dir . '/' . $hash . $suffix);
492  $src = $a_image_path . '/' . $hash . $suffix;
493  } else {
494  $src = ILIAS_HTTP_PATH . '/' . $file;
495  }
496 
497  // generate the image tag
498  switch ($this->output) {
499  case 'png':
500  list($width, $height) = getimagesize($file);
501  $width = round($width * $this->zoom_factor);
502  $height = round($height * $this->zoom_factor);
503  $mime = 'image/png';
504  break;
505 
506  case 'svg':
507  default:
508  $svg = simplexml_load_file($file);
509  $width = round($svg['width'] * $this->zoom_factor);
510  $height = round($svg['height'] * $this->zoom_factor);
511  $mime = 'image/svg+xml';
512  break;
513  }
514 
515 
516  // generate the image tag
517  switch ($this->rendering) {
518  case self::RENDER_SVG_AS_XML_EMBED:
519  $html = empty($response) ? file_get_contents($file) : $response;
520  break;
521 
522  case self::RENDER_SVG_AS_IMG_EMBED:
523  case self::RENDER_PNG_AS_IMG_EMBED:
524  $html = '<img src="data:' . $mime . ';base64,'
525  . base64_encode(empty($response) ? file_get_contents($file) : $response)
526  . '" style="width:' . $width . '; height:' . $height . ';" />';
527  break;
528 
529  case self::RENDER_SVG_AS_IMG_FILE:
530  case self::RENDER_PNG_AS_IMG_FILE:
531  $html = '<img src="' . $src . '" style="width:' . $width . '; height:' . $height . ';" />';
532  break;
533 
534  case self::RENDER_PNG_AS_FO_FILE:
535  $html = '<fo:external-graphic src="url(' . realpath($file) . ')"'
536  . ' content-height="' . $height . 'px" content-width="' . $width . 'px"></fo:external-graphic>';
537  break;
538 
539  default:
540  $html = htmlspecialchars($a_tex);
541  break;
542  }
543 
544  return $html;
545  } catch (Exception $e) {
546  return "[TeX rendering failed: " . $e->getMessage() . "]";
547  }
548  }
549 
550 
559  protected function renderMimetex($a_tex, $a_output_dir = null, $a_image_path = null)
560  {
561  $call = $this->mimetex_url . '?'
562  . rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', $a_tex))));
563 
564  if (empty($a_output_dir)) {
565  $html = '<img alt="' . htmlentities($a_tex) . '" src="' . $call . '" />';
566  } else {
567  $cnt = $this->mimetex_count++;
568 
569  // get image from cgi and write it to file
570  $fpr = @fopen($call, "r");
571  $lcnt = 0;
572  if ($fpr) {
573  while (!feof($fpr)) {
574  $buf = fread($fpr, 1024);
575  if ($lcnt == 0) {
576  if (is_int(strpos(strtoupper(substr($buf, 0, 5)), "GIF"))) {
577  $suffix = "gif";
578  } else {
579  $suffix = "png";
580  }
581  $fpw = fopen($a_output_dir . "/img" . $cnt . "." . $suffix, "w");
582  }
583  $lcnt++;
584  fwrite($fpw, $buf);
585  }
586  fclose($fpw);
587  fclose($fpr);
588  }
589 
590  $html = '<img alt="' . htmlentities($a_tex) . '" src=' . $a_image_path . '/img"' . $cnt . '.' . $suffix . '/' . '" />';
591  }
592 
593  return $html;
594  }
595 
600  public function getCacheSize()
601  {
602  $cache_dir = realpath($this->cache_dir);
603 
604  if (!is_dir($cache_dir)) {
605  $size = 0;
606  } else {
608  }
609 
610  $type = array("k", "M", "G", "T");
611  $size = $size / 1024;
612  $counter = 0;
613  while ($size >= 1024) {
614  $size = $size / 1024;
615  $counter++;
616  }
617 
618  return(round($size, 1) . " " . $type[$counter] . "B");
619  }
620 
624  public function clearCache()
625  {
626  ilUtil::delDir($this->cache_dir);
627  }
628 }
static $_instance
$size
Definition: RandomTest.php:84
renderMimetex($a_tex, $a_output_dir=null, $a_image_path=null)
Render image from tex code using mimetex.
Class for Server-side generation of latex formulas.
insertLatexImages($a_text, $a_start='[tex]', $a_end='[/tex]', $a_dir=null, $a_path=null)
Replace tex tags with formula image code New version of ilUtil::insertLatexImages.
settings()
Definition: settings.php:2
static strLen($a_string)
Definition: class.ilStr.php:78
$context
Definition: webdav.php:25
includeMathJax($a_tpl=null)
Include Mathjax javascript in a template.
const ENGINE_MIMETEX
static strPos($a_haystack, $a_needle, $a_offset=null)
Definition: class.ilStr.php:30
const RENDER_PNG_AS_IMG_EMBED
$type
renderMathJax($a_tex, $a_output_dir=null, $a_image_path=null)
Render image from tex code using the MathJax server.
$tpl
Definition: ilias.php:10
const ENGINE_SERVER
init($a_purpose=self::PURPOSE_BROWSER)
Initialize the usage This must be done before any rendering call.
const PURPOSE_PDF
const RENDER_SVG_AS_IMG_FILE
setRendering($a_rendering)
Set the image type rendered by the server.
static subStr($a_str, $a_start, $a_length=null)
Definition: class.ilStr.php:15
static strIPos($a_haystack, $a_needle, $a_offset=null)
Definition: class.ilStr.php:48
setDpi($a_dpi)
Set the dpi of the rendered images.
const PURPOSE_BROWSER
__construct()
Singleton: protected constructor.
const RENDER_PNG_AS_IMG_FILE
setZoomFactor($a_factor)
Set the zoom factor for images.
const ENGINE_CLIENT
getCacheSize()
Get the size of the image cache.
const PURPOSE_EXPORT
const RENDER_PNG_AS_FO_FILE
static dirsize($directory)
get size of a directory or a file.
clearCache()
Clear the cache of rendered graphics.
static getInstance()
Singleton: get instance.
const RENDER_SVG_AS_IMG_EMBED
const ENGINE_DEFERRED
$response
static delDir($a_dir, $a_clean_only=false)
removes a dir and all its content (subdirs and files) recursively
static getWebspaceDir($mode="filesystem")
get webspace directory
$html
Definition: example_001.php:87
const RENDER_SVG_AS_XML_EMBED
const PURPOSE_DEFERRED_PDF
const ENGINE_NONE