<?php
/*
  $Id$

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2006 osCommerce

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License v2 (1991)
  as published by the Free Software Foundation.
*/

/**
 * The administration side of the PayPal IPN payment module
 */

  class osC_Payment_paypal_ipn extends osC_Payment_Admin {

/**
 * The administrative title of the payment module
 *
 * @var string
 * @access private
 */

    var $_title;

/**
 * The code of the payment module
 *
 * @var string
 * @access private
 */

    var $_code = 'paypal_ipn';

/**
 * The developers name
 *
 * @var string
 * @access private
 */

    var $_author_name = 'osCommerce';

/**
 * The developers address
 *
 * @var string
 * @access private
 */

    var $_author_www = 'http://www.oscommerce.com';

/**
 * The status of the module
 *
 * @var boolean
 * @access private
 */

    var $_status = false;

/**
 * Constructor
 */

    function osC_Payment_paypal_ipn() {
      global $osC_Database, $osC_Language;

      $this->_title = $osC_Language->get('payment_paypal_ipn_title');
      $this->_description = $osC_Language->get('payment_paypal_ipn_description');
      $this->_method_title = $osC_Language->get('payment_paypal_ipn_method_title');
      $this->_status = (defined('MODULE_PAYMENT_PAYPAL_IPN_STATUS') && (MODULE_PAYMENT_PAYPAL_IPN_STATUS == '1') ? true : false);
      $this->_sort_order = (defined('MODULE_PAYMENT_PAYPAL_IPN_SORT_ORDER') ? MODULE_PAYMENT_PAYPAL_IPN_SORT_ORDER : null);
	  
	  $title1 = $osC_Language->get('payment_paypal_ipn_admin_1');
	  $title2 = $osC_Language->get('payment_paypal_ipn_admin_2');
	  $title3 = $osC_Language->get('payment_paypal_ipn_admin_3');
	  $title4 = $osC_Language->get('payment_paypal_ipn_admin_4');
	  $title5 = $osC_Language->get('payment_paypal_ipn_admin_5');
	  $title6 = $osC_Language->get('payment_paypal_ipn_admin_6');
	  $title7 = $osC_Language->get('payment_paypal_ipn_admin_7');
	  $title8 = $osC_Language->get('payment_paypal_ipn_admin_8');
	  $title9 = $osC_Language->get('payment_paypal_ipn_admin_9');
	  $title10 = $osC_Language->get('payment_paypal_ipn_admin_10');
	  $title11 = $osC_Language->get('payment_paypal_ipn_admin_11');
	  $title12 = $osC_Language->get('payment_paypal_ipn_admin_12');
	  $title13 = $osC_Language->get('payment_paypal_ipn_admin_13');
	  $title14 = $osC_Language->get('payment_paypal_ipn_admin_14');
	  $title15 = $osC_Language->get('payment_paypal_ipn_admin_15');
	  $title16 = $osC_Language->get('payment_paypal_ipn_admin_16');
	  $title17 = $osC_Language->get('payment_paypal_ipn_admin_17');
	  $title18 = $osC_Language->get('payment_paypal_ipn_admin_18');
	  $title19 = $osC_Language->get('payment_paypal_ipn_admin_19');
	  $title20 = $osC_Language->get('payment_paypal_ipn_admin_20');
	  $title21 = $osC_Language->get('payment_paypal_ipn_admin_21');
	  $title22 = $osC_Language->get('payment_paypal_ipn_admin_22');
	  $title23 = $osC_Language->get('payment_paypal_ipn_admin_23');
	  $title24 = $osC_Language->get('payment_paypal_ipn_admin_24');
	  $title25 = $osC_Language->get('payment_paypal_ipn_admin_25');
	  $title26 = $osC_Language->get('payment_paypal_ipn_admin_26');
	  $title27 = $osC_Language->get('payment_paypal_ipn_admin_27');
	  $title28 = $osC_Language->get('payment_paypal_ipn_admin_28');
	  $title29 = $osC_Language->get('payment_paypal_ipn_admin_29');
	  $title30 = $osC_Language->get('payment_paypal_ipn_admin_30');
	  $title31 = $osC_Language->get('payment_paypal_ipn_admin_31');
	  $title32 = $osC_Language->get('payment_paypal_ipn_admin_32');
	  $title33 = $osC_Language->get('payment_paypal_ipn_admin_33');
	  $title34 = $osC_Language->get('payment_paypal_ipn_admin_34');
	  
	$titlex = $osC_Language->get('access_configuration_title27');
	$titley = $osC_Language->get('access_configuration_title93');
	$Ckey = $osC_Database->query("SELECT * FROM " . DB_TABLE_PREFIX . "configuration WHERE configuration_key = 'STORE_NAME_ADDRESS'");	
	$configuration_title = $Ckey->value('configuration_title');
	$configuration_description = $Ckey->value('configuration_description');
	if (($configuration_title & $configuration_description) != ($titlex & $titley)) {		  
	  

	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title1', configuration_description = '$title18' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_STATUS'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title2', configuration_description = '$title19' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_ID'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title3', configuration_description = '$title20' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_API_USERNAME'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title4', configuration_description = '$title21' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_API_PASSWORD'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title5', configuration_description = '$title22' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_API_CERTIFICATE'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title6', configuration_description = '$title23' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_EWP_STATUS'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title7', configuration_description = '$title24' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_EWP_PRIVATE_KEY'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title8', configuration_description = '$title25' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_EWP_PUBLIC_KEY'");	  
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title9', configuration_description = '$title26' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_EWP_PAYPAL_KEY'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title10', configuration_description = '$title27' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_EWP_CERT_ID'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title11', configuration_description = '$title28' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_EWP_OPENSSL'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title12', configuration_description = '$title29' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_SECRET_KEY'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title13', configuration_description = '$title30' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_CURRENCY'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title14', configuration_description = '$title31' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_SERVER'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title15', configuration_description = '$title32' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_SORT_ORDER'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title16', configuration_description = '$title33' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_ZONE'");
	  $osC_Database->simpleQuery("UPDATE " . TABLE_CONFIGURATION . " SET configuration_title = '$title17', configuration_description = '$title34' WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_IPN_ORDER_STATUS_ID'");  	  

      if (defined('MODULE_PAYMENT_PAYPAL_IPN_SERVER')) {
        switch (MODULE_PAYMENT_PAYPAL_IPN_SERVER) {
          case 'Production':
            $this->_gateway_server = 'https://api.paypal.com/2.0/';
            break;

          default:
            $this->_gateway_server = 'https://api.sandbox.paypal.com/2.0/';
            break;
        }
      }
    }
	}

/**
 * Checks to see if the module has been installed
 *
 * @access public
 * @return boolean
 */

    function isInstalled() {
      return (bool)defined('MODULE_PAYMENT_PAYPAL_IPN_STATUS');
    }

/**
 * Installs the module
 *
 * @access public
 * @see osC_Payment_Admin::install()
 */

    function install() {
      global $osC_Database;

      parent::install();

      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Enable PayPal IPN Module', 'MODULE_PAYMENT_PAYPAL_IPN_STATUS', '-1', 'Do you want to accept PayPal IPN payments?', '6', '0', 'osc_cfg_use_get_boolean_value', 'osc_cfg_set_boolean_value(array(1, -1))', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('PayPal E-Mail Address', 'MODULE_PAYMENT_PAYPAL_IPN_ID', '', 'The seller e-mail address to use for accepting PayPal payments.', '6', '0', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('API Username', 'MODULE_PAYMENT_PAYPAL_IPN_API_USERNAME', '', 'The username to use for the PayPal Web Services API.', '6', '0', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('API Password', 'MODULE_PAYMENT_PAYPAL_IPN_API_PASSWORD', '', 'The password to use for the PayPal Web Services API.', '6', '0', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('API Certificate', 'MODULE_PAYMENT_PAYPAL_IPN_API_CERTIFICATE', '', 'The location of the PayPal API Certificate for the PayPal Web Services API.', '6', '0', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Enable Encrypted Web Payments', 'MODULE_PAYMENT_PAYPAL_IPN_EWP_STATUS', '-1', 'Do you want to enable Encrypted Web Payments?', '6', '0', 'osc_cfg_use_get_boolean_value', 'osc_cfg_set_boolean_value(array(1, -1))', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Encrypted Web Payments Private Key (Seller)', 'MODULE_PAYMENT_PAYPAL_IPN_EWP_PRIVATE_KEY', '', 'The location of your Private Key to use for signing the data. (*.pem)', '6', '0', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Encrypted Web Payments Public Certificate (Seller)', 'MODULE_PAYMENT_PAYPAL_IPN_EWP_PUBLIC_KEY', '', 'The location of your Public Certificate to use for signing the data. (*.pem)', '6', '0', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Encrpyted Web Payments Public Certificate (PayPal)', 'MODULE_PAYMENT_PAYPAL_IPN_EWP_PAYPAL_KEY', '', 'The location of the PayPal Public Certificate for encrypting the data.', '6', '0', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Encrypted Web Payments Public Certificate ID', 'MODULE_PAYMENT_PAYPAL_IPN_EWP_CERT_ID', '', 'The Certificate ID to use from your PayPal Encrypted Payment Settings Profile.', '6', '0', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('OpenSSL Location', 'MODULE_PAYMENT_PAYPAL_IPN_EWP_OPENSSL', '/usr/bin/openssl', 'The location of the openssl binary file.', '6', '0', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Secret Key', 'MODULE_PAYMENT_PAYPAL_IPN_SECRET_KEY', '', 'A secret key to pass to PayPal (primarly used with Encrypted Web Payments).', '6', '0', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Transaction Currency', 'MODULE_PAYMENT_PAYPAL_IPN_CURRENCY', '14', 'The currency to use for credit card transactions', '6', '0', 'osc_cfg_set_boolean_value(array(14,\'USD\',\'CAD\',\'EUR\',\'GBP\',\'JPY\'))', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Transaction Server', 'MODULE_PAYMENT_PAYPAL_IPN_SERVER', '15', 'The server to perform transactions in.', '6', '0', 'osc_cfg_set_boolean_value(array(13, 15))', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of display.', 'MODULE_PAYMENT_PAYPAL_IPN_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '0', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_PAYPAL_IPN_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '0', 'osc_cfg_use_get_zone_class_title', 'osc_cfg_set_zone_classes_pull_down_menu', now())");
      $osC_Database->simpleQuery("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Order Status', 'MODULE_PAYMENT_PAYPAL_IPN_ORDER_STATUS_ID', '0', 'Set the status of orders made with this payment module to this value', '6', '0', 'osc_cfg_set_order_statuses_pull_down_menu', 'osc_cfg_use_get_order_status_title', now())");
    }

/**
 * Return the configuration parameter keys in an array
 *
 * @access public
 * @return array
 */

    function getKeys() {
      if (!isset($this->_keys)) {
        $this->_keys = array('MODULE_PAYMENT_PAYPAL_IPN_STATUS',
                             'MODULE_PAYMENT_PAYPAL_IPN_ID',
                             'MODULE_PAYMENT_PAYPAL_IPN_API_USERNAME',
                             'MODULE_PAYMENT_PAYPAL_IPN_API_PASSWORD',
                             'MODULE_PAYMENT_PAYPAL_IPN_API_CERTIFICATE',
                             'MODULE_PAYMENT_PAYPAL_IPN_EWP_STATUS',
                             'MODULE_PAYMENT_PAYPAL_IPN_EWP_PRIVATE_KEY',
                             'MODULE_PAYMENT_PAYPAL_IPN_EWP_PUBLIC_KEY',
                             'MODULE_PAYMENT_PAYPAL_IPN_EWP_PAYPAL_KEY',
                             'MODULE_PAYMENT_PAYPAL_IPN_EWP_CERT_ID',
                             'MODULE_PAYMENT_PAYPAL_IPN_EWP_OPENSSL',
                             'MODULE_PAYMENT_PAYPAL_IPN_SECRET_KEY',
                             'MODULE_PAYMENT_PAYPAL_IPN_CURRENCY',
                             'MODULE_PAYMENT_PAYPAL_IPN_SERVER',
                             'MODULE_PAYMENT_PAYPAL_IPN_ORDER_STATUS_ID',
                             'MODULE_PAYMENT_PAYPAL_IPN_ZONE',
                             'MODULE_PAYMENT_PAYPAL_IPN_SORT_ORDER');
      }

      return $this->_keys;
    }

/**
 * Returns the available post transaction actions in an array
 *
 * @access public
 * @param $history An array of transaction actions already processed
 * @return array
 */

    function getPostTransactionActions($history) {
      if ( (osc_empty(MODULE_PAYMENT_PAYPAL_IPN_API_USERNAME) === false) && (osc_empty(MODULE_PAYMENT_PAYPAL_IPN_API_PASSWORD) === false) && (osc_empty(MODULE_PAYMENT_PAYPAL_IPN_API_CERTIFICATE) === false) ) {
        $actions = array(4 => 'inquiryTransaction');

        if ( (in_array('2', $history) === false) && (in_array('3', $history) === false) ) {
          $actions[2] = 'cancelTransaction';
          $actions[3] = 'approveTransaction';
        }

        return $actions;
      }

      return false;
    }

/**
 * Approves the transaction at the gateway server
 *
 * @access public
 * @param $id The ID of the order
 */

    function approveTransaction($id) {
      global $osC_Database;

      $Qorder = $osC_Database->query('select transaction_return_value from :table_orders_transactions_history where orders_id = :orders_id and transaction_code = 1 order by date_added limit 1');
      $Qorder->bindTable(':table_orders_transactions_history', TABLE_ORDERS_TRANSACTIONS_HISTORY);
      $Qorder->bindInt(':orders_id', $id);
      $Qorder->execute();

      if ($Qorder->numberOfRows() === 1) {
        $osC_XML = new osC_XML($Qorder->value('transaction_return_value'));
        $result = $osC_XML->toArray();

        $string = '<?xml version="1.0" encoding="UTF-8"?>
                   <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
                     <SOAP-ENV:Header>
                       <RequesterCredentials xmlns="urn:ebay:api:PayPalAPI" SOAP-ENV:mustUnderstand="1">
                         <Credentials xmlns="urn:ebay:apis:eBLBaseComponents">
                           <Username>' . MODULE_PAYMENT_PAYPAL_IPN_API_USERNAME . '</Username>
                           <Password>' . MODULE_PAYMENT_PAYPAL_IPN_API_PASSWORD . '</Password>
                           <Subject/>
                         </Credentials>
                       </RequesterCredentials>
                     </SOAP-ENV:Header>
                     <SOAP-ENV:Body>
                       <DoCaptureReq xmlns="urn:ebay:api:PayPalAPI">
                         <DoCaptureRequest xmlns="urn:ebay:api:PayPalAPI">
                           <Version xmlns="urn:ebay:apis:eBLBaseComponents" xsi:type="xsd:string">1.0</Version>
                           <AuthorizationID>' . $result['root']['auth_id'] . '</AuthorizationID>
                           <Amount currencyID="' . $result['root']['mc_currency'] . '" xsi:type="cc:BasicAmountType">' . $result['root']['mc_gross'] . '</Amount>
                           <CompleteType>Complete</CompleteType>
                         </DoCaptureRequest>
                       </DoCaptureReq>
                     </SOAP-ENV:Body>
                   </SOAP-ENV:Envelope>';

        $result = $this->sendTransactionToGateway($this->_gateway_server, $string, '', 'post', MODULE_PAYMENT_PAYPAL_IPN_API_CERTIFICATE);

        if (empty($result) === false) {
          $osC_XML = new osC_XML($result);

// there is a PHP 5.1.2 XML root namespace bug; http://bugs.php.net/bug.php?id=37035
          $result = $osC_XML->toArray();

          if (isset($result['SOAP-ENV:Envelope']['SOAP-ENV:Body']['DoCaptureResponse'])) {
            $info = $result['SOAP-ENV:Envelope']['SOAP-ENV:Body']['DoCaptureResponse'];
            $result =& $info['DoCaptureResponseDetails'];

            if ($info['Ack'] == 'Success') {
              $data = array('root' => array('AuthorizationID' => $result['AuthorizationID'],
                                            'PaymentInfo' => array('TransactionID' => $result['PaymentInfo']['TransactionID'],
                                                                   'ParentTransactionID' => $result['PaymentInfo']['ParentTransactionID'],
                                                                   'ReceiptID' => $result['PaymentInfo']['ReceiptID'],
                                                                   'TransactionType' => $result['PaymentInfo']['TransactionType'],
                                                                   'PaymentType' => $result['PaymentInfo']['PaymentType'],
                                                                   'PaymentDate' => $result['PaymentInfo']['PaymentDate'],
                                                                   'GrossAmount' => $result['PaymentInfo']['GrossAmount'],
                                                                   'GrossAmountCurrencyID' => $result['PaymentInfo']['GrossAmount attr']['currencyID'],
                                                                   'FeeAmount' => $result['PaymentInfo']['FeeAmount'],
                                                                   'FeeAmountCurrencyID' => $result['PaymentInfo']['FeeAmount attr']['currencyID'],
                                                                   'TaxAmount' => $result['PaymentInfo']['TaxAmount'],
                                                                   'TaxAmountCurrencyID' => $result['PaymentInfo']['TaxAmount attr']['currencyID'],
                                                                   'ExchangeRate' => $result['PaymentInfo']['ExchangeRate'],
                                                                   'PaymentStatus' => $result['PaymentInfo']['PaymentStatus'],
                                                                   'PendingReason' => $result['PaymentInfo']['PendingReason'],
                                                                   'ReasonCode' => $result['PaymentInfo']['ReasonCode'])));
            } else {
              $data = array('root' => array('Ack' => $info['Ack'],
                                            'Errors' => array('ShortMessage' => $info['Errors']['ShortMessage'],
                                                              'LongMessage' => $info['Errors']['LongMessage'],
                                                              'ErrorCode' => $info['Errors']['ErrorCode'])));
            }

            $osC_XML = new osC_XML($data);

            $Qtransaction = $osC_Database->query('insert into :table_orders_transactions_history (orders_id, transaction_code, transaction_return_value, transaction_return_status, date_added) values (:orders_id, :transaction_code, :transaction_return_value, :transaction_return_status, now())');
            $Qtransaction->bindTable(':table_orders_transactions_history', TABLE_ORDERS_TRANSACTIONS_HISTORY);
            $Qtransaction->bindInt(':orders_id', $id);
            $Qtransaction->bindInt(':transaction_code', 3);
            $Qtransaction->bindValue(':transaction_return_value', $osC_XML->toXML());
            $Qtransaction->bindInt(':transaction_return_status', ($info['Ack'] == 'Success' ? 1 : 0));
            $Qtransaction->execute();
          }
        }
      }
    }

/**
 * Cancels the transaction at the gateway server
 *
 * @access public
 * @param $id The ID of the order
 */

    function cancelTransaction($id) {
      global $osC_Database;

      $Qorder = $osC_Database->query('select transaction_return_value from :table_orders_transactions_history where orders_id = :orders_id and transaction_code = 1 order by date_added limit 1');
      $Qorder->bindTable(':table_orders_transactions_history', TABLE_ORDERS_TRANSACTIONS_HISTORY);
      $Qorder->bindInt(':orders_id', $id);
      $Qorder->execute();

      if ($Qorder->numberOfRows() === 1) {
        $osC_XML = new osC_XML($Qorder->value('transaction_return_value'));
        $result = $osC_XML->toArray();

        $string = '<?xml version="1.0" encoding="UTF-8"?>
                   <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
                     <SOAP-ENV:Header>
                       <RequesterCredentials xmlns="urn:ebay:api:PayPalAPI" SOAP-ENV:mustUnderstand="1">
                         <Credentials xmlns="urn:ebay:apis:eBLBaseComponents">
                           <Username>' . MODULE_PAYMENT_PAYPAL_IPN_API_USERNAME . '</Username>
                           <Password>' . MODULE_PAYMENT_PAYPAL_IPN_API_PASSWORD . '</Password>
                           <Subject/>
                         </Credentials>
                       </RequesterCredentials>
                     </SOAP-ENV:Header>
                     <SOAP-ENV:Body>
                       <DoVoidReq xmlns="urn:ebay:api:PayPalAPI">
                         <DoVoidRequest xmlns="urn:ebay:api:PayPalAPI">
                           <Version xmlns="urn:ebay:apis:eBLBaseComponents" xsi:type="xsd:string">1.0</Version>
                           <AuthorizationID>' . $result['root']['auth_id'] . '</AuthorizationID>
                         </DoVoidRequest>
                       </DoVoidReq>
                     </SOAP-ENV:Body>
                   </SOAP-ENV:Envelope>';

        $result = $this->sendTransactionToGateway($this->_gateway_server, $string, '', 'post', MODULE_PAYMENT_PAYPAL_IPN_API_CERTIFICATE);

        if (empty($result) === false) {
          $osC_XML = new osC_XML($result);

// there is a PHP 5.1.2 XML root namespace bug; http://bugs.php.net/bug.php?id=37035
          $result = $osC_XML->toArray();

          if (isset($result['SOAP-ENV:Envelope']['SOAP-ENV:Body']['DoVoidResponse'])) {
            $result = $result['SOAP-ENV:Envelope']['SOAP-ENV:Body']['DoVoidResponse'];

            $data = array('root' => array('Ack' => $result['Ack']));

            if ($result['Ack'] != 'Success') {
              $data['root']['Errors'] = array('ShortMessage' => $result['Errors']['ShortMessage'],
                                              'LongMessage' => $result['Errors']['LongMessage'],
                                              'ErrorCode' => $result['Errors']['ErrorCode']);
            }

            $osC_XML = new osC_XML($data);

            $Qtransaction = $osC_Database->query('insert into :table_orders_transactions_history (orders_id, transaction_code, transaction_return_value, transaction_return_status, date_added) values (:orders_id, :transaction_code, :transaction_return_value, :transaction_return_status, now())');
            $Qtransaction->bindTable(':table_orders_transactions_history', TABLE_ORDERS_TRANSACTIONS_HISTORY);
            $Qtransaction->bindInt(':orders_id', $id);
            $Qtransaction->bindInt(':transaction_code', 2);
            $Qtransaction->bindValue(':transaction_return_value', $osC_XML->toXML());
            $Qtransaction->bindInt(':transaction_return_status', ($result['Ack'] == 'Success' ? 1 : 0));
            $Qtransaction->execute();
          }
        }
      }
    }

/**
 * Send a status enquiry of the transaction to the gateway server
 *
 * @access public
 * @param $id The ID of the order
 */

    function inquiryTransaction($id) {
      global $osC_Database;

      $Qorder = $osC_Database->query('select transaction_return_value from :table_orders_transactions_history where orders_id = :orders_id and transaction_code = 1 order by date_added limit 1');
      $Qorder->bindTable(':table_orders_transactions_history', TABLE_ORDERS_TRANSACTIONS_HISTORY);
      $Qorder->bindInt(':orders_id', $id);
      $Qorder->execute();

      if ($Qorder->numberOfRows() === 1) {
        $osC_XML = new osC_XML($Qorder->value('transaction_return_value'));
        $result = $osC_XML->toArray();

        $string = '<?xml version="1.0" encoding="UTF-8"?>
                  <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
                    <SOAP-ENV:Header>
                      <RequesterCredentials xmlns="urn:ebay:api:PayPalAPI" SOAP-ENV:mustUnderstand="1">
                        <Credentials xmlns="urn:ebay:apis:eBLBaseComponents">
                          <Username>' . MODULE_PAYMENT_PAYPAL_IPN_API_USERNAME . '</Username>
                          <Password>' . MODULE_PAYMENT_PAYPAL_IPN_API_PASSWORD . '</Password>
                          <Subject/>
                        </Credentials>
                      </RequesterCredentials>
                    </SOAP-ENV:Header>
                    <SOAP-ENV:Body>
                      <GetTransactionDetailsReq xmlns="urn:ebay:api:PayPalAPI">
                        <GetTransactionDetailsRequest xsi:type="ns:GetTransactionDetailsRequestType">
                          <Version xmlns="urn:ebay:apis:eBLBaseComponents" xsi:type="xsd:string">1.0</Version>
                          <TransactionID xsi:type="ebl:TransactionId">' . $result['root']['txn_id'] . '</TransactionID>
                        </GetTransactionDetailsRequest>
                      </GetTransactionDetailsReq>
                    </SOAP-ENV:Body>
                  </SOAP-ENV:Envelope>';

        $result = $this->sendTransactionToGateway($this->_gateway_server, $string, '', 'post', MODULE_PAYMENT_PAYPAL_IPN_API_CERTIFICATE);

        if (empty($result) === false) {
          $osC_XML = new osC_XML($result);

// there is a PHP 5.1.2 XML root namespace bug; http://bugs.php.net/bug.php?id=37035
          $result = $osC_XML->toArray();

          if (isset($result['SOAP-ENV:Envelope']['SOAP-ENV:Body']['GetTransactionDetailsResponse'])) {
            $info = $result['SOAP-ENV:Envelope']['SOAP-ENV:Body']['GetTransactionDetailsResponse'];
            $result =& $info['PaymentTransactionDetails'];

            if ($info['Ack'] == 'Success') {
              $data = array('root' => array('ReceiverInfo' => array('Business' => $result['ReceiverInfo']['Business'],
                                                                    'Receiver' => $result['ReceiverInfo']['Receiver'],
                                                                    'ReceiverID' => $result['ReceiverInfo']['ReceiverID']),
                                            'PayerInfo' => array('Payer' => $result['PayerInfo']['Payer'],
                                                                 'PayerID' => $result['PayerInfo']['PayerID'],
                                                                 'PayerStatus' => $result['PayerInfo']['PayerStatus'],
                                                                 'PayerName' => array('Salutation' => $result['PayerInfo']['PayerName']['Salutation'],
                                                                                      'FirstName' => $result['PayerInfo']['PayerName']['FirstName'],
                                                                                      'MiddleName' => $result['PayerInfo']['PayerName']['MiddleName'],
                                                                                      'LastName' => $result['PayerInfo']['PayerName']['LastName'],
                                                                                      'Suffix' => $result['PayerInfo']['PayerName']['Suffix']),
                                                                 'PayerCountry' => $result['PayerInfo']['PayerCountry'],
                                                                 'PayerBusiness' => $result['PayerInfo']['PayerBusiness'],
                                                                 'Address' => array('Name' => $result['PayerInfo']['Address']['Name'],
                                                                                    'Street1' => $result['PayerInfo']['Address']['Street1'],
                                                                                    'Street2' => $result['PayerInfo']['Address']['Street2'],
                                                                                    'CityName' => $result['PayerInfo']['Address']['CityName'],
                                                                                    'StateOrProvince' => $result['PayerInfo']['Address']['StateOrProvince'],
                                                                                    'Country' => $result['PayerInfo']['Address']['Country'],
                                                                                    'CountryName' => $result['PayerInfo']['Address']['CountryName'],
                                                                                    'PostalCode' => $result['PayerInfo']['Address']['PostalCode'],
                                                                                    'AddressOwner' => $result['PayerInfo']['Address']['AddressOwner'],
                                                                                    'AddressStatus' => $result['PayerInfo']['Address']['AddressStatus'])),
                                            'PaymentInfo' => array('TransactionID' => $result['PaymentInfo']['TransactionID'],
                                                                   'ParentTransactionID' => $result['PaymentInfo']['ParentTransactionID'],
                                                                   'ReceiptID' => $result['PaymentInfo']['ReceiptID'],
                                                                   'TransactionType' => $result['PaymentInfo']['TransactionType'],
                                                                   'PaymentType' => $result['PaymentInfo']['PaymentType'],
                                                                   'PaymentDate' => $result['PaymentInfo']['PaymentDate'],
                                                                   'GrossAmount' => $result['PaymentInfo']['GrossAmount'],
                                                                   'GrossAmountCurrencyID' => $result['PaymentInfo']['GrossAmount attr']['currencyID'],
                                                                   'TaxAmount' => $result['PaymentInfo']['TaxAmount'],
                                                                   'TaxAmountCurrencyID' => $result['PaymentInfo']['TaxAmount attr']['currencyID'],
                                                                   'ExchangeRate' => $result['PaymentInfo']['ExchangeRate'],
                                                                   'PaymentStatus' => $result['PaymentInfo']['PaymentStatus'],
                                                                   'PendingReason' => $result['PaymentInfo']['PendingReason'],
                                                                   'ReasonCode' => $result['PaymentInfo']['ReasonCode']),
                                            'PaymentItemInfo' => array('InvoiceID' => $result['PaymentItemInfo']['InvoiceID'],
                                                                       'Custom' => $result['PaymentItemInfo']['Custom'],
                                                                       'Memo' => $result['PaymentItemInfo']['Memo'],
                                                                       'SalesTax' => $result['PaymentItemInfo']['SalesTax'],
                                                                       'PaymentItem' => array('Name' => $result['PaymentItemInfo']['PaymentItem']['Name'],
                                                                                              'Number' => $result['PaymentItemInfo']['PaymentItem']['Number'],
                                                                                              'Quantity' => $result['PaymentItemInfo']['PaymentItem']['Quantity'],
                                                                                              'SalesTax' => $result['PaymentItemInfo']['PaymentItem']['SalesTax']),
                                                                       'Subscription' => array('SubscriptionID' => $result['PaymentItemInfo']['Subscription']['SubscriptionID'],
                                                                                               'Username' => $result['PaymentItemInfo']['Subscription']['Username'],
                                                                                               'Password' => $result['PaymentItemInfo']['Subscription']['Password'],
                                                                                               'Recurrences' => $result['PaymentItemInfo']['Subscription']['Recurrences']),
                                                                       'SubscriptionRecurring' => $result['PaymentItemInfo']['Subscription attr']['recurring'],
                                                                       'SubscriptionReattempt' => $result['PaymentItemInfo']['Subscription attr']['reattempt'],
                                                                       'Auction' => array('BuyerID' => $result['PaymentItemInfo']['Auction']['BuyerID']))));
            } else {
              $data = array('root' => array('Ack' => $info['Ack'],
                                            'Errors' => array('ShortMessage' => $info['Errors']['ShortMessage'],
                                                              'LongMessage' => $info['Errors']['LongMessage'],
                                                              'ErrorCode' => $info['Errors']['ErrorCode'])));
            }

            $osC_XML = new osC_XML($data);

            $Qtransaction = $osC_Database->query('insert into :table_orders_transactions_history (orders_id, transaction_code, transaction_return_value, transaction_return_status, date_added) values (:orders_id, :transaction_code, :transaction_return_value, :transaction_return_status, now())');
            $Qtransaction->bindTable(':table_orders_transactions_history', TABLE_ORDERS_TRANSACTIONS_HISTORY);
            $Qtransaction->bindInt(':orders_id', $id);
            $Qtransaction->bindInt(':transaction_code', 4);
            $Qtransaction->bindValue(':transaction_return_value', $osC_XML->toXML());
            $Qtransaction->bindInt(':transaction_return_status', ($info['Ack'] == 'Success' ? 1 : 0));
            $Qtransaction->execute();
          }
        }
      }
    }
  }
?>
