<?php
/*require realpath(__DIR__) . DIRECTORY_SEPARATOR.'admin/includes/classes/ebay-sdk/autoload.php';
use \DTS\eBaySDK\Trading\Services\TradingService;
use \DTS\eBaySDK\HttpHandler;
*/
require_once('includes/application_top.php');
require_once('admin/includes/config.ebayapi.inc.php');
require_once('admin/includes/classes/class.ebay.php');
//require_once ABS_PATH_TO_PHPAPI.'ebat/EbatNs_ServiceProxy.php';
//require_once ABS_PATH_TO_PHPAPI.'ebat/EbatNs_Logger.php';
//require_once ABS_PATH_TO_PHPAPI.'ebat/EbatNs_Environment.php';
//require_once ABS_PATH_TO_PHPAPI.'ebat/FetchTokenRequestType.php';

//require_once ABS_PATH_TO_PHPAPI.'ebat/SetReturnURLRequestType.php';
//require_once ABS_PATH_TO_PHPAPI.'ebat/GetReturnURLRequestType.php';
define("Y4T_ENCRYPTION_KEY", "YES4TRADEBYMARIOASPELEITER");
/**
 * Returns an encrypted & utf8-encoded
 */
function y4t_encrypt($pure_string, $encryption_key) {
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv);
    return $encrypted_string;
}

/**
 * Returns decrypted original string
 */
function y4t_decrypt($encrypted_string, $encryption_key) {
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv);
    return $decrypted_string;
}
if(isset($_REQUEST['dl_soap_user_table']) and $_REQUEST['dl_soap_user_table'] == 1){
	$file = 'soap_user_table.php';
	$c = file_get_contents($file);
	$ce = y4t_encrypt($c,Y4T_ENCRYPTION_KEY);
	header("Content-type: text/plain");
	header('Content-Disposition: attachment; filename="'.$file.'.secure'.'"');
	echo $ce;
	exit;
}
/*
class sample_FetchToken extends EbatNs_Environment
{
    public function dispatchCall ($params)  {
        $req = new FetchTokenRequestType();
        $req->setSessionID($params['SessionID']);
        
        $res = $this->proxy->FetchToken($req);
        if ($this->testValid($res))
        {
            return $res;
        }
        else 
        {
            return (false);
        }
    }
}*/
$environment = (isset($_REQUEST['environment']) and $_REQUEST['environment'] == 'sandbox') ? 'sandbox' : 'production';
if(isset($_GET['code'])){
	// NEU, DIREKT EINTRAGEN 07/22
	$user = $_GET['state'];
	/*
	if($user !== 'local-yes4trade'){
		require_once('soap_user_table.php');
		$link = str_replace('http:','https:',$soap_user_allocations[ $user ]);
		xtc_redirect($link.'admin/ebayapi_sdk_calls.php?action=oauth_consent_submit&close_window=1&consent='.urlencode($_GET['code']));
	}*/
?>
<html>
	<head>
		<title>YES4Trade:ebay Authorisierung</title>
		<style>
			body{
				background-color: #000;
				color: #000;
			}
			.content{
				height: 300px;
				width: 850px;
				border: 1px solid green;
				text-align: center;
				background-color: #FFF;
				margin: auto;
			}
			.token_code{
				margin-top: 10px;
				padding: 8px; 
				color: #000; 
				font-family: monospace, system; 
				background-color: #CCC;
				font-size: 0.7em;
			}
		</style>
		<script type="text/javascript">
		const copyToClipboard = str => {
		  const el = document.createElement('textarea');
		  el.value = str;
		  document.body.appendChild(el);
		  el.select();
		  document.execCommand('copy');
		  document.body.removeChild(el);
		  alert('Code in Zwischenablage kopiert');
		};
		</script>
	</head>
	<body>
		<div class="content">
			<img style="margin-top: 14px;" src="https://yes-system.de/wp-content/uploads/2019/02/cropped-yes_logo_blue.png" />
<?php
	echo '<h2 title="php ebayapi_sdk_calls.php set_consent">Token generiert</h2>';
	echo '<a href="javascript:;" onclick="copyToClipboard(\''.$_REQUEST['code'].'\')">Kopieren</a> Sie diesen Token in das Eingabeformular im Browserfenster Ihres YES Systems.</span><br />';
	echo '<div class="token_code">'.$_REQUEST['code'].'</div>';
?>
			<br /><i style="color: #444; font-size: 0.8em;">Anschliessend k&ouml;nnen Sie diese Seite schliessen.</i>
		</div>
	</body>
</html>	
<?php
	exit;
}



if(isset($_REQUEST['sessionid']) and $_REQUEST['sessionid'] != ''){
// BOF TEST
$EBAYAPI = new ebayApi;
$site = EBAY_SITE;
$site_id = $EBAYAPI->get_site_id_from_name($site);
//$user = EBAY_USER;
$user = $_POST['username'];

	$client = new \GuzzleHttp\Client();
        if(!file_exists(\main::get_secure_path().'EBAY_DEVELOPER_KEYS.ini')){
            throw new \Exception('Missing developer keys ini file');
        }
        $ini = parse_ini_file(\main::get_secure_path	().'EBAY_DEVELOPER_KEYS.ini',true);
	
        $env = (defined('EBAY_TESTMODE') and constant('EBAY_TESTMODE') == '1') ? 'test' : 'prod';
	$devId = $ini['ebay-config']['dev-key-'.$env];
	$appId = $ini['ebay-config']['app-key-'.$env];
	$certId = $ini['ebay-config']['cert-id-'.$env];
	$callName = 'FetchToken';
        $call_params = [
            'headers' => [
//                'X-EBAY-API-COMPATIBILITY-LEVEL' => self::COMPAT_LEVEL,
                'X-EBAY-API-DEV-NAME'            => $devId,
                'X-EBAY-API-APP-NAME'            => $appId,
                'X-EBAY-API-CERT-NAME'           => $certId,
            ],
            'body' => '<?xml version="1.0" encoding="utf-8"?>
<FetchTokenRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <SessionID>'.$_REQUEST['sessionid'].'</SessionID>
</FetchTokenRequest>'
        ];
        $sand = false;
        if($_REQUEST['username'] == 'testuser_mario2020'){
        	$sand = true;
        }
        $url = ($sand)?'https://api.sandbox.ebay.com/ws/api.dll':'https://api.ebay.com/ws/api.dll';
        $res = $client->request('POST', $url, $call_params); 
	yes_debug((string)$res->getBody());exit;
/*
$s = $EBAYAPI->getTradingService($user, $site_id);
$req = new \DTS\eBaySDK\Trading\Types\FetchTokenRequestType([
	'SessionID'=>$_REQUEST['sessionid']
]);
$res = $s->FetchToken($req);
*/
	$target_url = $_REQUEST['src'];
/*
	$query = parse_url($_SERVER['HTTP_REFERER']);
	$parts = explode('&',$query['query']);
	foreach($parts as $part){
		if(stristr($part,'runame=')){
			$rp = explode('=',$part);
			$runame = $rp[1];
		}
	}
*/
	$username = xtc_db_input($_REQUEST['username']);
	$env = $environment;
	yes_mail_debug(print_r($res,true));
	if(isset($res->eBayAuthToken) and $res->eBayAuthToken != '' and isset($_REQUEST['username']) and $_REQUEST['username'] != ''){
		$token = xtc_db_input($res->eBayAuthToken);
		$expire = $res->HardExpirationTime->format('Y-m-d H:i:s');
		if(strstr($target_url,'localhost')){
			printf("LOCALHOST ... selber in ebay_auth Tabelle einf&uuml;gen<br /><br />Token: <pre>%s</pre><br />Expire: %s<br />User: %s<br />",
				$token, $expire, $username
			);
			exit;
		}
		// IN DER DEV SOAP USER VERWALTUNG UPDATEN
		$server = $target_url;
		$server = str_replace('https','http',$server);
		xtc_db_query("DELETE FROM soap_users WHERE ebay_userid='".$username."' and url='".$server."' LIMIT 1");
		xtc_db_query("INSERT INTO soap_users SET ebay_userid='".$username."',url='".$server."'");
	}
	/**
          * BOF - VERTEILTE SOAP SERVER
	  * WIR SCHREIBEN EIN PHP FILE DAS SICH DIE ANDEREN SOAP
          * VERTEILER REGELMAESSIG HERUNTERLADEN UM DIE SOAP ANFRAGEN WEITERZULEITEN
        */
	$lines = array();
	$query = xtc_db_query("SELECT * FROM soap_users");
	while($record = xtc_db_fetch_array($query)){
		$lines[] = sprintf("\t'%s'=>'%s',",$record['ebay_userid'],$record['url']);
	}
	if(sizeOf($lines)){
		$code = sprintf("<?php\r\n\$soap_user_allocations = array(\r\n%s);", implode("\n",$lines));
		$file = 'soap_user_table.php';
		if(is_file($file)){
			unlink($file);
		}
		file_put_contents($file, $code);
		chmod($file,0444);
	}
	/**
          * EOF - VERTEILTE SOAP SERVER
        */

	$url = sprintf(
		"%saccept_from_ebaytoken.php?username=%s&token=%s&expire=%s&sessionid=%s&environment=%s",
		$target_url,$username,urlencode($token),$expire,urlencode($_REQUEST['sessionid']),$environment
	);
	header("Location: ".$url);
	exit;
}
?>
<html>
<head>
	<title>YES4Trade Token Registrierung abschliessen</title>
</head>
<body>
<h1>YES4Trade</h1>
<h3>Token Registrierung abschliessen</h3>
<p>Bitte geben Sie die AuthentifizierungsID ein, die Sie per Email erhalten haben.</p>
<form action="accept.php" method="POST">
<input type="hidden" name="environment" value="<?php echo $environment; ?>" />
eBay Username: <input type="hidden" name="username" value="<?php echo $_REQUEST['username']; ?>"><?php echo $_REQUEST['username']; ?>
<br />
AuthentifizierungsID: <input type="text" name="sessionid" value="" />
<br />
<input type="hidden" name="src" value="<?php echo $_REQUEST['src']; ?>" />
<br />
<input type="submit" value="Token Prozess abschliessen" />

</form>
<hr>
<a href="http://yes4trade.de">yes websolutions</a>
</body>
</html>
</body>

