<?php
/*
  PayPal module for osCommerce, Open Source E-Commerce Solutions
  Author: Aziz Mahmoudy
  email: aziz.mahmoudy@hotmail.com

  v2.23 - dmglampers
  v2.24 - alexkid
*/

require('includes/application_top.php');
require('includes/classes/http_client.php');
include('constants.php');
require(DIR_WS_LANGUAGES . $language . '/create_account.php');

$API_UserName=API_USERNAME;
$API_Password=API_PASSWORD;
$API_Signature=API_SIGNATURE;
$API_Endpoint =API_ENDPOINT;
//$ALERTMAIL = ALERTMAIL;
$version = VERSION;
$CERT_FILE_PATH = MODULE_PAYMENT_PPEC_CERT_PATH;
$notif = MODULE_PAYMENT_PPEC_IPN;
$LOGO = LOGO;
$ccurl = CCURL;
$com = '';
$lg;
$im;
$currtag;
$arrtag = array();
$ctotal = 0; $cshipping = 0; $classot = array();

$error_show_array = array('SHORTMESSAGE','LONGMESSAGE','ERRORCODE','TIMESTAMP','ACK');
$ppec_debug = PPEC_DEBUG;

$con = $_REQUEST['con'];
if( isset($con)) {
  ppecon();
} else {
  $notif = $_REQUEST['notify_version'];
  if( isset($notif)) {
    $req = 'cmd=_notify-validate';

    foreach ($_POST as $key => $value) {
      $value = urlencode(stripslashes($value));
      $req .= "&$key=$value";
    }

    // post back to PayPal system to validate
    $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Host: www.paypal.com:80\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
    $fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);

    // assign posted variables to local variables
    $item_name = $_POST['item_name'];
    $item_number = $_POST['item_number'];
    $payment_status = $_POST['payment_status'];
    $payment_amount = $_POST['mc_gross'];
    $payment_currency = $_POST['mc_currency'];
    $txn_id = $_POST['txn_id'];
    $receiver_email = $_POST['receiver_email'];
    $payer_email = $_POST['payer_email'];

    if (!$fp) {
      // HTTP ERROR
    } else {
      fputs ($fp, $header . $req);
      while (!feof($fp)) {
        $res = fgets ($fp, 1024);
        if (strcmp ($res, "VERIFIED") == 0) {

          $req .= "Transaction Details: \n\n";
          foreach ($_POST as $key => $value) {
            $value = urldecode(stripslashes($value));
            $req .=  $value."\n";

            switch ($key) {
              case 'txn_id':
                $code = $value;
                break;
              case 'payment_status':
                $status = $value;
                break;
            }
          }

          tep_db_query("update ppec_transaction set paymentstatus = '".$status."' where transactionid = '" .$code. "'");
          $status = strtoupper($status);
          $ord_id = tep_db_query("SELECT status_id as st FROM ppec_transaction_status Where transaction_status = '" .$status. "'");
          $ordid = tep_db_fetch_array($ord_id);
          $st = $ordid['st'];
          $ord_id = tep_db_query("SELECT orders_id as or FROM ppec_transaction Where transactionid = '" .$code. "'");
          $ordid = tep_db_fetch_array($ord_id);
          $or = $ordid['or'];
          tep_db_query("update ".TABLE_ORDERS_STATUS." set orders_status = '".$st."' where orders_id = '" .$or. "'");
          $sql_data_array = array('orders_id' => $or,
                                  'orders_status_id' => $st,
                                  'date_added' => 'now()',
                                  'customer_notified' => '1',
                                  'comments' => '');
          tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

          $ord_id = tep_db_query("SELECT languages_id as la FROM languages Where code = 'fr'");
          $ordid = tep_db_fetch_array($ord_id);
          $la = $ordid['la'];
          $ord_id = tep_db_query("SELECT orders_status_name as na FROM ".TABLE_ORDERS_STATUS." Where orders_status_id = ".$st." and language_id = ".$la);
          $ordid = tep_db_fetch_array($ord_id);
          $na = $ordid['na'];

          //global $ALERTMAIL;
          //mail($ALERTMAIL, "PayPal Notification", $req);
        } else if (strcmp ($res, "INVALID") == 0) {
          // log for manual investigation
          $mail_From = $From_email;
          $mail_To = $receiver_email;
          $mail_Subject = "INVALID IPN POST";
          $mail_Body = "INVALID IPN POST. The raw POST string is below.\n\n" . $req;

          //mail($ALERTMAIL, $mail_Subject, $mail_Body);
        }
      }
      fclose ($fp);
    }

    $req .= "Szczegoly tranzakcji: \n\n";
    foreach ($_POST as $key => $value) {
      $value = urldecode(stripslashes($value));
      $req .=  $value."\n";

      switch ($key) {
        case 'txn_id':
          $code = $value;
          break;
        case 'payment_status':
          $status = $value;
        break;
      }
    }

    tep_db_query("update ppec_transaction set paymentstatus = '".$status."' where transactionid = '" .$code. "'");
    $status = strtoupper($status);
    $ord_id = tep_db_query("SELECT status_id as st FROM ppec_transaction_status Where transaction_status = '" .$status. "'");
    $ordid = tep_db_fetch_array($ord_id);
    $st = $ordid['st'];
    $ord_id = tep_db_query("SELECT orders_id as or FROM ppec_transaction Where transactionid = '" .$code. "'");
    $ordid = tep_db_fetch_array($ord_id);
    $or = $ordid['or'];
    tep_db_query("update ".TABLE_ORDERS_STATUS." set orders_status = '".$st."' where orders_id = '" .$or. "'");
    $sql_data_array = array('orders_id' => $or,
                            'orders_status_id' => $st,
                            'date_added' => 'now()',
                            'customer_notified' => '1',
                            'comments' => '');
    tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

    $ord_id = tep_db_query("SELECT languages_id as la FROM languages Where code = 'fr'");
    $ordid = tep_db_fetch_array($ord_id);
    $la = $ordid['la'];
    $ord_id = tep_db_query("SELECT orders_status_name as na FROM ".TABLE_ORDERS_STATUS." Where orders_status_id = ".$st." and language_id = ".$la);
    $ordid = tep_db_fetch_array($ord_id);
    $na = $ordid['na'];

    //global $ALERTMAIL;
    //mail($ALERTMAIL, "PayPal Notification", $req);
  } else {
    $geppec = $_REQUEST['geppec'];
    if( isset($geppec) ){

      if(!isset($shec) ) {
        $arruri = explode('&', urldecode($_SERVER['REQUEST_URI']));
        foreach ($arruri as $key => $value) {
          //echo $key.":   ".$value."<br>";
          // start - fix to detect & and &amp; correctly
          // fixed the fix 2.23
          if (substr($value, 0, 4) == "amp;") {
            $value = substr($value, 4, strlen($value));
          }
          // end - fix to detect & and &amp; correctly

          if (substr($value, 0, 6) == "cusid=") {
            $customer_id = substr($value, 6, strlen($value));
          } else if (substr($value, 0, 4) == "tok=") {
            $token = substr($value, 4, strlen($value));
          } else  if (substr($value, 0, 5) == "shec=") {
            $shppec = substr($value, 5, strlen($value));
          } else  if (substr($value, 0, 6) == "payid=") {
            $payerid = substr($value, 6, strlen($value));
          } else  if (substr($value, 0, 4) == "Amt=") {
            $paymentAmount = substr($value, 4, strlen($value));
          } else  if (substr($value, 0, 4) == "cur=") {
            $currencyCodeType = substr($value, 4, strlen($value));
          } else  if (substr($value, 0, 5) == "payt=") {
            $paymentType = substr($value, 5, strlen($value));
          }
        }
      } else {
        $customer_id = $_REQUEST['cusid'];
        $token = $_REQUEST['tok'];
        $shppec = $_REQUEST['shec'];
        $payerid = $_REQUEST['payid'];

        $paymentAmount = $_REQUEST['Amt'];
        $currencyCodeType = $_REQUEST['cur'];
        $paymentType = $_REQUEST['payt'];
        $payerid = $_REQUEST['payid'];
      }

      if($shppec == 'A') {
        $_SESSION['customer_id'] = $customer_id;
        $customer_default_address_id = $_REQUEST['addid'];
        $customer_first_name = $_REQUEST['fn'];
        $customer_country_id = $_REQUEST['cou'];
        $customer_zone_id = $_REQUEST['zonid'];

        $paymentAmount = $_REQUEST['Amt'];
        $currencyCodeType = $_REQUEST['cur'];
        $paymentType = $_REQUEST['payt'];

        tep_session_register('payerid');
        tep_session_register('token');
        tep_session_register('paymentAmount');
        tep_session_register('currencyCodeType');
        tep_session_register('paymentType');

        tep_session_register('shppec');

        tep_session_register('customer_first_name');
        tep_session_register('customer_default_address_id');
        tep_session_register('customer_country_id');
        tep_session_register('customer_zone_id');

        $ord_id = tep_db_query("select customers_default_address_id as co from " .TABLE_CUSTOMERS." where customers_id = ".$customer_id);
        $ordid = tep_db_fetch_array($ord_id);
        $aid = $ordid['co'];

        $sendto=$billto=$aid;
        tep_session_register('sendto');
        tep_session_register('billto');

        $payment = 'ppec';
        tep_session_register('payment');

        tep_redirect(tep_href_link(FILENAME_CHECKOUT_SHIPPING, '', 'SSL'));
      } else {
        tep_session_register('payerid');
        tep_session_register('token');
        tep_session_register('paymentAmount');
        tep_session_register('currencyCodeType');
        tep_session_register('paymentType');
        tep_session_register('customer_id');

        $addrid = tep_db_query("select customers_default_address_id from " .TABLE_CUSTOMERS." where customers_id = ".$customer_id);
        $add = tep_db_fetch_array($addrid);

        foreach ($add as $key => $value) {
          $aid = htmlspecialchars($value);
        }

        $sendto=$billto=$aid;
        tep_session_register('sendto');
        tep_session_register('billto');
        $doppec = '1';

        global $ccurl;
        $shppec = 'A';

        tep_session_register('shppec');
        tep_redirect(tep_href_link('ppeb.php', 'doppec='.$doppec.'&shec='.$shppec, 'SSL'));
      }
    } else {
      $doppec = $_REQUEST['doppec'];

      if( isset($doppec) ) {
        if($shppec == 'A') {
          $cust_query = tep_db_query("show tables");

          $found = false;
          while($row = mysql_fetch_row($cust_query)) {
            if($row[0] == "ppec_payer") {
              $found = true;
            }
          }

          if(!$found) {
            tep_db_query("CREATE TABLE ppec_payer (customers_id int(15), payerid varchar(15))");
            tep_db_query("CREATE TABLE ppec_transaction (transactionid varchar(50), paymentstatus varchar(20), orders_id int(15))");
            tep_db_query("CREATE TABLE ppec_transaction_status (transaction_status varchar(20), status_id int(15))");

            $maxi = tep_db_query("SELECT MAX(orders_status_id) as max FROM " . TABLE_ORDERS_STATUS);
            $max_ar = tep_db_fetch_array($maxi);
            $max = $max_ar['max']+1;

            $cust_query = tep_db_query("SELECT languages_id, code FROM " . TABLE_LANGUAGES);
            while($row = mysql_fetch_row($cust_query)) {
              if(strtoupper($row[1]) == "EN") {
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-None')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Reversal')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Completed')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Denied')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Expired')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Failed')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Pending')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Refunded')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Reversed')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Processed')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'Voided')");
                $max = $max - 10;
              } else if(strtoupper($row[1]) == "PL") {
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Brak statusu')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Operacja cofnięta')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Zakończone')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Odrzucone')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wygasłe')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Błędna płatność')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Oczekujace')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zwrócona')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wycofane')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zaakceptowana')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Autoryzacja unieważniona')");
                $max = $max - 10;
              } else if(strtoupper($row[1]) == "DE") {
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Brak statusu')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Operacja cofnięta')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Zakończone')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Odrzucone')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wygasłe')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Błędna płatność')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Oczekujace')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zwrócona')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wycofane')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zaakceptowana')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Autoryzacja unieważniona')");
                $max = $max - 10;
              } else if(strtoupper($row[1]) == "RU") {
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Brak statusu')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Operacja cofnięta')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Zakończone')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Odrzucone')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wygasłe')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Błędna płatność')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Oczekujace')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zwrócona')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wycofane')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zaakceptowana')");
                $max++;
                tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Autoryzacja unieważniona')");
                $max = $max - 10;
              }
            }
//            $max = $max - 10;
            tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('NONE', '" . (int)$max . "')");
            $max++;
            tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('CANCELED-REVERSAL', '" . (int)$max . "')");
            $max++;
            tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('COMPLETED', '" . (int)$max . "')");
            $max++;
            tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('DENIED', '" . (int)$max . "')");
            $max++;
            tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('EXPIRED', '" . (int)$max . "')");
            $max++;
            tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('FAILED', '" . (int)$max . "')");
            $max++;
            tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('PENDING', '" . (int)$max . "')");
            $max++;
            tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('REFUNDED', '" . (int)$max . "')");
            $max++;
            tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('REVERSED', '" . (int)$max . "')");
            $max++;
            tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('PROCESSED', '" . (int)$max . "')");
            $max++;
            tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('VOIDED', '" . (int)$max . "')");
          }

          $custid =urlencode( $_SESSION['customer_id']);
          $cust_add_id =urlencode( $_SESSION['customer_default_address_id']);
          $cust_country = urlencode($_SESSION['customer_country_id']);
          $customer_first_name = urlencode($_SESSION['customer_first_name']);
          $customer_zone_id = urlencode($_SESSION['customer_zone_id']);
          $payerid =urlencode( $_SESSION['payerid']);
          $token =urlencode( $_SESSION['token']);
          $paymentAmount = urlencode($_SESSION['paymentAmount']);
          $currencyCodeType = urlencode($_SESSION['currencyCodeType']);
          $paymentType = urlencode($_SESSION['paymentType']);
          $serverName = urlencode($_SERVER['SERVER_NAME']);

          // 2.23 removed function calls
          //reviewbasket();
          //reviewtotal();

          global $ccurl;
          global $ctotal;
          global $ctax; //ADDED 2.23
          global $subtotal; //ADDED 2.23
          global $cshipping;

          $ctotal = $ctax = $subtotal = $cshipping = 0;

          // ADDED 2.23 load selected modules
          require(DIR_WS_CLASSES . 'payment.php');
          $payment_modules = new payment($payment);

          require(DIR_WS_CLASSES . 'shipping.php');
          $shipping_modules = new shipping($shipping);

          require(DIR_WS_CLASSES . 'order.php');
          $order = new order;

          $payment_modules->update_status();

          require(DIR_WS_CLASSES . 'order_total.php');
          $order_total_modules = new order_total;

          $order_totals = $order_total_modules->process();

          for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
            $code_tmp = $order_totals[$i]['code'];

            if($code_tmp == 'ot_total') {
              $ctotal = tep_round($order_totals[$i]['value'],2);
            } else if($code_tmp == 'ot_shipping') {
              $cshipping = tep_round($order_totals[$i]['value'],2);
            } else if($code_tmp == 'ot_tax') {
              $ctax = tep_round($order_totals[$i]['value'],2);
            } else if($code_tmp == 'ot_subtotal') {
              $csubtotal = tep_round($order_totals[$i]['value'],2);
            }
          }

          if($ctotal != ($cshipping+$ctax+$csubtotal)) {
            $csubtotal = $ctotal-$cshipping-$ctax;
          }
          // 2.23  left $mt for <= 0 cart check
          $mt = $ctotal - $cshipping;

          //global $order;
          $SHIPTONAME = $order->delivery['firstname'] . ' ' . $order->delivery['lastname'];
          $SHIPTOSTREET = $order->delivery['street_address'];
          $SHIPTOSTREET2 = $order->delivery['suburb'];
          $SHIPTOCITY = $order->delivery['city'];
          $SHIPTOZIP = $order->delivery['postcode'];
          $SHIPTOSTATE = $order->delivery['state'];
          $EMAIL = $order->customer['email_address'];
          $PHONENUM = $order->customer['telephone'];
          $ord_id = tep_db_query("SELECT countries_iso_code_2 as co FROM ".TABLE_COUNTRIES." Where countries_id = '".$order->billing['country']['id']."'");
          $ordid = tep_db_fetch_array($ord_id);

          if(strtoupper($ordid['co']) == "FX") {
            $SHIPTOCOUNTRYCODE = "FR";
          } else {
            $SHIPTOCOUNTRYCODE = $ordid['co'];
          }
          if(round($mt, 2) <= 0) {
            tep_redirect(tep_href_link(FILENAME_SHOPPING_CART, '', 'SSL'));
          }

          $msg = "<?xml version='1.0' encoding='utf-8'?>".
          "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>".
          "<soap:Header>".
          "<RequesterCredentials xmlns='urn:ebay:api:PayPalAPI'>".
          "<Credentials xmlns='urn:ebay:apis:eBLBaseComponents'>".
          "<Username>".$API_UserName."</Username>".
          "<Password>".$API_Password."</Password>";

          if (!file_exists(MODULE_PAYMENT_PPEC_CERT_PATH))
          $msg .= "<Signature>".$API_Signature."</Signature>";

          // ADDED 2.23 tax, subtotal
          $msg .= "<Subject>"."</Subject>".
          "</Credentials>".
          "</RequesterCredentials>".
          "</soap:Header>".
          "<soap:Body>".
            "<DoExpressCheckoutPaymentReq xmlns='urn:ebay:api:PayPalAPI'>".
            "<DoExpressCheckoutPaymentRequest>".
              "<Version xmlns='urn:ebay:apis:eBLBaseComponents'>3</Version>".
              "<DoExpressCheckoutPaymentRequestDetails xmlns='urn:ebay:apis:eBLBaseComponents'>".
              "<PaymentAction>".MODULE_PAYMENT_PPEC_TRANSACTION_TYPE."</PaymentAction>".
              "<Token>".$token."</Token>".
              "<PayerID>".$payerid."</PayerID>".
              "<PaymentDetails>".
                "<OrderTotal currencyID='".$currency."'>".$ctotal."</OrderTotal>".
                "<OrderDescription></OrderDescription>".
                "<ItemTotal currencyID='".$currency."'>".$csubtotal."</ItemTotal>".
                "<ShippingTotal currencyID='".$currency."'>".$cshipping."</ShippingTotal>".
                "<HandlingTotal currencyID='".$currency."'></HandlingTotal>".
                "<TaxTotal currencyID='".$currency."'>".$ctax."</TaxTotal>".
                "<Custom></Custom>".
                "<InvoiceID></InvoiceID>".
                "<ButtonSource>OscGold_ShoppingCart_EC_PL</ButtonSource>".
                "<NotifyURL>".MODULE_PAYMENT_PPEC_IPN."</NotifyURL>";

               $msg .= "<ShipToAddress>".
                "<Name>".$SHIPTONAME."</Name>".
                "<Street1>".$SHIPTOSTREET."</Street1>".
                "<Street2>".$SHIPTOSTREET2."</Street2>".
                "<CityName>".$SHIPTOCITY."</CityName>".
                "<StateOrProvince>".$SHIPTOSTATE."</StateOrProvince>".
                "<PostalCode>".$SHIPTOZIP."</PostalCode>".
                "<Country>".$SHIPTOCOUNTRYCODE."</Country>".
                "</ShipToAddress>".
              "</PaymentDetails>".
            "</DoExpressCheckoutPaymentRequestDetails>".
            "</DoExpressCheckoutPaymentRequest>".
            "</DoExpressCheckoutPaymentReq>".
          "</soap:Body>".
          "</soap:Envelope>";

          $ch = curl_init();
          curl_setopt($ch, CURLOPT_POST,1);
          curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
          curl_setopt($ch, CURLOPT_VERBOSE, 1);

          if(USE_PROXY)
            curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);

          if (file_exists(MODULE_PAYMENT_PPEC_CERT_PATH)) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 180);
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, "PEM");
            curl_setopt($ch, CURLOPT_SSLCERT, MODULE_PAYMENT_PPEC_CERT_PATH);
          } else {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
          }

          curl_setopt($ch,CURLOPT_POSTFIELDS,$msg);

          $result=curl_exec ($ch);
          curl_close ($ch);

          $sax = xml_parser_create();
          xml_parser_set_option($sax, XML_OPTION_CASE_FOLDING, false);
          xml_parser_set_option($sax, XML_OPTION_SKIP_WHITE, true);
          xml_set_element_handler($sax, 'sax_start', 'sax_end');
          xml_set_character_data_handler($sax, 'sax_cdata');
          xml_parse($sax, $result, true);
          xml_parser_free($sax);
          sax_start($sax, $name, $attributes);
          $resArray = $arrtag;

          $_SESSION['reshash']=$resArray;

          $ack = strtoupper($resArray["ACK"]);

          //ADDED 2.23 for EC so after payment shppec does not equal A to reset checkout function for repeat orders
          $shppec = 'X';

          tep_session_unregister('comments');
          tep_session_unregister('shppec');

          if($ack!="SUCCESS") {
            echo '<center>';
            echo '<table cellpadding="3" cellspacing="1" border="0">';
            echo '<tr><td colspan="2" align="center" bgcolor="#525252"><font color=red>BLAD DANYCH !!!</font></td></tr>';
            foreach ($arrtag as $key => $value) {
              if (in_array($key, $error_show_array) || $ppec_debug) {
                echo '<tr><td align="left" bgcolor="#e7e7e7">'.$key.'</td><td bgcolor="#e7e7e7">'.$value.'</td></tr>';
              }
            }
            echo '<tr><td colspan="2" align="center"><font color=red><a href="' . tep_href_link(FILENAME_CHECKOUT_CONFIRMATION) . '">powrot do sklepu</a></font></td></tr>';
            echo '</table>';
            echo '</center>';
          } else {
            PPECprocess($resArray['TRANSACTIONID'], strtoupper($resArray['PAYMENTSTATUS']));
            tep_session_unregister('comments');
            tep_session_unregister('shppec');
            // remove items from wishlist if customer purchased them

            //kgt - discount coupons
            tep_session_unregister('coupon');
            //end kgt - discount coupons

            #### Points/Rewards Module V2.1rc2a balance customer points EOF ####*/
            if (tep_session_is_registered('customer_shopping_points')) tep_session_unregister('customer_shopping_points');
            if (tep_session_is_registered('customer_shopping_points_spending')) tep_session_unregister('customer_shopping_points_spending');
            if (tep_session_is_registered('customer_referral')) tep_session_unregister('customer_referral');
            #### Points/Rewards Module V2.1rc2a balance customer points EOF ####*/

            $wishlist->clear();
            $cart->reset(true); //          $cart->reset();
            tep_redirect(tep_href_link(FILENAME_CHECKOUT_SUCCESS, '', 'SSL'));
          }
        } else {
          $shppec = 'b';

          global $ccurl;
          global $ctotal;
          global $ctax; //ADDED 2.23
          global $subtotal; //ADDED 2.23
          global $cshipping;

          $ctotal = $ctax = $subtotal = $cshipping = 0;
          //2.23  to replace reviewbasket(); & reviewtotal();

          require(DIR_WS_CLASSES . 'payment.php');
          $payment_modules = new payment($payment);

          require(DIR_WS_CLASSES . 'shipping.php');
          $shipping_modules = new shipping($shipping);

          require(DIR_WS_CLASSES . 'order.php');
          $order = new order;

          $payment_modules->update_status();

          require(DIR_WS_CLASSES . 'order_total.php');
          $order_total_modules = new order_total;

          $order_totals = $order_total_modules->process();

          for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {

            $code_tmp = $order_totals[$i]['code'];

            if($code_tmp == 'ot_total') {
              $ctotal = tep_round($order_totals[$i]['value'],2);
            } else if($code_tmp == 'ot_shipping') {
              $cshipping = tep_round($order_totals[$i]['value'],2);
            } else if($code_tmp == 'ot_tax') {
              $ctax = tep_round($order_totals[$i]['value'],2);
            } else if($code_tmp == 'ot_subtotal') {
              $csubtotal = tep_round($order_totals[$i]['value'],2);
            }
          }

          if($ctotal != ($cshipping+$ctax+$csubtotal)) {
            $csubtotal = $ctotal-$cshipping-$ctax;
          }

          //global $order;

          //  2.23 removed below
          //require(DIR_WS_CLASSES . 'payment.php');
          //require(DIR_WS_CLASSES . 'shipping.php');
          //$shipping_modules = new shipping($shipping);

          // 2.23 might need to removed below calls
          //reviewbasket();
          //reviewtotal();
          //global $ctotal;
          //global $cshipping;
          $mt = $ctotal - $cshipping;

          tep_session_register('shppec');

          tep_redirect(tep_href_link('ppeb.php', 'shec=b', 'SSL'));
        }
      } else {
        session_name('ppec');
        session_id('12345');

        $token = $_REQUEST['token'];

        if(! isset($token)) {
          $serverName = $_SERVER['SERVER_NAME'];
          $serverPort = $_SERVER['SERVER_PORT'];
          // set the type of request (secure or not)
          $request_type = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
          $url=dirname($request_type.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);

          global $cart;

          if($cart->show_total() <= 0) {
            tep_redirect(tep_href_link(FILENAME_SHOPPING_CART, '', 'SSL'));
          }

          $paymentAmount=$cart->show_total();

          $currencyCodeType=$currency;

          $paymentType=MODULE_PAYMENT_PPEC_TRANSACTION_TYPE;

          $shppec=$_REQUEST['shec'];

          tep_session_register('paymentAmount');
          tep_session_register('currencyCodeType');
          tep_session_register('paymentType');
          tep_session_register('shppec');

          global $customer_id;

          $request_SSL = ($_SERVER['HTTPS'] == 'on') ? 'SSL' : 'NONSSL';

          //$returnURL = $url.'/ppeb.php';
          $returnURL = tep_href_link('ppeb.php', '', $request_SSL);

          //$cancelURL = $url.'/'.FILENAME_SHOPPING_CART;
          $cancelURL = tep_href_link(FILENAME_SHOPPING_CART, '', $request_SSL);

          global $lg;
          ppebin();

          global $com;
          if($shppec == 'b') {
            // ADDED 2.23 this for EC Mark
            require(DIR_WS_CLASSES . 'payment.php');
            $payment_modules = new payment($payment);

            require(DIR_WS_CLASSES . 'shipping.php');
            $shipping_modules = new shipping($shipping);

            require(DIR_WS_CLASSES . 'order.php');
            $order = new order;

            require(DIR_WS_CLASSES . 'order_total.php');
            $order_total_modules = new order_total;

            $order_totals = $order_total_modules->process();

            for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
              $code_tmp = $order_totals[$i]['code'];
              if($code_tmp == 'ot_total') {
                $ctotal = tep_round($order_totals[$i]['value'],2);
              }
            }
            // ADDED  2.23 so correct value is passed as SET as ECmark
            //$paymentAmount = $order->info['total'];
            $paymentAmount = $ctotal;

            $com = "&useraction=commit";

            $SHIPTONAME = $order->delivery['firstname'] . ' ' . $order->delivery['lastname'];
            $SHIPTOSTREET = $order->delivery['street_address'];
            $SHIPTOSTREET2 = $order->delivery['suburb'];
            $SHIPTOCITY = $order->delivery['city'];
            $SHIPTOZIP = $order->delivery['postcode'];
            if ( $order->delivery['country_id'] == '223' ) {
              $SHIPTOSTATE = tep_get_stan_code('223', $order->delivery['state'], 'CA');
            } else {
              $SHIPTOSTATE = $order->delivery['state'];
            }
            $EMAIL = $order->customer['email_address'];
            $PHONENUM = $order->customer['telephone'];
            $ord_id = tep_db_query("SELECT countries_iso_code_2 as co FROM ".TABLE_COUNTRIES." Where countries_id = '".$order->delivery['country_id']."'");
            $ordid = tep_db_fetch_array($ord_id);

            if(strtoupper($ordid['co']) == "FX") {
              $SHIPTOCOUNTRYCODE = "FR";
            } else {
              $SHIPTOCOUNTRYCODE = $ordid['co'];
            }

            $nvpstr = $nvpstr."&EMAIL=".$EMAIL."&SHIPTOCOUNTRYCODE=".$SHIPTOCOUNTRYCODE."&SHIPTOZIP=".$SHIPTOZIP."&SHIPTOCITY=".$SHIPTOCITY."&SHIPTOSTREET=".$SHIPTOSTREET."&SHIPTOSTREET2=".$SHIPTOSTREET2."&SHIPTONAME=".$SHIPTONAME;
          }

          $nvpstr = $nvpstr.$com;

          $msg = "<?xml version='1.0' encoding='utf-8'?>".
          "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>".
          "<soap:Header>".
          "<RequesterCredentials xmlns='urn:ebay:api:PayPalAPI'>".
          "<Credentials xmlns='urn:ebay:apis:eBLBaseComponents'>".
          "<Username>".$API_UserName."</Username>".
          "<Password>".$API_Password."</Password>";

          if (!file_exists(MODULE_PAYMENT_PPEC_CERT_PATH))
            $msg .= "<Signature>".$API_Signature."</Signature>";

            $msg .= "<Subject>"."</Subject>".
            "</Credentials>".
            "</RequesterCredentials>".
            "</soap:Header>".
            "<soap:Body>".
            "<SetExpressCheckoutReq xmlns='urn:ebay:api:PayPalAPI'>".
            "<SetExpressCheckoutRequest>".
            "<Version xmlns='urn:ebay:apis:eBLBaseComponents'>".$version."</Version>".
            "<SetExpressCheckoutRequestDetails xmlns='urn:ebay:apis:eBLBaseComponents'>".
            "<OrderTotal currencyID='".$currencyCodeType."'>".$paymentAmount."</OrderTotal>".
            "<Custom>".$shppec.$customer_id."</Custom>".
            "<ButtonSource>oscdub</ButtonSource>".
            "<ReturnURL>".$returnURL."</ReturnURL>".
            "<CancelURL>".$cancelURL."</CancelURL>".
            "<ReqConfirmShipping>"."0"."</ReqConfirmShipping>".
            "<NoShipping>"."0"."</NoShipping>".
            "<AddressOverride>"."1"."</AddressOverride>".
            "<LocaleCode>".$lg."</LocaleCode>".
            "<PageStyle>"."</PageStyle>";

            $serverName = $_SERVER['SERVER_NAME'];
            $serverPort = $_SERVER['SERVER_PORT'];
            // set the type of request (secure or not)
            $request_type = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
            $url=dirname($request_type.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);

            $msg .="<cpp-header-image>".$url."/ppec/ppec_image/".LOGO."</cpp-header-image>".
            "<cpp-header-border-color>"."</cpp-header-border-color>".
            "<cpp-header-back-color>"."</cpp-header-back-color>".
            "<cpp-payflow-color>"."</cpp-payflow-color>".
            "<PaymentAction>".MODULE_PAYMENT_PPEC_TRANSACTION_TYPE."</PaymentAction>".
            "<BuyerEmail>".$EMAIL."</BuyerEmail>".
            "<Address>".
            "<Name>".$SHIPTONAME."</Name>".
            "<Street1>".$SHIPTOSTREET."</Street1>".
            "<Street2>".$SHIPTOSTREET2."</Street2>".
            "<CityName>".$SHIPTOCITY."</CityName>".
            "<StateOrProvince>".$SHIPTOSTATE."</StateOrProvince>".
            "<PostalCode>".$SHIPTOZIP."</PostalCode>".
            "<Country>".$SHIPTOCOUNTRYCODE."</Country>".
            "<Phone>".$PHONENUM."</Phone>".
            "</Address>".
            "<SolutionType>"."Sole"."</SolutionType>".
            "<LandingPage>"."Billing"."</LandingPage>".
            "</SetExpressCheckoutRequestDetails>".
            "</SetExpressCheckoutRequest>".
            "</SetExpressCheckoutReq>".
            "</soap:Body>".
            "</soap:Envelope>";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST,1);
            curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_VERBOSE, 1);

            if(USE_PROXY)
              curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);

            if (file_exists(MODULE_PAYMENT_PPEC_CERT_PATH)) {
              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
              curl_setopt($ch, CURLOPT_TIMEOUT, 180);
              curl_setopt($ch, CURLOPT_SSLCERTTYPE, "PEM");
              curl_setopt($ch, CURLOPT_SSLCERT, MODULE_PAYMENT_PPEC_CERT_PATH);
            } else {
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            }

            curl_setopt($ch,CURLOPT_POSTFIELDS,$msg);

            $result=curl_exec ($ch);
            curl_close ($ch);

            $sax = xml_parser_create();
            xml_parser_set_option($sax, XML_OPTION_CASE_FOLDING, false);
            xml_parser_set_option($sax, XML_OPTION_SKIP_WHITE, true);
            xml_set_element_handler($sax, 'sax_start', 'sax_end');
            xml_set_character_data_handler($sax, 'sax_cdata');
            xml_parse($sax, $result, true);
            xml_parser_free($sax);
            sax_start($sax, $name, $attributes);
            $resArray = $arrtag;

            $_SESSION['reshash']=$resArray;
            $ack = strtoupper($resArray["ACK"]);
            if($ack=="SUCCESS") {
              $token = urldecode($resArray["TOKEN"]);
              $ecom = $com;

              $payPalURL = PAYPAL_URL.$token.$ecom;

              if($shppec == 'b') {
                echo "<meta http-equiv='refresh' content='0;url=".$payPalURL."'/>";
                echo '<center><img src="'.DIR_WS_TEMPLATES.'images/misc/loading.gif"></center>';
              } else {
                header("Location: ".$payPalURL);
              }
            } else  {
              if ($ppec_debug) {
                echo "<br>";
                echo "montant: ".$paymentAmount."<br>";
                echo "OrderTotal currencyID=".$currencyCodeType." ".$paymentAmount." OrderTotal "."<br>";
                foreach ($order->info as $key => $value) {
                  echo $key.": ".$value."<br>";
                }
              }
              echo '<center>';
              echo '<table cellpadding="3" cellspacing="1" border="0">';
              echo '<tr><td colspan="2" align="center" bgcolor="#525252"><font color=red>BLAD DANYCH !!!</font></td></tr>';
              foreach ($arrtag as $key => $value) {
                if (in_array($key, $error_show_array) || $ppec_debug) {
                  echo '<tr><td align="left" bgcolor="#e7e7e7">'.$key.'</td><td bgcolor="#e7e7e7">'.$value.'</td></tr>';
                }
              }
              echo '<tr><td colspan="2" align="center"><font color=red><a href="' . tep_href_link(FILENAME_CHECKOUT_CONFIRMATION) . '">powrot do sklepu</a></font></td></tr>';
              echo '</table>';
              echo '</center>';
            }
          } else {
            $msg = "<?xml version='1.0' encoding='utf-8'?>".
            "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>".
            "<soap:Header>".
            "<RequesterCredentials xmlns='urn:ebay:api:PayPalAPI'>".
            "<Credentials xmlns='urn:ebay:apis:eBLBaseComponents'>".
            "<Username>".$API_UserName."</Username>".
            "<Password>".$API_Password."</Password>";

            if (!file_exists(MODULE_PAYMENT_PPEC_CERT_PATH))
              $msg .= "<Signature>".$API_Signature."</Signature>";

              $msg .= "<Subject>"."</Subject>".
              "</Credentials>".
              "</RequesterCredentials>".
              "</soap:Header>".
              "<soap:Body>".
              "<GetExpressCheckoutDetailsReq xmlns='urn:ebay:api:PayPalAPI'>".
              "<GetExpressCheckoutDetailsRequest>".
              "<Version xmlns='urn:ebay:apis:eBLBaseComponents'>".$version."</Version>".
              "<Token>".$token."</Token>".
              "</GetExpressCheckoutDetailsRequest>".
              "</GetExpressCheckoutDetailsReq>".
              "</soap:Body>".
              "</soap:Envelope>";

              $ch = curl_init();
              curl_setopt($ch, CURLOPT_POST,1);
              curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
              curl_setopt($ch, CURLOPT_VERBOSE, 1);

              if(USE_PROXY)
                curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);

              if (file_exists(MODULE_PAYMENT_PPEC_CERT_PATH)) {
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_TIMEOUT, 180);
                curl_setopt($ch, CURLOPT_SSLCERTTYPE, "PEM");
                curl_setopt($ch, CURLOPT_SSLCERT, MODULE_PAYMENT_PPEC_CERT_PATH);
              } else {
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
              }

              curl_setopt($ch,CURLOPT_POSTFIELDS,$msg);

              $result=curl_exec ($ch);
              curl_close ($ch);

              $sax = xml_parser_create();
              xml_parser_set_option($sax, XML_OPTION_CASE_FOLDING, false);
              xml_parser_set_option($sax, XML_OPTION_SKIP_WHITE, true);
              xml_set_element_handler($sax, 'sax_start', 'sax_end');
              xml_set_character_data_handler($sax, 'sax_cdata');
              xml_parse($sax, $result, true);
              xml_parser_free($sax);
              sax_start($sax, $name, $attributes);
              $resArray = $arrtag;

              require(DIR_WS_CLASSES . 'order.php');
              $order = new order;

              $_SESSION['reshash']=$resArray;
              $ack = strtoupper($resArray["ACK"]);

              if($ack=="SUCCESS") {
                $ci = substr($resArray["CUSTOM"], 1, strlen($resArray["CUSTOM"]));
                $sh = substr($resArray["CUSTOM"], 0, 1);

                if($sh == 'A') {
                  $_SESSION['shppec'] = 'A';

                  databasemodif($resArray, $token, $paymentAmount, $currencyCodeType, $paymentType, $sh);
                } else {
                  $_SESSION['shppec'] = 'b';
                  $payerID = htmlspecialchars($resArray['PAYERID']);
                  global $ccurl;

                  if(strlen($ci)==0) {
                    tep_redirect(tep_href_link(FILENAME_LOGIN, '', 'SSL'));
                  } else {
                    tep_redirect(tep_href_link('ppeb.php', 'geppec=1&cusid='.$ci.'&payid='.$payerID.'&tok='.$token.'&cur='.$currencyCodeType.'&payt='.$paymentType.'&shec='.$shppec, 'SSL'));
                  }
                }
              } else  {
                echo '<center>';
                echo '<table cellpadding="3" cellspacing="1" border="0">';
                echo '<tr><td colspan="2" align="center" bgcolor="#525252"><font color=red>BLAD DANYCH !!!</font></td></tr>';
                foreach ($arrtag as $key => $value) {
                  if (in_array($key, $error_show_array) || $ppec_debug) {
                    echo '<tr><td align="left" bgcolor="#e7e7e7">'.$key.'</td><td bgcolor="#e7e7e7">'.$value.'</td></tr>';
                  }
                }
                echo '<tr><td colspan="2" align="center"><font color=red><a href="' . tep_href_link(FILENAME_CHECKOUT_CONFIRMATION) . '">powrot do sklepu</a></font></td></tr>';
                echo '</table>';
                echo '</center>';
              }
          }
      }
    }
  }
}

function sax_start($parser, $name, $attributes) {
  global $currtag;
  $currtag = strtoupper($name);
}

function sax_end($parser, $name) {
}

function sax_cdata($parser, $cdata) {
  global $arrtag, $currtag;
  $arrtag[$currtag] = strtoupper($cdata);
}

function databasemodif($resArray, $token, $paymentAmount, $currencyCodeType, $paymentType, $shppec){
  $payerid = $resArray['PAYERID'];
  $_SESSION['payerID'] = $resArray['PAYERID'];

  $firstname = ucfirst(strtolower($resArray['FIRSTNAME']));
  $lastname = ucfirst(strtolower($resArray['LASTNAME']));
  $email_address = strtolower($resArray['PAYER']);
  $fax = $newsletter = $password = $dob = $company = $suburb="";
  $telephone = $resArray['CONTACTPHONE'];
  $gender = "m";

  $street_address = ucfirst(strtolower($resArray['STREET1']." ".$resArray['STREET2']));
  $postcode = $resArray['POSTALCODE'];
  $city = ucfirst(strtolower($resArray['CITYNAME']));

  $codec = $resArray['COUNTRY'];

  $ord_id = tep_db_query("select countries_id as co from " .TABLE_COUNTRIES." where countries_iso_code_2 = '".$codec."'");
  $ordid = tep_db_fetch_array($ord_id);
  $countryid = $ordid['co'];

  $state = ucfirst(strtolower(htmlspecialchars($resArray['STATEORPROVINCE'])));
  // Uncomment line below to revert to v2.21
  // $state = htmlspecialchars($resArray['SHIPTOSTATE']);
  $zone_id = "0";

  $cust_query = tep_db_query("show tables");

  $found = false;
  while($row = mysql_fetch_row($cust_query)) {
    if ($row[0] == "ppec_payer") {
      $found = true;
    }
  }


  if(!$found)  {
    tep_db_query("CREATE TABLE ppec_payer (customers_id int(15), payerid varchar(15))");
    tep_db_query("CREATE TABLE ppec_transaction (transactionid varchar(50), paymentstatus varchar(20), orders_id int(15))");
    tep_db_query("CREATE TABLE ppec_transaction_status (transaction_status varchar(20), status_id int(15))");

    $maxi = tep_db_query("SELECT MAX(orders_status_id) as max FROM " . TABLE_ORDERS_STATUS);
    $max_ar = tep_db_fetch_array($maxi);
    $max = $max_ar['max']+1;

    $cust_query = tep_db_query("SELECT languages_id, code FROM " . TABLE_LANGUAGES);
    while($row = mysql_fetch_row($cust_query)){

      if (strtoupper($row[1]) == "EN") {
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-None')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Reversal')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Completed')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Denied')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Expired')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Failed')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Pending')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Refunded')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Reversed')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Processed')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'Voided')");
        $max = $max - 10;
      } elseif(strtoupper($row[1]) == "PL") {
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Brak statusu')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Operacja cofnięta')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Zakończone')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Odrzucone')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wygasłe')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Błędna płatność')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Oczekujce')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zwrócona')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wycofane')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zaakceptowana')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Autoryzacja unieważniona')");
        $max = $max - 10;
      } elseif(strtoupper($row[1]) == "DE") {
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Brak statusu')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Operacja cofnięta')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Zakończone')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Odrzucone')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wygasłe')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Błędna płatność')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Oczekujce')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zwrócona')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wycofane')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zaakceptowana')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Autoryzacja unieważniona')");
        $max = $max - 10;
      } elseif(strtoupper($row[1]) == "RU") {
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Brak statusu')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Operacja cofnięta')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Zakończone')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Odrzucone')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wygasłe')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Błędna płatność')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Oczekujce')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zwrócona')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Wycofane')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Płatność zaakceptowana')");
        $max++;
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . (int)$max. "', '". (int)$row[0] ."', 'PayPal-Autoryzacja unieważniona')");
        $max = $max - 10;
      }
    }

//    $max = $max - 10;
    tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('NONE', '" . (int)$max . "')");
    $max++;
    tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('CANCELED-REVERSAL', '" . (int)$max . "')");
    $max++;
    tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('COMPLETED', '" . (int)$max . "')");
    $max++;
    tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('DENIED', '" . (int)$max . "')");
    $max++;
    tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('EXPIRED', '" . (int)$max . "')");
    $max++;
    tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('FAILED', '" . (int)$max . "')");
    $max++;
    tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('PENDING', '" . (int)$max . "')");
    $max++;
    tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('REFUNDED', '" . (int)$max . "')");
    $max++;
    tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('REVERSED', '" . (int)$max . "')");
    $max++;
    tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('PROCESSED', '" . (int)$max . "')");
    $max++;
    tep_db_query("insert into ppec_transaction_status (transaction_status, status_id) values ('VOIDED', '" . (int)$max . "')");
  }

  $cust_query = tep_db_query("select ".TABLE_CUSTOMERS.".customers_id, ".TABLE_CUSTOMERS.".customers_default_address_id from ".TABLE_CUSTOMERS.", ppec_payer where ".TABLE_CUSTOMERS.".customers_id = ppec_payer.customers_id and ppec_payer.payerid = '".$payerid."'");

  if (!tep_db_num_rows($cust_query)){

    $password = tep_create_random_value(ENTRY_PASSWORD_MIN_LENGTH);
    $new_password = tep_encrypt_password($password);

    $sql_data_array = array('customers_firstname' => $firstname,
                            'customers_lastname' => $lastname,
                            'nick' => 'paypal',
                            'customers_email_address' => $email_address,
                            'customers_telephone' => $telephone,
                            'customers_fax' => $fax,
                            'customers_newsletter' => $newsletter,
                            'customers_password' => $new_password,
                            'customers_agreement' => '1',
                            'customers_status' => '1');

    if (ACCOUNT_GENDER == 'true') $sql_data_array['customers_gender'] = $gender;
    if (ACCOUNT_DOB == 'true') $sql_data_array['customers_dob'] = tep_date_raw($dob);

    tep_db_perform(TABLE_CUSTOMERS, $sql_data_array);

    $customer_id = tep_db_insert_id();

    $nazwa = $firstname . ' ' . $lastname;

    mail_create_account($nazwa,$password,$email_address,$lastname,$firstname,$customer_id,$gender);

    $sql_data_array = array('customers_id' => $customer_id,
                            'entry_firstname' => $firstname,
                            'entry_lastname' => $lastname,
                            'entry_street_address' => $street_address,
                            'entry_postcode' => $postcode,
                            'entry_city' => $city,
                            'entry_country_id' => $countryid);

    if (ACCOUNT_GENDER == 'true') $sql_data_array['entry_gender'] = $gender;
    if (ACCOUNT_COMPANY == 'true') $sql_data_array['entry_company'] = $company;
    if (ACCOUNT_SUBURB == 'true') $sql_data_array['entry_suburb'] = $suburb;
    if (ACCOUNT_STATE == 'true') {
      if ($zone_id > 0) {
        $sql_data_array['entry_zone_id'] = $zone_id;
        $sql_data_array['entry_state'] = '';
      } else {
        $sql_data_array['entry_zone_id'] = '0';
        $sql_data_array['entry_state'] = $state;
      }
    }

    tep_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array);

    $address_id = tep_db_insert_id();

    tep_db_query("update " . TABLE_CUSTOMERS . " set customers_default_address_id = '" . (int)$address_id . "' where customers_id = '" . (int)$customer_id . "'");

    tep_db_query("insert into " . TABLE_CUSTOMERS_INFO . " (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created) values ('" . (int)$customer_id . "', '0', now())");

    if (SESSION_RECREATE == 'True') {
      tep_session_recreate();
    }

    tep_db_query("INSERT ppec_payer values ('".$customer_id."', '".$payerid."')");

  } else {

    $row = mysql_fetch_row($cust_query);

    $customer_id = $row[0];
    $address_book_query = tep_db_query("SELECT UCASE(entry_firstname) as entry_firstname, UCASE(entry_lastname) as entry_lastname, UCASE(entry_street_address) as entry_street_address, UCASE(entry_postcode) as entry_postcode, UCASE(entry_city) as entry_city, UCASE(entry_state) as entry_state FROM ".TABLE_ADDRESS_BOOK." WHERE customers_id = " . $customer_id . "");

    //gecd_add store in array the address from the GetExpressCheckout API response
    $gecd_name_strlen = strlen($resArray['NAME']);
    $gecd_name_strcut = strpos($resArray['NAME'], " ");
    $gecd_add[0] = substr($resArray['NAME'], 0, $gecd_name_strcut);
    $gecd_add[1] = substr($resArray['NAME'], $gecd_name_strcut + 1, $gecd_name_strlen);
    $gecd_add[2] = $resArray['STREET1']." ".$resArray['STREET2'];
    $gecd_add[3] = $resArray['POSTALCODE'];
    $gecd_add[4] = $resArray['CITYNAME'];
    $gecd_add[5] = $resArray['STATEORPROVINCE'];

    //add_db store in array the address from the DB for this customerID and compare with gecd_add
    $i = 0;
    while($add_db = mysql_fetch_row($address_book_query)) {
      $result = array_diff($gecd_add,$add_db);
      if (!$result) {
        $add_result = true;
        $address_id_query = tep_db_query("SELECT address_book_id FROM ".TABLE_ADDRESS_BOOK." WHERE customers_id = " . $customer_id . " ");
        $default_address_id = mysql_result($address_id_query, $i);
        break;
      }
      $i++;
    }

    if ($add_result == true) {
      tep_db_query("update " . TABLE_CUSTOMERS . " set customers_default_address_id = '" . (int)$default_address_id . "' where customers_id = '" . (int)$customer_id . "'");
    } else {
      $sql_data_array = array('customers_id' => $customer_id,
                              'entry_firstname' => ucfirst(strtolower($gecd_add[0])),
                              'entry_lastname' => ucfirst(strtolower($gecd_add[1])),
                              'entry_street_address' => $street_address,
                              'entry_postcode' => $postcode,
                              'entry_city' => $city,
                              'entry_country_id' => $countryid);

      if (ACCOUNT_GENDER == 'true') $sql_data_array['entry_gender'] = $gender;
      if (ACCOUNT_COMPANY == 'true') $sql_data_array['entry_company'] = $company;
      if (ACCOUNT_SUBURB == 'true') $sql_data_array['entry_suburb'] = $suburb;
      if (ACCOUNT_STATE == 'true') {
        if ($zone_id > 0) {
          $sql_data_array['entry_zone_id'] = $zone_id;
          $sql_data_array['entry_state'] = '';
        } else {
          $sql_data_array['entry_zone_id'] = '0';
          $sql_data_array['entry_state'] = $state;
        }
      }

      tep_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array);

      $address_id = tep_db_insert_id();

      tep_db_query("update " . TABLE_CUSTOMERS . " set customers_default_address_id = '" . (int)$address_id . "' where customers_id = '" . (int)$customer_id . "'");

      //tep_db_query("insert into " . TABLE_CUSTOMERS_INFO . " (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created) values ('" . (int)$customer_id . "', '0', now())");

      if (SESSION_RECREATE == 'True') {
        tep_session_recreate();
      }
    }
  }
  tep_redirect(tep_href_link('ppeb.php', 'geppec=1&cusid='.$customer_id.'&addid='.$address_id.'&fn='.$firstname.'&cou='.$countryid.'&zonid='.$zone_id.'&payid='.$payerid.'&tok='.$token.'&Amt='.$paymentAmount.'&cur='.$currencyCodeType.'&payt='.$paymentType.'&shec='.$shppec, 'SSL'));
}

function PPECprocess($TRANSACTIONID, $PAYMENTSTATUS) {

  global $HTTP_POST_VARS, $customer_id, $sendto, $billto, $cart, $languages_id, $language, $classot, $order, $currency, $currencies, $shipping, $payment, $comments;
  global $ctotal, $cshipping, $order_totals, $paragon, $proforma; // $ALERTMAIL;
  global $ccurl;

  tep_db_connect();

  $ord_id = tep_db_query("SELECT status_id as stid FROM ppec_transaction_status Where transaction_status = '".$PAYMENTSTATUS."'");
  $ordid = tep_db_fetch_array($ord_id);
  $o_id = $ordid['stid'];

  $sql_data_array = array('customers_id' => $customer_id,
                          'customers_name' => $order->customer['firstname'] . ' ' . $order->customer['lastname'],
                          'customers_company' => $order->customer['company'],
                          'customers_nip' => $order->customer['nip'],
                          'customers_street_address' => $order->customer['street_address'],
                          'customers_suburb' => $order->customer['suburb'],
                          'customers_city' => $order->customer['city'],
                          'customers_postcode' => $order->customer['postcode'],
                          'customers_state' => $order->customer['state'],
                          'customers_country' => $order->customer['country']['title'],
                          'customers_telephone' => $order->customer['telephone'],
                          'customers_email_address' => $order->customer['email_address'],
                          'customers_address_format_id' => $order->customer['format_id'],
                          'customers_dummy_account' => '0',
                          'delivery_name' => $order->delivery['firstname'] . ' ' . $order->delivery['lastname'],
                          'delivery_company' => $order->delivery['company'],
                          'delivery_nip' => $order->delivery['nip'],
                          'delivery_street_address' => $order->delivery['street_address'],
                          'delivery_suburb' => $order->delivery['suburb'],
                          'delivery_city' => $order->delivery['city'],
                          'delivery_postcode' => $order->delivery['postcode'],
                          'delivery_state' => $order->delivery['state'],
                          'delivery_country' => $order->delivery['country']['title'],
                          'delivery_address_format_id' => $order->delivery['format_id'],
                          'billing_name' => $order->billing['firstname'] . ' ' . $order->billing['lastname'],
                          'billing_company' => $order->billing['company'],
                          'billing_nip' => $order->billing['nip'],
                          'billing_street_address' => $order->billing['street_address'],
                          'billing_suburb' => $order->billing['suburb'],
                          'billing_city' => $order->billing['city'],
                          'billing_postcode' => $order->billing['postcode'],
                          'billing_state' => $order->billing['state'],
                          'billing_country' => $order->billing['country']['title'],
                          'billing_address_format_id' => $order->billing['format_id'],
                          'payment_method' => $order->info['payment_method'],
                          'shipping_module' => $shipping['id'],
                          'payment_info' => '',
                          'cc_type' => $order->info['cc_type'],
                          'cc_owner' => $order->info['cc_owner'],
                          'cc_number' => $order->info['cc_number'],
                          'cc_expires' => $order->info['cc_expires'],
                          'date_purchased' => 'now()',
                          'orders_status' => $o_id,
                          'currency' => $order->info['currency'],
                          'currency_value' => $order->info['currency_value']);

  tep_db_perform(TABLE_ORDERS, $sql_data_array);
  $insert_id = tep_db_insert_id();
  for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
    $sql_data_array = array('orders_id' => $insert_id,
                            'title' => $order_totals[$i]['title'],
                            'text' => $order_totals[$i]['text'],
                            'value' => $order_totals[$i]['value'],
                            'class' => $order_totals[$i]['code'],
                            'sort_order' => $order_totals[$i]['sort_order']);
    tep_db_perform(TABLE_ORDERS_TOTAL, $sql_data_array);
  }

  tep_db_query("insert into ppec_transaction (transactionid, paymentstatus, orders_id) values ('" .$TRANSACTIONID. "', '".$PAYMENTSTATUS."', '".$insert_id."')");

  #### Points/Rewards Module V2.1rc2a balance customer points BOF ####
  //if ((USE_POINTS_SYSTEM == 'true') && (USE_REDEEM_SYSTEM == 'true')) {
  if (USE_POINTS_SYSTEM == 'true') {
    $pwa_query = tep_db_query("select guest_account from " . TABLE_CUSTOMERS . " where customers_id = '" . (int)$customer_id . "'");
    $pwa = tep_db_fetch_array($pwa_query);
    if ($pwa['guest_account'] != 1) {

      // customer pending points added
      if ($order->info['total'] > 0) {
        $points_toadd = get_points_toadd($order);
        $points_comment = 'TEXT_DEFAULT_COMMENT';
        $points_type = 'SP';
        if ((get_redemption_awards($customer_shopping_points_spending) == true) && ($points_toadd >0)) {
          tep_add_pending_points($customer_id, $insert_id, $points_toadd, $points_comment, $points_type);
        }
      }
      // customer referral points added
      if ((tep_session_is_registered('customer_referral')) && (tep_not_null(USE_REFERRAL_SYSTEM))) {
        $referral_twice_query = tep_db_query("select unique_id from " . TABLE_CUSTOMERS_POINTS_PENDING . " where orders_id = '". (int)$insert_id ."' and points_type = 'RF' limit 1");
        if (!tep_db_num_rows($referral_twice_query)) {
          $points_toadd = USE_REFERRAL_SYSTEM;
          $points_comment = 'TEXT_DEFAULT_REFERRAL';
          $points_type = 'RF';
          tep_add_pending_points($customer_referral, $insert_id, $points_toadd, $points_comment, $points_type);
        }
      }
      // customer shoppping points account balanced
      if ($customer_shopping_points_spending) {
        tep_redeemed_points($customer_id, $insert_id, $customer_shopping_points_spending);
      }
    }
  }
  #### Points/Rewards Module V2.1rc2a balance customer points EOF ####*/

  $customer_notification = (SEND_EMAILS == 'true') ? '1' : '0';
  if ( isset($paragon) && $paragon != '' ) {
    $dokument = '(Dokument sprzedaży: ' . $paragon . ') ';
  } else {
    $dokument = '';
  }
  $sql_data_array = array('orders_id' => $insert_id,
                          'orders_status_id' => $o_id,
                          'date_added' => 'now()',
                          'customer_notified' => $customer_notification,
                          'comments' => $dokument . ' ' . $order->info['comments']);
  tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

  //kgt - discount coupons
  if( tep_session_is_registered( 'coupon' ) && is_object( $order->coupon ) ) {
    $sql_data_array = array( 'coupons_id' => $order->coupon->coupon['coupons_id'],
                           'orders_id' => $insert_id );
    tep_db_perform( TABLE_DISCOUNT_COUPONS_TO_ORDERS, $sql_data_array );
  }
  //end kgt - discount coupons

  // -----------------------------------------
  // initialized for the email confirmation
  $products_ordered = '';
  $products_ordered_html = '';
  $subtotal = 0;
  $total_tax = 0;

  for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
    // Stock Update - Joao Correia
    // Security check if an IPN was already received
    $ord_id_check = tep_db_query("SELECT orders_status_id as st_check FROM ".TABLE_ORDERS_STATUS_HISTORY." Where orders_id = '" .$or. "'");
    $ordid_check = tep_db_fetch_array($ord_id_check);
    $st_check = $ordid_check['st_check'];
    $ord_id_check = tep_db_query("SELECT status_id as st_valid FROM ppec_transaction_status Where transaction_status = 'COMPLETED'");
    $ordid_check = tep_db_fetch_array($ord_id_check);
    $st_valid = $ordid_check['st_valid'];
    if ($st_check = $st_valid) {
      $nb_st = count($st_check);
      if ($nb_st=1) {

        if (STOCK_LIMITED == 'true') {
          $products_attributes = $order->products[$i]['attributes'];
          //if (DOWNLOAD_ENABLED == 'true') {
          //++++ QT Pro: End Changed Code
          $stock_query_raw = "SELECT products_quantity, pad.products_attributes_filename
                              FROM " . TABLE_PRODUCTS . " p
                              LEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES . " pa
                              ON p.products_id=pa.products_id
                              LEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad
                              ON pa.products_attributes_id=pad.products_attributes_id
                              WHERE p.products_id = '" . tep_get_prid($order->products[$i]['id']) . "'";
          // Will work with only one option for downloadable products
          // otherwise, we have to build the query dynamically with a loop
          //++++ QT Pro: Begin Changed code
          // $products_attributes = $order->products[$i]['attributes'];
          //++++ QT Pro: End Changed Code
          if (is_array($products_attributes)) {
            $stock_query_raw .= " AND pa.options_id = '" . $products_attributes[0]['option_id'] . "' AND pa.options_values_id = '" . $products_attributes[0]['value_id'] . "'";
          }
          $stock_query = tep_db_query($stock_query_raw);
        } else {
          $stock_query = tep_db_query("select products_quantity from " . TABLE_PRODUCTS . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
        }

        if (tep_db_num_rows($stock_query) > 0) {
          $stock_values = tep_db_fetch_array($stock_query);
          //++++ QT Pro: Begin Changed code
          $actual_stock_bought = $order->products[$i]['qty'];
          $download_selected = false;
          if ((DOWNLOAD_ENABLED == 'true') && isset($stock_values['products_attributes_filename']) && tep_not_null($stock_values['products_attributes_filename'])) {
            $download_selected = true;
            $products_stock_attributes='$$DOWNLOAD$$';
          }
          // If not downloadable and attributes present, adjust attribute stock
          if (!$download_selected && is_array($products_attributes)) {
            $all_nonstocked = true;
            $products_stock_attributes_array = array();
            foreach ($products_attributes as $attribute) {
              if ($attribute['track_stock'] == 1) {
                $products_stock_attributes_array[] = $attribute['option_id'] . "-" . $attribute['value_id'];
                $all_nonstocked = false;
              }
            }
            if ($all_nonstocked) {
              $actual_stock_bought = $order->products[$i]['qty'];
            }  else {
              asort($products_stock_attributes_array, SORT_NUMERIC);
              $products_stock_attributes = implode(",", $products_stock_attributes_array);
              $attributes_stock_query = tep_db_query("select products_stock_quantity from " . TABLE_PRODUCTS_STOCK . " where products_stock_attributes = '$products_stock_attributes' AND products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
              if (tep_db_num_rows($attributes_stock_query) > 0) {
                $attributes_stock_values = tep_db_fetch_array($attributes_stock_query);
                $attributes_stock_left = $attributes_stock_values['products_stock_quantity'] - $order->products[$i]['qty'];
                tep_db_query("update " . TABLE_PRODUCTS_STOCK . " set products_stock_quantity = '" . $attributes_stock_left . "' where products_stock_attributes = '$products_stock_attributes' AND products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
                $actual_stock_bought = ($attributes_stock_left < 1) ? $attributes_stock_values['products_stock_quantity'] : $order->products[$i]['qty'];
              } else {
                $attributes_stock_left = 0 - $order->products[$i]['qty'];
                tep_db_query("insert into " . TABLE_PRODUCTS_STOCK . " (products_id, products_stock_attributes, products_stock_quantity) values ('" . tep_get_prid($order->products[$i]['id']) . "', '" . $products_stock_attributes . "', '" . $attributes_stock_left . "')");
                $actual_stock_bought = 0;
              }
            }
          }
          if (!$download_selected) {
            $stock_left = $stock_values['products_quantity'] - $actual_stock_bought;
            if (STOCK_LIMITED == 'true') {
              tep_db_query("UPDATE " . TABLE_PRODUCTS . "
                            SET products_quantity = products_quantity - '" . $actual_stock_bought . "'
                            WHERE products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
            }
            //++++ QT Pro: End Changed Code
            if ( ($stock_left < 1) && (STOCK_ALLOW_CHECKOUT == 'false') ) {
              tep_db_query("update " . TABLE_PRODUCTS . " set products_status = '0' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
            }
          }
          //++++ QT Pro: Begin Changed code
        }
        //++++ QT Pro: End Changed Code
        // Update products_ordered (for bestsellers list)
        tep_db_query("update " . TABLE_PRODUCTS . " set products_ordered = products_ordered + " . sprintf('%d', $order->products[$i]['qty']) . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
        //++++ QT Pro: Begin Changed code
        if (!isset($products_stock_attributes)) $products_stock_attributes=null;
      }
    }

    $sql_data_array = array('orders_id' => $insert_id,
                            'products_id' => tep_get_prid($order->products[$i]['id']),
                            'products_model' => $order->products[$i]['model'],
                            'products_pkwiu' => $order->products[$i]['pkwiu'],
                            'products_name' => $order->products[$i]['name'],
                            'products_price' => $order->products[$i]['price'],
                            'final_price' => $order->products[$i]['final_price'],
                            'products_tax' => $order->products[$i]['tax'],
                            'products_quantity' => $order->products[$i]['qty'],
                            'products_stock_attributes' => $products_stock_attributes);
//++++ QT Pro: End Changed Code
    tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array);
    $order_products_id = tep_db_insert_id();

    //------insert customer choosen option to order--------
    $attributes_exist = '0';
    $products_ordered_attributes = '';
    // START: Add products extra fields to order email
    $products_ordered_extra_fields = '';
    // END: Add products extra fields to order email

    if (isset($order->products[$i]['attributes'])) {
      $attributes_exist = '1';
      for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) {
        if (DOWNLOAD_ENABLED == 'true') {
          $attributes_query = "select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix, pad.products_attributes_maxdays, pad.products_attributes_maxcount , pad.products_attributes_filename
                               from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa
                               left join " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad
                                on pa.products_attributes_id=pad.products_attributes_id
                               where pa.products_id = '" . $order->products[$i]['id'] . "'
                                and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "'
                                and pa.options_id = popt.products_options_id
                                and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "'
                                and pa.options_values_id = poval.products_options_values_id
                                and popt.language_id = '" . $languages_id . "'
                                and poval.language_id = '" . $languages_id . "'";
          $attributes = tep_db_query($attributes_query);
        } else {
          $attributes = tep_db_query("select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa where pa.products_id = '" . $order->products[$i]['id'] . "' and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "' and pa.options_id = popt.products_options_id and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "' and pa.options_values_id = poval.products_options_values_id and popt.language_id = '" . $languages_id . "' and poval.language_id = '" . $languages_id . "'");
        }
        $attributes_values = tep_db_fetch_array($attributes);

        $sql_data_array = array('orders_id' => $insert_id,
                                'orders_products_id' => $order_products_id,
                                'products_options' => $attributes_values['products_options_name'],
                                'products_options_values' => $attributes_values['products_options_values_name'],
                                'options_values_price' => $attributes_values['options_values_price'],
                                'price_prefix' => $attributes_values['price_prefix']);
        tep_db_perform(TABLE_ORDERS_PRODUCTS_ATTRIBUTES, $sql_data_array);

        if ((DOWNLOAD_ENABLED == 'true') && isset($attributes_values['products_attributes_filename']) && tep_not_null($attributes_values['products_attributes_filename'])) {
          $sql_data_array = array('orders_id' => $insert_id,
                                  'orders_products_id' => $order_products_id,
                                  'orders_products_filename' => $attributes_values['products_attributes_filename'],
                                  'download_maxdays' => $attributes_values['products_attributes_maxdays'],
                                  'download_count' => $attributes_values['products_attributes_maxcount']);
          tep_db_perform(TABLE_ORDERS_PRODUCTS_DOWNLOAD, $sql_data_array);
        }
        $products_ordered_attributes .= "\n\t" . $attributes_values['products_options_name'] . ': ' . $attributes_values['products_options_values_name'];
      }
    }

    // denuz text attr /////////////////////////////////// DODATKOWE POLA - CECHY TEKSTOWE
    if (!tep_session_is_registered('customer_id')) {
      $sesja = tep_session_id();
    } else {
      $sesja = (int)$customer_id;
    }
    $attr_q = tep_db_query("select * from customers_basket_text_attributes where session_id = '".$sesja."' and products_id = '" . tep_get_uprid($order->products[$i]['id'], $attributes) . "'");
    while ($attr = tep_db_fetch_array($attr_q)) {
       tep_db_query("insert into orders_text_attributes values ('".$insert_id."', '" . $order_products_id . "', " . $attr['products_text_attributes_id'] . ", '" .  $attr['products_text_attributes_text'] . "')");
    }
    tep_db_query("delete from customers_basket_text_attributes where products_id = '" . tep_get_uprid($order->products[$i]['id'], $attributes) . "' and session_id = '" . $sesja . "'");

    $products_text = '';
    $attr_a = tep_db_query("select ota.*, pta.products_text_attributes_name from orders_text_attributes as ota, products_text_attributes as pta where ota.orders_id = " . $insert_id . " and ota.products_id = " . $order_products_id . " and pta.products_text_attributes_id = ota.products_text_attributes_id");
    while ($attr = tep_db_fetch_array($attr_a)) {
      $products_text .= "\n\t" . $attr['products_text_attributes_name'] . ': ' . stripslashes($attr['products_text_attributes_text']);
    }

    //dodatkowo wstawilem w linii 389 po $products_attributes - $products_text

    // eof denuz text attr /////////////////////////////////// DODATKOWE POLA - CECHY TEKSTOWE

    //------insert customer choosen option eof ----

    // Manufacturer Name
	  //Use the products ID# to find the proper Manufacturer of this specific product
		$v_query = tep_db_query("SELECT manufacturers_id FROM ".TABLE_PRODUCTS." WHERE products_id = '".$order->products[$i]['id']."'");
		$v = tep_db_fetch_array($v_query);
	  //Select the proper Manufacturers Name via the Manufacturers ID# then display that name for a human readable output
		$mfg_query = tep_db_query("SELECT manufacturers_name FROM ".TABLE_MANUFACTURERS." WHERE manufacturers_id = '".$v['manufacturers_id']."'");
		$mfg = tep_db_fetch_array($mfg_query);
    // End Manufacturer Listing

    $total_weight += ($order->products[$i]['qty'] * $order->products[$i]['weight']);
    $total_tax += tep_calculate_tax($total_products_price, $products_tax) * $order->products[$i]['qty'];
    $total_cost += $total_products_price;

    // START: Add products extra fields to order email
    //TotalB2B start
    $products_ordered .= $order->products[$i]['qty'] . ' x ' . $order->products[$i]['name'] . ' (' . $order->products[$i]['model'] . ') = ' . $currencies->display_price_nodiscount($order->products[$i]['id'], $order->products[$i]['final_price'], $order->products[$i]['tax'], $order->products[$i]['qty']) . $products_ordered_attributes . $products_text  . "\n";
    $products_ordered_html .= '<tr>
                                <td align="left" style="background-color:#f0f0f0;font-family:Tahoma,Arial;font-size:12px;color:#474747">'.$order->products[$i]['name'] . '<i><span style="font-size:10px">'. str_replace("\n\t","<br>",$products_ordered_attributes . $products_text).'</span></i></td>
                                <td align="center" style="background-color:#f0f0f0;font-family:Tahoma,Arial;font-size:12px;color:#474747">'.$order->products[$i]['model'].'</td>
                                <td align="right" style="background-color:#f0f0f0;font-family:Tahoma,Arial;font-size:12px;color:#474747">'.$currencies->display_price_nodiscount( tep_get_prid($order->products[$i]['id']), $order->products[$i]['final_price'], $order->products[$i]['tax'], 1).'</td>
                                <td align="center" style="background-color:#f0f0f0;font-family:Tahoma,Arial;font-size:12px;color:#474747">'.$order->products[$i]['qty'].'</td>
                                <td align="right" style="background-color:#f0f0f0;font-family:Tahoma,Arial;font-size:12px;color:#474747" nowrap>'.$currencies->display_price_nodiscount( tep_get_prid($order->products[$i]['id']), $order->products[$i]['final_price'], $order->products[$i]['tax'], $order->products[$i]['qty']).'</td>
                              </tr>';
    //TotalB2B end
    // END: Add products extra fields to order email
    $products_ordered .= "\n" . BOX_HEADING_MANUFACTURER_INFO . ' : ' . $mfg['manufacturers_name'] . "\n";
  }

  /// --- start ---- checkout process email function
  include(DIR_WS_LANGUAGES . $language . '/' . FILENAME_CHECKOUT_PROCESS);

  /************************ WYSYLANIE PRO=FORMY MAILEM *************************/
  function recursive_mkdir($path, $mode = 0777) {
    $old_mask = umask(0);
    $dirs = explode(DIRECTORY_SEPARATOR , $path);
    $count = count($dirs);
    $path = '.';
    for ($i = 0; $i < $count; ++$i) {
      $path .= DIRECTORY_SEPARATOR . $dirs[$i];
      if (!is_dir($path) && !mkdir($path, $mode)) {
        return false;
      }
    }
    umask($old_mask);
    return true;
  }

  if ( $proforma == true ) {
    if ((POLISH_INVOICE_PDF_ARCHIVE != '') && (!recursive_mkdir('administracja/' . POLISH_INVOICE_PDF_ARCHIVE, 0755))) {
      die('Nie mozna utworzyc katalogu: ' . POLISH_INVOICE_PDF_ARCHIVE);
    }
    global $language;
    include('pdffaktura_email.php');
  }
  /************************************ THE END *************************************/

  include(DIR_WS_FUNCTIONS .'function_email_paypal.php');

}

/* Not used currently to fix Tax issue 2.23

 function reviewtotal()
 {
  global $ctotal, $cshipping, $classot, $language, $order_totals, $ctax, $subtotal;

  if (is_array($classot)) {
      for ($j=0, $k=sizeof($classot); $j<$k; $j++) {
               $class = $classot[$j];
               if ($GLOBALS[$class]->enabled) {
                  $GLOBALS[$class]->process();
                  include(DIR_WS_LANGUAGES.$language.'/modules/order_total/'.$class.'.php');

                  for ($i=0, $n=sizeof($GLOBALS[$class]->output); $i<$n; $i++) {

                             $order_totals[] = array('code' => $GLOBALS[$class]->code,
                                                     'title' => $GLOBALS[$class]->output[$i]['title'],
                                                     'text' => $GLOBALS[$class]->output[$i]['text'],
                                                     'value' => $GLOBALS[$class]->output[$i]['value'],
                                                     'sort_order' => $GLOBALS[$class]->sort_order);

                             if($GLOBALS[$class]->code == 'ot_total')
                             {
                                     $ctotal = $GLOBALS[$class]->output[$i]['value'];
                             }
                             else if($GLOBALS[$class]->code == 'ot_shipping')
                                  {
                                     $cshipping = $GLOBALS[$class]->output[$i]['value'];
                                  }
                  else if($GLOBALS[$class]->code == 'ot_tax')
                  {
                    $ctax = $GLOBALS[$class]->output[$i]['value'];
                  }
                  else if($GLOBALS[$class]->code == 'ot_subtotal')
                    {
                      $csubtotal = $GLOBALS[$class]->output[$i]['value'];
                    }
                 }
              }
        }
   }

 }

 function reviewbasket()
 {
    global $classot, $order, $shipping, $cart, $order_total_modules;

    require(DIR_WS_CLASSES . 'order.php');
    $order = new order;

    require(DIR_WS_CLASSES . 'order_total.php');
    $order_total_modules = new order_total;

    $classot = array();
    if (is_array($order_total_modules->modules)) {
           reset($order_total_modules->modules);
           while (list(, $value) = each($order_total_modules->modules)) {
                 $classot[] = substr($value, 0, strrpos($value, '.'));
           }
    }

 }

 2.23 */

function ppebin() {
  global $language, $lg;

  if($language == "french") {
    $lg = "FR";
  } elseif($language == "german") {
    $lg = "DE";
  } elseif($language == "italian") {
    $lg = "IT";
  } elseif($language == "spanish") {
    $lg = "ES";
  } elseif($language == "netherlands") {
    $lg = "NL";
  } elseif($language == "polish") {
    $lg = "PL";
  } elseif($language == "japanese") {
    $lg = "JP";
  } else {
    $lg = "US";
  }
}



function ppecon() {
  global $cart, $lg;
  $serverName = $_SERVER['SERVER_NAME'];
  $serverPort = $_SERVER['SERVER_PORT'];
  // set the type of request (secure or not)
  $request_type = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
  $url = dirname($request_type.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);

  $request_SSL = ($_SERVER['HTTPS'] == 'on') ? 'SSL' : 'NONSSL';

  if($cart->show_total()>0)
    //$returnURL = urlencode($url.'/'.FILENAME_CHECKOUT_SHIPPING);
    $returnURL =  urlencode(tep_href_link(FILENAME_CHECKOUT_SHIPPING, '', $request_SSL));
  else
    //$returnURL = urlencode($url.'/'.FILENAME_ACCOUNT);
    $returnURL =  urlencode(tep_href_link(FILENAME_ACCOUNT, '', $request_SSL));

  $cancelURL =  urlencode(tep_href_link(FILENAME_SHOPPING_CART, '', $request_SSL));
  $logoutURL =  urlencode(tep_href_link(FILENAME_LOGOFF, '', $request_SSL));
  // $cancelURL = urlencode($url.'/'.FILENAME_SHOPPING_CART);
  //$logoutURL = urlencode($url.'/'.FILENAME_LOGOFF);

  ppebin();

  $nvpstr="&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&LOGOUTURL=".$logoutURL."&LOCALECODE=".$lg;

  $resArray=hash_call("SetAuthFlowParam",$nvpstr);
  $_SESSION['reshash']=$resArray;
  $ack = strtoupper($resArray["ACK"]);
  if($ack=="SUCCESS"){
    $token = urldecode($resArray["TOKEN"]);
    $payPalURL = PAYPAL_URL_AUT.$token;

    header("Location: ".$payPalURL);

  } else  {
    $_SESSION['reshash']=$resArray;
    $ack = strtoupper($resArray["ACK"]);
    $cor = strtoupper($resArray['CORRELATIONID']);
    $ver = strtoupper($resArray['VERSION']);
    echo('ACK: '.$ack.'<br>');
    echo('Correlation: '.$cor.'<br>');
    echo('version: '.$ver.'<br>');

    $count=0;

    while (isset($resArray["L_SHORTMESSAGE".$count])) {
      $errorCode    = $resArray["L_ERRORCODE".$count];
      $shortMessage = $resArray["L_SHORTMESSAGE".$count];
      $longMessage  = $resArray["L_LONGMESSAGE".$count];
      echo('ACK: '.$errorCode.'<br>');
      echo('Correlation: '.$shortMessage.'<br>');
      echo('version: '.$longMessage.'<br>');
      $count=$count+1;
    }
  }

  $payerid  = "";
  $cust_query = tep_db_query("select ".TABLE_CUSTOMERS.".customers_id, ".TABLE_CUSTOMERS.".customers_default_address_id from ".TABLE_CUSTOMERS.", ppec_payer where ".TABLE_CUSTOMERS.".customers_id = ppec_payer.customers_id and ppec_payer.payerid = '".$payerid."'");

  if (tep_db_num_rows($cust_query)) {
    $row = mysql_fetch_row($cust_query);
    $customer_id = $row[0];
    $address_id = $row[1];
  } else {
  }

}


function tep_get_stan_code($country_id, $zone_name, $default_zone) {
    $zone_query = tep_db_query("select zone_code from " . TABLE_ZONES . " where zone_name = '" . $zone_name . "'");
    if (tep_db_num_rows($zone_query)) {
      $zone = tep_db_fetch_array($zone_query);
      return $zone['zone_code'];
    } else {
      return $default_zone;
    }
  }


?>