<?php

/**
 * @extensione  Extendible TM - Plugin for Marlev Templates
 * @author      Lev Milicenco
 * @copyright   (c) Marlev.it - Itroom SRLS - 2017. All rights reserved.
 */
defined('_JEXEC') or die;

class plgSystemExtendibletm extends JPlugin {

    public function onAfterRoute() {
        $app = JFactory::getApplication();
        if ($app->isSite()) {
            require_once JPATH_ADMINISTRATOR . "/components/com_tmarlevv2/helpers/plugin_helper.php";
            $template = $app->getTemplate(true);
            $cachegroup = 'marlev_layout';
            $cache_id = 'ml_template_' . $template->id;
            $plugin_helper = new ml_plugin_helper();
            $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);
            }
        }
    }

    public function OnAfterRender() {
        $app = JFactory::getApplication();
        if ($app->isSite()) {
            $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 = JFactory::getApplication()->getBody();
            $html = str_replace(['</head>', '</body>'], $replace, $html);
            JFactory::getApplication()->setBody($html);
        } elseif (JFactory::getApplication()->input->getString("option") === "com_tmarlevv2") {
            $id = JFactory::getApplication()->input->getInt("id");
            $db = JFactory::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 ($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')) {
                $lang = JFactory::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 = JFactory::getApplication()->getBody();
            $html = str_replace("<!--ml-append-messagge-->", $messagge, $html);
            JFactory::getApplication()->setBody($html);
        }
    }

    protected function get_trial($domain, $templatename) {
        $lang = JFactory::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(JUri::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) {
        $lang = JFactory::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>";
        }
    }

}
