CRM-14078 - 'Paid By' -> 'Payment Method'
[civicrm-core.git] / CRM / Member / Form / MembershipRenewal.php
index 507e0d20a82f45cf532f1b82bb7e077a7e085a91..8c63c91165a0c29f3739974894b0061ec0f50352 100644 (file)
@@ -91,6 +91,27 @@ class CRM_Member_Form_MembershipRenewal extends CRM_Member_Form {
    */
   public $_context;
 
+  /**
+   * End date of renewed membership.
+   *
+   * @var string
+   */
+  protected $endDate = NULL;
+
+  /**
+   * Has an email been sent.
+   *
+   * @var string
+   */
+  protected $isMailSent = FALSE;
+
+  /**
+   * The name of the renewed membership type.
+   *
+   * @var string
+   */
+  protected $membershipTypeName = '';
+
   /**
    * An array to hold a list of datefields on the form
    * so that they can be converted to ISO in a consistent manner
@@ -143,6 +164,8 @@ class CRM_Member_Form_MembershipRenewal extends CRM_Member_Form {
     }
 
     CRM_Utils_System::setTitle(ts('Renew Membership'));
+
+    parent::preProcess();
   }
 
   /**
@@ -331,7 +354,7 @@ class CRM_Member_Form_MembershipRenewal extends CRM_Member_Form {
       $this->add('text', 'num_terms', ts('Extend Membership by'), array('onchange' => "setPaymentBlock();"), TRUE);
       $this->addRule('num_terms', ts('Please enter a whole number for how many periods to renew.'), 'integer');
 
-      $this->add('select', 'payment_instrument_id', ts('Paid By'),
+      $this->add('select', 'payment_instrument_id', ts('Payment Method'),
         array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
         FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
       );
@@ -416,7 +439,7 @@ class CRM_Member_Form_MembershipRenewal extends CRM_Member_Form {
         $errors['total_amount'] = ts('Please enter a Contribution Amount.');
       }
       if (empty($params['payment_instrument_id'])) {
-        $errors['payment_instrument_id'] = ts('Paid By is a required field.');
+        $errors['payment_instrument_id'] = ts('Payment Method is a required field.');
       }
     }
     return empty($errors) ? TRUE : $errors;
@@ -430,11 +453,26 @@ class CRM_Member_Form_MembershipRenewal extends CRM_Member_Form {
    */
   public function postProcess() {
     // get the submitted form values.
-    $this->_params = $formValues = $this->controller->exportValues($this->_name);
+    $this->_params = $this->controller->exportValues($this->_name);
     $this->assignBillingName();
 
     try {
-      $statusMsg = $this->submit($formValues);
+      $this->submit();
+      $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $this->membershipTypeName, 2 => $this->_memberDisplayName));
+
+      if ($this->endDate) {
+        $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(
+            1 => CRM_Utils_Date::customFormat(substr($this->endDate, 0, 8)),
+        ));
+      }
+
+      if ($this->isMailSent) {
+        $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(
+            1 => $this->_contributorEmail,
+        ));
+        return $statusMsg;
+      }
+      return $statusMsg;
     }
     catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
       CRM_Core_Error::displaySessionError($e->getMessage());
@@ -446,127 +484,60 @@ class CRM_Member_Form_MembershipRenewal extends CRM_Member_Form {
     CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
   }
 
-  /**
-   * Determine if the form has a pending status.
-   *
-   * @deprecated
-   *
-   * @param CRM_Core_Form $form
-   * @param int $membershipID
-   *
-   * @return bool
-   */
-  public static function extractPendingFormValue($form, $membershipID) {
-    $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipID);
-    $pending = FALSE;
-    // @todo function was shared by 2 not-very-related forms & the below may include irrelevant stuff.
-    if (CRM_Utils_Array::value('minimum_fee', $membershipTypeDetails) > 0.0) {
-      if (((isset($form->_contributeMode) && $form->_contributeMode == 'notify') || !empty($form->_params['is_pay_later'])
-        ) &&
-        (($form->_values['is_monetary'] && $form->_amount > 0.0) ||
-          CRM_Utils_Array::value('record_contribution', $form->_params)
-        )
-      ) {
-        $pending = TRUE;
-      }
-    }
-    return $pending;
-  }
-
   /**
    * Process form submission.
    *
    * This function is also accessed by a unit test.
-   *
-   * @param array $formValues
-   *   Submitted values.
-   *
-   * @return array
    */
-  protected function submit($formValues) {
-    $this->storeContactFields($formValues);
-    // use values from screen
-
-    if ($formValues['membership_type_id'][1] <> 0) {
-      $defaults['receipt_text_renewal'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
-        $formValues['membership_type_id'][1],
-        'receipt_text_renewal'
-      );
-    }
+  protected function submit() {
+    $this->storeContactFields($this->_params);
 
     $now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
-    $this->convertDateFieldsToMySQL($formValues);
-    $this->assign('receive_date', $formValues['receive_date']);
+    $this->convertDateFieldsToMySQL($this->_params);
+    $this->assign('receive_date', $this->_params['receive_date']);
+    $this->processBillingAddress($now);
+    list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::singleton()->get('userID'));
+    $this->_params['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params,
+      CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee')
+    );
+    $this->_membershipId = $this->_id;
+    $customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($this->_params,
+      $this->_id,
+      'Membership'
+    );
+    if (empty($this->_params['financial_type_id'])) {
+      $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
+    }
+
+    $this->assign('membershipID', $this->_id);
+    $this->assign('contactID', $this->_contactID);
+    $this->assign('module', 'Membership');
+    $this->assign('receiptType', 'membership renewal');
+    $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
+    $this->_params['invoice_id'] = $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
 
     if (!empty($this->_params['send_receipt'])) {
-      $formValues['receipt_date'] = $now;
-      $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($formValues['receipt_date']));
+      $this->_params['receipt_date'] = $now;
+      $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($this->_params['receipt_date']));
     }
     else {
-      $formValues['receipt_date'] = NULL;
+      $this->_params['receipt_date'] = NULL;
     }
 
     if ($this->_mode) {
-      $formValues['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues,
-        CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee')
+      $this->_params['register_date'] = $now;
+      $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id']);
+
+      $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
+      $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
+      $this->assign('credit_card_exp_date', CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::format($this->_params['credit_card_exp_date'])));
+      $this->assign('credit_card_number',
+        CRM_Utils_System::mungeCreditCard($this->_params['credit_card_number'])
       );
-      if (empty($formValues['financial_type_id'])) {
-        $formValues['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
-      }
-
-      $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id']);
-
-      $fields = array();
-
-      // set email for primary location.
-      $fields['email-Primary'] = 1;
-      $formValues['email-5'] = $formValues['email-Primary'] = $this->_contributorEmail;
-      $formValues['register_date'] = $now;
-
-      // now set the values for the billing location.
-      foreach ($this->_fields as $name => $dontCare) {
-        $fields[$name] = 1;
-      }
-
-      // also add location name to the array
-      $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
-
-      $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
-
-      $fields["address_name-{$this->_bltID}"] = 1;
-
-      $fields["email-{$this->_bltID}"] = 1;
-
-      $nameFields = array('first_name', 'middle_name', 'last_name');
-
-      foreach ($nameFields as $name) {
-        $fields[$name] = 1;
-        if (array_key_exists("billing_$name", $formValues)) {
-          $formValues[$name] = $formValues["billing_{$name}"];
-          $formValues['preserveDBName'] = TRUE;
-        }
-      }
-dpm($fields);
-      //here we are setting up the billing contact - if different from the member they are already created
-      // but they will get billing details assigned
-      CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields,
-        $this->_contributorContactID, NULL, NULL,
-        CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type')
-      );
-
-      // add all the additional payment params we need
-      $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"]
-        = CRM_Core_PseudoConstant::stateProvinceAbbreviation($formValues["billing_state_province_id-{$this->_bltID}"]);
-      $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"]
-        = CRM_Core_PseudoConstant::countryIsoCode($formValues["billing_country_id-{$this->_bltID}"]);
-
-      $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($formValues);
-      $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($formValues);
-      $this->_params['description'] = ts('Office Credit Card Membership Renewal Contribution');
+      $this->assign('credit_card_type', $this->_params['credit_card_type']);
+      $this->_params['description'] = ts("Contribution submitted by a staff person using member's credit card for renewal");
       $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
-      $this->_params['amount'] = $formValues['total_amount'];
-      $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
-      $paymentParams['invoiceID'] = $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
+      $this->_params['amount'] = $this->_params['total_amount'];
 
       // at this point we've created a contact and stored its address etc
       // all the payment processors expect the name and address to be in the passed params
@@ -580,49 +551,38 @@ dpm($fields);
 
       CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
 
-      $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
+      $payment = $this->_paymentProcessor['object'];
 
-      if (!empty($formValues['auto_renew'])) {
+      if (!empty($this->_params['auto_renew'])) {
         $contributionRecurParams = $this->processRecurringContribution($paymentParams);
         $paymentParams = array_merge($paymentParams, $contributionRecurParams);
       }
+
       $result = $payment->doPayment($paymentParams);
+      $this->_params = array_merge($this->_params, $result);
 
-      if ($result) {
-        $this->_params = array_merge($this->_params, $result);
-      }
-      $formValues['contribution_status_id'] = 1;
-      $formValues['invoice_id'] = $this->_params['invoiceID'];
-      $formValues['trxn_id'] = $result['trxn_id'];
-      $formValues['payment_instrument_id'] = 1;
-      $formValues['is_test'] = ($this->_mode == 'live') ? 0 : 1;
+      $this->_params['contribution_status_id'] = $result['payment_status_id'];
+      $this->_params['trxn_id'] = $result['trxn_id'];
+      $this->_params['payment_instrument_id'] = 1;
+      $this->_params['is_test'] = ($this->_mode == 'live') ? 0 : 1;
       $this->set('params', $this->_params);
       $this->assign('trxn_id', $result['trxn_id']);
     }
 
-    $renewalDate = !empty($formValues['renewal_date']) ? $renewalDate = CRM_Utils_Date::processDate($formValues['renewal_date']) : NULL;
-
-    // This set is probably obsolete.
-    $this->set('renewalDate', $renewalDate);
-
-    $this->_membershipId = $this->_id;
-
-    $customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($formValues,
-      $this->_id,
-      'Membership'
-    );
+    $renewalDate = !empty($this->_params['renewal_date']) ? $renewalDate = CRM_Utils_Date::processDate($this->_params['renewal_date']) : NULL;
 
     // check for test membership.
     $isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
 
     // chk for renewal for multiple terms CRM-8750
     $numRenewTerms = 1;
-    if (is_numeric(CRM_Utils_Array::value('num_terms', $formValues))) {
-      $numRenewTerms = $formValues['num_terms'];
+    if (is_numeric(CRM_Utils_Array::value('num_terms', $this->_params))) {
+      $numRenewTerms = $this->_params['num_terms'];
     }
 
     //if contribution status is pending then set pay later
-    if ($formValues['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus())) {
+    $this->_params['is_pay_later'] = FALSE;
+    if ($this->_params['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus())) {
       $this->_params['is_pay_later'] = 1;
     }
 
@@ -633,84 +593,73 @@ dpm($fields);
     if (!empty($this->_params['membership_source'])) {
       $membershipSource = $this->_params['membership_source'];
     }
-    $isPayLater = NULL;
-    if (isset($this->_params)) {
-      $isPayLater = CRM_Utils_Array::value('is_pay_later', $this->_params);
-    }
-    $campaignId = NULL;
-    if (isset($this->_values) && is_array($this->_values) && !empty($this->_values)) {
-      $campaignId = CRM_Utils_Array::value('campaign_id', $this->_params);
-      if (!array_key_exists('campaign_id', $this->_params)) {
-        $campaignId = CRM_Utils_Array::value('campaign_id', $this->_values);
-      }
-    }
+
+    $isPending = ($this->_params['contribution_status_id'] == 2) ? TRUE : FALSE;
 
     list($renewMembership) = CRM_Member_BAO_Membership::renewMembership(
-      $this->_contactID, $formValues['membership_type_id'][1], $isTestMembership,
+      $this->_contactID, $this->_params['membership_type_id'][1], $isTestMembership,
       $renewalDate, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId,
-      self::extractPendingFormValue($this, $formValues['membership_type_id'][1]),
-      $contributionRecurID, $membershipSource, $isPayLater, $campaignId
+      $isPending,
+      $contributionRecurID, $membershipSource, $this->_params['is_pay_later'], CRM_Utils_Array::value('campaign_id',
+      $this->_params)
     );
 
-    $endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
+    $this->endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
 
-    list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::singleton()->get('userID'));
-
-    $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name');
+    $this->membershipTypeName = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id,
+      'name');
 
-    if (!empty($formValues['record_contribution']) || $this->_mode) {
+    if (!empty($this->_params['record_contribution']) || $this->_mode) {
       // set the source
-      $formValues['contribution_source'] = "{$memType} Membership: Offline membership renewal (by {$userName})";
+      $this->_params['contribution_source'] = "{$this->membershipTypeName} Membership: Offline membership renewal (by {$userName})";
 
       //create line items
       $lineItem = array();
 
-      $priceSetId = CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id']);
+      $priceSetId = CRM_Member_BAO_Membership::createLineItems($this, $this->_params['membership_type_id']);
       CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
         $this->_params, $lineItem[$priceSetId]
       );
       //CRM-11529 for quick config backoffice transactions
       //when financial_type_id is passed in form, update the
       //line items with the financial type selected in form
-      if ($submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues)) {
+      if ($submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $this->_params)) {
         foreach ($lineItem[$priceSetId] as &$li) {
           $li['financial_type_id'] = $submittedFinancialType;
         }
       }
-      $formValues['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
+      $this->_params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
       if (!empty($lineItem)) {
-        $formValues['lineItems'] = $lineItem;
-        $formValues['processPriceSet'] = TRUE;
+        $this->_params['lineItems'] = $lineItem;
+        $this->_params['processPriceSet'] = TRUE;
       }
 
       //assign contribution contact id to the field expected by recordMembershipContribution
       if ($this->_contributorContactID != $this->_contactID) {
-        $formValues['contribution_contact_id'] = $this->_contributorContactID;
+        $this->_params['contribution_contact_id'] = $this->_contributorContactID;
         if (!empty($this->_params['soft_credit_type_id'])) {
-          $formValues['soft_credit'] = array(
+          $this->_params['soft_credit'] = array(
             'soft_credit_type_id' => $this->_params['soft_credit_type_id'],
             'contact_id' => $this->_contactID,
           );
         }
       }
-      $formValues['contact_id'] = $this->_contactID;
+      $this->_params['contact_id'] = $this->_contactID;
       //recordMembershipContribution receives params as a reference & adds one variable. This is
       // not a great pattern & ideally it would not receive as a reference. We assign our params as a
       // temporary variable to avoid e-notice & to make it clear to future refactorer that
       // this function is NOT reliant on that var being set
-      $temporaryParams = array_merge($formValues, array('membership_id' => $renewMembership->id));
+      $temporaryParams = array_merge($this->_params, array('membership_id' => $renewMembership->id));
       CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams);
     }
 
-    $receiptSend = FALSE;
-    if (!empty($formValues['send_receipt'])) {
-      $receiptSend = TRUE;
+    if (!empty($this->_params['send_receipt'])) {
 
-      $receiptFrom = $formValues['from_email_address'];
+      $receiptFrom = $this->_params['from_email_address'];
 
-      if (!empty($formValues['payment_instrument_id'])) {
+      if (!empty($this->_params['payment_instrument_id'])) {
         $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
-        $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
+        $this->_params['paidBy'] = $paymentInstrument[$this->_params['payment_instrument_id']];
       }
       //get the group Tree
       $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $this->_id, FALSE, $this->_memType);
@@ -733,20 +682,17 @@ dpm($fields);
       }
       CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
 
-      $this->assign_by_ref('formValues', $formValues);
-      if (!empty($formValues['contribution_id'])) {
-        $this->assign('contributionID', $formValues['contribution_id']);
+      $this->assign_by_ref('formValues', $this->_params);
+      if (!empty($this->_params['contribution_id'])) {
+        $this->assign('contributionID', $this->_params['contribution_id']);
       }
-      $this->assign('membershipID', $this->_id);
-      $this->assign('contactID', $this->_contactID);
-      $this->assign('module', 'Membership');
-      $this->assign('receiptType', 'membership renewal');
-      $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date));
-      $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date));
+
       $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
         $renewMembership->membership_type_id
       ));
       $this->assign('customValues', $customValues);
+      $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date));
+      $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date));
       if ($this->_mode) {
         // assign the address formatted up for display
         $addressParts = array(
@@ -758,19 +704,12 @@ dpm($fields);
         );
         $addressFields = array();
         foreach ($addressParts as $part) {
-          list($n, $id) = explode('-', $part);
+          list($n) = explode('-', $part);
           if (isset($this->_params['billing_' . $part])) {
             $addressFields[$n] = $this->_params['billing_' . $part];
           }
         }
         $this->assign('address', CRM_Utils_Address::format($addressFields));
-        $date = CRM_Utils_Date::format($this->_params['credit_card_exp_date']);
-        $date = CRM_Utils_Date::mysqlToIso($date);
-        $this->assign('credit_card_exp_date', $date);
-        $this->assign('credit_card_number',
-          CRM_Utils_System::mungeCreditCard($this->_params['credit_card_number'])
-        );
-        $this->assign('credit_card_type', $this->_params['credit_card_type']);
         $this->assign('contributeMode', 'direct');
         $this->assign('isAmountzero', 0);
         $this->assign('is_pay_later', 0);
@@ -781,7 +720,7 @@ dpm($fields);
         }
       }
 
-      list($mailSend) = CRM_Core_BAO_MessageTemplate::sendTemplate(
+      list($this->isMailSent) = CRM_Core_BAO_MessageTemplate::sendTemplate(
         array(
           'groupName' => 'msg_tpl_workflow_membership',
           'valueName' => 'membership_offline_receipt',
@@ -793,18 +732,6 @@ dpm($fields);
         )
       );
     }
-
-    $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $memType, 2 => $this->_memberDisplayName));
-
-    if ($endDate) {
-      $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(1 => CRM_Utils_Date::customFormat(substr($endDate, 0, 8))));
-    }
-
-    if ($receiptSend && $mailSend) {
-      $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
-      return $statusMsg;
-    }
-    return $statusMsg;
   }
 
   /**
@@ -814,10 +741,12 @@ dpm($fields);
    */
   public function testSubmit($formValues) {
     $this->_memType = $formValues['membership_type_id'][1];
+    $this->_params = $formValues;
     $this->submit($formValues);
   }
 
   protected function assignBillingName() {
+    $name = '';
     if (!empty($this->_params['billing_first_name'])) {
       $name = $this->_params['billing_first_name'];
     }
@@ -832,4 +761,36 @@ dpm($fields);
     $this->assign('billingName', $name);
   }
 
+  /**
+   * Add the billing address to the contact who paid.
+   */
+  protected function processBillingAddress() {
+    $fields = array();
+
+    // set email for primary location.
+    $fields['email-Primary'] = 1;
+    $this->_params['email-5'] = $this->_params['email-Primary'] = $this->_contributorEmail;
+
+    // also add location name to the array
+    $this->_params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $this->_params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $this->_params) . ' ' . CRM_Utils_Array::value('billing_last_name', $this->_params);
+
+    $this->_params["address_name-{$this->_bltID}"] = trim($this->_params["address_name-{$this->_bltID}"]);
+
+    $fields["address_name-{$this->_bltID}"] = 1;
+    $fields["email-{$this->_bltID}"] = 1;
+
+    list($hasBillingField, $addressParams) = CRM_Contribute_BAO_Contribution::getPaymentProcessorReadyAddressParams($this->_params, $this->_bltID);
+
+    $addressParams['preserveDBName'] = TRUE;
+    if ($hasBillingField) {
+      $addressParams = array_merge($this->_params, $addressParams);
+      //here we are setting up the billing contact - if different from the member they are already created
+      // but they will get billing details assigned
+      CRM_Contact_BAO_Contact::createProfileContact($addressParams, $fields,
+        $this->_contributorContactID, NULL, NULL,
+        CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type')
+      );
+    }
+  }
+
 }