<?php

if (MH_PLATFORM_GAMBIO >= 2.0) {
    if (method_exists('MainFactory', 'load_origin_class')) {
        MainFactory::load_origin_class('Smarty');
    }
}


if (!class_exists('Smarty')) {

    if (version_compare(phpversion(), '7.1.0') >= 0) {
        // load smarty 4+ if not exists
        require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/Smarty_4/libs/Smarty.class.php'); // include smarty
    } else {
        // load smarty 3.1+ if not exists
        require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/Smarty_3/SmartyBC.class.php'); // include smarty
    }


}


class mh_Smarty extends Smarty
{

    var $wrapper_version;

    var $caching = null;
    var $template_dir = null;
    var $compile_dir = null;
    var $config_dir = null;
    var $cache_dir = null;
    var $compile_check = null;
    var $compile_id = null;

    var $legacy_init_done = false;

    public function __construct(array $options = array())
    {

        $version = $this->getVersion($this);
        if (version_compare($version, '4', '>=')) {
            parent::__construct();
            $this->wrapper_version = 'S4';
            if (!isset($this->registered_plugins['block']['php'])) {
                // register {php} tag
//                $this->registerPlugin('block', 'php', 'mh_smarty_php_tag');
            }

            if (!isset($this->registered_plugins['modifier']['in_array'])) {
                $this->registerPlugin('modifier', 'in_array', 'smarty_modifier_in_array');
            }
            if (method_exists('Smarty', 'muteUndefinedOrNullWarnings')) {
                $this->muteUndefinedOrNullWarnings();
            }

        } elseif (version_compare($version, '3.1.31', '>=')) {
            parent::__construct();
            $this->wrapper_version = 'S313';

            if (!isset($this->registered_plugins['block']['php'])) {
                // register {php} tag
                $this->registerPlugin('block', 'php', 'mh_smarty_php_tag');
            }

        } elseif ((float)$version >= 3.1) {
            parent::__construct($options);
            // version 3.1
            $this->wrapper_version = 'S31';


            if (!isset($this->smarty->registered_plugins['block']['php'])) {
                // register {php} tag
                $this->registerPlugin('block', 'php', 'mh_smarty_php_tag');
            }
        } elseif ((float)$version >= 3 && (float)$version < 3.1) {
            // not supported
            echo "Smarty 3.0 is not supported";
            mh_exit();

        } else {

            if (method_exists('Smarty', 'Smarty')) {
                Smarty::Smarty();
            } else {
                parent::__construct();
            }

            $this->wrapper_version = 'S26';
        }

        $this->setErrorReporting(E_ALL & ~E_NOTICE & ~E_WARNING);

        $this->setCaching(mh_cfg('MAILBEEZ_CONFIG_TEMPLATE_ENGINE_CACHING'));
        $this->setCompileDir(mh_cfg('MAILBEEZ_CONFIG_TEMPLATE_ENGINE_COMPILE_DIR'));
        $this->setTemplateDir(mh_cfg('MAILBEEZ_CONFIG_TEMPLATE_ENGINE_TEMPLATE_DIR'));
        $this->setConfigDir(mh_cfg('MAILBEEZ_CONFIG_TEMPLATE_ENGINE_CONFIG_DIR'));
        $this->setCacheDir(mh_cfg('MAILBEEZ_CONFIG_TEMPLATE_ENGINE_CACHE_DIR'));
        $this->setCompileCheck(true);
        $this->load_plugins();

        // handle strange errors on estugo / hostkraft servern
        switch (MH_PLATFORM) {
            case 'xtc':
            case 'gambio':
                if ($this->wrapper_version != 'S26' && $this->wrapper_version != 'S4') {
                    Smarty::muteExpectedErrors();
                }
                break;
        }
        return $this;
    }

    static function getVersion($smarty_obj)
    {
        if (class_exists('Smarty') && defined('Smarty::SMARTY_VERSION')) {
            // smarty 3.1.x
            $version_string = Smarty::SMARTY_VERSION;
        } else {
            // smarty 2.x, 3.0
            $version_string = $smarty_obj->_version;
        }
        return str_replace('Smarty-', '', $version_string);
    }


    function setCacheDir($cacheDir)
    {
        if ($cacheDir === null) {
            return $this;
        }

        if ($this->wrapper_version == 'S26') {
            $this->cache_dir = $cacheDir;
            return $this;
        } else {
            return parent::setCacheDir($cacheDir);
        }
    }


    function setConfigDir($configDir)
    {
        if ($configDir === null) {
            return $this;
        }

        if ($this->wrapper_version == 'S26') {
            $this->config_dir = $configDir;
            return $this;
        } else {
            return parent::setConfigDir($configDir);
        }
    }

    function getConfigDir($index = null)
    {
        if ($this->wrapper_version == 'S26') {
            return $this->config_dir;
        } else {
            return parent::getConfigDir($index);
        }
    }

    function getConfigVars($index = null, $searchParents = true)
    {
        if ($this->wrapper_version == 'S26') {
            return $this->get_config_vars($index);
        } else {
            return parent::getConfigVars($index, $searchParents);
        }
    }

    function configLoad($config_file, $sections = null, $scope = null)
    {
        if ($this->wrapper_version == 'S26') {
            parent::config_load($config_file, $sections, $scope);
            return true;
        } else {
            return parent::configLoad($config_file, $sections, $scope);
        }
    }


    function setCompileDir($compileDir)
    {
        if ($compileDir === null) {
            return $this;
        }

        if ($this->wrapper_version == 'S26') {
            $this->compile_dir = $compileDir;
            return $this;
        } else {
            return parent::setCompileDir($compileDir);
        }
    }


    function getCompileDir($index = null)
    {
        if ($this->wrapper_version == 'S26') {
            return $this->compile_dir;
        } else {
            return parent::getCompileDir();
        }
    }


    function setCaching($caching)
    {
        if ($caching === null) {
            return $this;
        }

        $this->caching = $caching;
        return $this;
    }


    function getCaching()
    {
        return $this->caching;
    }


    function setTemplateDir($templateDir, $isConfig = false)
    {
        if ($templateDir === null) {
            return $this;
        }

        if ($this->wrapper_version == 'S26') {
            $this->template_dir = $templateDir;
            return $this;
        } else {
            return parent::setTemplateDir($templateDir, $isConfig);
        }
    }


    function getTemplateDir($index = null, $isConfig = false)
    {
        if ($this->wrapper_version == 'S26') {
            return $this->template_dir;
        } else {
            return parent::getTemplateDir($index, $isConfig);
        }
    }


    function setCompileCheck($compile_check)
    {
        if ($compile_check === null) {
            return $this;
        }
        $this->compile_check = $compile_check;
        return $this;
    }


    function getCompileCheck()
    {
        return $this->compile_check;
    }

    function setCompileId($compile_id)
    {
        if ($compile_id === null) {
            return $this;
        }
        $this->compile_id = $compile_id;
        return $this;
    }

    function getCompileId()
    {
        return $this->compile_id;
    }


    function templateExists($template)
    {
        if ($this->wrapper_version == 'S26') {
            return parent::template_exists($template);
        } else {
            return parent::templateExists($template);
        }
    }


    function mh_getTemplateVars($varname = null, $_ptr = null, $search_parents = true)
    {
        if ($this->wrapper_version == 'S26') {
            return parent::get_template_vars($varname);
        } else {
            return parent::getTemplateVars($varname, $_ptr, $search_parents);
        }
    }

    function mh_setLanguage($language)
    {
        list($smarty_config_dir) = $this->getConfigDir();
        if (stream_resolve_include_path($smarty_config_dir . $language . '.conf')) {
            $this->assign('language', $language);
        } else {
            $this->assign('language', 'english');
        }
    }


    function assign($tpl_var, $value = null, $nocache = false)
    {
//        $this->init_legacy_attributes();
        return parent::assign($tpl_var, $value, $nocache);
    }


    function fetch($template = null, $cache_id = null, $compile_id = null, $parent = null, $display = false, $merge_tpl_vars = true, $no_output_filter = false)
    {
        $this->init_legacy_attributes();
        if (mh_cfg('MH_PLATFORM_GAMBIO_GX_CONFIGURATION')) {
            foreach ($this->getTemplateVars() as $templateVar => $templateVarValue) {
                $templateVarString = $this->getTemplateVars($templateVar);
                if (is_string($templateVarString)) {
                    if (stristr($templateVarString, '$smarty.const.')) {
                        $pattern = preg_quote('$smarty.const.') . '([0-9A-Za-z_]+)';
                        if (preg_match("/$pattern/", $templateVarString, $match)) {
                            $term = $match[0];
                            $constName = $match[1];
                            $templateVarString = str_replace('{' . $term . '}', '{mh_cfg key="' . $constName . '" default=""}', $templateVarString);
                            $templateVarString = str_replace($term, '{mh_cfg key="' . $constName . '" default=""}', $templateVarString);
                            $this->assign($templateVar, $templateVarString);
                        }
                    }
                }
            }
        }
        return parent::fetch($template, $cache_id, $compile_id, $parent, $display, $merge_tpl_vars, $no_output_filter);
    }


    function init_legacy_attributes()
    {
        if (!$this->legacy_init_done) {
            $this->setCaching($this->caching);
            $this->setTemplateDir($this->template_dir);
            $this->setCompileDir($this->compile_dir);
            $this->setConfigDir($this->config_dir);
            $this->setCompileCheck($this->compile_check);
            $this->setCompileId($this->compile_id);
//            $this->legacy_init_done = true;
        }
        return true;
    }


    function load_plugins()
    {
        $mhPluginDir = array();
        $mhPluginDir[] = MH_DIR_CONFIG . 'config_editor/smarty_plugins/';
        $mhPluginDir[] = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/smarty_plugins/';
        if ($this->wrapper_version == 'S26') {
            foreach ($mhPluginDir as $pDir) {
                $this->plugins_dir[] = $pDir;
            }
        } else {
            foreach ($mhPluginDir as $pDir) {
                $this->addPluginsDir($pDir);
            }
        }
        return true;
    }

    function clearCompiledTemplate($resource_name = null, $compile_id = null, $exp_time = null)
    {
        if ($this->wrapper_version == 'S26') {
            $this->clear_compiled_tpl();
            return $this;
        } else {
            return parent::clearCompiledTemplate($resource_name, $compile_id, $exp_time);
        }
    }


    public function setLeftDelimiter($left_delimiter)
    {
        if (method_exists('Smarty', 'setLeftDelimiter')) {
            return parent::setLeftDelimiter($left_delimiter);
        }
        $this->left_delimiter = $left_delimiter;
    }


    public function setRightDelimiter($right_delimiter)
    {
        if (method_exists('Smarty', 'setRightDelimiter')) {
            return parent::setRightDelimiter($right_delimiter);
        }
        $this->right_delimiter = $right_delimiter;
    }


    public function mh_fetch($template)
    {

        // default template to avoid overwrite
        if (mh_smarty_template_exists($this, $template . '.tpl.html')) {
            $real_template = $template;
        } elseif (mh_smarty_template_exists($this, 'default_' . $template . '.tpl.html')) {
            $real_template = 'default_' . $template;
        } else {

            list($dir) = $this->getTemplateDir();
            return "template <b>$dir - $template</b> not found";
        }

        $output = $this->fetch($real_template . '.tpl.html');
        return $output;
    }

    public function setErrorReporting($error_reporting)
    {
        if (method_exists('Smarty', 'setErrorReporting')) {
            return parent::setErrorReporting($error_reporting);
        }

    }

}

if (!function_exists('mh_smarty_php_tag')) {
    function mh_smarty_php_tag($params, $content, $template, &$repeat)
    {
        eval($content);

        return '';
    }
}

if (!function_exists('smarty_modifier_in_array')) {

    function smarty_modifier_in_array($needle, $haystack)
    {
        if (!is_array($haystack)) {
            return false;
        }
        return in_array($needle, $haystack);
    }
}
