--- uc_signup.module.orig	2009-10-09 23:48:39.000000000 -0400
+++ uc_signup.module	2009-10-16 01:22:33.000000000 -0400
@@ -1,13 +1,14 @@
 <?php
 // $Id: uc_signup.module,v 1.45 2009/09/29 16:15:51 ezrag Exp $
-/*
+
+/**
  * Implementation of hook_perm().
  */
 function uc_signup_perm() {
   return array('administer UC_Signup');
 }
 
-/*
+/**
  * Implementation of hook_menu().
  */
 function uc_signup_menu() {
@@ -41,7 +42,7 @@ function uc_signup_attendees_form_access
   return TRUE;
 }
 
-/*
+/**
  * Implementation of hook_theme().
  */
 function uc_signup_theme() {
@@ -139,17 +140,20 @@ function uc_signup_attendees_form_emails
 }
 function uc_signup_attendees_form_submit($form, &$form_state) {
 
+  // push values into storage
   foreach ($form_state['values'] as $key => $value) {
     if (is_numeric($key)) {
       $form_state['storage']['uc_signup']['nids'][$key] = $value;
     }
-    if ($key == 'profile') {
-      $form_state['storage']['uc_signup']['profile'] = $value;
+    else {
+      // 'profile' or 'content_profile' or ??
+      $form_state['storage']['uc_signup'][$key] = $value;
     }
   }
+
   // Store entered email addresses in the session in case the user navigates away from the form and returns.
   $_SESSION['uc_signup'] = $form_state['storage']['uc_signup'];
-  if ($form_state['storage']['step'] == 'profiles') {
+  if ($form_state['storage']['step'] == 'profiles' || (!variable_get('uc_signup_profiles_enabled', 0) && $form_state['storage']['step'] == 'emails')) {
     drupal_goto('cart/checkout');
   }
 
@@ -200,14 +204,22 @@ function uc_signup_attendees_form(&$form
     drupal_goto('uc_signup/attendees/emails');
   }
 
-  //Otherwise, the user is requesting the profiles form.
-   return uc_signup_attendees_form_profiles($form_state, $events);
+  // If we're collecting profiles, then the user is requesting the profiles form.
+  if (variable_get('uc_signup_profiles_enabled', 0)) {
+    return uc_signup_attendees_form_profiles($form_state, $events);
+  }
+
+  // If we get to here, just go to checkout
+  drupal_goto('cart/checkout');
 }
 
 function uc_signup_attendees_form_profiles(&$form_state, $events = array()) {
+  //need this? include_once(drupal_get_path('module', 'user') .'/user.pages.inc');
+
   $form_state['storage']['step'] = 'profiles';
   $mails = array();
   $nodes = array();
+
   // Build an array keyed on email addresses
   foreach ($form_state['storage']['uc_signup']['nids'] as $nid => $attendees) {
     if (!in_array($nid, $nodes)) {
@@ -221,8 +233,7 @@ function uc_signup_attendees_form_profil
     }
   }
 
-  include_once(drupal_get_path('module', 'user') .'/user.pages.inc');
-  $profile_form = array_values(module_invoke('profile', 'user', 'register', array(), (object)array()));
+  // Build form elements per $mail
   $mail = '';
   foreach ($mails as $mail => $events) {
     $form[$mail] = array(
@@ -239,39 +250,20 @@ function uc_signup_attendees_form_profil
 
     // Is there an account for this email address?
     $account = user_load(array('mail' => $mail));
-    if (empty($account->uid)) {
-      $profile_form = array_values(module_invoke('profile', 'user', 'register', array(), (object)array()));
-      if (!empty($profile_form)) {
-        $profile_form = $profile_form[0];
-        $form[$mail]['profile'] = $profile_form;
-        foreach ($form[$mail]['profile'] as $key => $value) {
-          $default = $form_state['values']['profile'][$key .'_'. $mail];
-          if (empty($default)) {
-            $default = $_SESSION['uc_signup']['profile'][$key .'_'. $mail];
-          }
-          if ($key[0] != '#') {
-            $form[$mail]['profile'][$key .'_'. $mail] = $value;
-            unset($form[$mail]['profile'][$key]);
-            $form[$mail]['profile'][$key .'_'. $mail]['#default_value'] = $default;
-            $form[$mail]['profile']['#tree'] = TRUE;
-          }
-          drupal_add_css(drupal_get_path('module', 'uc_signup') .'/uc_signup.css');
-          $form[$mail]['has_account'] = array(
-            '#type' => 'markup',
-            '#value' => theme('uc_signup_needs_account', t('Please enter additional information about this attendee.')),
-            '#weight' => -4,
-          );
-        }
-      }
+    $has_account_html = '';
+    if (!$account->uid) {
+      uc_signup_attendees_form_add_profile_forms($form[$mail], $form_state, $mail);
+      $has_account_html = theme('uc_signup_needs_account', t('Please enter additional information about this attendee.'));
     }
     else {
-      drupal_add_css(drupal_get_path('module', 'uc_signup') .'/uc_signup.css');
-      $form[$mail]['has_account'] = array(
-        '#type' => 'markup',
-        '#value' => theme('uc_signup_has_account', t('We already have contact information for this attendee in our system.')),
-        '#weight' => -4,
-      );
+      $has_account_html = theme('uc_signup_has_account', t('We already have contact information for this attendee in our system.'));
     }
+
+    $form[$mail]['has_account'] = array(
+      '#type' => 'markup',
+      '#value' => $has_account_html,
+      '#weight' => -4,
+    );
   }
 
   $form['back'] = array(
@@ -284,15 +276,49 @@ function uc_signup_attendees_form_profil
     '#attributes' => array('class' => 'uc_signup_next'),
   );
 
+  drupal_add_css(drupal_get_path('module', 'uc_signup') .'/uc_signup.css');
   return $form;
 }
 
+function uc_signup_attendees_form_add_profile_forms(&$form, &$form_state, $mail) {
+
+  // Profile fields
+  if (module_exists('profile')) {
+    $profile_form = array_values(module_invoke('profile', 'user', 'register', array(), (object)array()));
+
+    if (!empty($profile_form)) {
+      $profile_form = $profile_form[0];
+      $profile_form['#tree'] = TRUE;
+
+      foreach (element_children($profile_form) as $key) {
+        $field = $profile_form[$key];
+
+        // set default
+        $default = $form_state['values']['profile'][$key .'_'. $mail];
+        if (empty($default)) {
+          $default = $_SESSION['uc_signup']['profile'][$key .'_'. $mail];
+        }
+
+        // update unique key
+        $unique_key = $key . '_' . $mail;
+        $profile_form[$unique_key] = $field;
+        $profile_form[$unique_key]['#default_value'] = $default;
+        unset($profile_form[$key]);
+      }
+
+      // add to form
+      $form['profile'] = $profile_form;
+    }
+  }
+
+}
+
 function theme_uc_signup_needs_account($message = '') {
-  return '<span class="uc_signup_needs_account">'. $message .'</span>';
+  return '<div class="uc_signup_needs_account">'. $message .'</div>';
 }
 
 function theme_uc_signup_has_account($message = '') {
-  return '<span class="uc_signup_has_account">'. $message .'</span>';
+  return '<div class="uc_signup_has_account">'. $message .'</div>';
 }
 
 function theme_uc_signup_user_events($events = array(), $nodes = array()) {
@@ -315,7 +341,7 @@ function theme_uc_signup_event_text($nod
   return check_plain($node->title) .' - '. $date_formatted;
 }
 
-/*
+/**
  * Implementation of hook_form_alter().
  */
 function uc_signup_form_alter(&$form, &$form_state, $form_id) {
@@ -328,7 +354,7 @@ function uc_signup_form_alter(&$form, &$
       }
     }
   }
-  if (strpos($form_id, 'uc_product_add_to_cart_form') !== FALSE || strpos($form_id, 'uc_catalog_buy_it_now_form') !== FALSE) {
+  elseif (strpos($form_id, 'uc_product_add_to_cart_form') !== FALSE || strpos($form_id, 'uc_catalog_buy_it_now_form') !== FALSE) {
     $node = $form['#parameters']['2'];
     if (isset($node->signup) && $node->signup == 1) {
       $add_cart_text = variable_get('uc_signup_add_cart_text', '');
@@ -351,7 +377,7 @@ function uc_signup_form_alter(&$form, &$
       }
     }
   }
-  if ($form_id == 'uc_cart_view_form') {
+  elseif ($form_id == 'uc_cart_view_form') {
     $form['#validate'][] = 'uc_signup_cart_view_form_validate';
     $form['checkout']['#submit'][] = 'uc_signup_cart_view_form_submit';
     $form['update']['#submit'][] = 'uc_signup_cart_view_form_submit';
@@ -395,7 +421,7 @@ function uc_signup_cart_view_form_valida
 }
 
 
-/*
+/**
  * Implementation of hook_ca_predicate().
  */
 function uc_signup_ca_predicate() {
@@ -461,7 +487,7 @@ function uc_signup_ca_predicate() {
   return $configurations;
 }
 
-/*
+/**
  * Implementation of hook_ca_action().
  */
 function uc_signup_ca_action() {
@@ -576,79 +602,66 @@ function uc_signup_order($op, &$arg1, $a
           $events_to_signup[] = $product;
         }
       }
-      if (!empty($events_to_signup)) {
-        //Clear any existing placeholder signups before proceeding.
-        uc_signup_cancel_temporary_signups($order);
-        foreach ($_SESSION['uc_signup']['nids'] as $nid => $attendees) {
-          foreach ($attendees as $key => $mail) {
-            $account = user_load(array('mail' => $mail));
-            if (empty($account->uid)) {
-              $form_state['values']['mail'] = $mail;
-              $namenew = preg_replace('/@.*$/', '', $mail);
-              // From the email registration module:
-              if (db_result(db_query("SELECT count(*) FROM {users} WHERE LOWER(name) = LOWER('%s')", $namenew)) > 0) {
-                 // Find the next number available to append to the name
-                $sql = "SELECT SUBSTRING_INDEX(name,'_',-1) FROM {users} WHERE name REGEXP '%s' ORDER BY CAST(SUBSTRING_INDEX(name,'_',-1) AS UNSIGNED) DESC LIMIT 1";
-                $nameidx = db_result(db_query($sql, '^'. $namenew .'_[0-9]+$'));
-                $namenew .= '_'. ($nameidx + 1);
-              }
-              $form_state['values']['name'] = $namenew;
-              $form_state['values']['op'] = t('Create new account');
-              $form_state['values']['pass'] =  user_password(8);
-              $form_state['values']['notify'] = FALSE;
-              $profile_form = array_values(module_invoke('profile', 'user', 'register', array(), (object)array()));
-              $profile_form = $profile_form[0];
-              foreach ($profile_form as $key => $value) {
-                if ($key[0] != '#') {
-                  $form_state['values'][$key] = $_SESSION['uc_signup']['profile'][$key .'_'. $mail];
+      if (empty($events_to_signup)) {
+        return;
+      }
+
+      //Clear any existing placeholder signups before proceeding.
+      uc_signup_cancel_temporary_signups($order);
+      $profiles_enabled = variable_get('uc_signup_profiles_enabled', 0);
+      foreach ($_SESSION['uc_signup']['nids'] as $nid => $attendees) {
+        foreach ($attendees as $key => $mail) {
+          $account = uc_signup_create_user($mail, TRUE);
+          if (!$account->uid) {
+            uc_signup_cancel_temporary_signups($order);
+            return array(array('pass' => FALSE, 'message' => t('There was an error saving attendee contact information. Please verify that you have entered all required fields at the '. l('Attendee forms','uc_signup/attendees/emails'))));
+          }
+          if ($profiles_enabled && $account->is_new) {
+            // save profile fields
+            if (!empty($_SESSION['uc_signup']['profile'])) {
+              $edit = array();
+              foreach ($_SESSION['uc_signup']['profile'] as $field_key => $field_value) {
+                $profile_key = str_replace('_' . $mail, '', $field_key);
+                if ($profile_key) {
+                  $edit[$profile_key] = $field_value;
                 }
               }
-
-              //We masquerade as user 1 in case there is captcha or other protection on the user_register form that could cause submission to fail.
-              global $user;
-              $temp_user = $user;
-              //Always set this to false in case the operation fails.
-              session_save_session(FALSE);
-              $user = user_load(1);
-              drupal_execute('user_register', $form_state);
-              $user = $temp_user;
-              session_save_session(TRUE);
-              $account = $form_state['user'];
-              if (!$account->uid) {
-                uc_signup_cancel_temporary_signups($order);
-                return array(array('pass' => FALSE, 'message' => t('There was an error saving attendee contact information. Please verify that you have entered all required fields at the '. l('Attendee profile contact information form','uc_signup/attendees/profiles'))));
+              if (!empty($edit)) {
+                module_invoke('profile', 'user', 'insert', $edit, $account);
               }
             }
-            $to_signup[$nid][] = $account->uid;
           }
+
+          $to_signup[$nid][] = $account->uid;
         }
-        unset($nid);
-        foreach ($to_signup as $nid => $uids) {
-          //Perform the final verification that the node is available for signups in the desired quantity.
-          //Note that we do not pass the quantity in order to avoid our own placeholder signups from counting against the number of available spots.
-          $node = node_load($nid);
-          _uc_signup_node_available($node, 0, $message);
-          if ($message) {
-            uc_signup_cancel_temporary_signups($order);
-            return array(array('pass' => FALSE, 'message' => t($message)));
-          }
-          foreach ($uids as $key => $uid) {
-            $signup_form = array(
-              'nid' => $nid,
-              'uid' => $uid,
-            );
-            $sid = NULL;
-            $sid = signup_sign_up_user($signup_form, FALSE);
-            if (is_numeric($sid)) {
-              db_query("INSERT INTO {uc_signup_log} (oid, sid, type) VALUES (%d, %d, %d)", $arg1->order_id, $sid, 0);
-            }
+      }
+
+      unset($nid);
+      foreach ($to_signup as $nid => $uids) {
+        //Perform the final verification that the node is available for signups in the desired quantity.
+        //Note that we do not pass the quantity in order to avoid our own placeholder signups from counting against the number of available spots.
+        $node = node_load($nid);
+        _uc_signup_node_available($node, 0, $message);
+        if ($message) {
+          uc_signup_cancel_temporary_signups($order);
+          return array(array('pass' => FALSE, 'message' => t($message)));
+        }
+        foreach ($uids as $key => $uid) {
+          $signup_form = array(
+            'nid' => $nid,
+            'uid' => $uid,
+          );
+          $sid = NULL;
+          $sid = signup_sign_up_user($signup_form, FALSE);
+          if (is_numeric($sid)) {
+            db_query("INSERT INTO {uc_signup_log} (oid, sid, type) VALUES (%d, %d, %d)", $arg1->order_id, $sid, 0);
           }
         }
       }
+
   }
 }
 
-
 function _uc_signup_node_available($node, $qty, &$message) {
   $type_name = db_result(db_query("SELECT name from {node_type} WHERE type = '%s'", $node->type));
 
@@ -656,7 +669,7 @@ function _uc_signup_node_available($node
     $message = t(variable_get('uc_signup_signups_closed_text', "Signups are closed for this event."));
   }
   if (_signup_node_completed($node)) {
-    $message = t("We're sorry, but the @type %title has already passed.", array('@type' => $type_name, '%title' => $node->title));
+    $message = t("We're sorry, but the @type @title has already passed.", array('@type' => $type_name, '@title' => $node->title));
   }
   if ($node->signup_close_signup_limit !=0) {
     $spots_remaining = $node->signup_close_signup_limit - $node->signup_total;
@@ -664,12 +677,12 @@ function _uc_signup_node_available($node
       $only = 'only ';
     }
     if ($spots_remaining < $qty) {
-      $message = t("We're sorry, but there @is $only@available @spot left for the @type %title.", array(
+      $message = t("We're sorry, but there @is $only@available @spot left for the @type @title.", array(
         '@is' => format_plural($spots_remaining, "is", "are"),
         '@spot' => format_plural($spots_remaining, "spot", "spots"),
         '@available' => $spots_remaining,
         '@type' => $type_name,
-        '%title' => $node->title
+        '@title' => $node->title
       ));
     }
   }
@@ -681,13 +694,33 @@ function uc_signup_settings_form() {
     '#title' => t('Add to cart text'),
     '#description' => t("The text to use to add the signup-enabled node to the cart. If left blank, Ubercart's default 'Add to cart' text will be used."),
     '#default_value' => variable_get('uc_signup_add_cart_text', ''),
+    '#weight' => -5,
   );
   $form['uc_signup_signups_closed_text'] = array(
-  '#type' => 'textfield',
-  '#title' => t('Signups closed text'),
-  '#description' => t("The signup/add to cart button will be disabled and display this text when signups are closed for a node. This text will be displayed when capacity is reached for an event."),
-  '#default_value' => variable_get('uc_signup_signups_closed_text', t("Signups are closed for this event.")),
+    '#type' => 'textfield',
+    '#title' => t('Signups closed text'),
+    '#description' => t("The signup/add to cart button will be disabled and display this text when signups are closed for a node. This text will be displayed when capacity is reached for an event."),
+    '#default_value' => variable_get('uc_signup_signups_closed_text', t("Signups are closed for this event.")),
+    '#weight' => -4,
+  );
+
+  // Profile Collection
+  $supported_profile_modules = array('profile');
+  $all_modules = module_list();
+  $available_profile_modules = array_intersect($supported_profile_modules, $all_modules);
+  $can_collect_profiles = !empty($available_profile_modules);
+  if (!$can_collect_profiles) {
+    variable_set('uc_signup_profiles_enabled', 0);
+  }
+  $form['profiles']['uc_signup_profiles_enabled'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Enable attendee profile collection'),
+    '#description' => t("This enables the collection of profile fields for each attendee that is not a current user. Profile modules available: " . ($can_collect_profiles ? implode(', ', $available_profile_modules) : '<b>NONE</b>')),
+    '#default_value' => variable_get('uc_signup_profiles_enabled', 0),
+    '#disabled' => !$can_collect_profiles,
+    '#weight' => -3,
   );
+
   return system_settings_form($form);
 }
 
@@ -762,3 +795,57 @@ function uc_signup_views_api() {
     'path' => drupal_get_path('module', 'uc_signup') .'/views',
   );
 }
+
+/**
+ * Find or create a user based on email only
+ */
+function uc_signup_create_user($email_, $notify = FALSE) {
+  // clean up a little
+  $email = trim($email_);
+
+  // if an account exists already, return it
+  $existing = user_load(array('mail' => $email));
+  if (!empty($existing)) {
+    return $existing;
+  }
+
+  if (!valid_email_address($email)) {
+    return NULL;
+  }
+
+  // Create account
+  $plain_pass = user_password(variable_get('uc_pwd_length', 8));
+  $fields = array(
+    'name' => uc_store_email_to_username($email),
+    'mail' => $email,
+    'init' => $email,
+    'pass' => $plain_pass,
+    'roles' => array(),
+    'status' => 1,
+  );
+  $account = user_save('', $fields);
+
+  // return if something went wrong in user creation
+  if (!$account->uid) {
+    return NULL;
+  }
+
+  // add is_new flag so can tell if account was created
+  $account->is_new = TRUE;
+
+
+  // Send the customer their account details if enabled.
+  if ($notify) {
+    // Manually set the password so it appears in the e-mail.
+    $cipher_pass = $account->password;
+    $account->password = $plain_pass;
+
+    // Send the e-mail through the user module.
+    drupal_mail('user', 'register_no_approval_required', $email, NULL, array('account' => $account), uc_store_email_from());
+
+    // set this back to the cipher password
+    $account->password = $cipher_pass;
+  }
+
+  return $account;
+}
