--- drupal-6.13/sites/all/modules/uc_ogone/uc_ogone_payment.module.org	2009-08-13 21:58:39.000000000 +0200
+++ drupal-6.13/sites/all/modules/uc_ogone/uc_ogone_payment.module	2009-09-29 12:30:04.000000000 +0200
@@ -1,4 +1,5 @@
 <?php
+// $Id$
 
 /**
  * @file
@@ -11,7 +12,9 @@
  *
  */
 
-
+/*******************************************************************************
+ * Hook implementations
+ ******************************************************************************/
 
 /**
  * Implementation of hook_payment_method().
@@ -32,85 +35,101 @@
 }
 
 /**
+ * Implementation of hook_form_alter().
+ */
+function uc_ogone_payment_form_alter(&$form, &$form_state, $form_id) {
+  if ($form_id == 'uc_cart_checkout_review_form' && ($order_id = intval($_SESSION['cart_order'])) > 0) {
+    $order = uc_order_load($order_id);
+
+    if ($order->payment_method == 'ogone_payment') {
+      drupal_add_css(drupal_get_path('module', 'uc_2checkout') .'/uc_2checkout.css');
+      unset($form['submit']);
+      $form['#prefix'] = '<table id="uc-ogone-payment-review-table"><tr><td>';
+      $form['#suffix'] = '</td><td width="100%">'. drupal_get_form('uc_ogone_payment_form', $order) .'</td></tr></table>';
+    }
+  }
+}
+
+/**
  * Implementation of hook_menu().
  */
 function uc_ogone_payment_menu() {
   $items = array();
 
-    $items['cart/checkout/ogone_redirect'] = array(
-      'title' => 'Secure Payment Page',
-      'page callback' => 'uc_ogone_redirect_form',
-      'access arguments' => array('access content'),
-      'type' => MENU_CALLBACK,
-    );
-
-    $items['cart/ogone_return_ok'] = array(
-      'title' => 'Ogone Payment return status',
-      'page callback' => 'uc_ogone_return_ok',
-      'access arguments' => array('access content'),
-      'type' => MENU_CALLBACK,
-    );
-
-    $items['cart/ogone_ok'] = array(
-      'title' => 'Ogone Payment OK',
-      'page callback' => 'uc_ogone_ok',
-      'access arguments' => array('access content'),
-      'type' => MENU_CALLBACK,
-    );
-
-    $items['cart/ogone_false'] = array(
-      'title' => 'Ogone Payment Error',
-      'page callback' => 'uc_ogone_false',
-      'access arguments' => array('access content'),
-      'type' => MENU_CALLBACK,
-    );
-
-    $items['cart/checkout/ogone_cancel'] = array(
-      'title' => 'Ogone Payment cancel',
-      'page callback' => 'uc_ogone_return_cancel',
-      'access arguments' => array('access content'),
-      'type' => MENU_CALLBACK,
-    );
-
-    $items['ogone_template_call'] = array(
-      'title' => 'Ogone Secure Payment',
-      'page callback' => 'uc_ogone_template',
-      'access arguments' => array('access content'),
-      'type' => MENU_CALLBACK,
-    );
+  // The ogone_callback is is the general direct feedback url for Ogone 
+  $items['cart/ogone_callback'] = array(
+    'title' => 'Ogone Payment return status',
+    'page callback' => 'uc_ogone_payment_callback',
+    'access callback' => TRUE,
+    'type' => MENU_CALLBACK,
+  );
+
+  // The following callback menus are user redirects which don't update any order information
+  // They are only used by Ogone when the ogone_callback timed out
+  $items['cart/ogone_payment_accepted/%'] = array(
+    'title' => 'Ogone Payment Accepted',
+    'page callback' => 'uc_ogone_payment_accepted',
+    'page arguments' => array(2),
+    'access arguments' => array('access content'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['cart/ogone_payment_exception/%'] = array(
+    'title' => 'Ogone Payment Exception',
+    'page callback' => 'uc_ogone_payment_exception',
+    'page arguments' => array(2),
+    'access arguments' => array('access content'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['cart/ogone_payment_declined/%'] = array(
+    'title' => 'Ogone Payment Declined',
+    'page callback' => 'uc_ogone_payment_declined',
+    'page arguments' => array(2),
+    'access arguments' => array('access content'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['cart/ogone_payment_canceled/%'] = array(
+    'title' => 'Ogone Payment Cancel',
+    'page callback' => 'uc_ogone_payment_canceled',
+    'page arguments' => array(2),
+    'access arguments' => array('access content'),
+    'type' => MENU_CALLBACK,
+  );
+
+  // This callback returns a template to be used by ogone when showing the payment form
+  $items['cart/ogone_payment_template'] = array(
+    'title' => 'Ogone Secure Payment',
+    'page callback' => 'uc_ogone_payment_template',
+    'access arguments' => array('access content'),
+    'type' => MENU_CALLBACK,
+  );
 
   return $items;
 }
 
+/**
+ * Implementation of hook_cron
+ */ 
+function uc_ogone_payment_cron() {
+  //TODO: Remove orphaned or expired records from {uc_payment_ogone}
+}
 
 /**
  * Implementation of hook_order().
  */
 function uc_ogone_payment_order($op, &$arg1, $arg2) {
+  global $user;
+  //watchdog('ogone_order', '%op called for order %order_id', array('%op' => $op, '%order_id' => $arg1->order_id));
   switch ($op) {
-    case 'submit': //This is the place!
-        //Called at submit [Submit order]
-        if ($arg1->payment_method == 'ogone_payment') {
-          uc_ogone_call($arg1, $arg2);
-          exit;
-        }
-      break;
-
-      case 'load':
-        //echo 'load';
-        //Called at openen Review order na  submit 'review order'
-      break;
-
     case 'save':
-        //echo 'save';
-        //Called at submit [review order]
-      if ($arg1->payment_method == 'ogone_payment') {
-        //Nothing??
-      }
+      // Nothing to be done here
+      break;
+    case 'update':
+      // If the status is updated, maybe it should be reported to Ogone with direct link
+      // but first check if the update was not made by Ogone
+      // for example: authorized -> data capture  
       break;
-
     case 'delete':
-      //db_query("DELETE FROM {uc_payment_credit} WHERE order_id = %d", $arg1);
+      db_query("DELETE FROM {uc_payment_ogone} WHERE order_id = %d", $arg1->order_id);
       break;
   }
 }
@@ -123,171 +142,137 @@
  * Callback from hook payment_method
  */
 function uc_payment_method_ogone($op, $arg1) {
+  //watchdog('ogone_payment', '%op called for order %order_id', array('%op' => $op, '%order_id' => $arg1->order_id));
   switch($op) {
-    case 'order-view':
-    case 'customer-view':
-      $result = db_query("SELECT description FROM {uc_payment_ogone} WHERE "
-                        ."order_id = %d", $arg1->order_id);
-      if ($row = db_fetch_object($result)) {
-        $output = t('Type:') .' '. $row->description;
-      }
-      else {
-        $output = t('Type:') .' '. t('Unknown');
-      }
-      return $output;
-
-    case 'order-details':
-      $details = drupal_get_form('uc_ogone_payment_method_form', $arg1);
-      return uc_strip_form($details);
-
-    case 'edit-process':
-      $changes['payment_details']['pm_ogone_description'] = check_plain($_POST['pm_ogone_description']);
-      return $changes;
-
     case 'settings':
-        return(uc_ogone_payment_settings_form());
-        break;
-    case 'order-load':
-      $result = db_query("SELECT description FROM {uc_payment_ogone} WHERE "
-                        ."order_id = %d", $arg1->order_id);
-      if ($row = db_fetch_object($result)) {
-        $arg1->payment_details['description'] = $row->description;
-      }
-      break;
-
-    case 'order-save':
-      db_query("DELETE FROM {uc_payment_ogone} WHERE order_id = %d", $arg1->order_id);
-      if (strlen($arg1->payment_details['pm_ogone_description']) > 0) {
-        db_query("INSERT INTO {uc_payment_ogone} (order_id, description) VALUES "
-                ."(%d, '%s')", $arg1->order_id,
-                $arg1->payment_details['pm_ogone_description']);
-      }
+      return(uc_ogone_payment_settings_form());
       break;
   }
 }
 
-function uc_ogone_payment_method_form($order) {
-  $form['pm_ogone_description'] = array(
-    '#type' => 'textfield',
-    '#size' => 32,
-    '#maxlength' => 64,
-    '#default_value' => $order->payment_details['description'],
-  );
-
-  return $form;
-}
-
-
-function theme_uc_ogone_payment_method_form($form) {
-  $output = '<table class="order-edit-table"><tr><td class="oet-label">jdkl'
-          . t('Description:') .'</td><td>'
-          . drupal_render($form['pm_ogone_description'])
-          .'</td></tr></table>';
-  return $output;
-}
-
-
 /**
  * Callback for payment gateway settings.
  */
 function uc_ogone_payment_settings_form() {
-  $form['ogone_url'] = array(
+  $form['configuration'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Configuration'),
+    '#collapsible' => FALSE,
+    '#collapsed' => FALSE,
+  );
+  $form['configuration']['uc_ogone_payment_url'] = array(
     '#type' => 'textfield',
     '#title' => t('Ogone URL'),
-    '#default_value' => variable_get('ogone_url', 'https://secure.ogone.com/ncol/test/orderstandard.asp'),
+    '#default_value' => variable_get('uc_ogone_payment_url', 'https://secure.ogone.com/ncol/test/orderstandard.asp'),
     '#description' => t('The URL for the Ogone PSP service. Use https://secure.ogone.com/ncol/test/orderstandard.asp for testpurposes, https://secure.ogone.com/ncol/prod/orderstandard.asp for production use.'),
   );
-  $form['ogone_catalog_url'] = array(
+  $form['configuration']['uc_ogone_payment_catalog_url'] = array(
     '#type' => 'textfield',
     '#title' => t('Merchant catalog URL'),
-    '#default_value' => variable_get('ogone_catalog_url', 'catalog'),
+    '#default_value' => variable_get('uc_ogone_payment_catalog_url', 'catalog'),
     '#description' => t('The relative path to your catalog page. For instance if your catalog page is www.yourdomain.com/catalog enter catalog'),
   );
-  $form['ogone_pspid_id'] = array(
+  $form['configuration']['uc_ogone_payment_pspid_id'] = array(
     '#type' => 'textfield',
     '#title' => t('pspid'),
-    '#default_value' => variable_get('ogone_pspid_id', ''),
+    '#default_value' => variable_get('uc_ogone_payment_pspid_id', ''),
     '#description' => t('The login username for the Ogone PSP service.'),
   );
-  $form['ogone_currency'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Currency'),
-    '#default_value' => variable_get('ogone_currency', 'EUR'),
-    '#description' => t('Use "EUR", "USD" or "GBP" for currency. See Ogone documentation for details.'),
-  );
-  $form['ogone_language'] = array(
+  $form['configuration']['uc_ogone_payment_language'] = array(
     '#type' => 'textfield',
     '#title' => t('Language'),
-    '#default_value' => variable_get('ogone_language', 'en_US'),
+    '#default_value' => variable_get('uc_ogone_payment_language', 'en_US'),
     '#description' => t('Use "en_US" notation for language. See Ogone documentation for details.'),
   );
-  //Layout
-  $form['ogone_layout_title'] = array(
+  $form['configuration']['uc_ogone_payment_checkout_button'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Submit button'),
+    '#default_value' => variable_get('uc_ogone_payment_checkout_button', 'Submit Order'),
+    '#description' => t('The submit button text to show on the review order page before submitting to Ogone.'),
+  );
+  $form['security'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Security'),
+    '#collapsible' => FALSE,
+    '#collapsed' => FALSE,
+  );
+  $form['security']['uc_ogone_payment_sha1_signature_pre'] = array(
+    '#type' => 'textfield',
+    '#title' => t('SHA-1 Signature pre'),
+    '#default_value' => variable_get('uc_ogone_payment_sha1_signature_pre', ''),
+    '#description' => t('SHA-1 signature for pre payment verification.'),
+  );
+  $form['security']['uc_ogone_payment_sha1_signature_post'] = array(
+    '#type' => 'textfield',
+    '#title' => t('SHA-1 Signature post'),
+    '#default_value' => variable_get('uc_ogone_payment_sha1_signature_post', ''),
+    '#description' => t('SHA-1 signature for post payment verification.'),
+  );
+  $form['layout'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Layout'),
+    '#collapsible' => FALSE,
+    '#collapsed' => FALSE,
+  );
+  $form['layout']['uc_ogone_payment_layout_title'] = array(
     '#type' => 'textfield',
     '#title' => t('Title'),
-    '#default_value' => variable_get('ogone_layout_title', 'Secure Checkout'),
+    '#default_value' => variable_get('uc_ogone_payment_layout_title', 'Secure Checkout'),
     '#description' => t('Shown in payment page.'),
   );
-  $form['ogone_layout_bgcolor'] = array(
+  $form['layout']['uc_ogone_payment_layout_bgcolor'] = array(
     '#type' => 'textfield',
     '#title' => t('BG Color'),
-    '#default_value' => variable_get('ogone_layout_bgcolor', ''),
+    '#default_value' => variable_get('uc_ogone_payment_layout_bgcolor', ''),
     '#description' => t('Background color payment page.(empty for default)'),
   );
-  $form['ogone_layout_txtcolor'] = array(
+  $form['layout']['uc_ogone_payment_layout_txtcolor'] = array(
     '#type' => 'textfield',
     '#title' => t('text Color'),
-    '#default_value' => variable_get('ogone_layout_txtcolor', ''),
+    '#default_value' => variable_get('uc_ogone_payment_layout_txtcolor', ''),
     '#description' => t('Text color payment page.(empty for default)'),
   );
-  $form['ogone_layout_tblbgcolor'] = array(
+  $form['layout']['uc_ogone_payment_layout_tblbgcolor'] = array(
     '#type' => 'textfield',
     '#title' => t('Table BG Color'),
-    '#default_value' => variable_get('ogone_layout_tblbgcolor', ''),
+    '#default_value' => variable_get('uc_ogone_payment_layout_tblbgcolor', ''),
     '#description' => t('Background color tables in payment page.(empty for default)'),
   );
-  $form['ogone_layout_tbltxtcolor'] = array(
+  $form['layout']['uc_ogone_payment_layout_tbltxtcolor'] = array(
     '#type' => 'textfield',
     '#title' => t('Table Text Color'),
-    '#default_value' => variable_get('ogone_layout_tbltxtcolor', ''),
+    '#default_value' => variable_get('uc_ogone_payment_layout_tbltxtcolor', ''),
     '#description' => t('Text color tables in payment page.(empty for default)'),
   );
-  $form['ogone_layout_buttonbgcolor'] = array(
+  $form['layout']['uc_ogone_payment_layout_buttonbgcolor'] = array(
     '#type' => 'textfield',
     '#title' => t('Button Color'),
-    '#default_value' => variable_get('ogone_layout_buttonbgcolor', ''),
+    '#default_value' => variable_get('uc_ogone_payment_layout_buttonbgcolor', ''),
     '#description' => t('Button color in payment page.(empty for default)'),
   );
-  $form['ogone_layout_buttontxtcolor'] = array(
+  $form['layout']['uc_ogone_payment_layout_buttontxtcolor'] = array(
     '#type' => 'textfield',
     '#title' => t('Button Text Color'),
-    '#default_value' => variable_get('ogone_layout_buttontxtcolor', ''),
+    '#default_value' => variable_get('uc_ogone_payment_layout_buttontxtcolor', ''),
     '#description' => t('Button text color in payment page.(empty for default)'),
   );
-  $form['ogone_layout_logo'] = array(
+  $form['layout']['uc_ogone_payment_layout_logo'] = array(
     '#type' => 'textfield',
     '#title' => t('Logo Path'),
-    '#default_value' => variable_get('ogone_layout_logo', ''),
+    '#default_value' => variable_get('uc_ogone_payment_layout_logo', ''),
     '#description' => t('Logo to use on payment page.(empty for none)'),
   );
-  $form['ogone_layout_fonttype'] = array(
+  $form['layout']['uc_ogone_payment_layout_fonttype'] = array(
     '#type' => 'textfield',
     '#title' => t('Fonttype'),
-    '#default_value' => variable_get('ogone_layout_fonttype', ''),
-  );
-  $form['ogone_sha1_signature_pre'] = array(
-    '#type' => 'textfield',
-    '#title' => t('SHA-1 Signature pre'),
-    '#default_value' => variable_get('ogone_sha1_signature_pre', ''),
-    '#description' => t('SHA-1 signature for pre payment verification.'),
+    '#default_value' => variable_get('uc_ogone_payment_layout_fonttype', ''),
   );
-  $form['ogone_sha1_signature_post'] = array(
-    '#type' => 'textfield',
-    '#title' => t('SHA-1 Signature post'),
-    '#default_value' => variable_get('ogone_sha1_signature_post', ''),
-    '#description' => t('SHA-1 signature for post payment verification.'),
+  $form['layout']['uc_ogone_payment_template'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Template'),
+    '#default_value' => variable_get('uc_ogone_payment_template', ''),
+    '#description' => t('Template used by Ogone to display the payment pages. This template will only be used by Ogone if you are entitled to use a template. You can use HTML markup and PHP tags and should use $$$PAYMENT ZONE$$$ where Ogone must place their content.'),
   );
-
   return $form;
 }
 
@@ -291,227 +276,427 @@
   return $form;
 }
 
+/**
+ * Form to build the submission to Ogone.
+ */
+function uc_ogone_payment_form($form_state, $order) {
+  $ogone_url = filter_xss(variable_get('uc_ogone_payment_url', TRUE));
+
+  $pspid = variable_get('uc_ogone_payment_pspid_id', '');
+  $orderid = $order->order_id;
+  $amount = $order->order_total * 100;
+  $currency = variable_get('uc_currency_code', 'EUR');
+  $sha1_suffix = variable_get('uc_ogone_payment_sha1_signature_pre', '');
+  
+  $sha1_signature = sha1($orderid.$amount.$currency.$pspid.$sha1_suffix);
+  
+  $data = array(
+    'PSPID' => $pspid,
+    'orderID' => $orderid,
+    'amount' => $amount,
+    'currency' => $currency,
+    'SHASign' => $sha1_signature,
+    'language' => _uc_ogone_payment_language(),
+    'TITLE' => variable_get('uc_ogone_payment_layout_title', ''),
+    'BGCOLOR' => variable_get('uc_ogone_payment_layout_bgcolor', ''),
+    'TXTCOLOR' => variable_get('uc_ogone_payment_layout_txtcolor', ''),
+    'TBLBGCOLOR' => variable_get('uc_ogone_payment_layout_tblbgcolor', ''),
+    'TBLTXTCOLOR' => variable_get('uc_ogone_payment_layout_tbltxtcolor', ''),
+    'BUTTONBGCOLOR' => variable_get('uc_ogone_payment_layout_buttonbgcolor', ''),
+    'BUTTONTXTCOLOR' => variable_get('uc_ogone_payment_layout_buttontxtcolor', ''),
+    'LOGO' => variable_get('uc_ogone_payment_layout_logo', ''),
+    'FONTTYPE' => variable_get('uc_ogone_payment_layout_fonttype', ''),
+    'TP' => _uc_ogone_payment_url('cart/ogone_payment_template'),
+    'homeurl' => _uc_ogone_payment_url('<front>'),
+    'catalogurl' => _uc_ogone_payment_url(variable_get('uc_ogone_payment_catalog_url', 'catalog')),
+    'accepturl' => _uc_ogone_payment_url('cart/ogone_payment_accepted/' . $orderid),
+    'declineurl' => _uc_ogone_payment_url('cart/ogone_payment_declined/' . $orderid),
+    'exceptionurl' => _uc_ogone_payment_url('cart/ogone_payment_exception/' . $orderid),
+    'cancelurl' => _uc_ogone_payment_url('cart/ogone_payment_canceled/' . $orderid),
+    'COM' => t('Online order !order_id', array('!order_id' => $order->order_id)), 
+    'CN' => $order->billing_first_name . ' ' . $order->billing_last_name,
+    'EMAIL' => $order->primary_email,
+    'owneraddress' => $order->billing_street1 . ' ' . $order->billing_street2,
+    'ownerZIP' => $order->billing_postal_code,
+    'ownertown' => $order->billing_city,
+    'ownercty' => _uc_ogone_payment_country_code($order->billing_country),
+    'ownertelno' => $order->billing_phone,
+  );
 
-function uc_ogone_call(&$arg1, $arg2) {
+  $form['#action'] = variable_get('uc_ogone_payment_url', 'https://secure.ogone.com/ncol/test/orderstandard.asp');
 
-  /*global $user; //Todo: find a way to detect user language
-  if (!($user->language)) {
-    $language = 'en_US';
+  foreach ($data as $name => $value) {
+    $form[$name] = array('#type' => 'hidden', '#value' => $value);
   }
 
-  $currency_sign = substr(htmlspecialchars(uc_currency_format('0')),0,3);
-  $currency_sign = htmlspecialchars($currency_sign);
-
-  switch($currency_sign) { //This needs review! Doesn't work properly
-    case '$':
-      $currency = 'USD';
-      break;
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t(variable_get('uc_ogone_payment_checkout_button', 'Submit Order')),
+  );
 
-    case '�':
-      $currency = 'GBP';
-      break;
+  return $form;
+}
 
-    //case "�":
-    default:
-      $currency = 'EUR';
-      break;
-  }*/ //Disabled KK 180608, autodetection needs work
+function uc_ogone_payment_callback() {
+  global $user;
+  
+  $sha1_suffix = variable_get('uc_ogone_payment_sha1_signature_post', '');
+  
+  $sha1_string = $_POST['orderID'].$_POST['currency'].$_POST['amount'].$_POST['PM'].$_POST['ACCEPTANCE'].
+      $_POST['STATUS'].$_POST['CARDNO'].$_POST['PAYID'].$_POST['NCERROR'].$_POST['BRAND'].$sha1_suffix;
+  $sha1_key=strtoupper(sha1($sha1_string));
+  
+  $order_id = $_POST['orderID'];
+  $status_id = $_POST['STATUS'];
+  $amount = $_POST['amount'];
+  
+  $order = db_fetch_object(db_query("SELECT order_id, uid, order_status, data FROM {uc_orders} WHERE order_id = %d", $order_id));
+  
+  // Only proceed if the provided order id exists
+  if (!empty($order)) {
+    if (strtoupper($_POST['SHASIGN']) == $sha1_key) {
+      $sha1_match = 1;
+      $complete_checkout = FALSE;
+      $enter_payment = FALSE;
+      $message_type = NULL;
+      $new_status = NULL;
+      // First check the error code
+      switch ($_POST['NCERROR']) {
+        case '50001074':
+          $new_status = 'ogone_auth_expired';
+          $message_type = 'admin';
+          $message = 'Authorization expired';
+          break;
+      }
+      if (!$new_status) {
+        switch ($status_id) {
+          case 0:
+            $new_status = 'ogone_invalid';
+            $message_type = 'order';
+            $message = 'Invalid Ogone payment';
+            break;
+          case 1:
+            $new_status = uc_order_state_default('canceled');
+            $message_type = 'order';
+            $message = 'Payment canceled by client';
+            break;
+          case 2:
+            $new_status = 'ogone_declined';
+            $message_type = 'order';
+            $message = 'Payment declined by acquirer';
+            break;
+          case 4:
+            $complete_checkout = TRUE;
+            $new_status = 'ogone_stored';
+            $message_type = 'order';
+            $message = 'Payment pending at Ogone with reference ' . $_POST['PAYID'] . '/' . $_POST['PAYIDSUB'];
+            break;
+          case 41:
+            $message_type = 'admin';
+            $message = 'Waiting for client payment';
+            break;
+          case 5:
+            $complete_checkout = TRUE;
+            $new_status = 'ogone_authorized';
+            $message_type = 'order';
+            $message = 'Payment authorized by acquirer with reference ' . $_POST['PAYID'] . '/' . $_POST['PAYIDSUB'];
+            break;
+          case 51:
+            $message_type = 'admin';
+            $message = 'Waiting for authorization';
+            break;
+          case 52:
+            $new_status = 'ogone_uncertain_auth';
+            $message_type = 'order';
+            $message = 'Authorization not known';
+            break;
+          case 55:
+            $message_type = 'admin';
+            $message = 'Stand-by';
+            break;
+          case 59:
+            $message_type = 'admin';
+            $message = 'Authorized to capture manually';
+            break;
+          case 6:
+            $new_status = 'ogone_canceled';
+            $message_type = 'order';
+            $message = 'The payment was authorized, but canceled afterwards';
+            break;
+          case 61:
+            $message_type = 'admin';
+            $message = 'Waiting for authorization to delete the payment';
+            break;
+          case 62:
+            $message_type = 'admin';
+            $message = 'Authorization for deletion uncertain';
+            break;
+          case 63:
+            $message_type = 'admin';
+            $message = 'Authorization for deletion refused';
+            break;
+          case 64:
+            $message_type = 'admin';
+            $message = 'Authorization and canceled';
+            break;
+          case 7:
+            $new_status = 'ogone_deleted';
+            $message_type = 'order';
+            $message = 'Payment deleted';
+            break;
+          case 71:
+            $message_type = 'admin';
+            $message = 'Payment pending for deletion';
+            break;
+          case 72:
+            $message_type = 'admin';
+            $message = 'Payment deletion uncertain';
+            break;
+          case 73:
+            $message_type = 'admin';
+            $message = 'Payment deletion refused';
+            break;
+          case 74:
+            $message_type = 'admin';
+            $message = 'Payment deleted';
+            break;
+          case 75:
+            $message_type = 'admin';
+            $message = 'Deletion processed by merchant';
+            break;
+          case 8:
+            $new_status = 'ogone_refund';
+            $message_type = 'order';
+            $message = 'Refunded payment';
+            break;
+          case 81:
+            $message_type = 'admin';
+            $message = 'Refund pending';
+            break;
+          case 82:
+            $message_type = 'admin';
+            $message = 'Refund uncertain';
+            break;
+          case 83:
+            $message_type = 'admin';
+            $message = 'Refund refused';
+            break;
+          case 84:
+            $message_type = 'admin';
+            $message = 'Refund declined by acquirer';
+            break;
+          case 85:
+            $message_type = 'admin';
+            $message = 'Refund processed by merchant';
+            break;
+          case 9:
+            $enter_payment = TRUE;
+            $complete_checkout = TRUE;
+            $new_status = uc_order_state_default('payment_received');
+            $message_type = 'order';
+            $message = 'Payment received with reference ' . $_POST['PAYID'] . '/' . $_POST['PAYIDSUB'];
+            break;
+          case 91:
+            $new_status = 'processing';
+            $message_type = 'admin';
+            $message = 'Payment processing';
+            break;
+          case 92:
+            $new_status = (uc_order_status_data($order->order_status, 'state') == 'payment_received')? 'ogone_uncertain_cap' : 'ogone_uncertain_pay';
+            $message_type = 'order';
+            $message = 'Payment uncertain';
+            break;
+          case 93:
+            $message_type = 'admin';
+            $message = 'Payment refused';
+            break;
+          case 94:
+            $message_type = 'admin';
+            $message = 'Payment declined by acquirer';
+            break;
+          case 95:
+            $message_type = 'admin';
+            $message = 'Payment processed by merchant';
+            break;
+          case 99:
+            $message_type = 'admin';
+            $message = 'Payment being processed';
+            break;
+        }
+      }
+      
+      if ($new_status &&  $new_status != $order->order_status) {
+        if (uc_order_update_status($order_id, $new_status)) {
+          $order->order_status = $new_status;
+        }
+      }
+      
+      if ($complete_checkout) {
+        // The actions that need to be done here are executed when the user is redirected from Ogone back to the shop
+        // This will empty the cart and create a user if the order was completed by an anonymous user
+      }
+      
+      if ($enter_payment) {
+        uc_payment_enter($order_id, 'ogone_payment', $amount, $user->uid, array('payment_id' => $_POST['PAYID']), $message);
+      }
+      
+      if ($_POST['NCERRORPLUS']) {
+        uc_order_comment_save($order_id, $user->uid, $_POST['NCERRORPLUS'], 'order', $new_status);
+      }
+      else {
+        if ($message_type) {
+          uc_order_comment_save($order_id, $user->uid, $message, $message_type, $new_status);
+        }
+        else {
+          watchdog(
+            'ogone payment',
+            'Incoming callback with invalid status %status_id for order %order_id', 
+            array('%status_id' => $status_id, '%order_id' => $order_id),
+            WATCHDOG_ERROR
+          );
+        }
+      }
+      
+    }
+    else {
+      $sha1_match = 0;
+      watchdog(
+        'ogone payment',
+        'Callback from %remote_ip for order <%order_id> with invalid sha1 signature', 
+        array('%remote_ip' => $_SERVER["REMOTE_ADDR"], '%order_id' => $order_id),
+        WATCHDOG_WARNING
+      );
+    }
+  
+    db_query(
+      "INSERT INTO {uc_payment_ogone}(order_id, timestamp, payment_id, payment_date, payment_acceptance, payment_method, card_no, card_brand, error_code, error_message, payment_status, sha1_match)
+       VALUES(%d,'%s',%d,'%s','%s','%s','%s','%s','%s','%s',%d,%d)",
+      $order_id,
+      date('c'),
+      $_POST['PAYID'],
+      $_POST['TRXDATE'],
+      $_POST['ACCEPTANCE'],
+      $_POST['PM'],
+      $_POST['CARDNO'],
+      $_POST['BRAND'],
+      $_POST['NCERROR'],
+      $_POST['NCERRORPLUS'],
+      $_POST['STATUS'],
+      $sha1_match
+    );
+  }
+  else {
+    watchdog(
+      'ogone payment',
+      'Callback from %remote_ip for non existing order <%order_id>', 
+      array('%remote_ip' => $_SERVER["REMOTE_ADDR"], '%order_id' => $order_id),
+      WATCHDOG_WARNING
+    );
+  }
+  
+  print "OK";
+}
 
-  //$ogone_url = 'https://secure.ogone.com/ncol/prod/orderstandard.asp';
-  $ogone_url = filter_xss(variable_get('ogone_url', TRUE));
+function uc_ogone_payment_accepted($order_id) {
+  //global $user;
+  //drupal_set_message(t('Your payment has been accepted by Ogone.'), 'status');
+  //drupal_goto('user/' . $user->uid . '/order/' . $order_id);
+  
+  // Use the default checkout complete procedure
+  $_SESSION['cart_order'] = $order_id;
+  $_SESSION['do_complete'] = TRUE;
+  drupal_goto('cart/checkout/complete');
+}
 
-  //Set base url
-  if (function_exists('i18n_get_lang')){
-    $url_base = current(parse_url($_SERVER['HTTP_REFERER'])).'://'.$_SERVER['HTTP_HOST'].'/'.i18n_get_lang();
-  }
-  else{
-    current(parse_url($_SERVER['HTTP_REFERER'])).'://'.$_SERVER['HTTP_HOST'];
-  }
-
-  $pspid = filter_xss(variable_get('ogone_pspid_id', TRUE));
-  $orderid = $arg1->order_id;
-  $amount = $arg1->order_total * 100;   //amount *100
-
-  $currency = filter_xss(variable_get('ogone_currency', TRUE));
-  $language = filter_xss(variable_get('ogone_language', 'en_US'));
-
-  $layout_title = filter_xss(variable_get('ogone_layout_title', TRUE));
-  $layout_bgcolor = filter_xss(variable_get('ogone_layout_bgcolor', TRUE));
-  $layout_txtcolor = filter_xss(variable_get('ogone_layout_txtcolor', TRUE));
-  $layout_tblbgcolor = filter_xss(variable_get('ogone_layout_tblbgcolor', TRUE));
-  $layout_tbltxtcolor = filter_xss(variable_get('ogone_layout_tbltxtcolor', TRUE));
-  $layout_buttonbgcolor = filter_xss(variable_get('ogone_layout_buttonbgcolor', TRUE));
-  $layout_buttontxtcolor = filter_xss(variable_get('ogone_layout_buttontxtcolor', TRUE));
-  $layout_logo = filter_xss(variable_get('ogone_layout_logo', TRUE));
-  $layout_fonttype = filter_xss(variable_get('ogone_layout_fonttype', TRUE));
-  $layout_template = $url_base.'/ogone_template_call';
-
-  //$redirect_accepturl = $url_base.'/cart/ogone_ok';
-  $redirect_declineurl = $url_base.'/cart/checkout';
-  $redirect_exceptionurl = $url_base.'/cart/checkout';
-  $redirect_cancelurl = $url_base.'/cart/checkout/ogone_cancel';
-
-  $order_description = 'Expert Delivery order: '.$arg1->order_id;
-  $customer_name = $arg1->delivery_first_name.' '.$arg1->delivery_last_name;
-  $customer_name = substr($customer_name, 0, 35); //Make sure this is < 35 char, else Ogone freaks out
-  $customer_email = $arg1->primary_email;
-  $brand = '';
-  $pm = '';
-  $customer_zip = $arg1->delivery_postal_code;
-  $customer_address = $arg1->delivery_street1.' '.$arg1->delivery_street2.' '.$arg1->delivery_street2.' '.$arg1->delivery_city;
-
-  $redirect_message1 = t('One moment please, you will automaticaly be redirected to the payment gateway...');
-  $redirect_message2 = t('Popupblockers might stop the paymentpage from opening, please click the button to open the payment page if it does not open automaticaly.');
-  $ogone_button_text = t('Click here to go to payment page manualy');
-
-  $orderid = $arg1->order_id;
-  $amount = $arg1->order_total * 100;   //amount *100
-
-  $sha_suffix = variable_get('ogone_sha1_signature_pre', TRUE);
-
-  //Make SHA1 string for pre payment verification
-  $sha1_signature = sha1($orderid.$amount.$currency.$pspid.$sha_suffix);
-
-  $_SESSION['ogone_order_id'] = $arg1->order_id;
-  $_SESSION['ogone_form']='
-  <div class="ogone_redirect_message_top">
-  '.$redirect_message1.'
-  </div>
-  <div class="ogone_redirect_container">
-  <div align="center" class="ogone_redirect_form">
-  <FORM METHOD="post" ACTION="'.$ogone_url.'" id="ogone_form" name="ogone_form"  '. /*target="ogone_popup" */ 'onsubmit="">
-  <INPUT type="hidden" NAME="PSPID" value="'.$pspid.'" />
-  <INPUT type="hidden" NAME="orderID" VALUE="'.$orderid.'" />
-  <INPUT type="hidden" NAME="amount" VALUE="'.$amount.'" />
-  <INPUT type="hidden" NAME="currency" VALUE="'.$currency.'" />
-  <INPUT type="hidden" NAME="language" VALUE="'.$language.'" />
-  <!-- sha1_signature -->
-  <INPUT type="hidden" NAME="SHASign" VALUE="'.$sha1_signature.'" />
-  <!-- lay out information -->
-  <INPUT type="hidden" NAME="TITLE" VALUE="'.$layout_title.'" />
-  <INPUT type="hidden" NAME="BGCOLOR" VALUE="'.$layout_bgcolor.'" />
-  <INPUT type="hidden" NAME="TXTCOLOR" VALUE="'.$layout_tbltxtcolor.'" />
-  <INPUT type="hidden" NAME="TBLBGCOLOR" VALUE="'.$layout_tbltxtcolor.'" />
-  <INPUT type="hidden" NAME="TBLTXTCOLOR" VALUE="'.$layout_tbltxtcolor.'" />
-  <INPUT type="hidden" NAME="BUTTONBGCOLOR" VALUE="'.$layout_buttonbgcolor.'" />
-  <INPUT type="hidden" NAME="BUTTONTXTCOLOR" VALUE="'.$layout_buttontxtcolor.'" />
-  <INPUT type="hidden" NAME="LOGO" VALUE="'.$layout_logo.'" />
-  <INPUT type="hidden" NAME="FONTTYPE" VALUE="'.$layout_fonttype.'" />
-  <INPUT type="hidden" NAME="HOMEURL" VALUE="'.$url_base.'" />
-  <INPUT type="hidden" NAME="CATALOGURL" VALUE="'.$url_base.'/'.$catalog_url.'" />
-  <!-- or dynamic template page -->
-  <INPUT type="hidden" NAME="TP" VALUE="'.$layout_template.'" />
-  <!-- post-payment redirection -->
-  <INPUT type="hidden" NAME="ACCEPTURL" VALUE="'./*$redirect_accepturl //For security reasons this URL is set in the Ogone backend*/'" />
-  <INPUT type="hidden" NAME="declineurl" VALUE="'.$redirect_declineurl.'" />
-  <INPUT type="hidden" NAME="exceptionurl" VALUE="'.$redirect_exceptionurl.'" />
-  <INPUT type="hidden" NAME="cancelurl" VALUE="'.$redirect_cancelurl.'" />
-  <!-- miscellanous -->
-  <INPUT type="hidden" NAME="COM" VALUE="'.$order_description.'" />
-  <INPUT type="hidden" NAME="CN" VALUE="'.$customer_name.'" />
-  <INPUT type="hidden" name="EMAIL" value="'.$customer_email.'" />
-  <INPUT type="hidden" NAME="PM" VALUE="" />
-  <INPUT type="hidden" NAME="BRAND" VALUE="" />
-  <INPUT type="hidden" NAME="ownerZIP" VALUE="'.$customer_zip.'" />
-  <INPUT type="hidden" NAME="owneraddress" VALUE="'.$customer_address.'" />
-  <input type="submit" value="'.$ogone_button_text.'" id="submit2" name="submit2" />
-  </form>
-  <script language="JavaScript">
-  document.ogone_form.submit();
-  </script>
-  </div>
-  <div class="ogone_redirect_message_bottom">
-  '.$redirect_message2.'
-  </div>
-  </div>'
-  ;
-  drupal_goto('cart/checkout/ogone_redirect');
-}
-
-
-function uc_ogone_ok() {
-  $result = db_query("SELECT sha1_test_succes FROM {uc_payment_ogone} WHERE order_id = %d", $_SESSION['ogone_order_id']);
-  $ogone_order = db_fetch_object($result);
-  //Debug
-  //print_r($ogone_order);
-  //exit;
-  if ($ogone_order->sha1_test_succes == 'OK'){
-    uc_order_update_status($_SESSION['ogone_order_id'], uc_order_state_default('payment_received'));
-
-    //Debug
-    //drupal_set_message('cartid:'.uc_cart_get_id().' ogone order id:'.$_SESSION['ogone_order_id']);
-
-    // Ensure the cart we're looking at is the one that payment was attempted for.
-    $_SESSION['cart_order'] = $_SESSION['ogone_order_id'];
-    unset($_SESSION['ogone_order_id']);
-
-    // This lets us know it's a legitimate access of the complete page.
-    $_SESSION['do_complete'] = TRUE;
-
-    drupal_goto('cart/checkout/complete');
-  }else{
-    drupal_goto('cart/ogone_false');
-  }
-}
-
-function uc_ogone_false() {
-  drupal_set_message(t('Ogone returned an error for your payment. Your order is not completed. Please try again or contact us.'), 'ERROR');
-  watchdog('uc_ogone_payment', 'Ogone returned an error for this payment.', WATCHDOG_ERROR);
+function uc_ogone_payment_canceled($order_id) {
+  drupal_set_message(t('Your order could not be completed because you canceled your payment. Please try again or contact us.'), 'warning');
   drupal_goto('cart/checkout');
 }
 
-function uc_ogone_template() {
-  $template = '<html><head><title>'.filter_xss(variable_get('ogone_layout_title', TRUE)).'</title></head><body style="background-color: #dfdfdf;">';
-  $template .= '<div align="right"><img src="https://www.qspeed.nl/httpsimg/lock.gif" alt="Secure Payment by Qrios" /></div>';
-  $template .= '<div align="center"><div align="left" style="width: 550px; padding: 10px; border:2px solid #666; background-color: #fff;">';
-  $template .= '<h1>'.filter_xss(variable_get('ogone_layout_title', TRUE)).'</h1>';
-  $template .= '$$$PAYMENT ZONE$$$';
-  $template .= '</div></div></body></html>';
-  print $template;
-  exit;
+function uc_ogone_payment_declined($order_id) {
+  drupal_set_message(t('Your order could not be completed because your payment has been declined by your acquirer. Please try again or contact us.'), 'error');
+  drupal_goto('cart/checkout');
 }
 
-function uc_ogone_return_cancel() {
-  drupal_set_message(t('Ogone returned a cancel for your payment. Your order is not completed. Please try again or contact us.'), 'ERROR');
+function uc_ogone_payment_exception($order_id) {
+  $message = t('Your order could not be completed because Ogone returned an exception. Please try again or contact the service desk.'); 
+  $order = db_fetch_object(db_query("SELECT order_id, uid, order_status FROM {uc_orders} WHERE order_id = %d", $order_id));
+  if (uc_order_status_data($order->order_status, 'id') == 'ogone_uncertain_pay') {
+    $message = t('Your order could not be completed because the transaction with the acquirer could not be finished. It is uncertain whether your payment has been succesfully registered or not. Please contact the service desk for more information before trying again!'); 
+  }
+  if (uc_order_status_data($order->order_status, 'id') == 'ogone_uncertain_auth') {
+    $message = t('Your order could not be completed because the transaction with the acquirer could not be finished. It is uncertain whether your payment has been succesfully authorized or not. Please contact the service desk for more information before trying again!'); 
+  }
+  drupal_set_message($message, 'error');
   drupal_goto('cart/checkout');
 }
 
-function uc_ogone_redirect_form() {
-  if ($_SESSION['ogone_form'] !== FALSE) {
-    drupal_add_css(drupal_get_path('module', 'uc_ogone_payment') .'/uc_ogone_payment_form.css');
-    $ogone_form = $_SESSION['ogone_form'];
-    $_SESSION['ogone_form'] = FALSE;
-    return($ogone_form );
-  }else{
-    drupal_goto('cart/');
+/*******************************************************************************
+ * Helper functions
+ ******************************************************************************/
+
+/**
+ * Convert the current language code to a Ogone supported language code
+ * 
+ * @return language code for Ogone
+ */
+function _uc_ogone_payment_language($lang = NULL) {
+  global $language;
+  if (!isset($lang)) {
+    $lang = $language->language;
+  }
+  // Languages supported by Ogone
+  $code = array(
+    'en' => 'en_US',
+    'fr' => 'fr_FR',
+    'nl' => 'nl_BE',
+    'it' => 'it_IT',
+    'de' => 'de_DE',
+    'es' => 'es_ES',
+    'no' => 'no_NO',
+    'tr' => 'tr_TR',
+  );
+  if (!($lang = $code[$lang])) {
+    $lang = variable_get('ogone_language', 'en_US');
   }
+  return $lang;
 }
 
+/**
+ * Convert the Ubercart country id to a 2 character ISO country code
+ * 
+ * @param $country_id
+ * @return country code
+ */
+function _uc_ogone_payment_country_code($country_id) {
+  $sql = "SELECT country_iso_code_2 FROM {uc_countries} WHERE country_id = %d";
+  $result = db_query($sql, array($country_id));
+  return db_result($result);  
+}
 
-//This is caled by Ogone itself NOT within the user session!
-function uc_ogone_return_ok() {
-  $secret = variable_get('ogone_sha1_signature_post', TRUE);
-  $sha1_string = $_GET['orderID'].$_GET['currency'].$_GET['amount'].$_GET['PM'].$_GET['ACCEPTANCE'].
-  $_GET['STATUS'].$_GET['CARDNO'].$_GET['PAYID'].$_GET['NCERROR'].$_GET['BRAND'].$secret;
-  $sha1_key=strtoupper(sha1($sha1_string));
-  $sha1_return_key=strtoupper($_GET['SHASIGN']);
-
-  $orderid = $_GET['orderID'];
-  $description = 'description';
-  $pm = $_GET['PM'];
-  $status = $_GET['STATUS'];
-  $sha_test = 'OK';
-
-  //Uncomment for manual SHA comparison for debug purposes
-  //echo $sha1_return_key.'<br>'.$sha1_key;
-  //exit;
-
-  if($sha1_key == $sha1_return_key){
-    db_query("INSERT INTO {uc_payment_ogone} (order_id, description, payment_method, order_status, sha1_test_succes) VALUES('$orderid','$description','$pm','$status','$sha_test')");
-    drupal_goto('cart/ogone_ok');
-    //uc_ogone_ok();
-  }else{
-    drupal_goto('cart/ogone_false');
+/**
+ * Provide the external url for a certain drupal path
+ * 
+ * @param $path
+ * @param $lang
+ * @return url
+ */
+function _uc_ogone_payment_url($path, $lang = NULL) {
+  global $language;
+  
+  if (!isset($lang)) {
+    $lang = $language->language;
+  }
+  if ($lang != language_default('language')) {
+    $path = $lang . '/' . $path;
   }
+  if (function_exists('securepages_url')) {
+    $url = securepages_url($path);
+  }
+  else {
+    $url = url($path);
+  }
+  return $url;
 }
+
 ?>
