<?php

/****************************************************
 PayPal includes the following API Signature for making API
 calls to the PayPal sandbox:

 API Username 	sdk-three_api1.sdk.com
 API Password 	QFZCWN5HZM8VBG7Q
 API Signature 	A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU

 ****************************************************/

/*
 # true - тестовый режим, https://www.sandbox.paypal.com
 # false - рабочий режим, https://www.paypal.com/
*/
//$SandboxFlag = false;
$SandboxFlag = true;

/**
 # API user: The user that is identified as making the call. you can
 # also use your own API username that you created on PayPal’s sandbox
 # or the PayPal live site
 */

define('API_USERNAME', 'nataly_1314795713_biz_api1.hostmake.ru');

/**
 # API_password: The password associated with the API user
 # If you are using your own API username, enter the API password that
 # was generated by PayPal below
 # IMPORTANT - HAVING YOUR API PASSWORD INCLUDED IN THE MANNER IS NOT
 # SECURE, AND ITS ONLY BEING SHOWN THIS WAY FOR TESTING PURPOSES
 */

define('API_PASSWORD', '1314795733');

/**
 # API_Signature:The Signature associated with the API user. which is generated by paypal.
 */

define('API_SIGNATURE', 'AKF.NjiuiXmELognC3ImjWqYgQ89APiQyO8rxvI5sctA-ADaTNXZo30s');

// BN Code is only applicable for partners
define('sBNCode','PP-ECWizard');

/**
 # Endpoint: this is the server URL which you have to connect for submitting your API request.
 */

/* Define the PayPal URL. This is the URL that the buyer is
 first sent to to authorize payment with their paypal account
 change the URL depending if you are testing on the sandbox
 or going to the live PayPal site
 For the sandbox, the URL is
 https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
 For the live site, the URL is
 https://www.paypal.com/webscr&cmd=_express-checkout&token=
 */
if ($SandboxFlag == true)
{
	define('API_ENDPOINT', "https://api-3t.sandbox.paypal.com/nvp");
	define('PAYPAL_URL', "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=");
}
else
{
	define('API_ENDPOINT', "https://api-3t.paypal.com/nvp");
	define('PAYPAL_URL', "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=");
}

/*
 # Third party Email address that you granted permission to make api call.
 */
define('SUBJECT','sdk-three@sdk.com');

/**
 USE_PROXY: Set this variable to TRUE to route all the API requests through proxy.
 like define('USE_PROXY',TRUE);
 */
define('USE_PROXY', FALSE);

/**
 PROXY_HOST: Set the host name or the IP address of proxy server.
 PROXY_PORT: Set proxy port.

 PROXY_HOST and PROXY_PORT will be read only if USE_PROXY is set to TRUE
 */
define('PROXY_HOST', '127.0.0.1');
define('PROXY_PORT', '808');

/**
 # Version: this is the API version in the request.
 # It is a mandatory parameter for each API request.
 # The only supported value at this time is 2.3
 */
define('VERSION', 56.0);

// Ack related constants
define('ACK_SUCCESS', 'Success');
define('ACK_SUCCESS_WITH_WARNING', 'SuccessWithWarning');

/* Оплата через PayPal */
class system_of_pay_handler
{
	/* Определяем валюты для USD */
	var $default_currency_id = 5;

	/**
	 * Обработка статуса оплаты
	 *
	 */
	function ProcessResult()
	{
		/* Информация о заказе */
		$order_id = to_int($_REQUEST['order_id']);

		if (!$order_id)
		{
			return false;
		}

		$shop = & singleton('shop');

		$order_row = $shop->GetOrder($order_id);

		if (!$order_row)
		{
			return false;
		}

		$shop_row = $shop->GetShop($order_row['shop_shops_id']);

		ini_set('session.bug_compat_42',0);
		ini_set('session.bug_compat_warn',0);

		/* Gather the information to make the final call to
		 finalize the PayPal payment.  The variable nvpstr
		 holds the name value pairs
		 */
		//$_SESSION['token'] = $_REQUEST['token'];
		//$_SESSION['payer_id'] = $_REQUEST['PayerID'];

		//$_SESSION['paymentAmount']=$_REQUEST['paymentAmount'];
		//$_SESSION['currCodeType']=$_REQUEST['currencyCodeType'];
		//$_SESSION['paymentType']=$_REQUEST['paymentType'];

		//$resArray = $_SESSION['reshash'];
		//$_SESSION['TotalAmount']= $resArray['AMT'] + $resArray['SHIPDISCAMT'];

		$token =urlencode($_REQUEST['token']);
		$paymentType = urlencode($_REQUEST['paymentType']);
		$currCodeType = urlencode($_REQUEST['currencyCodeType']);
		$payerID = urlencode($_REQUEST['PayerID']);
		$serverName = urlencode($_SERVER['SERVER_NAME']);
		
		$paymentAmount =urlencode ($_SESSION['TotalAmount']);

		$nvpstr  = '&TOKEN=' . $token . '&PAYERID=' . $payerID . '&PAYMENTREQUEST_0_PAYMENTACTION=' . $paymentType . '&PAYMENTREQUEST_0_AMT=' . $paymentAmount;
		$nvpstr .= '&PAYMENTREQUEST_0_CURRENCYCODE=' . $currCodeType . '&IPADDRESS=' . $serverName; 
		
		if(defined("VERSION") && VERSION < 63) 
		{
			$nvpstr .= '&PAYMENTACTION=' . $paymentType . '&AMT=' . $paymentAmount;
		}

		/* Make the call to PayPal to finalize payment
		 If an error occured, show the resulting errors
		 */
		$resArray = $this->hash_call("DoExpressCheckoutPayment", $nvpstr);

		/* Display the API response back to the browser.
		 If the response from PayPal was a success, display the response parameters'
		 If the response was an error, display the errors received using APIError.php.
		 */
		$ack = strtoupper($resArray["ACK"]);

		/* Устанавливаем параметры */
		$param['id'] = $order_row['shop_order_id'];
		$param['shop_shops_id'] = $order_row['shop_shops_id'];

		if( $ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING" )
		{
			/* Проверка прошла успешно!
			 Добавляем комментарий */
			$param['system_information'] = "Товар оплачен через PayPal.\n".
			"Атрибуты:\n".
			"Transaction ID: {$resArray['TRANSACTIONID']}\n".
			"Amount: {$resArray['AMT']} {$currCodeType}";

			/* Устанавливаем признак оплаты */
			//$param['date_of_pay'] = date("Y-m-d H:i:s");
			//$param['status_of_pay'] = true;

			// Обновляем информацию о заказе
			$shop->InsertOrder($param);

			// Изменяем статус оплаты ПОСЛЕ ОБНОВЛЕНИЯ ИНФОРМАЦИ, генерируем ссылки для эл.товаров, списываем товары
			$shop->SetOrderPaymentStatus($order_id);
		}
		else
		{
			$param['system_information'] = "PayPal не подтвердил платеж, ответ: {$ack}!";

			// Обновляем информацию о заказе
			$shop->InsertOrder($param);
		}

		// Отправку письма об оплате делаем только после вставки информации об оплате
		if( $ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING" )
		{
			$structure = & singleton('Structure');
			$structure_row = $structure->GetStructureItem(to_int($shop_row['structure_id']));

			$lib = new lib();
			$LA = $lib->LoadLibPropertiesValue(to_int($structure_row['lib_id']), to_int($structure_row['structure_id']));

			$order_row = $shop->GetOrder($order_id);

			// Отправляем письмо администратору о подтверждении платежа
			$shop->SendMailAboutOrder($order_row['shop_shops_id'], $order_id, $order_row['site_users_id'],
			to_str($LA['xsl_letter_to_admin']),
			to_str($LA['xsl_letter_to_user']),
			$order_row['shop_order_users_email'],
			array(
			'admin-content-type' => 'html',
			'user-content-type' => 'html',
			'admin-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_confirm_admin_subject'], $order_id, $shop_row['shop_shops_name'], $order_row['shop_order_date_of_pay']),
			'user-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_confirm_user_subject'], $order_id, $shop_row['shop_shops_name'], $order_row['shop_order_date_of_pay']),
			'email_from_admin' => $order_row['shop_order_users_email']));
		}
	}

	function GetHandlerUrl($shop_shops_id)
	{
		$shop = & singleton('shop');
		$shop_row = $shop->GetShop($shop_shops_id);

		if ($shop_row)
		{
			/* Информация об алиасе сайта */
			$site = & singleton ('site');
			$site_alias = $site->GetCurrentAlias($shop_row['site_id']);

			/* Получаем путь к магазину */
			$Structure = & singleton('Structure');
			$shop_path = "/".$Structure->GetStructurePath($shop_row['structure_id'], 0);

			$handler_url = 'http://'.$site_alias.$shop_path.'cart/';
		}
		else
		{
			$handler_url = '';
		}

		return $handler_url;
	}


	/**
	 * Отображает стартовую страницу для оплаты через Web Money.
	 *
	 */
	function ShowPurseRequest()
	{
		$shop = & singleton('shop');
		
		/* ID платежной системы берем из сессии */
		$system_of_pay_id = to_int($_SESSION['system_of_pay_id']);
		$row_system_of_pay = $shop->GetSystemOfPay($system_of_pay_id);
		
		if ($row_system_of_pay)
		{
			$shop_id = $row_system_of_pay['shop_shops_id'];
		}
		else
		{
			return false;
		}

		/* Получаем id текущего пользователя сайта */
		if (class_exists('SiteUsers'))
		{
			/* Получаем id текущего пользователя сайта */
			$SiteUsers = & singleton('SiteUsers');
			$site_users_id = $SiteUsers->GetCurrentSiteUser();
		}
		else
		{
			$site_users_id = false;
		}

		// статус платежа, по умолчанию 0
		$order_row['status_of_pay'] = 0 ;

		// дата платежа, по умолчанию пустая строка
		$order_row['date_of_pay'] = '';

		$order_row['description'] = to_str($_SESSION['description']);

		// описание и системная информация, по умолчанию пустая строка
		if (to_str($_SESSION['shop_coupon_text']) != '')
		{
			$order_row['description'] .= "Купон на скидку: ".to_str($_SESSION['shop_coupon_text'])."\n";
		}

		if (!isset($_SESSION['last_order_id']))
		{
			$_SESSION['last_order_id'] = 0;
		}

		// Если заказ еще не был оформлен
		if ($_SESSION['last_order_id'] == 0)
		{
			/* Оформляем заказ */
			$order_id = $shop->ProcessOrder($shop_id, $site_users_id, $system_of_pay_id, $order_row);
		}
		else
		{
			$order_id = $_SESSION['last_order_id'];
		}

		if ($order_id > 0)
		{
			if (!class_exists('SiteUsers'))
			{
				/* Класс пользователей сайта не существует, дописываем информацию о заказчике
				 в поле shop_order_description из текущей сессии */
				if ($order_row)
				{
					/* Описание заказчика */
					$order_row['description'] .= "Информация о заказчике:\n"
					."Имя: ".to_str($_SESSION['site_users_name'])."\n"
					."Фамилия: ".to_str($_SESSION['site_users_surname'])."\n"
					."Отчество: ".to_str($_SESSION['site_users_patronymic'])."\n"
					."E-Mail: ".to_str($_SESSION['site_users_email'])."\n"
					."Телефон: ".to_str($_SESSION['site_users_phone'])."\n"
					."Факс: ".to_str($_SESSION['site_users_fax'])."\n"
					."Адрес: ".to_str($_SESSION['full_address'])."\n";

					/* Дополнительная информация о заказе */
					$order_row['system_information'] = to_str($_SESSION['system_information']);

					/* Обязательно добавляем идентификатор! */
					$order_row['id'] = $order_id;

					$shop->InsertOrder($order_row);
				}
			}

			$order_row = $shop->GetOrder($order_id);

			if ($order_row)
			{
				$this->PrintOrder($order_id);
			}

			$shop_row = $shop->GetShop($shop_id);

			if ($_SESSION['last_order_id'] == 0)
			{
				$structure = & singleton('Structure');
				$structure_row = $structure->GetStructureItem(to_int($shop_row['structure_id']));

				$lib = new lib();
				$LA = $lib->LoadLibPropertiesValue(to_int($structure_row['lib_id']), to_int($structure_row['structure_id']));

				$date_str = date("d.m.Y H:i:s");

				if (trim(to_str($order_row['shop_order_account_number'])) != '')
				{
					$shop_order_account_number = trim(to_str($order_row['shop_order_account_number']));
				}
				else
				{
					$shop_order_account_number = $order_id;
				}

				/* Отправляем письмо заказчику */
				$shop->SendMailAboutOrder($shop_id,
				$order_id,
				$site_users_id,
				to_str($LA['xsl_letter_to_admin']),
				to_str($LA['xsl_letter_to_user']),
				$order_row['shop_order_users_email'],
				array('admin-content-type' => 'html',
				'user-content-type' => 'html',
				'admin-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_admin_subject'], $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
				'user-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_user_subject'], $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
				'email_from_admin' => $order_row['shop_order_users_email']));
			}

			// Сохраняем ID последнего оформленного заказа ТОЛЬКО ПОСЛЕ ОТПРАВКИ ПИСЬМА
			$_SESSION['last_order_id'] = $order_id;
		}
		else
		{
			switch ($order_id)
			{
				case -1:
					{
						?><div id="error">Ошибка вставки заказа в базу данных. Обратитесь к администратору.</div><?php
						break;
					}
				case -2:
					{
						?><div id="error">Ошибка - не найден магазин. Обратитесь к администратору.</div><?php
						break;
					}
				case -3:
					{
						?><div id="error">Ошибка - корзина пуста. Добавьте товар в корзину и оформите заказ.</div><?php
						break;
					}
			}
		}
	}

	/**
	 * Метод, запускающий выполнение обработчика
	 */
	function Execute()
	{
		/* Пришло подтверждение оплаты, обработаем его */
		if (isset($_REQUEST['PayPalOrderConfirmation']))
		{
			$this->ProcessResult();
			return true;
		}
		
		/* Пришел запрос на редирект, обработаем его */
		if (isset($_REQUEST['paymentType']))
		{
			$this->ReviewOrder();
			return true;
		}

		/* Иначе оформляем заказ и отображаем стартовую страницу для оплаты через PayPal */
		$this->ShowPurseRequest();
	}

	/**
	 * Обработка формы для получения ссылки и редирект
	 *
	 * @param int $order_id идентификатор заказа
	 */
	function ReviewOrder()
	{
		/* Информация о заказе */
		$order_id = to_int($_REQUEST['order_id']);

		if (!$order_id)
		{
			return false;
		}

		$shop = & singleton('shop');

		$order_row = $shop->GetOrder($order_id);

		if (!$order_row)
		{
			return false;
		}

		$shop_row = $shop->GetShop($order_row['shop_shops_id']);

		/****************************************************
		 CallerService.php

		 This file uses the constants.php to get parameters needed
		 to make an API call and calls the server.if you want use your
		 own credentials, you have to change the constants.php

		 Called by TransactionDetails.php, ReviewOrder.php,
		 DoDirectPaymentReceipt.php and DoExpressCheckoutPayment.php.

		 ****************************************************/

		/* An express checkout transaction starts with a token, that
		 identifies to PayPal your transaction
		 In this example, when the script sees a token, the script
		 knows that the buyer has already authorized payment through
		 paypal.  If no token was found, the action is to send the buyer
		 to PayPal to first authorize payment
		 */
		if(!isset($_REQUEST['token']))
		{
			/* The servername and serverport tells PayPal where the buyer
			 should be directed back to after authorizing payment.
			 In this case, its the local webserver that is running this script
			 Using the servername and serverport, the return URL is the first
			 portion of the URL that buyers will return to after authorizing payment
			 */
			$currencyCodeType = $_REQUEST['currencyCodeType'];
			$paymentType = $_REQUEST['paymentType'];

			/*$personName = $_REQUEST['PERSONNAME'];
			$SHIPTOSTREET = $_REQUEST['SHIPTOSTREET'];
			$SHIPTOCITY = $_REQUEST['SHIPTOCITY'];
			$SHIPTOSTATE = $_REQUEST['SHIPTOSTATE'];
			$SHIPTOCOUNTRYCODE = $_REQUEST['SHIPTOCOUNTRYCODE'];
			$SHIPTOZIP = $_REQUEST['SHIPTOZIP'];
			$L_NAME0 = $_REQUEST['L_NAME0'];
			$L_AMT0 = $_REQUEST['L_AMT0'];
			$L_QTY0 = $_REQUEST['L_QTY0'];*/

			/* The returnURL is the location where buyers return when a
			 payment has been succesfully authorized.
			 The cancelURL is the location buyers are sent to when they hit the
			 cancel button during authorization of payment during the PayPal flow
			 */

			$handler_url = $this->GetHandlerUrl($order_row['shop_shops_id']);

			$returnURL = urlencode($handler_url."?currencyCodeType={$currencyCodeType}&paymentType={$paymentType}&order_id={$order_id}&payment=success&PayPalOrderConfirmation=1");
			$cancelURL = urlencode($handler_url."?paymentType={$paymentType}&order_id={$order_id}&payment=failed");

			$paymentAmount = $this->GetOrderSum($order_id);

			$nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
			$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
			$nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
			$nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
			$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
			
			if(defined("VERSION") && VERSION < 63)
			{
				$nvpstr = $nvpstr . "&AMT=" . $paymentAmount;
			}
			
			$_SESSION["currencyCodeType"] = $currencyCodeType;	  
			$_SESSION["PaymentType"] = $paymentType;
			$_SESSION['TotalAmount'] = $paymentAmount;

			//'--------------------------------------------------------------------------------------------------------------- 
			//' Make the API call to PayPal
			//' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.  
			//' If an error occured, show the resulting errors
			//'---------------------------------------------------------------------------------------------------------------
			
			$resArray = $this->hash_call("SetExpressCheckout", $nvpstr);
			$ack = strtoupper($resArray["ACK"]);
			
			if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
			{
				// Redirect to paypal.com here
				$token = urldecode($resArray["TOKEN"]);
				$payPalURL = PAYPAL_URL.$token;
				?>
				<script language="JavaScript" type="text/javascript">
				location="<?php echo $payPalURL?>";
				</script>
				<?php
				exit();
			} else  {
				//Display a user friendly Error on the page using any of the following error information returned by PayPal
				$ErrorCode = urldecode(to_str($resArray["L_ERRORCODE0"]));
				$ErrorShortMsg = urldecode(to_str($resArray["L_SHORTMESSAGE0"]));
				$ErrorLongMsg = urldecode(to_str($resArray["L_LONGMESSAGE0"]));
				$ErrorSeverityCode = urldecode(to_str($resArray["L_SEVERITYCODE0"]));

				echo "<p><b>SetExpressCheckout API call failed.</b></p>";
				echo "Detailed Error Message: " . $ErrorLongMsg;
				echo "<br />Short Error Message: " . $ErrorShortMsg;
				echo "<br />Error Code: " . $ErrorCode;
				echo "<br />Error Severity Code: " . $ErrorSeverityCode;
			}
		} else {
			/* At this point, the buyer has completed in authorizing payment
			 at PayPal.  The script will now call PayPal with the details
			 of the authorization, incuding any shipping information of the
			 buyer.  Remember, the authorization is not a completed transaction
			 at this state - the buyer still needs an additional step to finalize
			 the transaction
			 */
			 

			//$token = urlencode($_REQUEST['token']);

			/* Build a second API request to PayPal, using the token as the
			 ID to get the details on the payment authorization
			 */
			//$nvpstr="&TOKEN=".$token;

			/* Make the API call and store the results in an array.  If the
			 call was a success, show the authorization details, and provide
			 an action to complete the payment.  If failed, show the error
			 */
			/*$resArray = $this->hash_call("GetExpressCheckoutDetails", $nvpstr);
			//$_SESSION['reshash'] = $resArray;
			$ack = strtoupper($resArray["ACK"]);
			var_dump($resArray);
			if($ack == "SUCCESS" || $ack=="SUCCESSWITHWARNING")
			{
				$_SESSION['token'] = $resArray['token'];
				$_SESSION['payer_id'] = $resArray['PayerID'];

				$_SESSION['paymentAmount'] = $resArray['paymentAmount'];
				$_SESSION['currCodeType'] = $resArray['currencyCodeType'];
				$_SESSION['paymentType'] = $resArray['paymentType'];

				//$resArray = $_SESSION['reshash'];
				$_SESSION['TotalAmount'] = $resArray['AMT'] + $resArray['SHIPDISCAMT'];
			}
			else
			{
				//Redirecting to APIError.php to display errors.
				//$location = "APIError.php";
				//header("Location: $location");
				//var_dump($ack);
			}*/
		}
	}

	function GetOrderSum($order_id)
	{
		$shop = & singleton('shop');

		$order_row = $shop->GetOrder($order_id);

		if ($order_row)
		{
			$order_sum = $shop->GetOrderSum($order_id);

			$shop_row = $shop->GetShop($order_row['shop_shops_id']);

			/* Делаем перерасчет суммы в валюты, выбранные для PayPal */
			$shop_currency_id = $shop_row['shop_currency_id'];

			/* Для валюты, в которой осуществляется платеж */
			$coefficient = $shop->GetCurrencyCoefficientToShopCurrency($shop_currency_id, $this->default_currency_id);
			$default_sum = round($order_sum * $coefficient, 2);
		}
		else
		{
			$default_sum = false;
		}
		return $default_sum;
	}

	/**
	 * Метод для отображения формы заказа для печати.
	 *
	 * @param int $order_id идентификатор заказа
	 */
	function PrintOrder($order_id)
	{
		$shop = & singleton('shop');

		$order_row = $shop->GetOrder($order_id);
		if (!$order_row)
		{
			return false;
		}

		if ($order_row)
		{
			$default_sum = $this->GetOrderSum($order_id);

			$handler_url = $this->GetHandlerUrl($order_row['shop_shops_id']);

			?>
<h1>Оплата через систему PayPal</h1>

<!-- Форма для оплаты через WMR -->
<form id="pay" name="pay" method="post" action="<?php echo $handler_url?>">
<input type="hidden" name="paymentType" value="Sale">
<input type="hidden" name="L_NAME0"	value="Order N <?php echo $order_row['shop_order_account_number']?>">
<input type="hidden" name="L_AMT0" value="<?php echo $default_sum?>" /> 
<input type="hidden" name="L_QTY0" value="1" />
<table>
	<tr>
		<td class="field"><strong><?php echo $default_sum?></strong></td>
		<td><select name="currencyCodeType">
			<option value="USD">USD</option>
			 <!--<option value="GBP">GBP</option> -->
					 <!--<option value="EUR">EUR</option>
					<option value="JPY">JPY</option>
					<option value="CAD">CAD</option>
					<option value="AUD">AUD</option>-->
		</select></td>
	</tr>
	<!--<tr>
		<td class="field">Ship To:</td>
		<td>&nbsp;</td>
	</tr>

	<tr>
		<td class="field">Name:</td>
		<td><input type="text" size="30" maxlength="32" name="PERSONNAME"
			value="" /></td>
	</tr>
	<tr>
		<td class="field">Street:</td>
		<td><input type="text" size="30" maxlength="32" name="SHIPTOSTREET"
			value="" /></td>
	</tr>
	<tr>
		<td class="field">City:</td>
		<td><input type="text" size="30" maxlength="32" name="SHIPTOCITY"
			value="" /></td>
	</tr>
	<tr>
		<td class="field">State:</td>
		<td><input type="text" size="30" maxlength="32" name="SHIPTOSTATE"
			value="" /></td>
	</tr>
	<tr>
		<td class="field">Country:</td>
		<td><input type="text" size="30" maxlength="32"
			name="SHIPTOCOUNTRYCODE" value="" /></td>
	</tr>
	<tr>
		<td class="field">Zip Code:</td>
		<td><input type="text" size="30" maxlength="32" name="SHIPTOZIP"
			value="" /></td>
	</tr>-->
	<tr>
		<td colspan="2" align="center"><input type="image" name="submit"
			src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" /></td>
	</tr>
	<tr>
		<td colspan="2" align="center"><small>Save time. Pay securely without
		sharing your financial information.</small></td>
	</tr>
</table>

<!-- Для определения платежной системы на странице корзины --> <input
	type="hidden" name="order_id" value="<?php echo $order_id?>">

<div style="clear: both;"></div>
</form>

			<?php
		}
	}

	/**
	 * Изменение статуса заказа. Позволяет пользователю внедрять собственные
	 * обработчики при изменении статуса.
	 *
	 * @param array $param массив атрибутов
	 * - $param['shop_order_id'] идентификатор заказа
	 * - $param['prev_order_row'] информация о предыдущем состоянии заказа (доступно не всегда)
	 * - $param['action'] выполняемое действие над заказом, может принимать значения:
	 * edit (редактирование заказа), cancel (отмена заказа),
	 * status (изменение статуса заказа), delete (удаление заказа),
	 * edit_item (редактирование товара в заказе), delete_item (удаление товара в заказе)
	 */
	function ChangeStatus($param = array())
	{
		// Если произошло изменение статуса
		if (isset($param['action']) && in_array($param['action'], array('status', 'edit')))
		{
			$shop_order_id = to_int($param['shop_order_id']);

			$shop = & singleton('shop');

			$order_row = $shop->GetOrder($shop_order_id);

			// Получаем информацию о магазине
			$shop_id = to_int($order_row['shop_shops_id']);

			$shop_row = $shop->GetShop($shop_id);

			$structure = & singleton('Structure');
			$structure_row = $structure->GetStructureItem(to_int($shop_row['structure_id']));

			$lib = new lib();
			$LA = $lib->LoadLibPropertiesValue(to_int($structure_row['lib_id']), to_int($structure_row['structure_id']));

			if ($order_row)
			{
				$DateClass = new DateClass();
				$date_str = $DateClass->datetime_format($order_row['shop_order_date_time']);
			}
			else
			{
				$date_str = '';
			}

			// Если предыдущий статус заказа был 1, то меняем тему на подтверждение
			if (to_int($order_row['shop_order_status_of_pay']) == 1)
			{
				$admin_subject = $GLOBALS['MSG_shops']['shop_order_confirm_admin_subject'];
				$user_subject = $GLOBALS['MSG_shops']['shop_order_confirm_user_subject'];
			}
			else
			{
				$admin_subject = $GLOBALS['MSG_shops']['shop_order_admin_subject'];
				$user_subject = $GLOBALS['MSG_shops']['shop_order_user_subject'];
			}

			$not_paid = isset($param['prev_order_row']) && $param['prev_order_row']['shop_order_status_of_pay'] == 0;
			
			// Письмо отправляем только при установке статуса активности для заказа
			if (to_int($order_row['shop_order_status_of_pay']) == 1 && $not_paid)
			{
				if (trim(to_str($order_row['shop_order_account_number'])) != '')
				{
					$shop_order_account_number = trim(to_str($order_row['shop_order_account_number']));
				}
				else
				{
					$shop_order_account_number = $shop_order_id;
				}

				/* Отправляем письмо заказчику */
				$shop->SendMailAboutOrder($shop_id,
				$shop_order_id,
				$order_row['site_users_id'],
				to_str($LA['xsl_letter_to_admin']),
				to_str($LA['xsl_letter_to_user']),
				$order_row['shop_order_users_email'],
				array('admin-content-type' => 'html',
				'user-content-type' => 'html',
				'admin-subject' => sprintf($admin_subject, $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
				'user-subject' => sprintf($user_subject, $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
				'email_from_admin' => $order_row['shop_order_users_email']));
			}
		}
	}

	/**
	  '-------------------------------------------------------------------------------------------------------------------------------------------
	  * hash_call: Function to perform the API call to PayPal using API signature
	  * @methodName is name of API  method.
	  * @nvpStr is nvp string.
	  * returns an associtive array containing the response from the server.
	  '-------------------------------------------------------------------------------------------------------------------------------------------
	*/
	function hash_call($methodName,$nvpStr)
	{
		//setting the curl parameters.
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, API_ENDPOINT);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);

		//turning off the server and peer verification(TrustManager Concept).
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_POST, 1);
		
	    //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
	   //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php 
		if(USE_PROXY)
			curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST. ":" . PROXY_PORT); 

		//NVPRequest for submitting to server
		$nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode(VERSION) . "&PWD=" . urlencode(API_PASSWORD) . "&USER=" . urlencode(API_USERNAME) . "&SIGNATURE=" . urlencode(API_SIGNATURE) . $nvpStr . "&BUTTONSOURCE=" . urlencode(sBNCode);

		//setting the nvpreq as POST FIELD to curl
		curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

		//getting response from server
		$response = curl_exec($ch);

		//convrting NVPResponse to an Associative Array
		$nvpResArray = $this->deformatNVP($response);
		$nvpReqArray = $this->deformatNVP($nvpreq);
		$_SESSION['nvpReqArray']=$nvpReqArray;

		if (curl_errno($ch)) 
		{
			// moving to display page to display curl errors
			  $_SESSION['curl_error_no']=curl_errno($ch) ;
			  $_SESSION['curl_error_msg']=curl_error($ch);

			  //Execute the Error handling module to display errors. 
		} 
		else 
		{
			 //closing the curl
		  	curl_close($ch);
		}

		return $nvpResArray;
	}

	/** This function will take NVPString and convert it to an Associative Array and it will decode the response.
	 * It is usefull to search for a particular key and displaying arrays.
	 * @nvpstr is NVPString.
	 * @nvpArray is Associative Array.
	 */
	function deformatNVP($nvpstr)
	{
		$intial=0;
	 	$nvpArray = array();

		while(strlen($nvpstr))
		{
			//postion of Key
			$keypos= strpos($nvpstr,'=');
			//position of value
			$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);

			/*getting the Key and Value values and storing in a Associative Array*/
			$keyval=substr($nvpstr,$intial,$keypos);
			$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
			//decoding the respose
			$nvpArray[urldecode($keyval)] =urldecode( $valval);
			$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
	     }
		return $nvpArray;
	}
}
?>