<?php
/**
 * LaTeX common syntax base
 * 
 * Primary Author: Wizardry and Steamworks <wizardry.steamworks@outlook.com>
 * @license GPL 2
 */

if(!defined('DOKU_INC')) die();
require_once(__DIR__ . '/class.latexrender.php');

abstract class syntax_plugin_latexwas_common extends DokuWiki_Syntax_Plugin {
    public $_latex;

    public function __construct() {
        global $conf;
        $namespace = $this->getConf('latex_namespace');
        $meddir = $conf['mediadir'] . '/' . strtr($namespace, ':', '/');
        
        $this->_mkpath($meddir, $conf['dmode']);
        $this->_mkpath($meddir . '/tmp', $conf['dmode']);

        $this->_latex = new LatexRender(
            $meddir, 
            DOKU_BASE . 'lib/exe/fetch.php?media=' . $namespace . ':', 
            $meddir . '/tmp'
        );

        $this->_latex->_latex_path = $this->getConf("latex_path");
        $this->_latex->_dvips_path = $this->getConf("dvips_path");
        $this->_latex->_convert_path = $this->getConf("convert_path") . ' ' . $this->getConf("convert_options");
        $this->_latex->_identify_path = $this->getConf("identify_path");
        $this->_latex->_image_format = $this->getConf("image_format");
        $this->_latex->_xsize_limit = $this->getConf("xsize_limit");
        $this->_latex->_ysize_limit = $this->getConf("ysize_limit");
        $this->_latex->_string_length_limit = $this->getConf("string_length_limit");
        $this->_latex->_preamble = $this->getConf("preamble");
        $this->_latex->_postamble = $this->getConf("postamble");
    }

    public function getType() { return 'protected'; }
    public function getSort() { return 405; }

    protected function el($tag, $attr = [], $content = '', $selfClosing = false) {
        $html = "<{$tag}";
        foreach ($attr as $k => $v) { $html .= " {$k}=\"" . htmlspecialchars($v, ENT_QUOTES, 'UTF-8') . "\""; }
        if ($selfClosing) return $html . ' />';
        return $html . ">" . $content . "</{$tag}>";
    }

    protected function _mkpath($path, $dmask = 0777) {
        if (@mkdir($path, $dmask) || file_exists($path)) return true;
        return ($this->_mkpath(dirname($path), $dmask) && mkdir($path, $dmask));
    }

    public function render($mode, Doku_Renderer $renderer, $data) {
        if ($data[1] !== DOKU_LEXER_UNMATCHED) return true;
        if ($mode === 'xhtml') {
            $url = $this->_latex->getFormulaURL($data[0]);
            $title = $url ? $data['title'] : "Render Error " . $this->_latex->_errorcode;
            if (!$url) $url = DOKU_BASE . 'lib/plugins/latexwas/images/renderfail.png';
            
            $renderer->doc .= $this->el('img', [
                'src' => $url,
                'class' => $data['class'],
                'alt' => $data[0],
                'title' => $title
            ], '', true);
            return true;
        }
        return false;
    }
}
