* Original Author: Benjamin Zeiss * * @license GPL 2 */ class LatexRender { protected $_picture_path = ""; protected $_picture_path_httpd = ""; protected $_tmp_dir = ""; protected $_work_dir = ""; public $_keep_tmp = false; public $_latex_path = "latex"; public $_dvips_path = "dvips"; public $_convert_path = "convert"; public $_convert_options = ""; public $_identify_path = "identify"; public $_xsize_limit = 1000; public $_ysize_limit = 500; public $_string_length_limit = 2000; public $_image_format = "png"; public $_font_size = 10; public $_latexclass = "article"; public $_tmp_filename; public $_latex_tags_blacklist = [ '\\input', '\\include', '\\openin', '\\read', '\\openout', '\\write', '\\immediate', '\\special', '\\directlua', '\\latelua', '\\lua', '\\write18', '\\verbatiminput', '\\lstinputlisting', '\\inputminted', '\\ShellEscape', ]; public $_errorcode = 0; public $_errorextra = ""; public $_filename; public $_cmdoutput = ""; public $_preamble = ""; public $_postamble = ""; public function __construct($picture_path, $picture_path_httpd, $tmp_dir) { $this->_picture_path = $picture_path; $this->_picture_path_httpd = $picture_path_httpd; $this->_tmp_dir = $tmp_dir; } public function getPicturePath() { return $this->_picture_path; } public function getPicturePathHTTPD() { return $this->_picture_path_httpd; } public function getFormulaURL($latex_formula) { $latex_formula = str_ireplace(['>', '<'], ['>', '<'], $latex_formula); $this->latex_document = $this->_preamble . "\n" . trim($latex_formula) . "\n" . $this->_postamble; $formula_hash = md5($latex_formula); $filename = "img" . $formula_hash . '.' . $this->_image_format; $full_path_filename = $this->getPicturePath() . "/" . $filename; $this->_filename = $full_path_filename; if (is_readable($full_path_filename)) { return $this->getPicturePathHTTPD() . $filename; } if (strlen($latex_formula) > $this->_string_length_limit) { $this->_errorcode = 1; $this->_errorextra = ': ' . strlen($latex_formula); return false; } foreach ($this->_latex_tags_blacklist as $tag) { if (stristr($latex_formula, $tag)) { $this->_errorcode = 2; return false; } } if ($this->renderLatex($this->latex_document, $full_path_filename)) { return $this->getPicturePathHTTPD() . $filename; } return false; } protected function getDimensions($filename) { $output = $this->myexec([$this->_identify_path, $filename], $status); $result = preg_split('/\s+/', trim($output)); if (!isset($result[2])) return ["x" => 0, "y" => 0]; $dim = explode("x", $result[2]); return ["x" => (int)$dim[0], "y" => (int)$dim[1]]; } public function renderLatex($latex_document, $destination) { if (!is_dir($this->_tmp_dir)) return false; try { $this->_tmp_filename = bin2hex(random_bytes(16)); } catch (Exception $e) { $this->_tmp_filename = md5(uniqid('', true)); } $work = $this->_tmp_dir . '/' . $this->_tmp_filename; if (!@mkdir($work, 0700, true)) return false; $this->_work_dir = $work; $tex = $work . '/' . $this->_tmp_filename . '.tex'; $dvi = $work . '/' . $this->_tmp_filename . '.dvi'; $ps = $work . '/' . $this->_tmp_filename . '.ps'; $img = $work . '/' . $this->_tmp_filename . '.' . $this->_image_format; if (file_put_contents($tex, $latex_document) === false) { if (!$this->_keep_tmp) $this->cleanTemporaryDirectory(); $this->_errorcode = 4; return false; } $this->myexec([ $this->_latex_path, '-no-shell-escape', '-interaction=nonstopmode', '-halt-on-error', $tex, ], $status_latex, 30); if (!file_exists($dvi)) { if (!$this->_keep_tmp) $this->cleanTemporaryDirectory(); $this->_errorcode = 4; return false; } $this->myexec([$this->_dvips_path, $dvi, '-o', $ps], $status_dvips, 20); $convert = [$this->_convert_path]; $raw_options = trim((string)$this->_convert_options); if ($raw_options !== '') { $opts = str_getcsv($raw_options, ' '); if (is_array($opts)) $convert = array_merge($convert, $opts); } $convert[] = $ps; $convert[] = $img; $this->myexec($convert, $status_convert, 20); if ($status_dvips || $status_convert) { if (!$this->_keep_tmp) $this->cleanTemporaryDirectory(); $this->_errorcode = 6; return false; } $dim = $this->getDimensions($img); if ($dim["x"] > $this->_xsize_limit || $dim["y"] > $this->_ysize_limit) { if (!$this->_keep_tmp) $this->cleanTemporaryDirectory(); $this->_errorcode = 5; $this->_errorextra = ": " . $dim["x"] . "x" . $dim["y"]; return false; } $status_code = copy($img, $destination); if (!$this->_keep_tmp) $this->cleanTemporaryDirectory(); if (!$status_code) { $this->_errorcode = 7; return false; } return true; } protected function _env() { $env = [ 'PATH' => '/usr/bin:/bin', 'HOME' => $this->_work_dir, 'TEXMFOUTPUT' => $this->_work_dir, 'TEXMFVAR' => $this->_work_dir . '/texmf-var', 'LC_ALL' => 'C', ]; return $env; } protected function myexec($cmd, &$status, $timeout = 20) { if (is_string($cmd)) { $cmd = [$cmd]; } $status = 127; $descriptors = [ 0 => ['file', '/dev/null', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w'], ]; $process = proc_open($cmd, $descriptors, $pipes, $this->_work_dir ?: null, $this->_env()); if (!is_resource($process)) { $this->_cmdoutput .= "\n>>>>> " . implode(' ', array_map('escapeshellarg', $cmd)) . "\n --- spawn failed"; return ''; } stream_set_blocking($pipes[1], false); stream_set_blocking($pipes[2], false); $out = ''; $err = ''; $start = microtime(true); $timed_out = false; $max_output = 1048576; while (true) { $read = [$pipes[1], $pipes[2]]; $write = null; $except = null; $ready = @stream_select($read, $write, $except, 0, 200000); if ($ready > 0) { foreach ($read as $pipe) { $chunk = stream_get_contents($pipe); if ($chunk === false || $chunk === '') continue; if (strlen($out) + strlen($err) < $max_output) { if ($pipe === $pipes[1]) { $out .= $chunk; } else { $err .= $chunk; } } } } $st = proc_get_status($process); if (!$st['running']) { $status = (int)$st['exitcode']; break; } if ((microtime(true) - $start) > $timeout) { $timed_out = true; proc_terminate($process, 9); $status = 124; break; } usleep(50000); } $out .= stream_get_contents($pipes[1]); $err .= stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); $close_status = proc_close($process); if (!$timed_out && ($status < 0 || $status === 127)) { $status = $close_status; } $this->_cmdoutput .= "\n>>>>> " . implode(' ', array_map('escapeshellarg', $cmd)) . "\n" . trim($out . "\n" . $err) . "\n --- exit status " . $status . ($timed_out ? " (timed out)" : ""); return trim($out); } public function cleanTemporaryDirectory() { if ($this->_work_dir && is_dir($this->_work_dir)) { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($this->_work_dir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($it as $file) { if ($file->isDir()) { @rmdir($file->getPathname()); } else { @unlink($file->getPathname()); } } @rmdir($this->_work_dir); $this->_work_dir = ''; return; } if (!$this->_tmp_filename) return; foreach (['tex', 'aux', 'log', 'dvi', 'ps', $this->_image_format] as $ext) { @unlink($this->_tmp_dir . "/" . $this->_tmp_filename . "." . $ext); } } }