<?php

/**
 * @extensione  Extendible TM - Plugin for Marlev Templates
 * @author      Lev Milicenco
 * @copyright   (c) Marlev.it - Itroom SRLS - 2022. All rights reserved.
 */
defined('_JEXEC') or die;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\Registry\Registry;
require_once JPATH_ROOT . '/administrator/components/com_tmarlevv2/src/Helper/plugin_helper.php';
use Marlev\Component\Tmarlevv2\Administrator\Helper\ml_plugin_helper;
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
//for_use

class plgSystemExtendibletm extends CMSPlugin
{

    public function onAfterRoute()
    {
        $app = Factory::getApplication();
        if ($app->isClient('site')) {
            $plugin_helper = new ml_plugin_helper();
            $template = $app->getTemplate(true);
            $lifemode = preg_replace("&[^a-zA-Z0-9]&", "", $app->input->getString("tm-life", false));

            if ($lifemode != false) {
                if (file_exists(JPATH_ADMINISTRATOR . "/cache/marlev_lifemode/" . $lifemode . ".php") && is_file(JPATH_ADMINISTRATOR . "/cache/marlev_lifemode/" . $lifemode . ".php")) {
                    $get_content = file_get_contents(JPATH_ADMINISTRATOR . "/cache/marlev_lifemode/" . $lifemode . ".php");
                    preg_match('&>\n(.*)$&', $get_content, $match);
                    if (isset($match[1])) {
                        $get = array();
                        $get_life = json_decode($match[1]);
                        $registry = new Registry;
                        $registry->loadString($get_life->layout);
                        $get['tlayout'] = $registry->toArray();
                        $get['tid'] = "null";

                        $registry = new Registry;
                        $registry->loadString($get_life->params);
                        $get[] = $registry->toArray();
                        $get["socials"] = $plugin_helper::socials_helper($template);
                        foreach ($get as $key => $value) {
                            $template->params->set($key, $value);
                        }
                        return true;
                    }
                }
            }


            $cachegroup = 'marlev_layout';
            $cache_id = 'ml_template_' . $template->id;

            $get_cache = $plugin_helper->prepare_cache($cache_id, $cachegroup);
            if ($get_cache === false) {
                $get = $plugin_helper->get_layout($template->id, $template->template, $template);
                $plugin_helper->set_cache($get, $cache_id, $cachegroup);
            } else {
                $get = json_decode($get_cache, true);
            }
            if (!is_array($get)) {
                return;
            }

            foreach ($get as $key => $value) {
                $template->params->set($key, $value);
            }
                $this->antispam($app,$template);
        }
    }
    protected static function antispam($app,$template){
       $view = $app->input->get("view");
        $option = $app->input->get("option");
        if ($template->params->get('enable_antispam', 1) == 1 && $option == "com_contact" && $view == 'contact') {
            $jform = $app->input->post->get("jform");
            if (isset($jform["contact_name"]) && isset($jform["contact_email"]) && isset($jform["formlastname"]) && !empty($jform["contact_name"]) && !empty($jform["contact_email"]) && !empty($jform["formlastname"])) {
                exit();
            }
        }
    }
    public function onAfterRender()
    {
        $app = Factory::getApplication();
        if ($app->isClient('site')) {
            $lifemode = preg_replace("&[^a-zA-Z0-9]&", "", $app->input->getString("tm-life", false));
            if ($lifemode != false) {
                define("TM_LIFEMODE", $lifemode);
                if (file_exists(JPATH_ADMINISTRATOR . "/cache/marlev_lifemode/" . $lifemode . ".php") && is_file(JPATH_ADMINISTRATOR . "/cache/marlev_lifemode/" . $lifemode . ".php")) {
                    $get_content = file_get_contents(JPATH_ADMINISTRATOR . "/cache/marlev_lifemode/" . $lifemode . ".php");
                    preg_match('&.*\n(.*)$&', $get_content, $match);
                    if (isset($match[1])) {
                        $get_life = json_decode($match[1]);
                        $css = str_replace("../../../../", Uri::base(), $get_life->css);
                        $html = Factory::getApplication()->getBody();
                        $html = str_replace('</head>', "<style>" . $css . "</style>" . PHP_EOL . '</head>', $html);
                        $new = preg_replace_callback('/href="([^"#]*)"/isU', "self::add_query_to_link", $html);
                        Factory::getApplication()->setBody($new);
                        return;
                    }
                }
            }
            $template = $app->getTemplate(true);
            $marlev = $this->get_marlev($template->template);
            if ($marlev === false || $marlev['result'] === "allowed") {
                return;
            }

            $replace = self::for_front_end($template->template);
            $html = Factory::getApplication()->getBody();
            $html = str_replace(['</head>', '</body>'], $replace, $html);
            Factory::getApplication()->setBody($html);
        } elseif (Factory::getApplication()->input->getString("option") == "com_tmarlevv2") {
            $id = Factory::getApplication()->input->getInt("id");
            $db = Factory::getDbo();
            $query = $db->getQuery(true);
            $query->select('template');
            $query->from('#__template_styles');
            $query->where('id=' . $db->Quote($id));
            $db->setQuery($query);
            $tm = $db->loadResult();
            $marlev = self::get_marlev($tm);

            if (version_compare(JVERSION, '4')) {
                $getBody = Factory::getApplication()->getBody();
                $rewrited = preg_replace('#<script.*admin-menu\.js.*</script>#', "", $getBody);
                $rewrited = preg_replace_callback("#<\s*body[^>]*>.*<\s*/\s*body[^>]*>#si", array('plgSystemExtendibletm','run_tmarlev_helper'), $rewrited);
                Factory::getApplication()->setBody($rewrited);
            }
            if ($marlev === false || $marlev['result'] === "allowed") {
                return;
            }

            $messagge = '<div class="license-required">';
            $messagge .= self::switch_hosting($tm);
            if ($marlev['trial'] === "allowed") {
                $messagge .= self::get_trial($marlev['domain'], $tm);
            } elseif (!ini_get('allow_url_fopen')) {
                $app = Factory::getApplication();
                $lang = $app->getLanguage();
                $langtag = explode("-", $lang->getTag());
                if ($langtag[0] == "it") {
                    $messagge .= '<br/>*Versione di prova non disponibile con allow_url_fopen=Off<br/> Attiva allow_url_fopen nella configurazione  PHP oppure contatta il tuo Hosting Provider';
                } else {
                    $messagge .= '<br/>*Trial version is not avvaiable with allow_url_fopen=Off<br/> Enable allow_url_fopen in your PHP configuration or contact your Hosting Provider';
                }
            }
            $messagge .= '</div>';
            $html = Factory::getApplication()->getBody();
            $html = str_replace("<!--ml-append-messagge-->", $messagge, $html);
            Factory::getApplication()->setBody($html);
        }
    }
    protected function add_query_to_link($match)
    {
        if (preg_match("&\?&", $match[1])) {
            return 'href="'.$match[1] . "&amp;tm-life=" . TM_LIFEMODE.'"';
        } else {
            return 'href="'.$match[1] . "?tm-life=" . TM_LIFEMODE.'"';
        }

    }

    protected function run_tmarlev_helper($match)
    {
        $patern = array(
            '+<div\sid="wrapper".*<\/div>+siU',
            '+<nav\sclass="main-nav-container".*<\/nav>+siU',
            '+<div\sid="subhead-container.*<\/div>+siU',
        );
        $replacement = array("", "", "", "");
        return preg_replace($patern, $replacement, $match[0]);

    }

    protected function get_trial($domain, $templatename)
    {
        $app = Factory::getApplication();
        $lang = $app->getLanguage();
        $langtag = explode("-", $lang->getTag());
        $return = new \stdClass();
        $triallink = "https://itroom.it/trial-version?domainname=" . $domain . "&vendor=itroom&templatename=" . $templatename;
        if ($langtag[0] == "it") {
            $l_message = "Attiva la versione di prova";
            $_alert = '<br/><span class="small">*Dopo l\'avvenuta attivazione della versione di prova, aggiorna la pagina corrente.</span>';
        } else {
            $l_message = "Activate trial version";
            $_alert = '<br/><span class="small">*After the activation of trial version, update the current page</span>';
        }
        return "<div style='text-align:center;margin-bottom:10px;'><a class='btn-primary btn' target='_blank' href='" . $triallink . "'>" . $l_message . "</a>" . $_alert . "</div>";
    }

    protected function for_front_end($template)
    {
        $virtid = substr(md5(rand(1, 35) . time()), 0, 12);
        $virtid = "y" . substr(md5($template), 0, 12);
        $div = "<div class='" . $virtid . "' style='position:fixed !important; bottom: 0px !important; z-index:99999999 !important; background: red !important; width:100% !important; height:100px !important; left:0 !important; text-align: center; color:white !important; padding-top:10px; !important; visibility:visible !important; display:block !important;'>";
        $messagge = $div . self::switch_hosting($template) . '</div>';
        $replace = array();
        $replace[] = self::get_ml_script($virtid, $template, $messagge) . '</head>';
        $replace[] = $messagge . '</body>';
        return $replace;
    }

    protected function get_ml_script($virtid, $templatename, $messagge)
    {
        $return = '<script type="text/javascript">';
        $return .= '      function show_abuse() {';
        $return .= '   return  jQuery("body").append(" ' . $messagge . '")}';
        $return .= '   function checker_block() {';
        $return .= '    setInterval(function () {';
        $return .= '       var el = jQuery(".' . $virtid . '");';
        $return .= '      if (el.length == 0) {';
        $return .= '         show_abuse();';
        $return .= '        alert("Template ' . ucfirst($templatename) . '[Itroom Edition] is not authorized to run on this server");';
        $return .= '     }';
        $return .= '    else if (el.is(":hidden")) {';
        $return .= '        show_abuse();';
        $return .= '        el.css({"display": "block", "visible": "visible"});';
        $return .= '        alert("Template ' . ucfirst($templatename) . '[Itroom Edition] is not authorized to run on this server");';
        $return .= '    }';
        $return .= '   },' . rand(900, 1300) . ');';
        $return .= '   }';
        $return .= '  jQuery(document).ready(function () {  checker_block(); });';
        $return .= ' </script>';
        return $return;
    }

    protected function get_marlev($template)
    {
        $fl = JPATH_ROOT . "/templates/" . $template . "/templateDetails.xml";
        if (is_file($fl)) {
            $xml = simplexml_load_file($fl);
            if (isset($xml->{'updateservers'}->{'server'})) {
                $exp = explode("&", $xml->{'updateservers'}->{'server'});
                if (isset($exp[1]) && $exp[1] == 'type=free') {

                    return self::checker_license();
                }
            }
        }
        return false;
    }

    static function checker_license()
    {
        $sem = 7;
        $odin = 1;
        if (filter_input(INPUT_SERVER, "SERVER_ADDR")) {
            $requestaddr = filter_input(INPUT_SERVER, "SERVER_ADDR");
            $requestname = filter_input(INPUT_SERVER, "SERVER_NAME");
        } else {
            $requestaddr = $_SERVER["SERVER_ADDR"];
            $requestname = $_SERVER["SERVER_NAME"];
        }
        $jbase = strpos(Uri::base(), "localhost");
        $dva = 2;
        $alloweds = array($odin . $dva . $sem . ".0.0." . $odin, "::1");
        $risposta = array("result" => "denied", "trial" => "denied", "domain" => $requestname);
        if (in_array($requestaddr, $alloweds) && $requestname == "localhost" && $jbase) {
            $risposta = array("result" => "allowed", "trial" => "denied");
        }
        if ($risposta["result"] == "denied") {
            $risposta = self::validate_domainip($requestaddr, $requestname, $risposta);
        }
        return $risposta;
    }

    static function validate_domainip($requestaddr, $requestname, $risposta)
    {
        $temip = "?tempmip=" . $requestaddr;
        $temname = "&domainname=" . $requestname;
        $mirors = array("license.itroom.eu", "license-mirror1.itroom.eu", "license-mirror2.itroom.eu");
        foreach ($mirors as $key => $value) {
            if (ini_get('allow_url_fopen') && $xml = simplexml_load_file('https://' . $value . '/template_checker.php' . $temip . $temname)) {
                $risposta["result"] = trim($xml->allowed);
                $risposta["trial"] = trim($xml->trial);
                break;
            }
        }
        return $risposta;
    }

    static protected function switch_hosting($templatename)
    {
        $app = Factory::getApplication();
        $lang = $app->getLanguage();
        $langtag = explode("-", $lang->getTag());
        $buylink = "https://itroom.it/buytemplate.php?templatename=" . $templatename . "&lang=" . $langtag[0];
        if ($langtag[0] == "it") {
            return "<span style='font-size:14px; font-weight:bold;'>Template " . ucfirst($templatename) . " [IE] </span><br/> Template " . ucfirst($templatename) . " [Itroom Edition]  &egrave; autorizzato a funzionare solo nei servers di itroom.it oppure in localhost.<br/> Per poter continuare ad utilizzare il template, sposta il sito su Hosting di https://itroom.it oppure <a style='color:white; text-decoration:underline;'href='" . $buylink . "' >acquista la versione commerciale di Template " . ucfirst($templatename) . "</a>";
        } else {
            return "<span style='font-size:14px; font-weight:bold;'>Template " . ucfirst($templatename) . " [IE] </span><br/> Template " . ucfirst($templatename) . " [Itroom Edition]  is authorized to work only on the servers of itroom.it or in the localhost.<br/> In order to continue using the template, move your site to https://itroom.it Hosting Service or  <a style='color:white;  text-decoration:underline;'href='" . $buylink . "' >buy the commercial version of Template " . ucfirst($templatename) . "</a>";
        }
    }

}
