<?php



include(dirname(__FILE__).'/../../config/config.inc.php');

include(dirname(__FILE__).'/paypal.php');



$errors = '';

$paypal = new Paypal();



$params = 'cmd=_notify-validate';

foreach ($_POST AS $key => $value)

	$params .= '&'.$key.'='.urlencode(stripslashes($value));

	

$paypalServer = 'www.'.(Configuration::get('PAYPAL_SANDBOX') ? 'sandbox.' : '').'paypal.com';



$header = 'POST /cgi-bin/webscr HTTP/1.0'."\r\n" .

          'Host: '.$paypalServer."\r\n".

          'Content-Type: application/x-www-form-urlencoded'."\r\n".

          'Content-Length: '.Tools::strlen($params)."\r\n".

          'Connection: close'."\r\n\r\n";



if ($fd = fsockopen($paypalServer, 80, $errno, $errstr, 30))

{

	fputs($fd, $header.$params);

	

	$verified = false;

	$read = '';

    while (!feof($fd))

	{

		$reading = trim(fgets($fd, 1024));

		if ($reading == 'VERIFIED')

		{

		 	$verified = true;

			break;

		}

		$read .= $reading;

	}

	fclose ($fd);

	

	if ($verified)

	{

		if (!isset($_POST['mc_gross']))

			$errors .= $paypal->getL('mc_gross').'<br />';

		if (!isset($_POST['payment_status']))

			$errors .= $paypal->getL('payment_status').'<br />';

		elseif ($_POST['payment_status'] != 'Completed')

			$errors .= $paypal->getL('payment').$_POST['payment_status'].'<br />';

		if (!isset($_POST['custom']))

			$errors .= $paypal->getL('custom').'<br />';

		if (!isset($_POST['txn_id']))

			$errors .= $paypal->getL('txn_id').'<br />';

		if (!isset($_POST['mc_currency']))

			$errors .= $paypal->getL('mc_currency').'<br />';

		if (empty($errors))

		{

			$cart = new Cart(intval($_POST['custom']));

			if (!$cart->id)

				$errors = $paypal->getL('cart').'<br />';

			elseif (Order::getOrderByCartId(intval($_POST['custom'])))

				$errors = $paypal->getL('order').'<br />';

			else

				$paypal->validateOrder($_POST['custom'], _PS_OS_PAYMENT_, $_POST['mc_gross'], $paypal->displayName, $paypal->getL('transaction').$_POST['txn_id']);

		}

	}

	else

		$errors .= $paypal->getL('verified').'<br />'.$read;

	

}

else

	$errors .= $paypal->getL('connect');



if (!empty($errors) AND isset($_POST['custom']))

	$paypal->validateOrder(intval($_POST['custom']), _PS_OS_ERROR_, 0, $paypal->displayName, $errors);



?>