From f9fe993b62f7a8422cbb871447b677885eec953d Mon Sep 17 00:00:00 2001
From: Peter <aegir@create.simplistechsolutions.com>
Date: Mon, 27 Sep 2010 13:10:14 -0500
Subject: [PATCH] fixed duplicate emails and new user login for paypal wps

---
 payment/uc_payment/uc_payment.ca.inc  |   16 ++-
 payment/uc_paypal/uc_paypal.pages.inc |    2 +-
 uc_cart/uc_cart.module                |  303 +++++++++++++++++++++++----------
 3 files changed, 232 insertions(+), 89 deletions(-)

diff --git a/payment/uc_payment/uc_payment.ca.inc b/payment/uc_payment/uc_payment.ca.inc
index 164637f..092dfe0 100644
--- a/payment/uc_payment/uc_payment.ca.inc
+++ b/payment/uc_payment/uc_payment.ca.inc
@@ -71,7 +71,7 @@ function uc_payment_ca_predicate() {
   // of the products are shippable, and the balance is less than or equal to 0.
   $predicates['uc_checkout_complete_paid'] = array(
     '#title' => t('Update order status upon checkout completion with full payment'),
-    '#trigger' => 'uc_checkout_complete',
+    '#trigger' => 'uc_checkout_complete_paid',
     '#class' => 'payment',
     '#status' => 1,
     '#weight' => 1,
@@ -136,6 +136,20 @@ function uc_payment_ca_trigger() {
       ),
     ),
   );
+  $triggers['uc_checkout_complete_paid'] = array(
+    '#title' => t('Update order status to completed if full payment'),
+    '#category' => t('Cart'),
+    '#arguments' => array(
+      'order' => array(
+        '#entity' => 'uc_order',
+        '#title' => t('Order'),
+      ),
+      'account' => array(
+        '#entity' => 'user',
+        '#title' => t('Customer user account'),
+      )
+    ),
+  );
 
   return $triggers;
 }
diff --git a/payment/uc_paypal/uc_paypal.pages.inc b/payment/uc_paypal/uc_paypal.pages.inc
index 07b1a66..ff7d6f1 100644
--- a/payment/uc_paypal/uc_paypal.pages.inc
+++ b/payment/uc_paypal/uc_paypal.pages.inc
@@ -104,7 +104,7 @@ function uc_paypal_ipn($order_id = 0) {
         }
         $comment = t('PayPal transaction ID: @txn_id', array('@txn_id' => $txn_id));
         uc_payment_enter($order_id, 'paypal_wps', $payment_amount, $order->uid, NULL, $comment);
-        uc_cart_complete_sale($order);
+        uc_cart_complete_sale($order, FALSE, TRUE);
         uc_order_comment_save($order_id, 0, t('Payment of @amount @currency submitted through PayPal.', array('@amount' => uc_price($payment_amount, $context, $options), '@currency' => $payment_currency)), 'order', 'payment_received');
         uc_order_comment_save($order_id, 0, t('PayPal IPN reported a payment of @amount @currency.', array('@amount' => uc_price($payment_amount, $context, $options), '@currency' => $payment_currency)));
         break;
diff --git a/uc_cart/uc_cart.module b/uc_cart/uc_cart.module
index 691aca8..d7691b1 100644
--- a/uc_cart/uc_cart.module
+++ b/uc_cart/uc_cart.module
@@ -1190,111 +1190,240 @@ function uc_cart_continue_shopping_url($unset = TRUE) {
  * @return
  *   The HTML text of the default order completion page.
  */
-function uc_cart_complete_sale($order, $login = FALSE) {
+function uc_cart_complete_sale($order, $login = FALSE, $ipn = FALSE) {
   global $user;
+dd($order);
+  //Most of this is an exact copy of the section below.
+  //A whole new "if" section was added because I didn't know how my changes would effect other payment methods
+  //The only "new" stuff is the "else if (isset($order->data['new_user']['name']))" so that a user is still logged in
+  //   even if they user has already be created by the IPN
+  if ($order->payment_method == 'paypal_wps') {
+            // Logic to create new user if necessary:
+          if ($order->uid == 0) {
+            // Check for an existing user account with the e-mail address from checkout.
+            $result = db_query("SELECT uid FROM {users} WHERE mail = '%s'", $order->primary_email);
+
+            // If it was found, update the order.
+            if ($account = db_fetch_object($result)) {
+              $order->uid = $account->uid;
+              $account = user_load($account->uid);
+              db_query("UPDATE {uc_orders} SET uid = %d WHERE order_id = %d", $order->uid, $order->order_id);
+              $message_type = 'existing_user';
+            }
+            else {
+              // Get a valid new username.
+              if (empty($order->data['new_user']['name'])) {
+                $name = uc_store_email_to_username($order->primary_email);
+              }
+              else {
+                $name = $order->data['new_user']['name'];
+              }
 
-  // Logic to create new user if necessary:
-  if ($order->uid == 0) {
-    // Check for an existing user account with the e-mail address from checkout.
-    $result = db_query("SELECT uid FROM {users} WHERE mail = '%s'", $order->primary_email);
-
-    // If it was found, update the order.
-    if ($account = db_fetch_object($result)) {
-      $order->uid = $account->uid;
-      $account = user_load($account->uid);
-      db_query("UPDATE {uc_orders} SET uid = %d WHERE order_id = %d", $order->uid, $order->order_id);
-      $message_type = 'existing_user';
-    }
-    else {
-      // Get a valid new username.
-      if (empty($order->data['new_user']['name'])) {
-        $name = uc_store_email_to_username($order->primary_email);
-      }
-      else {
-        $name = $order->data['new_user']['name'];
-      }
+              // Setup the account fields array and save it as a new user.
+              $fields = array(
+                'name' => $name,
+                'mail' => $order->primary_email,
+                'init' => $order->primary_email,
+                'pass' => empty($order->data['new_user']['pass']) ? user_password(variable_get('uc_pwd_length', 6)) : $order->data['new_user']['pass'],
+                'roles' => array(),
+                'status' => variable_get('uc_new_customer_status_active', TRUE) ? 1 : 0,
+              );
+              $account = user_save('', $fields);
+
+              // Send the customer their account details if enabled.
+              if (variable_get('uc_new_customer_email', TRUE)) {
+                // Manually set the password so it appears in the e-mail.
+                $account->password = $fields['pass'];
+
+                // Send the e-mail through the user module.
+                drupal_mail('user', 'register_no_approval_required', $order->primary_email, NULL, array('account' => $account), uc_store_email_from());
+              }
 
-      // Setup the account fields array and save it as a new user.
-      $fields = array(
-        'name' => $name,
-        'mail' => $order->primary_email,
-        'init' => $order->primary_email,
-        'pass' => empty($order->data['new_user']['pass']) ? user_password(variable_get('uc_pwd_length', 6)) : $order->data['new_user']['pass'],
-        'roles' => array(),
-        'status' => variable_get('uc_new_customer_status_active', TRUE) ? 1 : 0,
-      );
-      $account = user_save('', $fields);
+              // Store the login details in the session for use on the page display.
+              $_SESSION['new_user'] = array('name' => $fields['name'], 'pass' => $fields['pass']);
 
-      // Send the customer their account details if enabled.
-      if (variable_get('uc_new_customer_email', TRUE)) {
-        // Manually set the password so it appears in the e-mail.
-        $account->password = $fields['pass'];
+              // Update the order's uid in this request and in the database.
+              $order->uid = $account->uid;
+              unset($order->data['new_user']['pass']);
+              db_query("UPDATE {uc_orders} SET uid = %d, data = '%s' WHERE order_id = %d", $order->uid, serialize($order->data), $order->order_id);
 
-        // Send the e-mail through the user module.
-        drupal_mail('user', 'register_no_approval_required', $order->primary_email, NULL, array('account' => $account), uc_store_email_from());
-      }
+              // Login the user if specified.
+              if ($login && !$ipn) {
+                $form_state = array('values' => $fields);
+                drupal_execute('user_login', $form_state);
+              }
+              $message_type = 'new_user';
+            }
+          }
+          //just allows the new user to be logged in even if the uid exists because the IPN created it first
+          //    before the user got back to the site.
+          else if (isset($order->data['new_user']['name'])) {
+	      $account = user_load($order->uid);
+              $_SESSION['new_user'] = array('name' => $fields['name'], 'pass' => '*****');
+              // Login the user if specified.
+              if ($login && !$ipn) {
+		$user = $account;
+              }
 
-      // Store the login details in the session for use on the page display.
-      $_SESSION['new_user'] = array('name' => $fields['name'], 'pass' => $fields['pass']);
+              $message_type = 'new_user';
 
-      // Update the order's uid in this request and in the database.
-      $order->uid = $account->uid;
-      unset($order->data['new_user']['pass']);
-      db_query("UPDATE {uc_orders} SET uid = %d, data = '%s' WHERE order_id = %d", $order->uid, serialize($order->data), $order->order_id);
+          }
+          else {
+            if ($order->uid == $user->uid) {
+              $message_type = 'logged_in';
+              $account = clone $user;
+            }
+            else {
+              $message_type = 'existing_user';
+              $account = user_load($order->uid);
+            }
+          }
 
-      // Login the user if specified.
-      if ($login) {
-        $form_state = array('values' => $fields);
-        drupal_execute('user_login', $form_state);
-      }
+          $messages['uc_msg_order_submit_format'] = variable_get('uc_msg_order_submit', uc_get_message('completion_message'));
+          $message = variable_get('uc_msg_order_'.$message_type, uc_get_message('completion_'.$message_type));
+          if ($message != '') {
+            $variables['!new_username'] = check_plain($_SESSION['new_user']['name']);
+            $variables['!new_password'] = check_plain($_SESSION['new_user']['pass']);
+            $messages['uc_msg_order_'.$message_type.'_format'] = strtr($message, $variables);
+          }
+          $messages['uc_msg_continue_shopping_format'] = variable_get('uc_msg_continue_shopping', uc_get_message('continue_shopping'));
 
-      $message_type = 'new_user';
-    }
+          $output_message = '';
+          foreach ($messages as $format => $message) {
+            $message = token_replace_multiple($message, array('global' => NULL, 'order' => $order));
+            $message = check_markup($message, variable_get($format, FILTER_FORMAT_DEFAULT), FALSE);
+            $output_message .= $message;
+          }
+          $themed_output = theme('uc_cart_complete_sale', $output_message);
+
+          // Move an order's status from "In Checkout" to "Pending"
+          $status = db_result(db_query("SELECT order_status FROM {uc_orders} WHERE order_id = %d", $order->order_id));
+          if (uc_order_status_data($status, 'state') == 'in_checkout') {
+            uc_order_update_status($order->order_id, uc_order_state_default('post_checkout'));
+          }
+
+          // Empty that cart...
+          uc_cart_empty(uc_cart_get_id());
+
+          // Clear our the session variables used to force the cart workflow.
+          unset($_SESSION['cart_order'], $_SESSION['do_complete'], $_SESSION['new_user']);
+
+          module_invoke_all('uc_checkout_complete', $order, $account);
+          if ($ipn) {
+            ca_pull_trigger('uc_checkout_complete_paid', $order, $account);
+          }
+          else {
+	    ca_pull_trigger('uc_checkout_complete', $order, $account);
+          }
+          return $themed_output;
   }
   else {
-    if ($order->uid == $user->uid) {
-      $message_type = 'logged_in';
-      $account = clone $user;
-    }
-    else {
-      $message_type = 'existing_user';
-      $account = user_load($order->uid);
-    }
-  }
 
-  $messages['uc_msg_order_submit_format'] = variable_get('uc_msg_order_submit', uc_get_message('completion_message'));
-  $message = variable_get('uc_msg_order_'.$message_type, uc_get_message('completion_'.$message_type));
-  if ($message != '') {
-    $variables['!new_username'] = check_plain($_SESSION['new_user']['name']);
-    $variables['!new_password'] = check_plain($_SESSION['new_user']['pass']);
-    $messages['uc_msg_order_'.$message_type.'_format'] = strtr($message, $variables);
-  }
-  $messages['uc_msg_continue_shopping_format'] = variable_get('uc_msg_continue_shopping', uc_get_message('continue_shopping'));
 
-  $output_message = '';
-  foreach ($messages as $format => $message) {
-    $message = token_replace_multiple($message, array('global' => NULL, 'order' => $order));
-    $message = check_markup($message, variable_get($format, FILTER_FORMAT_DEFAULT), FALSE);
-    $output_message .= $message;
-  }
-  $themed_output = theme('uc_cart_complete_sale', $output_message);
+      // Logic to create new user if necessary:
+      if ($order->uid == 0) {
+        // Check for an existing user account with the e-mail address from checkout.
+        $result = db_query("SELECT uid FROM {users} WHERE mail = '%s'", $order->primary_email);
 
-  // Move an order's status from "In Checkout" to "Pending"
-  $status = db_result(db_query("SELECT order_status FROM {uc_orders} WHERE order_id = %d", $order->order_id));
-  if (uc_order_status_data($status, 'state') == 'in_checkout') {
-    uc_order_update_status($order->order_id, uc_order_state_default('post_checkout'));
-  }
+        // If it was found, update the order.
+        if ($account = db_fetch_object($result)) {
+          $order->uid = $account->uid;
+          $account = user_load($account->uid);
+          db_query("UPDATE {uc_orders} SET uid = %d WHERE order_id = %d", $order->uid, $order->order_id);
+          $message_type = 'existing_user';
+        }
+        else {
+          // Get a valid new username.
+          if (empty($order->data['new_user']['name'])) {
+            $name = uc_store_email_to_username($order->primary_email);
+          }
+          else {
+            $name = $order->data['new_user']['name'];
+          }
 
-  // Empty that cart...
-  uc_cart_empty(uc_cart_get_id());
+          // Setup the account fields array and save it as a new user.
+          $fields = array(
+            'name' => $name,
+            'mail' => $order->primary_email,
+            'init' => $order->primary_email,
+            'pass' => empty($order->data['new_user']['pass']) ? user_password(variable_get('uc_pwd_length', 6)) : $order->data['new_user']['pass'],
+            'roles' => array(),
+            'status' => variable_get('uc_new_customer_status_active', TRUE) ? 1 : 0,
+          );
+          $account = user_save('', $fields);
 
-  // Clear our the session variables used to force the cart workflow.
-  unset($_SESSION['cart_order'], $_SESSION['do_complete'], $_SESSION['new_user']);
+          // Send the customer their account details if enabled.
+          if (variable_get('uc_new_customer_email', TRUE)) {
+            // Manually set the password so it appears in the e-mail.
+            $account->password = $fields['pass'];
+
+            // Send the e-mail through the user module.
+            drupal_mail('user', 'register_no_approval_required', $order->primary_email, NULL, array('account' => $account), uc_store_email_from());
+          }
 
-  module_invoke_all('uc_checkout_complete', $order, $account);
-  ca_pull_trigger('uc_checkout_complete', $order, $account);
+          // Store the login details in the session for use on the page display.
+          $_SESSION['new_user'] = array('name' => $fields['name'], 'pass' => $fields['pass']);
 
-  return $themed_output;
+          // Update the order's uid in this request and in the database.
+          $order->uid = $account->uid;
+          unset($order->data['new_user']['pass']);
+          db_query("UPDATE {uc_orders} SET uid = %d, data = '%s' WHERE order_id = %d", $order->uid, serialize($order->data), $order->order_id);
+
+          // Login the user if specified.
+          if ($login) {
+            $form_state = array('values' => $fields);
+            drupal_execute('user_login', $form_state);
+          }
+
+          $message_type = 'new_user';
+        }
+      }
+      else {
+        if ($order->uid == $user->uid) {
+          $message_type = 'logged_in';
+          $account = clone $user;
+        }
+        else {
+          $message_type = 'existing_user';
+          $account = user_load($order->uid);
+        }
+      }
+
+      $messages['uc_msg_order_submit_format'] = variable_get('uc_msg_order_submit', uc_get_message('completion_message'));
+      $message = variable_get('uc_msg_order_'.$message_type, uc_get_message('completion_'.$message_type));
+      if ($message != '') {
+        $variables['!new_username'] = check_plain($_SESSION['new_user']['name']);
+        $variables['!new_password'] = check_plain($_SESSION['new_user']['pass']);
+        $messages['uc_msg_order_'.$message_type.'_format'] = strtr($message, $variables);
+      }
+      $messages['uc_msg_continue_shopping_format'] = variable_get('uc_msg_continue_shopping', uc_get_message('continue_shopping'));
+
+      $output_message = '';
+      foreach ($messages as $format => $message) {
+        $message = token_replace_multiple($message, array('global' => NULL, 'order' => $order));
+        $message = check_markup($message, variable_get($format, FILTER_FORMAT_DEFAULT), FALSE);
+        $output_message .= $message;
+      }
+      $themed_output = theme('uc_cart_complete_sale', $output_message);
+
+      // Move an order's status from "In Checkout" to "Pending"
+      $status = db_result(db_query("SELECT order_status FROM {uc_orders} WHERE order_id = %d", $order->order_id));
+      if (uc_order_status_data($status, 'state') == 'in_checkout') {
+        uc_order_update_status($order->order_id, uc_order_state_default('post_checkout'));
+      }
+
+      // Empty that cart...
+      uc_cart_empty(uc_cart_get_id());
+
+      // Clear our the session variables used to force the cart workflow.
+      unset($_SESSION['cart_order'], $_SESSION['do_complete'], $_SESSION['new_user']);
+
+      module_invoke_all('uc_checkout_complete', $order, $account);
+      ca_pull_trigger('uc_checkout_complete', $order, $account);
+      ca_pull_trigger('uc_checkout_complete_paid', $order, $account);
+
+      return $themed_output;
+  }
 }
 
 /**
-- 
1.5.4.3

