<?php
defined('_JEXEC') or die('Restricted access');

/**
 * Overrided VmPlugin class for the OPC ajax and checkout
 * 
 * This class was overrided due to few serious bugs in the orginal release and to be able to add additional functionality to it 
 *
 * @package One Page Checkout for VirtueMart 2
 * @subpackage opc
 * @author stAn
 * @author RuposTel s.r.o.
 * @copyright Copyright (C) 2007 - 2012 RuposTel - All rights reserved.
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 * One Page checkout is free software released under GNU/GPL and uses some code from VirtueMart
 * VirtueMart is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * 
 *
 ORIGINAL LICENSE AND COPYRIGHT
 * abstract class for payment plugins
 *
 * @package	VirtueMart
 * @subpackage Plugins
 * @author Valérie Isaksen
 * @link http://www.virtuemart.net
 * @copyright Copyright (c) 2004 - 2011 VirtueMart Team. All rights reserved.
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 * VirtueMart is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * @version $Id: vmplugin.php 4599 2011-11-02 18:29:04Z alatak $
 */
// Load the helper functions that are needed by all plugins
if (!class_exists('ShopFunctions'))
require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'shopfunctions.php');


require_once(JPATH_ROOT.DS.'components'.DS.'com_onepage'.DS.'helpers'.DS.'cache.php'); 

// Get the plugin library
jimport('joomla.plugin.plugin');

abstract class vmPlugin extends JPlugin {

	// var Must be overriden in every plugin file by adding this code to the constructor:
	// $this->_name = basename(__FILE, '.php');
	// just as note: protected can be accessed only within the class itself and by inherited and parent classes

	//This is normal name of the plugin family, custom, payment
	protected $_psType = 0;
	
	//Id of the joomla table where the plugins are registered
	protected $_jid = 0;

	protected $_vmpItable = 0;
	//the name of the table to store plugin internal data, like payment logs
	protected $_tablename = 0;

	protected $_tableId = 'id';
	//Name of the primary key of this table, for exampel virtuemart_calc_id or virtuemart_order_id
	protected $_tablepkey = 0;

	protected $_vmpCtableAll = array();
	protected $_vmpCtable = 0;
	//the name of the table which holds the configuration like paymentmethods, shipmentmethods, customs
	protected $_configTable = 0;
	protected $_configTableFileName = 0;
	protected $_configTableClassName = 0;
	protected $_xParams = 0;
	protected $_varsToPushParam = 0;
	//id field of the config table
	protected $_idName = 0;
	//Name of the field in the configtable, which holds the parameters of the pluginmethod
	protected $_configTableFieldName = 0;

	protected $_debug = false;
	protected $_loggable = false;
	static $payment_logos = null;
	/**
	 * Constructor
	 *
	 * @param object $subject The object to observe
	 * @param array  $config  An array that holds the plugin configuration
	 * @since 1.5
	 */
	function __construct(& $subject, $config) {

		parent::__construct($subject, $config);
		
		$this->_psType = substr($this->_type, 2);

		$lang = JFactory::getLanguage();
		$filename = 'plg_' . $this->_type . '_' . $this->_name;

		if(VmConfig::get('enableEnglish', 1)){
		    $lang->load($filename, JPATH_ADMINISTRATOR, 'en-GB', true);
		}
		    $lang->load($filename, JPATH_ADMINISTRATOR, $lang->getDefault(), true);
		$lang->load($filename, JPATH_ADMINISTRATOR, null, true);
/*
		$knownLanguages=$lang->getKnownLanguages();
		foreach($knownLanguages as $key => $knownLanguage) {
			$lang->load ($filename, JPATH_ADMINISTRATOR, $key, TRUE);
		}
		*/
		if (!class_exists ('JParameter')) {
			require(JPATH_VM_LIBRARIES . DS . 'joomla' . DS . 'html' . DS . 'parameter.php');
		}

		$this->_tablename = '#__virtuemart_' . $this->_psType . '_plg_' . $this->_name;
		$this->_tableChecked = FALSE;
	}

/**
	 * @return array
	 */
	function getTableSQLFields() {

		return array();
	}

function getOwnUrl(){

		if(JVM_VERSION!=1){
			$url = '/plugins/'.$this->_type.'/'.$this->_name;
		} else{
			$url = '/plugins/'.$this->_type;
		}
		return $url;
	}

	function display3rdInfo($intro,$developer,$contactlink,$manlink){
		$logolink = $this->getOwnUrl() ;
		return shopfunctions::display3rdInfo($this->_name,$intro,$developer,$logolink,$contactlink,$manlink);
	}

	/**
	 * Checks if this plugin should be active by the trigger
	 *
	 * @author Max Milbers
	 * @param string $psType shipment,payment,custom
	 * @param        string the name of the plugin for example textinput, paypal
	 * @param        int/array $jid the registered plugin id(s) of the joomla table
	 *
	 * @param int/array $id the registered plugin id(s) of the joomla table
	 */
	protected function selectedThis ($psType, $name = 0, $jid = 0) {

		if ($psType !== 0) {
			if($psType!=$this->_psType){
				vmdebug('selectedThis $psType does not fit');
				
				return false;
			}
		}

		if($name!==0){
			if($name!=$this->_name){
 				vmdebug('selectedThis $name '.$name.' does not fit pluginname '.$this->_name);
				
				return false;
			}
		}

		if($jid===0){
		     
			return false;
		} else {
			if($this->_jid===0){
				$this->getJoomlaPluginId();
			}
			if(is_array($jid)){
				if(!in_array($this->_jid,$jid)){
					//vmdebug('selectedThis id '.$jid.' not in array does not fit '.$this->_jid);
			
			return false;
				}
			} else {
				if($jid!=$this->_jid){
					//vmdebug('selectedThis $jid '.$jid.' does not fit '.$this->_jid);
					//echo $jid; 
				//	echo '<br />'.$this->_jid.'<br />'; 
					return false;
				}
			}
		}

		return true;
	}
	public function getPluginMethodsOPC($vendorid = 0)
	{
		
	}
	public static $iCount; 
	public function plgVmDisplayListFEShipmentOPC(&$cart, $selected = 0, &$htmlIn)
	{
		if ($this->_type != 'vmshipment') return; 

		$pluginmethod_id = $this->_idName; //virtuemart_shipmentmethod_id
		$pluginName = $this->_psType . '_name'; // shipment_name
			
		$pluginName = $this->_name; 
		$data = array($selected, $pluginmethod_id, $pluginName ); 
			

			
		$hash = OPCcache::getGeneralCacheHash('plgVmDisplayListFEShipment', $cart, $data); 
		$val = OPCcache::getValue($hash); 
			
		VmPlugin::$iCount++; 
		
		
		
		
			if (!empty($val))
			{
				
				if (empty($val[0])) 
				{
				break;
				//return $val[0]; 
				}
				else
				{
				foreach ($val[1] as $vala)
				{
				 $htmlIn[] = $vala; 
				}
				
				return true; 
				}
			}
			
		
		
		
			
		
		
		
		$htmlIn2 = array(); 
		$val = $this->plgVmDisplayListFEShipment($cart, $selected, $htmlIn2);
		$html = ''; 
		if (is_array($htmlIn2))
		{
		foreach ($htmlIn2 as $h)
		{
			if (is_array($h))
			{
				foreach ($h as $h2)
				  $html .= $h2; 
			}
			  else
			$html .= $h; 
		}
		}
		else $html  = $htmlIn2; 
		if (!empty($html) || (stripos($html, 'virtuemart_shipmentmethod_id')!==false))
		if (stripos($html, 'error')===false)
		$val2 = OPCcache::setValue($hash, array($val, $htmlIn2 )); 
		
	
	
		if (!empty($htmlIn2))
		{
			$htmlIn = array_merge($htmlIn, $htmlIn2); 
		}
		
		return $val; 
	}
	
	public function plgVmGetSpecificCache($cart, $id=0)
	{
		
		
		
		if ($this->_type == 'vmshipment')
		{
		
		if (empty($cart->virtuemart_shipmentmethod_id)) 
		{
		
		return ""; 
		}
		else
		$virtuemart_shipmentmethod_id = $cart->virtuemart_shipmentmethod_id; 
	     
	    
		if (!($this->selectedThisByMethodId($virtuemart_shipmentmethod_id))) {
			return "";
		}
		
		
		
		
		$to_address = (($cart->ST == 0) ? $cart->BT : $cart->ST);
	    
		require(JPATH_SITE.DS.'components'.DS.'com_onepage'.DS.'helpers'.DS.'third_party'.DS.'third_party_shipping_permanent_cache.php'); 

		}
	}
	function &setCache(&$value)
	{
	  $arg_list = func_get_args();
	  $hash = ''; 
	  for ($i = 1; $i < count($arg_list); $i++) {
        $hash .= serialize($arg_list[$i]); 
	  }
	  $hash = md5($hash); 
	  vmPlugin::$qCache[$hash] = $arg_list[0]; 
	  return $value; 
	  /*
	  $cache = & JFactory::getCache();
	  $orig = $cache->getCaching(); 
	  $cache->setCaching( 1 );
	  $cache->store($value, $hash, 'opccache'); 
	  $cache->setCaching( $orig );
	  */
	  return $value; 
	}
	
	function &getCache()
	{
	  $f = false; 
	  return $f;
	  $arg_list = func_get_args();
	  $hash = ''; 
	  for ($i = 0; $i < count($arg_list); $i++) {
        $hash .= serialize($arg_list[$i]); 
	  }
	  $hash = md5($hash); 
	  if (isset(vmPlugin::$qCache[$hash])) 
	  {
	   // we have a match, let's measure it
	  if (empty(vmPlugin::$ccount)) vmPlugin::$ccount = 1; 
	  else vmPlugin::$ccount++;
	  
	  return vmPlugin::$qCache[$hash]; 
	  }
	  $res = false; 
	  /*
	  $cache = & JFactory::getCache();
	  $orig = $cache->getCaching(); 
	  $cache->setCaching( 1 );
	  $res = $cache->get($hash, 'opccache'); 
	  $cache->setCaching( $orig );
	  */
	  return $res; 
	  
	  
	}
	/**
	* Checks if this plugin should be active by the trigger
	* @author Max Milbers
	* @author Valérie Isaksen
	* @param string $psType shipment,payment,custom
	* @param string the name of the plugin for exampel textinput, paypal
	* @param int/array $id the registered plugin id(s) of the joomla table
	*/
	static $qCache; 
	public static $ccount; 
	
	function selectedThisByMethodId(  $id='type') {
		//echo '<br />selectedThisByMethodId:'.$id.' type:'.$this->_psType.' idName:'.$this->_idName.' name:'.$this->_name.'<br />'; 
		//selectedThisByMethodId:2 type:shipment idName:virtuemart_shipmentmethod_id
		//if($psType!=$this->_psType) return false;
		
		
		$db = JFactory::getDBO();
		
		if($id==='type'){
			return true;
		} else {
			$db = JFactory::getDBO();
			
			if (VmConfig::isJ15()) {
				$q = 'SELECT vm.* FROM `'.$this->_configTable.'` AS vm,
							#__plugins AS j WHERE vm.`'.$this->_idName.'` = "'.$id.'"
							AND vm.'.$this->_psType.'_jplugin_id = j.id
							AND j.element = "'.$this->_name.'"';
			} else {
				$q = 'SELECT vm.* FROM `'.$this->_configTable.'` AS vm,
							#__extensions AS j WHERE vm.`'.$this->_idName.'` = "'.$id.'"
							AND vm.'.$this->_psType.'_jplugin_id = j.extension_id
							AND j.element = "'.$this->_name.'"';
			}
			$x = vmPlugin::getCache('selectedThisByMethodId', $q); if (!empty($x)) return $x; 
			//echo 'selectedThisByMethod'.$this->_psType;
			$db->setQuery($q);
			if(!$res = $db->loadObject() ){
// 				//vmError('selectedThisByMethodId '.$db->getQuery());
				$res = false; 
				$x = vmPlugin::setCache($res, 'selectedThisByMethodId', $q); 
				return false; 
			} else {
				$x = vmPlugin::setCache($res, 'selectedThisByMethodId', $q); 
				return $res;
			}
		}
	}
/**
	* Checks if this plugin should be active by the trigger
	* @author Max Milbers
	* @author Valérie Isaksen
	* @param string the name of the plugin for exampel textinput, paypal
	* @param int/array $id the registered plugin id(s) of the joomla table
	*/
	protected function selectedThisByJPluginId(  $jplugin_id='type') {

		$db = JFactory::getDBO();

		if($jplugin_id==='type'){
			return true;
		} else {
			$db = JFactory::getDBO();

			if (VmConfig::isJ15()) {
				$q = 'SELECT vm.* FROM `'.$this->_configTable.'` AS vm,
							#__plugins AS j WHERE vm.`'.$this->_psType.'_jplugin_id`  = "'.$jplugin_id.'"
							AND vm.'.$this->_psType.'_jplugin_id = j.id
							AND j.`element` = "'.$this->_name.'"';
			} else {
				$q = 'SELECT vm.* FROM `'.$this->_configTable.'` AS vm,
							#__extensions AS j WHERE vm.`'.$this->_psType.'_jplugin_id`  = "'.$jplugin_id.'"
							AND vm.`'.$this->_psType.'_jplugin_id` = j.extension_id
							AND j.`element` = "'.$this->_name.'"';
			}
			
			$x = vmPlugin::getCache('selectedThisByJPluginId', $q);  if (!empty($x)) return $x; 
			
			$db->setQuery($q);
			if(!$res = $db->loadObject() ){
// 				vmError('selectedThisByMethodId '.$db->getQuery());
				$res = false; 
				return vmPlugin::setCache($res, 'selectedThisByJPluginId', $q);  
			} else {
				return vmPlugin::setCache($res, 'selectedThisByJPluginId', $q);  
				
			}
		}
	}

	/**
	 * Gets the id of the joomla table where the plugin is registered
	 * @author Max Milbers
	 */
	final protected function getJoomlaPluginId(){

		if(!empty($this->_jid)) return $this->_jid;
		$db = JFactory::getDBO();

		if (VmConfig::isJ15()) {
			$q = 'SELECT j.`id` AS c FROM #__plugins AS j
					WHERE j.element = "'.$this->_name.'" AND j.folder = "'.$this->_type.'"';
		} else {
			$q = 'SELECT j.`extension_id` AS c FROM #__extensions AS j
					WHERE j.element = "'.$this->_name.'" AND j.`folder` = "'.$this->_type.'"';
		}
		$x = vmPlugin::getCache('getJoomlaPluginId', $q);  if (!empty($x)) return $x; 
		
		$db->setQuery($q);
		$this->_jid = $db->loadResult();
		if(!$this->_jid){
			vmError('getJoomlaPluginId '.$db->getErrorMsg());
			$res = false; 
			return vmPlugin::setCache($res, 'getJoomlaPluginId', $q);
			return false;
		} else {
		    return vmPlugin::setCache($this->_jid, 'getJoomlaPluginId', $q);
			return $this->_jid;
		}
	}

	/**
	* Create the table for this plugin if it does not yet exist.
	* @author Valérie Isaksen
	* @author Max Milbers
	*/
	protected function onStoreInstallPluginTable($psType, $name=FALSE) {
// stAn merge sept 2012
if(!empty($name) and $name!=$this->_name){
			return false;
		}

		if($psType==$this->_psType){
			$query = $this->getVmPluginCreateTableSQL();
			
			if(empty($query)){
				return false;
			} else {
				$db = JFactory::getDBO();
				$db->setQuery($query);
				if (!$db->query()) {
					JError::raiseWarning(1, $this->_name.'::onStoreInstallPluginTable: ' . JText::_('COM_VIRTUEMART_SQL_ERROR') . ' ' . $db->stderr(true));
					echo $this->_name.'::onStoreInstallPluginTable: ' . JText::_('COM_VIRTUEMART_SQL_ERROR') . ' ' . $db->stderr(true);
				}
else {
return true; 
}

			}
		}

return false;
	}


	function getTableSQLLoggablefields() {
		return array(
		    'created_on' => ' datetime NOT NULL default \'0000-00-00 00:00:00\'',
		    'created_by' => "int(11) NOT NULL DEFAULT '0'",
		    'modified_on' => ' datetime NOT NULL DEFAULT \'0000-00-00 00:00:00\'',
		    'modified_by' => "int(11) NOT NULL DEFAULT '0'",
		    'locked_on' => ' datetime NOT NULL DEFAULT \'0000-00-00 00:00:00\'',
		    'locked_by' => 'int(11) NOT NULL DEFAULT \'0\''
		);

	    }

   /**
	 * @param $tableComment
	 * @return string
	 */
	protected function createTableSQL ($tableComment,$tablesFields=0) {

		$query = "CREATE TABLE IF NOT EXISTS `" . $this->_tablename . "` (";
		if(!empty($tablesFields)){
			foreach ($tablesFields as $fieldname => $fieldtype) {
				$query .= '`' . $fieldname . '` ' . $fieldtype . " , ";
			}
		} else {
			$SQLfields = $this->getTableSQLFields ();
			$loggablefields = $this->getTableSQLLoggablefields ();
			foreach ($SQLfields as $fieldname => $fieldtype) {
				$query .= '`' . $fieldname . '` ' . $fieldtype . " , ";
			}
			foreach ($loggablefields as $fieldname => $fieldtype) {
				$query .= '`' . $fieldname . '` ' . $fieldtype . ", ";
			}
		}

		$query .= "	      PRIMARY KEY (`id`)
	    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='" . $tableComment . "' AUTO_INCREMENT=1 ;";
		return $query;
	}
	
	/**
	 *
	 * @param $psType
	 * @param $name
	 * @param $id
	 * @param $xParams
	 * @param $varsToPush
	 * @return bool
	 */
	protected function getTablePluginParams ($psType,$name, $id, &$xParams,&$varsToPush) {
		//vmdebug('getTablePluginParams $this->_psType '.$this->_psType.' sets $psType '.$psType.' $name',$name);
		if (!empty($this->_psType) and !$this->selectedThis ($psType, $name, $id)) {
			return FALSE;
		}
		//$x = $this->myClass(); 
		$varsToPush = $this->_varsToPushParam;
		$xParams = $this->_xParams;
		
		//vmdebug('getTablePluginParams '.$name.' sets xParams '.$xParams.' vars',$varsToPush);
	}

	function myClass()
	 {
	   $y = get_class($this); 
	   return $y; 
	 }
	/**
	 * Set with this function the provided plugin parameters
	 *
	 * @param string $paramsFieldName
	 * @param array $varsToPushParam
	 */
	function setConfigParameterable($paramsFieldName,$varsToPushParam){
	    //$x = $this->myClass(); 
		$this->_varsToPushParam = $varsToPushParam;
		if (!isset($this->_varsToPushParam[$this->_psType.'_logos']))
		$this->_varsToPushParam[$this->_psType.'_logos'] = array('', 'char'); 
		
		$this->_xParams = $paramsFieldName;
		
		
	}

	protected function setOnTablePluginParams($name,$id,&$table){

		//Todo I think a test on this is wrong here
		//Adjusted it like already done in declarePluginParams
		if (!empty($this->_psType) and !$this->selectedThis ($this->_psType, $name, $id)) {
			return FALSE;
		}
		else {
		    //$x = $this->myClass(); 
			$table->setParameterable ($this->_xParams, $this->_varsToPushParam);
			return TRUE;
		}

	}

	/**
	 * @param $psType
	 * @param $name
	 * @param $id
	 * @param $data
	 * @return bool
	 */
	protected function declarePluginParams ($psType, $name, $id, &$data) {

		//vmdebug('declarePluginParams '.$this->_psType.' '.$psType);
		//Todo I know a test only on seledtThis is wrong here, it works now with extra !empty($this->_psType)
		if(!empty($this->_psType) and !$this->selectedThis($psType,$name,$id)){
		
			return FALSE;
		}
		if (!class_exists ('VmTable')) {
			require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'vmtable.php');
		}
		//$x = $this->myClass();
		VmTable::bindParameterable ($data, $this->_xParams, $this->_varsToPushParam);
		return TRUE;
		// 			vmdebug('getDeclaredPluginParams return '.$this->_xParams);
		// 			return array($this->_xParams,$this->_varsToPushParam);
		// 		} else {
		// 			return false;
		// 		}
	}

	
	
	public function &getVmPluginMethod($int, $cache=true){

	$class = $this->myClass(); 	  
	/*
	  $cache = true; 
	  
	  if ($cache)
	  {
	  $x = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS & DEBUG_BACKTRACE_PROVIDE_OBJECT, 5); 
	   foreach ($x as $l)
	   {
		   if ($l['function'] == 'plgVmOnSelectedCalculatePriceShipment')
		   {
			   
			   
		   }
		   
	   }
	   }
	  */

	  
	
	  
	   
	   $x = vmPlugin::getCache('getVmPluginMethod', $class.$int); 
	   {
	   $this->_vmpCtable = $x;
	   
	   // vm 2.0.20
	   if (!empty($x))
	   if (!isset($x->tax_id)) $x->tax_id = -1; 
	   
	   if (!empty($x)) return $x; 
	   }
	   $x = $this->selectedThisByMethodId($int); 
	   if (empty($x)) 
	   {
	   $res = false; 
	   return vmPlugin::setCache($res, 'getVmPluginMethod', $class.$int); 
	   }

	    /*
		static $lastInt; 
		if (!empty($lastInt))
		{
		  if ($int != $lastInt) 
		   $refresh = true; 
		  else $refresh = false;
		}
		else 
		{
		  $refresh = true; 
		  $lastInt = $int; 
		}
		*/
		
		if (!class_exists ('VmTable')) {
			require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'vmtable.php');
		}

		
		if (empty($this->_vmpCtableAll)) $this->_vmpCtableAll = array(); 
		$type = $this->_psType; 
		
	    
		
		if((empty($this->_vmpCtableAll[$type.$int])))
		{
			$db = JFactory::getDBO();

			if(!class_exists($this->_configTableClassName))require(JPATH_VM_ADMINISTRATOR.DS.'tables'.DS.$this->_configTableFileName.'.php');
			$this->_vmpCtableAll[$type.$int] = new $this->_configTableClassName($db);
			
			
			
		}
		
			
			
			
			
		// some plugins are missing some of the params:
		$this->_vmpCtableAll[$type.$int]->setParameterable($this->_xParams,$this->_varsToPushParam);
		$this->_vmpCtable = $this->_vmpCtableAll[$type.$int];
			
			
		
		
		$x = $this->_vmpCtableAll[$type.$int]->load($int);
		if (!empty($x))
		if (!isset($x->payment_logos)) $x->payment_logos = ''; 
		if (!isset($x->tax_id)) $x->tax_id = -1; 
		
		return vmPlugin::setCache($x, 'getVmPluginMethod', $class.$int);
	}

	protected function storeVmPluginMethod () {

	}
	
	/**
	 * This stores the data of the plugin, attention NOT the configuration of the pluginmethod,
	 * this function should never be triggered only called from triggered functions.
	 *
	 * @author Max Milbers
	 * @param array  $values array or object with the data to store
	 * @param string $tableName When different then the default of the plugin, provid it here
	 * @param string $tableKey an additionally unique key
	 */
	protected function storePluginInternalData (&$values, $primaryKey = 0, $id = 0, $preload = FALSE) {

		if ($primaryKey === 0) {
			$primaryKey = $this->_tablepkey;
		}
		if ($this->_vmpItable === 0) {
			$this->_vmpItable = $this->createPluginTableObject ($this->_tablename, $this->tableFields, $primaryKey, $this->_tableId, $this->_loggable);
		}
		//vmdebug('storePluginInternalData',$value);
		$this->_vmpItable->bindChecknStore ($values, $preload);
		$errors = $this->_vmpItable->getErrors ();
		if (!empty($errors)) {
			foreach ($errors as $error) {
				vmError ($error);


			}
		}
		return $values;

	}
	
	
	/**
	 * This loads the data stored by the plugin before, NOT the configuration of the method,
	 * this function should never be triggered only called from triggered functions.
	 *
	 * @param int    $id
	 * @param string $primaryKey
	 */
	protected function &getPluginInternalData ($id, $primaryKey = 0) {
		$x = vmPlugin::getCache('getPluginInternalData', $this->_vmpItable, $id, $this->_tablename, $this->tableFields, $primaryKey, $this->_tableId, $this->_loggable); 
		if (!empty($x)) return $x; 
		
		if (isset($this->_vmpItable))
		$vmpItableStored = $this->_vmpItable; 
		else $vmpItableStored = null; 
		
		if ($primaryKey === 0) {
			$primaryKey = $this->_tablepkey;
		}
		if ($this->_vmpItable === 0) {
			$this->_vmpItable = $this->createPluginTableObject ($this->_tablename, $this->tableFields, $primaryKey, $this->_tableId, $this->_loggable);
		}
		
		// 		vmdebug('getPluginInternalData $id '.$id.' and $primaryKey '.$primaryKey);
		$ret = $this->_vmpItable->load ($id);
		return vmPlugin::setCache($ret, 'getPluginInternalData',$vmpItableStored, $id, $this->_tablename, $this->tableFields, $primaryKey, $this->_tableId, $this->_loggable); 
		
	}


	/**
	 * This loads the data stored by the plugin before, NOT the configuration of the method,
	 * this function should never be triggered only called from triggered functions.
	 *
	 * @param int    $id
	 * @param string $primaryKey
	 */
	protected function &getPluginInternalData2 ($id, $primaryKey = 0) {
		$x = vmPlugin::getCache('getPluginInternalData', $id, $this->_tablename, $this->tableFields, $primaryKey, $this->_tableId, $this->_loggable); 
		if (!empty($x)) return $x; 
		
		if ($primaryKey === 0) {
			$primaryKey = $this->_tablepkey;
		}
		if ($this->_vmpItable === 0) {
			$this->_vmpItable = $this->createPluginTableObject ($this->_tablename, $this->tableFields, $primaryKey, $this->_tableId, $this->_loggable);
		}
		
		// 		vmdebug('getPluginInternalData $id '.$id.' and $primaryKey '.$primaryKey);
		$ret = $this->_vmpItable->load ($id);
		return vmPlugin::setCache($ret, 'getPluginInternalData', $id, $this->_tablename, $this->tableFields, $primaryKey, $this->_tableId, $this->_loggable); 
		
	}

	/**
	 * @param      $tableName
	 * @param      $tableFields
	 * @param      $primaryKey
	 * @param      $tableId
	 * @param bool $loggable
	 * @return VmTableData
	 */
	protected function createPluginTableObject ($tableName, $tableFields, $primaryKey, $tableId, $loggable = FALSE) {

		if (!class_exists ('VmTableData')) {
			require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'vmtabledata.php');
		}
		$db = JFactory::getDBO ();
		$table = new VmTableData($tableName, $tableId, $db);
		foreach ($tableFields as $field) {
			$table->$field = 0;
		}
		
		if (substr($tableName, 0, 6) == 'TableS')
		if (!isset($table->shipment_logos)) $table->shipment_logos = ''; 
		if (substr($tableName, 0, 6) == 'TableP')
		if (!isset($table->payment_logos)) $table->payment_logos = ''; 
		if ($primaryKey !== 0) {
			$table->setPrimaryKey ($primaryKey);
		}
		if ($loggable) {
			$table->setLoggable ();
		}
		
		if (!$this->_tableChecked) {
			$this->onStoreInstallPluginTable ($this->_psType);
			$this->_tableChecked = TRUE;
		}

		return $table;
	}

	/**
	 * @param     $id
	 * @param int $primaryKey
	 * @return mixed
	 */
	protected function removePluginInternalData ($id, $primaryKey = 0) {
		if ($primaryKey === 0) {
			$primaryKey = $this->_tablepkey;
		}
		if ($this->_vmpItable === 0) {
			$this->_vmpItable = $this->createPluginTableObject ($this->_tablename, $this->tableFields, $primaryKey, $this->_tableId, $this->_loggable);
		}
		vmdebug ('removePluginInternalData $id ' . $id . ' and $primaryKey ' . $primaryKey);
		return $this->_vmpItable->delete ($id);
	}

	/**
	 * Get the path to a layout for a type
	 *
	 * @param   string  $type  The name of the type
	 * @param   string  $layout  The name of the type layout. If alternative
	 *                           layout, in the form template:filename.
	 * @param   array   $viewData  The data you want to use in the layout
	 *                           can be an object/array/string... to reuse in the template
	 * @return  string  The path to the type layout
	 * original from libraries\joomla\application\module\helper.php
	 * @since   11.1
	 * @author Patrick Kohl, Valérie Isaksen
	 */
	public function renderByLayout ($layout = 'default', $viewData = NULL, $name = NULL, $psType = NULL) {
		if ($name === NULL) {
			$name = $this->_name;
		}

		if ($psType === NULL) {
			$psType = $this->_psType;
		}
		$layout = vmPlugin::_getLayoutPath ($name, 'vm' . $psType, $layout);
		if (strpos($layout, 'payment_form')!==false)
		if (strpos($layout, 'klarna')!==false)
		 {
		   $layout = JPATH_SITE.DS.'components'.DS.'com_onepage'.DS.'overrides'.DS.'klarna'.DS.'payment_form.php'; 
		 }
		ob_start ();
		include ($layout);
		return ob_get_clean ();

	}
	
	public function __call($method, $arguments)
    {
		if (method_exists($this, $method))
        return $this->__call($method, $arguments);
	    else return null; 
    }
	
	
	/**
	 *  Note: We have 2 subfolders for versions > J15 for 3rd parties developers, to avoid 2 installers
	 *
	 * @author Patrick Kohl, Valérie Isaksen
	 */
	private function _getLayoutPath ($pluginName, $group, $layout = 'default') {
		$app = JFactory::getApplication ();
		// get the template and default paths for the layout
		if (JVM_VERSION === 2) {
			$templatePath = JPATH_SITE . DS . 'templates' . DS . $app->getTemplate () . DS . 'html' . DS . $group . DS . $pluginName . DS . $layout . '.php';
			$defaultPath = JPATH_SITE . DS . 'plugins' . DS . $group . DS . $pluginName . DS . $pluginName . DS . 'tmpl' . DS . $layout . '.php';
		}
		else {
			$templatePath = JPATH_SITE . DS . 'templates' . DS . $app->getTemplate () . DS . 'html' . DS . $group . DS . $pluginName . DS . $layout . '.php';
			$defaultPath = JPATH_SITE . DS . 'plugins' . DS . $group . DS . $pluginName . DS . 'tmpl' . DS . $layout . '.php';
		}


		// if the site template has a layout override, use it
		jimport ('joomla.filesystem.file');
		if (JFile::exists ($templatePath)) {
			return $templatePath;
		}
		else {
			return $defaultPath;
		}
	}
	public static function pBS()
	{
		$x = debug_backtrace(); 
		echo 'Bakctrace'."<br />\n"; 
		foreach ($x as $l) echo $l['file'].' '.$l['line']."<br />\n"; 
	    die(); 
	}
	/*
	function plgVmOnSelectedCalculatePriceShipmentOPC (VirtueMartCart $cart, array &$cart_prices, &$cart_prices_name) 
	{
		// if ($cart->virtuemart_shipmentmethod_id==10)
			{
				$cart_prices['shipmentTax'] = 1;
		$cart_prices['shipmentValue'] = 10; 
		
		return true; 
			}
		if (!($method = $this->getVmPluginMethod ($cart->virtuemart_shipmentmethod_id))) {
			return NULL; // Another method was selected, do nothing
		}
		 
		
		if (!$this->selectedThisElement ($method->shipment_element)) {
			return FALSE;
		}
		

		$cart_prices['shipmentTax'] = 1;
		$cart_prices['shipmentValue'] = 10; 
		
		return true; 

		
		
	}
    */
	
}
