<?php
/**
* @copyright	Copyright (C) 2020 SiteGuarding.com
* @license		GNU/GPL, see LICENSE.php
* @contact		team@siteguarding.com
* @author		SiteGuarding.com
*/

defined( '_JEXEC' ) or die( 'Restricted access' );

/**
 * Website Antivirus Scanner for Joomla Plugin
 */


if(class_exists('JPlugin')) {
    class DynamicParentJMWAScannerPlugin extends JPlugin {}
} else {
    class DynamicParentJMWAScannerPlugin extends Joomla\CMS\Plugin\CMSPlugin {}
}
	
class plgSystemjmwascannerplugin extends DynamicParentJMWAScannerPlugin
{

	public function __construct(&$subject, $config)
	{
		parent::__construct($subject, $config);

	}
	
	public function isAdmin() {
		$app   = (class_exists('\Joomla\CMS\Factory')) ? \Joomla\CMS\Factory::getApplication() : JFactory::getApplication();
		if (JVERSION < 4) {
			return $app->isAdmin();
		}
		return $app->isClient('admin');
	}

	public function onAfterRender()
	{
		$app   = (class_exists('\Joomla\CMS\Factory')) ? \Joomla\CMS\Factory::getApplication() : JFactory::getApplication();
		
		if (!$this->isAdmin() && $this->isEnabled()) {

			$sHtml = $app->getBody();

			if (strlen($_SERVER['REQUEST_URI']) < 5 && strpos($sHtml, 'sg_protected_by') === false)
			{
					  $links = array(
						'https://www.siteguarding.com/en/',
						'https://www.siteguarding.com/en/website-antivirus',
						'https://www.siteguarding.com/en/protect-your-website',
						'https://www.siteguarding.com/en/services/malware-removal-service'
					  );
					  $link = $links[ mt_rand(0, count($links)-1) ];
					
				$protectedBy = '<div class="sg_protected_by" style="font-size:10px; padding:0 2px;position: fixed;bottom:0;right:0;z-index:1000;text-align:center;background-color:#F1F1F1;color:#222;opacity:0.8;">Protected with <a style="color:#4B9307" href="'.$link.'" target="_blank" title="Website Security services. Website Malware removal. Website Antivirus protection.">SiteGuarding.com Antivirus Protection</a></div></body>';
					
				$sHtml = str_replace('</body>', $protectedBy, $sHtml);
			}	

			

			$app->setBody($sHtml);
		}
	}

    public function isEnabled()
    {
        $dbo = JFactory::getDbo();
  
        $table_name = $dbo->getPrefix() . 'plgwap2_config';
		$tables = $dbo->getTableList();

        if (!in_array($table_name, $tables)) return false;

		$query = $dbo->getQuery(true);  
		$query->select(array('*'));
		$query->from($table_name);
		$query->where("var_name = 'show_protectedby'");
		$dbo->setQuery($query);
		$row = $dbo->loadObjectList();
		if (!$row) return false;
        return $row[0]->var_value;
    }


}
