--- authorizenetwebform.module.weborm3.patched	2010-10-26 16:07:25.000000000 -0400
+++ authorizenetwebform.module	2010-10-26 17:56:03.000000000 -0400
@@ -311,6 +311,17 @@
     $form_values['submitted'][$exp_date_key] = preg_replace('/[^0-9]+/','',$form_values['submitted'][$exp_date_key]);
   }
 
+  $recur = 'none';
+  $recur_unit_string_key = $flipped_map['x_recur_unit'];
+  // if submitting we'll need the int key
+  // // if submitting we'll need the int key
+  $recur_unit_int_key = webform_get_cid($node, $flipped_map['x_recur_unit'], 0);
+  if(array_key_exists($recur_unit_string_key,$form_values['submitted'])) {
+    $recur= $form_values['submitted'][$recur_unit_string_key];
+  } elseif (array_key_exists($recur_unit_int_key,$form_values['submitted'])) {
+    $recur= $form_values['submitted'][$recur_unit_int_key];
+  }
+
   // get an array with the webform keys replaced with the authorizenet keys
   $submitted = authorizenetwebform_translate_keys($form_values['submitted'],$map);
 
@@ -389,23 +400,36 @@
   }
   
   
-  // This section takes the input fields and converts them to the proper format
-  // for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"
-  $post_string = "";
-  foreach ( $post_vars as $key => $value ) { 
-    $post_string .= "$key=". urlencode( $value ) ."&"; 
-  } 
-  $post_string = rtrim( $post_string, "& " );
-  $request = curl_init($post_url); // initiate curl object
-    curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
-    curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
-    curl_setopt($request, CURLOPT_POSTFIELDS, $post_string); // use HTTP POST to send form data
-    curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
-    $post_response = curl_exec($request); // execute curl post and store results in $post_response
-  @curl_close ($ch); // close curl object
+  // If it's recurring and we're validating... use the same code to test the
+  // credit card as we use for single payment
+  // However, if we're submitting and it's recurring... use a different
+  // call
+  if($recur != 'none' && $step == "submit") {
+    // fixme, we try to process on the validate step, not the submit step
+    $form_state['values'] = $form_values;
+    return $form_state;
+  } elseif($recur != 'none' && $step == "validate") {
+    // process recurring payment
+    $response_array = authorizenetwebform_submit_subscription($post_vars,$nid);
+  } else {
+    // This section takes the input fields and converts them to the proper format
+    // for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"
+    $post_string = "";
+    foreach ( $post_vars as $key => $value ) { 
+      $post_string .= "$key=". urlencode( $value ) ."&"; 
+    } 
+    $post_string = rtrim( $post_string, "& " );
+    $request = curl_init($post_url); // initiate curl object
+      curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
+      curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
+      curl_setopt($request, CURLOPT_POSTFIELDS, $post_string); // use HTTP POST to send form data
+      curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
+      $post_response = curl_exec($request); // execute curl post and store results in $post_response
+    @curl_close ($ch); // close curl object
 
-  // This line takes the response and breaks it into an array using the specified delimiting character
-  $response_array = explode($post_vars["x_delim_char"], $post_response);
+    // This line takes the response and breaks it into an array using the specified delimiting character
+    $response_array = explode($post_vars["x_delim_char"], $post_response);
+  }
 
   if ($step == "validate") {
     if ($response_array[2] > 1) {
@@ -422,6 +446,7 @@
       $_SESSION['anwf_trans_id'] = $form_values['submitted'][$flipped_map['x_trans_id']];
     }  
   }
+
   if  ($step == "submit") {
     if ($response_array[2] > 1) {
       watchdog('authorizenetwebform', 'Error response from Authorize.net: %resposne', array("%resposne" => "<pre>". print_r($response_array, TRUE) ."</pre>"));
@@ -476,3 +501,129 @@
 	$node = node_load($form_state['values']['details']['nid']);
 	$form_state = authorizenetwebform_process("submit", $node, $form_id, $form_state);
 }
+
+/**
+ * Submit variables and return response for subscription request
+ **/
+function authorizenetwebform_submit_subscription($vars,$nid) {
+  $content = authorizenetwebform_build_subscribe_xml_data($vars,$nid);
+  $response = authorizenetwebform_send_request_via_curl($content);
+  // eliminate the header, leaving just the xml
+  // xml should start after first blank line
+  $array = explode("\n",$response);
+  $xml_data = '';
+  $passed_blank = false;
+  while(list(,$line) = each($array)) {
+    $line = trim($line);
+    if(empty($line)) {
+      $passed_blank = true;
+    }
+    if($passed_blank) $xml_data .= $line;
+  }
+
+  // surpress errors
+  libxml_use_internal_errors(true);
+  $xml = new SimpleXMLElement($xml_data);
+
+  // try create a response_array similar to the one returned for the
+  // one time payment. keys:
+  // 2 => error code 
+  // 3 => error message
+  // 6 => transaction id - we stick the subscription id for subs
+  // drupal_set_message(print_r($xml,true)); 
+  
+  $response_array = array();
+  // First see if it's an error
+  if($xml->messages->resultCode == 'Error') {
+    $response_array[2] = 9999;
+    $response_array[3] = $xml->messages->message->text;
+    $response_array[6] = null;
+  } else {
+    $response_array[2] = 0;
+    $response_array[3] = null;
+    $response_array[6] = intval($xml->subscriptionId);
+  }
+ 
+  return $response_array;
+
+  /*
+  SimpleXMLElement Object ( 
+    [refId] => 54 
+    [messages] => SimpleXMLElement Object ( 
+      [resultCode] => Ok 
+      [message] => SimpleXMLElement Object ( 
+        [code] => I00001 
+        [text] => Successful. 
+      ) 
+    ) 
+    [subscriptionId] => 8017053 
+  ) 
+  */
+}
+
+//function to send xml request via curl
+function authorizenetwebform_send_request_via_curl($content)
+{
+  
+  if(AUTHORIZENETWEBFORM_MODE == 'test') {
+    $posturl = "https://apitest.authorize.net/xml/v1/request.api";
+  } else {
+    $posturl = "https://api.authorize.net/xml/v1/request.api";
+  }
+
+	$ch = curl_init();
+	curl_setopt($ch, CURLOPT_URL, $posturl);
+	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+	curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
+	curl_setopt($ch, CURLOPT_HEADER, 1);
+	curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
+	curl_setopt($ch, CURLOPT_POST, 1);
+	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
+	$response = curl_exec($ch);
+	return $response;
+}
+
+/**
+ * Build xml data for subscription payment
+ **/
+function authorizenetwebform_build_subscribe_xml_data($vars,$nid) {
+  //build xml to post
+  $content =
+        "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
+        "<ARBCreateSubscriptionRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">" .
+        "<merchantAuthentication>".
+        "<name>" . $vars['x_login'] . "</name>".
+        "<transactionKey>" . $vars['x_tran_key'] . "</transactionKey>".
+        "</merchantAuthentication>".
+		    "<refId>" . $nid . "</refId>".
+        "<subscription>".
+        "<name>" . $vars['x_first_name'] . ' ' . $vars['x_last_name'] . "</name>".
+        "<paymentSchedule>".
+        "<interval>".
+        "<length>". $vars['x_recur_length'] ."</length>".
+        "<unit>". $vars['x_recur_unit'] ."</unit>".
+        "</interval>".
+        "<startDate>" . date('Y-m-d',time() + 86400) . "</startDate>".
+        "<totalOccurrences>9999</totalOccurrences>".
+        "<trialOccurrences>0</trialOccurrences>".
+        "</paymentSchedule>".
+        "<amount>". $vars['x_amount'] ."</amount>".
+        "<trialAmount>0</trialAmount>".
+        "<payment>".
+        "<creditCard>".
+        "<cardNumber>" . $vars['x_card_num'] . "</cardNumber>".
+        "<expirationDate>" . $vars['x_exp_date'] . "</expirationDate>".
+        "</creditCard>".
+        "</payment>".
+        "<billTo>".
+        "<firstName>". $vars['x_first_name'] . "</firstName>".
+        "<lastName>" . $vars['x_last_name'] . "</lastName>".
+        "</billTo>".
+        "</subscription>".
+        "</ARBCreateSubscriptionRequest>";
+
+  return $content;
+}
+
+
+
