<?php
/**
 * @version		$Id: opc.php$
 * @copyright	Copyright (C) 2005 - 2014 RuposTel.com
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// no direct access
defined('_JEXEC') or die;

jimport('joomla.plugin.plugin');
jimport( 'joomla.session.session' );

//stAn - this line will make sure that joomla uses it's session handler all the time. If any other extension is using $ _SESSION before this line, the session may not be consistent
JFactory::getSession(); 

// many 3rd party plugins faild on JParameter not found: 
jimport( 'joomla.html.parameter' );
// many 3rd party plugins also fail on JRegistry not found: 
jimport( 'joomla.registry.registry' );
// basic security classes should also be globally included: 
jimport( 'joomla.filesystem.folder' );
jimport( 'joomla.filesystem.file' );

if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR); 

if (!class_exists('vmPlugin'))
{
if (!JFactory::getApplication()->isAdmin())
require(JPATH_SITE.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'overrides'.DIRECTORY_SEPARATOR.'vmplugin.php'); 
}


/*
if(version_compare(JVERSION,'3.0.0','ge')) {
  if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR); 
  JLoader::register('JDate', JPATH_SITE.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'overrides'.DIRECTORY_SEPARATOR.'joomla3'.DIRECTORY_SEPARATOR.'date.php'); 
 // require_once(JPATH_SITE.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'overrides'.DIRECTORY_SEPARATOR.'joomla3'.DIRECTORY_SEPARATOR.'date.php'); 
// Joomla! 1.7 code here
}
*/


//require_once(JPATH_ROOT.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'language.php'); 
class plgSystemOpc extends JPlugin
{
	
	// vm3.0.6 forces automatic shipment and payment even when disabled: 
	public function plgVmOnCheckAutomaticSelectedShipment($cart, $prices, &$counter)
	{
		
		if (empty($counter)) $counter = 1; 
		return "-0"; 
	}
	public function plgVmOnCheckAutomaticSelectedPayment($cart, $prices, &$counter)
	{
		if (empty($counter)) $counter = 1; 
		return "-0"; 
	}


	
    public static $opc_jquery_loaded; 
    public function onBeforeCompileHead() {
	
	  if (empty(self::$opc_jquery_loaded)) return; 
	  if (self::_check(true)) 
	  {
	  
	  
	    return OPCplugin::modifyHeader(); 
	  }
	  
	}
	
	function plgVmConfirmedOrderUNITTEST ($cart, $order) {
		echo 'plgVmConfirmedOrder opc...'; 
	}
	
	
	function plgVmOnShowOrderBEPayment($virtuemart_order_id, $payment_method_id)
	{
		$virtuemart_order_id = (int)$virtuemart_order_id; 
		if (empty($virtuemart_order_id)) return; 
		
		JFactory::getLanguage()->load('com_onepage', JPATH_ADMINISTRATOR);
		
	
		$f = JPATH_SITE.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'vat.php'; 
		
		
		if (!file_exists($f)) return; 
		
		
		
 		require_once($f); 
	    
		
			require_once(JPATH_SITE.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'mini.php'); 
			
			$orders = OPCmini::getModel('orders'); 
			$order = $orders->getOrder($virtuemart_order_id); 
			
			if (empty($order['details'])) return; 
			if (empty($order['details']['BT'])) return; 
			
			if (isset($order['details']['BT']->opc_vat))
			{
				return OPCvat::plgVmOnShowOrderBEPayment($virtuemart_order_id, $payment_method_id, $order); 
			}
			
				
				 
	}
	
	
    public function onAfterRoute() {
	
    // to support opc vm fields: 
	JFactory::getLanguage()->load('com_onepage', JPATH_SITE); 
	
	  if (!self::_check())  return; 
	  
	  
	   require_once(JPATH_SITE.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'config.php');
	   
	   $opc_load_jquery = OPCConfig::getValue('opc_load_jquery', '', 0, false, false); 
	   self::$opc_jquery_loaded = (bool)$opc_load_jquery; 
	   if (!empty($opc_load_jquery))
	   {
	    require_once(JPATH_SITE.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'javascript.php');
		OPCJavascript::loadJquery();  
	
	   }
	
	   
	  

	  
	
	
	

	
	
	
	if (!OPCplugin::checkLoad()) return; 
	
	OPCplugin::loadShoppergroups();
	  
	if (!OPCplugin::isOPCcheckoutEnabled()) return;
	OPCplugin::getContinueLink(); 
	OPCplugin::getCache(); 

	  if (OPCplugin::alterActivation()) return; 
	  if (OPCplugin::alterRegistration()) return; 
	  
	  
	  
	  OPCplugin::enableSilentRegistration(); 
	  if (!OPCplugin::checkOPCtask()) return; 
	  OPCplugin::keyCaptchaSupport(); 
	  
	 
	  if (!OPCplugin::loadOPCcartView()) return; 
	  OPCplugin::fixVMbugVirtuemartUser(); 
	  OPCplugin::fixVMbugNewShippingAddress(); 
	  
	  OPCplugin::setItemid(); 
	  OPCplugin::loadOpcForLoggedUser(); 
	  OPCplugin::updateJoomlaCredentials(); 
	  OPCplugin::updateAmericanTax(); 
	
	  
	  
	  
	
	
	}
	
	
	public function onVmSiteController($controller)
	{
	   
	   if ($controller == 'opc')
	   if (!class_exists('VirtueMartControllerOpc'))
	    {
		   
		   
		   require_once(JPATH_SITE.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'controllers'.DIRECTORY_SEPARATOR.'opc.php'); 
		   
		   
		   
		   
		}
	}
	
	
	
	
	
	
		private static function _check($allowAdmin=false)
	{
	    if (defined('OPC_GENERAL_CHECK')) return OPC_GENERAL_CHECK; 
	
		if (!$allowAdmin)
		{
	  	$app = JFactory::getApplication();
		if ($app->getName() != 'site') {
			define('OPC_GENERAL_CHECK', false); 
			return false;
		}
		}
		
		
		$format = JRequest::getVar('format', 'html'); 
		if ($format != 'html') return false;

		$doc = JFactory::getDocument(); 
		$class = strtoupper(get_class($doc)); 
		
		$arr = array('JDOCUMENTHTML', 'JDOCUMENTOPCHTML'); 
		if (!in_array($class, $arr)) 
		{
		define('OPC_GENERAL_CHECK', false); 
		return false; 
		}

	    if (!file_exists(JPATH_ADMINISTRATOR.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_virtuemart'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'config.php')) 
		{
		define('OPC_GENERAL_CHECK', false); 
		return false;
		}
		
		if (!file_exists(JPATH_ROOT.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'plugin.php')) 
		{
		define('OPC_GENERAL_CHECK', false); 
		return false;
		}
		
		JLoader::register('OPCplugin', JPATH_ROOT.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'plugin.php' );
		
		JLoader::register('OPCconfig', JPATH_SITE.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'config.php' );
		
		require_once(JPATH_SITE.DIRECTORY_SEPARATOR.'administrator'.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'compatibility.php'); 
		
		if (!file_exists(JPATH_SITE.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'opctracking.php')) 
		{
		define('OPC_GENERAL_CHECK', false); 
		return false;
		}
		
		JLoader::register('OPCtrackingHelper', JPATH_SITE.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'opctracking.php' );
		
		define('OPC_GENERAL_CHECK', true); 
		return true; 

	}

	
	/**
	 * Converting the site URL to fit to the HTTP request
	 */
	public function onAfterRender()
	{

		//opc tracking start
		 //if (!empty(self::$delay)) return; 
	   
	   
	   
	   if (!$this->_check()) return; 

	  

		$app = JFactory::getApplication();


		$format = JRequest::getVar('format', 'html'); 
		
		
		$task = JRequest::getVar('task', ''); 
		$task = strtolower($task); 
		$view = JRequest::getCMD('view'); 
		$option = JRequest::getVar('option', ''); 
		 //if(('com_virtuemart' == JRequest::getCMD('option') && !$app->isAdmin()) && (('cart'==$view) || ($view=='pluginresponse') || ((($view=='user') && ($task=='editaddresscheckout'))))) 
		 
		 
		 // see also: C:\Users\RuposTel\AppData\Local\Temp\scp59647\root@192.168.122.1\srv\www\rupostel.com\web\vm2\components\com_onepage\helpers\plugin.php
		 
		 
		 
		 if (defined('OPC_IN_REGISTRATION_MODE') || (defined('OPC_CHECKOUT_RENDERED')))
		 {
		 
		 
		 
		 
			 $buffer = JResponse::getBody();
	  
		//Replace src links
		$base	= JURI::base(true).'/';
		
		 //orig opc: 
		 $buffer = str_replace('$(".virtuemart_country_id").vm2', '// $(".virtuemart_country_id").vm2', $buffer); 
		 $buffer = str_replace('$("select.virtuemart_country_id").vm2', '// $("select.virtuemart_country_id").vm2', $buffer); 
		 $buffer = str_replace('$("select.shipto_virtuemart_country_id").vm2', '// $("select.shipto_virtuemart_country_id").vm2', $buffer); 
		 $buffer = str_replace('$(".virtuemart_country_id").vm2front', '// $(".virtuemart_country_id").vm2front', $buffer); 
		 $buffer = str_replace('$("#virtuemart_country_id").vm2front', '// $("#virtuemart_country_id").vm2front', $buffer);
		 $buffer = str_replace('$("#shipto_virtuemart_country_id").vm2front', '// $("#shipto_virtuemart_country_id").vm2front', $buffer);
		 $buffer = str_replace('jQuery(\'#zip_field, #shipto_zip_field\')', '// jQuery(\'#zip_field, #shipto_zip_field\')', $buffer); 
		

		 if (stripos($buffer, 'components/com_onepage/assets/js/vmcreditcard.js')!==false)
		 {
			 $buffer = str_replace('components/com_virtuemart/assets/js/vmcreditcard.js', 'components/com_onepage/assets/js/emptyscript.js', $buffer); 
		 }
		 else
		 {
		 $buffer = str_replace('components/com_virtuemart/assets/js/vmcreditcard.js', 'components/com_onepage/assets/js/vmcreditcard.js', $buffer); 
		 }
		 //$buffer = str_replace('$(".vm-chzn-select").chosen', '// $(".vm-chzn-select").chosen', $buffer);
		 $buffer = str_replace('/plugins/vmpayment/klarna/klarna/assets/js/klarna_general.js', '/components/com_onepage/overrides/payment/klarna/klarna_general.js', $buffer); 
		 
		 $inside = JRequest::getVar('insideiframe', ''); 
		 if (!empty($inside))
		  {
		    $buffer = str_replace('<body', '<body onload="javascript: return parent.resizeIframe(document.body.scrollHeight);"', $buffer); 
		  }
		 //$buffer = str_replace('$(".virtuemart_country_id").vm2front("list",{dest : "#virtuemart_state_id",ids : ""});', '', $buffer); 
		$buffer = str_replace('jQuery("input").click', 'jQuery(null).click', $buffer);
		$buffer = str_replace('#paymentForm', '#adminForm', $buffer);
		
		
		 
		
		    if (class_exists('plgSystemBit_vm_change_shoppergroup'))
			{
				$js_text = "<script type=\"text/javascript\">location.reload()</script>";
				//$js_text = "location.reload()";
				$c = 0; 
				$buffer = str_replace($js_text, '', $buffer, $c); 
				
				 
				
			}
			// removing stupid VM messages which have nothing to do with hacking attempts:
			$buffer = str_replace('Hacking attempt loading userinfo, you got logged', '', $buffer); 
			
			JResponse::setBody($buffer);
		
		
		}

		
		
		return true;
	}
	// we will disable the 
	public function plgVmInterpreteMathOp2($calc, $rule, $price, $revert)
	{
		return false; 
	}
	
	public function plgVmonSelectedCalculatePriceShipment(VirtueMartCart $cart, &$cart_prices, &$cart_prices_name) {
	  
	  if (!empty($cart->virtuemart_shipmentmethod_id))
	  if ($cart->virtuemart_shipmentmethod_id < 0)
	  if (class_exists('OPCcache'))
	  if (!empty(OPCcache::$cachedResult['currentshipping']))
	  {
		return OPCcache::getStoredCalculation($cart, $cart_prices, $cart_prices_name); 
	  }
	}
	// triggered from: \administrator\components\com_virtuemart\models\orders.php
	public function plgVmOnUserOrder(&$_orderData)
	{
		// fix vm2.0.22 bug
		if (empty($_orderData->order_payment) && (empty($_orderData->order_payment_tax)))
		{
			
		 if (!class_exists('VirtueMartCart'))
		 require(JPATH_VM_SITE . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'cart.php');

			
					$cart = VirtueMartCart::getCart();
					$prices = $cart->getCartPrices();
					if (!empty($prices['salesPricePayment']))
					{
						$_orderData->order_payment = (float)$prices['salesPricePayment'];
					}
			
		}
	}
	function plgVmOnUserStore(&$data)
	{
	  
	  //if ((empty($data['username'])) && (!empty($data['email']))) $data['username'] = $data['email']; 
	}
	public function plgVmRemoveCoupon($_code, $_force)
	{
	   if (!file_exists(JPATH_ROOT.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'plugin.php')) return;
	   if (empty($_force))
	    {
		   include(JPATH_ROOT.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'onepage.cfg.php'); 
		   if (!empty($do_not_allow_gift_deletion)) return true; 
		}
		return null; 
	}
	public function plgVmOnUpdateOrderPayment(&$data,$old_order_status)
	{
	  if (!file_exists(JPATH_ROOT.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'plugin.php')) return;
	  require_once(JPATH_ROOT.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'plugin.php'); 
	  OPCplugin::checkGiftCoupon($data, $old_order_status);  
	  
	  
	}
	
	// code to update shopper groups: 
	public static $saveGroups; 
	public function onUserLogin($user, $options = array())
	{
	   $session = JFactory::getSession();
	   self::$saveGroups = $session->get('vm_shoppergroups_add',array(),'vm'); 
	   $session->set('vm_shoppergroups_add',array(),'vm'); 
	   
	}
	public function onUserLoginFailure($resp)
	{
	
	   if (!empty(self::$saveGroups))
	   {
	    $session = JFactory::getSession();
	    $session->set('vm_shoppergroups_add',self::$saveGroups,'vm'); 
	   }
	}
	
	public function onUserLogout($user, $options = array())
	{
	 
	}
	
	// deprecated: 
	public static function registerCart()
	{
	}
	

  	
	
}



// php 5.3 does not support static loading of this function with the same syntax as php5.5, therefore we included it outside the class scope
function fatal_error_catch()
	{
	
	
	
	if (function_exists('fastcgi_finish_request')) fastcgi_finish_request(); 
	
	$errfile = "unknown file";
  $errstr  = "shutdown";
  $errno   = E_CORE_ERROR;
  $errline = 0;

  $error = error_get_last();
 
 //blank_screens_email
 
  if( $error !== NULL) {
  
    $types = array(E_ERROR,  E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_RECOVERABLE_ERROR); 
	
    $errno   = $error["type"];
	
	if (!in_array($errno, $types)) return;
	
	
	 include(JPATH_ROOT.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_onepage'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'onepage.cfg.php'); 
     if (empty($opc_debug2)) return;
	
    $errfile = $error["file"];
    $errline = $error["line"];
    $errstr  = $error["message"];
	if (class_exists('JDate'))
	{
	$date = new JDate(); 
	$date = $date->toISO8601();
	}
	else
	$date = date('c'); 
	
    $dataMsg = $errno.' '.$errstr.' in file: '.$errfile.' line: '.$errline." timestamp: ".$date."\n";
   $f = JPATH_SITE. DIRECTORY_SEPARATOR .'logs'. DIRECTORY_SEPARATOR .'php_errors.log.php'; 
   if (!file_exists($f))
   {
     $data = '<?php die(); ?>'."\n".$dataMsg; 
     @file_put_contents($f, $data); 
   }
   else
    {
	   @file_put_contents($f, $dataMsg, FILE_APPEND); 
	}
	
	
	$email = $blank_screens_email; 
	  if (!empty($email))
	  {
	    $mailer = JFactory::getMailer();
		$mailer->addRecipient( $blank_screens_email );
		$subject = 'Fatal Error Detected on your Joomla Site'; 
		$mailer->setSubject(  html_entity_decode( $subject) );
		$mailer->isHTML( false );
		
		$body = "RuposTel OPC plugin detected a problem with your site. \nYour site caused a blank screen upon a visit of this URL: \n"; 

	 $pageURL = 'http';
     if ((isset($_SERVER['HTTPS'])) && ($_SERVER["HTTPS"] == "on")) {$pageURL .= "s";}
     $pageURL .= "://";
     if ($_SERVER["SERVER_PORT"] != "80") {
      $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
     } else {
      $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
     }		
			$body .= $pageURL."\n"; 
			$body .= 'Error message data: '."\n"; 
			$body .= $dataMsg; 
			$body .= "\n\nTo disable these emails proceed to your Components -> Onepage -> General tab -> Log Blank Screens\n";
			$body .= "It is very important that you fix all php fatal errors on your site. Resend this email to your developer."; 
		$config = JFactory::getConfig();
		$sender = array( $config->get( 'mailfrom' ), $config->get( 'fromname' ) );
		$mailer->setBody( $body );
		$mailer->setSender( $sender );
		$mailer->Send();
	  }
	
  }
	}
	
if (function_exists('register_shutdown_function'))
register_shutdown_function( "fatal_error_catch" );
	