/**
  * @param mixed $level
  * @param string $message
  * @param array $context
  *
  * @return null
  */
 public function log($level, $message, array $context = array())
 {
     if (!isset($context['hostname'])) {
         $context['hostname'] = CRM_Utils_System::ipAddress();
     }
     $rec = new CRM_Core_DAO_SystemLog();
     $separateFields = array('contact_id', 'hostname');
     foreach ($separateFields as $separateField) {
         if (isset($context[$separateField])) {
             $rec->{$separateField} = $context[$separateField];
             unset($context[$separateField]);
         }
     }
     $rec->level = $level;
     $rec->message = $message;
     $rec->context = json_encode($context);
     $rec->save();
 }
 /**
  * Process the renewal form.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     $ids = array();
     $config = CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $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');
     }
     $now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
     $this->convertDateFieldsToMySQL($formValues);
     $this->assign('receive_date', $formValues['receive_date']);
     if (!empty($this->_params['send_receipt'])) {
         $formValues['receipt_date'] = $now;
         $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($formValues['receipt_date']));
     } else {
         $formValues['receipt_date'] = NULL;
     }
     if ($this->_mode) {
         $formValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params, CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee'));
         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'], $this->_mode);
         $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;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $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;
             }
         }
         //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, $ctype);
         // 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($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['description'] = ts('Office Credit Card Membership Renewal Contribution');
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $formValues['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $paymentParams['invoiceID'] = $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         // 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
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         $paymentParams['contactID'] = $this->_contributorContactID;
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
         if (!empty($paymentParams['auto_renew'])) {
             $contributionRecurParams = $this->processRecurringContribution($paymentParams);
             $this->_params['contributionRecurID'] = $contributionRecurParams['contributionRecurID'];
             $paymentParams = array_merge($paymentParams, $contributionRecurParams);
         }
         $result = $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"));
         }
         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->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
     }
     $renewalDate = NULL;
     if ($formValues['renewal_date']) {
         $this->set('renewalDate', CRM_Utils_Date::processDate($formValues['renewal_date']));
     }
     $this->_membershipId = $this->_id;
     // membership type custom data
     $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $formValues['membership_type_id'][1]);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
     $customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     // 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 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'] = 1;
     }
     $renewMembership = CRM_Member_BAO_Membership::renewMembershipFormWrapper($this->_contactID, $formValues['membership_type_id'][1], $isTestMembership, $this, NULL, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId);
     $endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name');
     if (!empty($formValues['record_contribution']) || $this->_mode) {
         // set the source
         $formValues['contribution_source'] = "{$memType} Membership: Offline membership renewal (by {$userName})";
         //create line items
         $lineItem = array();
         $priceSetId = NULL;
         CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
         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)) {
             foreach ($lineItem[$priceSetId] as &$li) {
                 $li['financial_type_id'] = $submittedFinancialType;
             }
         }
         $formValues['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
         if (!empty($lineItem)) {
             $formValues['lineItems'] = $lineItem;
             $formValues['processPriceSet'] = TRUE;
         }
         //assign contribution contact id to the field expected by recordMembershipContribution
         if ($this->_contributorContactID != $this->_contactID) {
             $formValues['contribution_contact_id'] = $this->_contributorContactID;
             if (!empty($this->_params['soft_credit_type_id'])) {
                 $formValues['soft_credit'] = array('soft_credit_type_id' => $this->_params['soft_credit_type_id'], 'contact_id' => $this->_contactID);
             }
         }
         $formValues['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));
         CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams);
     }
     $receiptSend = FALSE;
     if (!empty($formValues['send_receipt'])) {
         $receiptSend = TRUE;
         $receiptFrom = $formValues['from_email_address'];
         if (!empty($formValues['payment_instrument_id'])) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
         }
         //get the group Tree
         $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $this->_id, FALSE, $this->_memType);
         // retrieve custom data
         $customFields = $customValues = $fo = array();
         foreach ($this->_groupTree as $groupID => $group) {
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
         }
         $members = array(array('member_id', '=', $this->_membershipId, 0, 0));
         // check whether its a test drive
         if ($this->_mode == 'test') {
             $members[] = array('member_test', '=', 1, 0, 0);
         }
         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('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);
         if ($this->_mode) {
             if (!empty($this->_params['billing_first_name'])) {
                 $name = $this->_params['billing_first_name'];
             }
             if (!empty($this->_params['billing_middle_name'])) {
                 $name .= " {$this->_params['billing_middle_name']}";
             }
             if (!empty($this->_params['billing_last_name'])) {
                 $name .= " {$this->_params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = 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);
             $this->assign('isPrimary', 1);
             if ($this->_mode == 'test') {
                 $this->assign('action', '1024');
             }
         }
         list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $this->_receiptContactId, 'from' => $receiptFrom, 'toName' => $this->_contributorDisplayName, 'toEmail' => $this->_contributorEmail, 'isTest' => $this->_mode == 'test'));
     }
     $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));
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
 }
 /**
  * Begin post processing.
  *
  * This function aims to start to bring together common postProcessing functions.
  *
  * Eventually these are also shared with the front end forms & may need to be moved to where they can also
  * access this function.
  */
 protected function beginPostProcess()
 {
     if (in_array('credit_card_exp_date', array_keys($this->_params))) {
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
     }
     $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
 }
Example #4
0
 /**
  * Process the form submission.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Member_BAO_Membership::del($this->_id);
         return;
     }
     $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus();
     $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
     $isTest = $this->_mode == 'test' ? 1 : 0;
     $lineItems = NULL;
     if (!empty($this->_lineItem)) {
         $lineItems = $this->_lineItem;
     }
     $config = CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $this->convertDateFieldsToMySQL($formValues);
     $params = $softParams = $ids = array();
     $membershipTypeValues = array();
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypeValues[$memType]['membership_type_id'] = $memType;
     }
     //take the required membership recur values.
     if ($this->_mode && !empty($this->_params['auto_renew'])) {
         $params['is_recur'] = $this->_params['is_recur'] = $formValues['is_recur'] = TRUE;
         $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit');
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array());
             foreach ($mapping as $mapVal => $mapParam) {
                 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 if (!$count) {
                     $this->_params[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 }
             }
             $count++;
         }
     }
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = NULL;
     if (!($priceSetId = CRM_Utils_Array::value('price_set_id', $formValues))) {
         CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     $termsByType = array();
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$priceSetId]);
         if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
             $params['tax_amount'] = $this->_params['tax_amount'];
         }
         $params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
         $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
         if (!empty($lineItem[$priceSetId])) {
             foreach ($lineItem[$priceSetId] as &$li) {
                 if (!empty($li['membership_type_id'])) {
                     if (!empty($li['membership_num_terms'])) {
                         $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
                     }
                 }
                 ///CRM-11529 for quick config backoffice transactions
                 //when financial_type_id is passed in form, update the
                 //lineitems with the financial type selected in form
                 if ($isQuickConfig && $submittedFinancialType) {
                     $li['financial_type_id'] = $submittedFinancialType;
                 }
             }
         }
     }
     $this->storeContactFields($formValues);
     $params['contact_id'] = $this->_contactID;
     $fields = array('status_id', 'source', 'is_override', 'campaign_id');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (empty($params['is_override'])) {
         $params['exclude_is_admin'] = TRUE;
     }
     // process date params to mysql date format.
     $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
     foreach ($dateTypes as $dateField => $dateVariable) {
         ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]);
     }
     $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
     $calcDates = array();
     foreach ($this->_memTypeSelected as $memType) {
         if (empty($memTypeNumTerms)) {
             $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
         }
         $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate, $memTypeNumTerms);
     }
     foreach ($calcDates as $memType => $calcDate) {
         foreach (array_keys($dateTypes) as $d) {
             //first give priority to form values then calDates.
             $date = CRM_Utils_Array::value($d, $formValues);
             if (!$date) {
                 $date = CRM_Utils_Array::value($d, $calcDate);
             }
             $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
             //$params[$d] = CRM_Utils_Date::processDate( $date );
         }
     }
     // max related memberships - take from form or inherit from membership type
     foreach ($this->_memTypeSelected as $memType) {
         if (array_key_exists('max_related', $formValues)) {
             $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
         }
     }
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $session = CRM_Core_Session::singleton();
     $ids['userId'] = $session->get('userID');
     // membership type custom data
     foreach ($this->_memTypeSelected as $memType) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $memType);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
         $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     }
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType);
     }
     $membershipType = implode(', ', $membershipTypes);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     //CRM-13981, allow different person as a soft-contributor of chosen type
     if ($this->_contributorContactID != $this->_contactID) {
         $params['contribution_contact_id'] = $this->_contributorContactID;
         if (!empty($this->_params['soft_credit_type_id'])) {
             $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
             $softParams['contact_id'] = $this->_contactID;
         }
     }
     if (!empty($formValues['record_contribution'])) {
         $recordContribution = array('total_amount', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!$this->_onlinePendingContributionId) {
             if (empty($formValues['source'])) {
                 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
             } else {
                 $params['contribution_source'] = $formValues['source'];
             }
         }
         if (empty($params['is_override']) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             $params['is_pay_later'] = 1;
             $this->assign('is_pay_later', 1);
         }
         if (!empty($formValues['send_receipt'])) {
             $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
         }
         //insert financial type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $formValues['financial_type_id']);
     }
     // process line items, until no previous line items.
     if (!empty($lineItem)) {
         $params['lineItems'] = $lineItem;
         $params['processPriceSet'] = TRUE;
     }
     $createdMemberships = array();
     if ($this->_mode) {
         if (empty($formValues['total_amount']) && !$priceSetId) {
             // if total amount not provided minimum for membership type is used
             $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1], 'minimum_fee');
         } else {
             $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
         }
         if ($priceSetId && !$isQuickConfig) {
             $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'financial_type_id');
         } else {
             $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
         }
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail;
         $params['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;
         //ensure we don't over-write the payer's email with the member's email
         if ($this->_contributorContactID == $this->_contactID) {
             $fields["email-{$this->_bltID}"] = 1;
         }
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $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;
             }
         }
         if ($this->_contributorContactID == $this->_contactID) {
             //see CRM-12869 for discussion of why we don't do this for separate payee payments
             CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, $ctype);
         }
         // 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($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['description'] = ts('Office Credit Card Membership Signup Contribution');
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         $this->_params['financial_type_id'] = $params['financial_type_id'];
         // 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
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         $paymentParams['contactID'] = $this->_contributorContactID;
         //CRM-10377 if payment is by an alternate contact then we need to set that person
         // as the contact in the payment params
         if ($this->_contributorContactID != $this->_contactID) {
             if (!empty($this->_params['soft_credit_type_id'])) {
                 $softParams['contact_id'] = $params['contact_id'];
                 $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
             }
         }
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         // CRM-7137 -for recurring membership,
         // we do need contribution and recuring records.
         $result = NULL;
         if (!empty($paymentParams['is_recur'])) {
             $contributionType = new CRM_Financial_DAO_FinancialType();
             $contributionType->id = $params['financial_type_id'];
             if (!$contributionType->find(TRUE)) {
                 CRM_Core_Error::fatal('Could not find a system table');
             }
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $paymentParams, $result, $this->_contributorContactID, $contributionType, TRUE, FALSE, $isTest, $lineItems);
             //create new soft-credit record, CRM-13981
             if ($softParams) {
                 $softParams['contribution_id'] = $contribution->id;
                 $softParams['currency'] = $contribution->currency;
                 $softParams['amount'] = $contribution->total_amount;
                 CRM_Contribute_BAO_ContributionSoft::add($softParams);
             }
             $paymentParams['contactID'] = $this->_contactID;
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             $ids['contribution'] = $contribution->id;
             $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
         }
         if ($params['total_amount'] > 0.0) {
             $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
             $result = $payment->doDirectPayment($paymentParams);
         }
         if (is_a($result, 'CRM_Core_Error')) {
             //make sure to cleanup db for recurring case.
             if (!empty($paymentParams['contributionID'])) {
                 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
             }
             if (!empty($paymentParams['contributionRecurID'])) {
                 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
             //assign amount to template if payment was successful
             $this->assign('amount', $params['total_amount']);
         }
         // if the payment processor returns a contribution_status_id -> use it!
         if (isset($result['contribution_status_id'])) {
             $result['payment_status_id'] = $result['contribution_status_id'];
         }
         if (isset($result['payment_status_id'])) {
             // CRM-16737 $result['contribution_status_id'] is deprecated in favour
             // of payment_status_id as the payment processor only knows whether the payment is complete
             // not whether payment completes the contribution
             $params['contribution_status_id'] = $result['payment_status_id'];
         } else {
             $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ? 2 : 1;
         }
         if ($params['contribution_status_id'] != array_search('Completed', $allContributionStatus)) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             // unset send-receipt option, since receipt will be sent when ipn is received.
             unset($this->_params['send_receipt'], $formValues['send_receipt']);
             //as membership is pending set dates to null.
             $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
             foreach ($memberDates as $dp => $dv) {
                 ${$dv} = NULL;
                 foreach ($this->_memTypeSelected as $memType) {
                     $membershipTypeValues[$memType][$dv] = NULL;
                 }
             }
         }
         $params['receive_date'] = $now;
         $params['invoice_id'] = $this->_params['invoiceID'];
         $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName));
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (!empty($this->_params['send_receipt'])) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         //create membership record.
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
             }
             $membershipParams = array_merge($membershipTypeValues[$memType], $params);
             //CRM-15366
             if (!empty($softParams) && empty($paymentParams['is_recur'])) {
                 $membershipParams['soft_credit'] = $softParams;
             }
             if (!empty($paymentParams['is_recur']) && CRM_Utils_Array::value('payment_status_id', $result) == 1) {
                 // CRM-16993 we have a situation where line items have already been created.
                 unset($membershipParams['lineItems']);
             }
             $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
             $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
             unset($params['lineItems']);
             $this->_membershipIDs[] = $membership->id;
             $createdMemberships[$memType] = $membership;
             $count++;
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
             // update membership as well as contribution object, CRM-4395
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
             if (!empty($result) && !empty($params['contribution_id'])) {
                 $lineItem = array();
                 $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
                 $itemId = key($lineItems);
                 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
                 $fieldType = NULL;
                 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
                     $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
                 }
                 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
                 $lineItems[$itemId]['line_total'] = $params['total_amount'];
                 $lineItems[$itemId]['id'] = $itemId;
                 $lineItem[$priceSetId] = $lineItems;
                 $contributionBAO = new CRM_Contribute_BAO_Contribution();
                 $contributionBAO->id = $params['contribution_id'];
                 $contributionBAO->contact_id = $params['contact_id'];
                 $contributionBAO->find();
                 CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
                 //create new soft-credit record, CRM-13981
                 if ($softParams) {
                     $softParams['contribution_id'] = $params['contribution_id'];
                     while ($contributionBAO->fetch()) {
                         $softParams['currency'] = $contributionBAO->currency;
                         $softParams['amount'] = $contributionBAO->total_amount;
                     }
                     CRM_Contribute_BAO_ContributionSoft::add($softParams);
                 }
             }
             //carry updated membership object.
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(TRUE);
             $cancelled = TRUE;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 if (!in_array($membership->status_id, array(array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), array_search('Expired', CRM_Member_PseudoConstant::membershipStatus())))) {
                     $cancelled = FALSE;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
             // FIX ME: need to recheck this
             // here we might updated dates, so get from object.
             foreach ($calcDates[$membership->membership_type_id] as $date => &$val) {
                 if ($membership->{$date}) {
                     $val = $membership->{$date};
                 }
             }
             $createdMemberships[] = $membership;
         } else {
             $count = 0;
             foreach ($this->_memTypeSelected as $memType) {
                 if ($count && !empty($formValues['record_contribution']) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                     $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
                 }
                 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
                 if (!empty($formValues['int_amount'])) {
                     $init_amount = array();
                     foreach ($formValues as $key => $value) {
                         if (strstr($key, 'txt-price')) {
                             $init_amount[$key] = $value;
                         }
                     }
                     $membershipParams['init_amount'] = $init_amount;
                 }
                 if (!empty($softParams)) {
                     $membershipParams['soft_credit'] = $softParams;
                 }
                 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
                 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
                 unset($params['lineItems']);
                 $this->_membershipIDs[] = $membership->id;
                 $createdMemberships[$memType] = $membership;
                 $count++;
             }
         }
     }
     if (!empty($lineItem[$priceSetId])) {
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         $taxAmount = FALSE;
         $totalTaxAmount = 0;
         foreach ($lineItem[$priceSetId] as &$priceFieldOp) {
             if (!empty($priceFieldOp['membership_type_id'])) {
                 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-';
                 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-';
             } else {
                 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
             }
             if ($invoicing && isset($priceFieldOp['tax_amount'])) {
                 $taxAmount = TRUE;
                 $totalTaxAmount += $priceFieldOp['tax_amount'];
             }
         }
         if ($invoicing) {
             $dataArray = array();
             foreach ($lineItem[$priceSetId] as $key => $value) {
                 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
                     if (isset($dataArray[$value['tax_rate']])) {
                         $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                     } else {
                         $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                     }
                 }
             }
             if ($taxAmount) {
                 $this->assign('totalTaxAmount', $totalTaxAmount);
                 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
             }
             $this->assign('dataArray', $dataArray);
         }
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $receiptSend = FALSE;
     $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
     $membershipIds = $this->_membershipIDs;
     if ($contributionId && !empty($membershipIds)) {
         $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
         if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') {
             $receiptSend = TRUE;
         }
     }
     if (!empty($formValues['send_receipt']) && $receiptSend) {
         $formValues['contact_id'] = $this->_contactID;
         $formValues['contribution_id'] = $contributionId;
         // send email receipt
         $mailSend = self::emailReceipt($this, $formValues, $membership);
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         //end date can be modified by hooks, so if end date is set then use it.
         $endDate = $membership->end_date ? $membership->end_date : $endDate;
         $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName));
         if ($endDate && $endDate !== 'null') {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend) {
             $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         // FIX ME: fix status messages
         $statusMsg = array();
         foreach ($membershipTypes as $memType => $membershipType) {
             $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(1 => $membershipType, 2 => $this->_memberDisplayName));
             $membership = $createdMemberships[$memType];
             $memEndDate = $membership->end_date ? $membership->end_date : $endDate;
             //get the end date from calculated dates.
             if (!$memEndDate && empty($params['is_recur'])) {
                 $memEndDate = CRM_Utils_Array::value('end_date', $calcDates[$memType]);
             }
             if ($memEndDate && $memEndDate !== 'null') {
                 $memEndDate = CRM_Utils_Date::customFormat($memEndDate);
                 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
             }
         }
         $statusMsg = implode('<br/>', $statusMsg);
         if ($receiptSend && !empty($mailSend)) {
             $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     }
     // finally set membership id if already not set
     if (!$this->_id) {
         $this->_id = $membership->id;
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=member"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&context=membership&cid={$this->_contactID}"));
     }
 }
Example #5
0
 /**
  * Set variables up before form is built.
  */
 public function preProcess()
 {
     $config = CRM_Core_Config::singleton();
     parent::preProcess();
     // lineItem isn't set until Register postProcess
     $this->_lineItem = $this->get('lineItem');
     $this->_paymentProcessor = $this->get('paymentProcessor');
     $this->_params = $this->controller->exportValues('Main');
     $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
     $this->_params['amount'] = $this->get('amount');
     if (isset($this->_params['amount'])) {
         $this->setFormAmountFields($this->_params['priceSetId']);
     }
     $this->_params['tax_amount'] = $this->get('tax_amount');
     $this->_useForMember = $this->get('useForMember');
     if (isset($this->_params['credit_card_exp_date'])) {
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
     }
     $this->_params['currencyID'] = $config->defaultCurrency;
     if (!empty($this->_membershipBlock)) {
         $this->_params['selectMembership'] = $this->get('selectMembership');
     }
     if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) {
         $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
         $this->_params = array_merge($this->_params, $preApprovalParams);
     }
     // We may have fetched some billing details from the getPreApprovalDetails function so we
     // want to ensure we set this after that function has been called.
     CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $this->_params, FALSE);
     $this->_params['is_pay_later'] = $this->get('is_pay_later');
     $this->assign('is_pay_later', $this->_params['is_pay_later']);
     if ($this->_params['is_pay_later']) {
         $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
     }
     // if onbehalf-of-organization
     if (!empty($this->_values['onbehalf_profile_id']) && !empty($this->_params['onbehalf']['organization_name'])) {
         // CRM-15182
         $this->_params['organization_id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_params['onbehalf']['organization_name'], 'id', 'display_name');
         $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name'];
         $addressBlocks = array('street_address', 'city', 'state_province', 'postal_code', 'country', 'supplemental_address_1', 'supplemental_address_2', 'supplemental_address_3', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'address_name');
         $blocks = array('email', 'phone', 'im', 'url', 'openid');
         foreach ($this->_params['onbehalf'] as $loc => $value) {
             $field = $typeId = NULL;
             if (strstr($loc, '-')) {
                 list($field, $locType) = explode('-', $loc);
             }
             if (in_array($field, $addressBlocks)) {
                 if ($locType == 'Primary') {
                     $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
                     $locType = $defaultLocationType->id;
                 }
                 if ($field == 'country') {
                     $value = CRM_Core_PseudoConstant::countryIsoCode($value);
                 } elseif ($field == 'state_province') {
                     $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
                 }
                 $isPrimary = 1;
                 if (isset($this->_params['onbehalf_location']['address']) && count($this->_params['onbehalf_location']['address']) > 0) {
                     $isPrimary = 0;
                 }
                 $this->_params['onbehalf_location']['address'][$locType][$field] = $value;
                 if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) {
                     $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
                 }
                 $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
             } elseif (in_array($field, $blocks)) {
                 if (!$typeId || is_numeric($typeId)) {
                     $blockName = $fieldName = $field;
                     $locationType = 'location_type_id';
                     if ($locType == 'Primary') {
                         $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
                         $locationValue = $defaultLocationType->id;
                     } else {
                         $locationValue = $locType;
                     }
                     $locTypeId = '';
                     $phoneExtField = array();
                     if ($field == 'url') {
                         $blockName = 'website';
                         $locationType = 'website_type_id';
                         list($field, $locationValue) = explode('-', $loc);
                     } elseif ($field == 'im') {
                         $fieldName = 'name';
                         $locTypeId = 'provider_id';
                         $typeId = $this->_params['onbehalf']["{$loc}-provider_id"];
                     } elseif ($field == 'phone') {
                         list($field, $locType, $typeId) = explode('-', $loc);
                         $locTypeId = 'phone_type_id';
                         //check if extension field exists
                         $extField = str_replace('phone', 'phone_ext', $loc);
                         if (isset($this->_params['onbehalf'][$extField])) {
                             $phoneExtField = array('phone_ext' => $this->_params['onbehalf'][$extField]);
                         }
                     }
                     $isPrimary = 1;
                     if (isset($this->_params['onbehalf_location'][$blockName]) && count($this->_params['onbehalf_location'][$blockName]) > 0) {
                         $isPrimary = 0;
                     }
                     if ($locationValue) {
                         $blockValues = array($fieldName => $value, $locationType => $locationValue, 'is_primary' => $isPrimary);
                         if ($locTypeId) {
                             $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
                         }
                         if (!empty($phoneExtField)) {
                             $blockValues = array_merge($blockValues, $phoneExtField);
                         }
                         $this->_params['onbehalf_location'][$blockName][] = $blockValues;
                     }
                 }
             } elseif (strstr($loc, 'custom')) {
                 if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) {
                     $value = $this->_params['onbehalf']["{$loc}_id"];
                 }
                 $this->_params['onbehalf_location']["{$loc}"] = $value;
             } else {
                 if ($loc == 'contact_sub_type') {
                     $this->_params['onbehalf_location'][$loc] = $value;
                 } else {
                     $this->_params['onbehalf_location'][$field] = $value;
                 }
             }
         }
     } elseif (!empty($this->_values['is_for_organization'])) {
         // no on behalf of an organization, CRM-5519
         // so reset loc blocks from main params.
         foreach (array('phone', 'email', 'address') as $blk) {
             if (isset($this->_params[$blk])) {
                 unset($this->_params[$blk]);
             }
         }
     }
     $this->setRecurringMembershipParams();
     if ($this->_pcpId) {
         $params = $this->processPcp($this, $this->_params);
         $this->_params = $params;
     }
     $this->_params['invoiceID'] = $this->get('invoiceID');
     //carry campaign from profile.
     if (array_key_exists('contribution_campaign_id', $this->_params)) {
         $this->_params['campaign_id'] = $this->_params['contribution_campaign_id'];
     }
     // assign contribution page id to the template so we can add css class for it
     $this->assign('contributionPageID', $this->_id);
     $this->set('params', $this->_params);
 }
Example #6
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once "CRM/Event/BAO/Participant.php";
         CRM_Event_BAO_Participant::deleteParticipant($this->_participantId);
         return;
     }
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $params)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $params);
     }
     $config =& CRM_Core_Config::singleton();
     //check if discount is selected
     if (CRM_Utils_Array::value('discount_id', $params)) {
         $discountId = $params['discount_id'];
     } else {
         $params['discount_id'] = 'null';
         $discountId = null;
     }
     if ($this->_isPaidEvent) {
         //lets carry currency, CRM-4453
         $params['fee_currency'] = $config->defaultCurrency;
         // fix for CRM-3088
         if ($discountId && !empty($this->_values['discount'][$discountId])) {
             $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
             $this->assign('amount_level', $params['amount_level']);
         } else {
             if (!isset($params['priceSetId'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
                 $this->assign('amount_level', $params['amount_level']);
             } else {
                 if (!$this->_online) {
                     $lineItem = array();
                     CRM_Price_BAO_Set::processAmount($this->_values['fee']['fields'], $params, $lineItem[0]);
                     $this->set('lineItem', $lineItem);
                     $this->assign('lineItem', $lineItem);
                     $this->_lineItem = $lineItem;
                 }
             }
         }
         $params['fee_level'] = $params['amount_level'];
         $contributionParams = array();
         $contributionParams['total_amount'] = $params['amount'];
     }
     //fix for CRM-3086
     $params['fee_amount'] = $params['amount'];
     $this->_params = $params;
     unset($params['amount']);
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params));
     $params['contact_id'] = $this->_contactID;
     if ($this->_participantId) {
         $params['id'] = $this->_participantId;
     }
     $status = null;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $participantBAO =& new CRM_Event_BAO_Participant();
         $participantBAO->id = $this->_participantId;
         $participantBAO->find();
         while ($participantBAO->fetch()) {
             $status = $participantBAO->status_id;
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
         }
         $params['discount_id'] = null;
         //re-enter the values for UPDATE mode
         $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
         $params['fee_amount'] = $participantBAO->fee_amount;
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session =& CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     require_once "CRM/Event/BAO/Participant.php";
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         //modify params according to parameter used in create
         //participant method (addParticipant)
         $params['participant_status_id'] = $params['status_id'];
         $params['participant_role_id'] = $params['role_id'];
         $params['participant_register_date'] = $params['register_date'];
         $params['participant_source'] = $params['source'];
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $params["email-Primary"] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['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
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = true;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, null, null, $ctype);
     }
     // build custom data getFields array
     $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('role_id', $params), $this->_roleCustomDataTypeID);
     $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', false, false, null, null, true));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_participantId, 'Participant');
     if ($this->_mode) {
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // 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
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactID}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         // set source if not set
         $this->_params['description'] = ts('Submit Credit Card for Event Registration by: %1', array(1 => $userName));
         require_once 'CRM/Event/Form/Registration/Confirm.php';
         require_once 'CRM/Event/Form/Registration.php';
         //add contribution record
         $this->_params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'contribution_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution reocord
         $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, false);
         // add participant record
         $participants = array();
         $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID);
         //add custom data for participant
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         require_once 'CRM/Event/BAO/ParticipantPayment.php';
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         $this->_contactIds[] = $this->_contactID;
     } else {
         $participants = array();
         // fix note if deleted
         if (!$params['note']) {
             $params['note'] = 'null';
         }
         if ($this->_single) {
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactID;
         }
         if (CRM_Utils_Array::value('record_contribution', $params)) {
             if (CRM_Utils_Array::value('id', $params)) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})";
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert contribution type name in receipt.
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contributionParams['contribution_type_id']));
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $contributions = array();
             if ($this->_single) {
                 $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (!$ids['contribution']) {
                 require_once 'CRM/Event/DAO/ParticipantPayment.php';
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO =& new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem) {
         require_once 'CRM/Price/BAO/LineItem.php';
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $line) {
                         $line['entity_table'] = 'civicrm_participant';
                         $line['entity_id'] = $participants[$num]->id;
                         CRM_Price_BAO_LineItem::create($line);
                     }
                 }
             }
         }
     }
     $updateStatusMsg = null;
     //send mail when participant status changed, CRM-4326
     if ($this->_participantId && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && CRM_Utils_Array::value('is_notify', $params)) {
         require_once "CRM/Event/BAO/Participant.php";
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_participantId, $params['status_id'], $this->_statusId);
     }
     if (CRM_Utils_Array::value('send_receipt', $params)) {
         $receiptFrom = "{$userName} <{$userEmail}>";
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $event['participant_role'] = $role[$params['role_id']];
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             require_once 'CRM/Core/BAO/Location.php';
             $location = CRM_Core_BAO_Location::getValues($locationParams, true);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $params)) {
                 $name = $params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $params)) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $params)) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($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($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (CRM_Utils_Array::value('is_test', $this->_defaultValues)) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template =& CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customValue = array('data' => $fieldValue['value']);
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID]);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $eventAmount[$num] = array('label' => $params['amount_level'], 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues));
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
             }
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($params['send_receipt'] && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (CRM_Utils_Array::value('send_receipt', $params) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     require_once "CRM/Core/Session.php";
     CRM_Core_Session::setStatus("{$statusMsg}");
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=participant"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context=participant&cid={$this->_contactID}"));
         }
     }
 }
 /**
  * @param $submittedValues
  */
 public function processCreditCard($submittedValues)
 {
     $config = CRM_Core_Config::singleton();
     $session = CRM_Core_Session::singleton();
     $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id');
     foreach ($unsetParams as $key) {
         if (isset($submittedValues[$key])) {
             unset($submittedValues[$key]);
         }
     }
     // Get the required fields value only.
     $params = $this->_params = $submittedValues;
     //get the payment processor id as per mode.
     //@todo unclear relevance of mode - seems like a lot of duplicated params here!
     $this->_params['payment_processor'] = $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
     $now = date('YmdHis');
     $fields = array();
     // we need to retrieve email address
     if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
         list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
         $this->assign('displayName', $this->userDisplayName);
     }
     //set email for primary location.
     $fields['email-Primary'] = 1;
     $params['email-Primary'] = $this->_contributorEmail;
     // now set the values for the billing location.
     foreach ($this->_fields as $name => $dontCare) {
         $fields[$name] = 1;
     }
     // also add location name to the array
     $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
     $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
     $fields["address_name-{$this->_bltID}"] = 1;
     $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
     $nameFields = array('first_name', 'middle_name', 'last_name');
     foreach ($nameFields as $name) {
         $fields[$name] = 1;
         if (array_key_exists("billing_{$name}", $params)) {
             $params[$name] = $params["billing_{$name}"];
             $params['preserveDBName'] = TRUE;
         }
     }
     if (!empty($params['source'])) {
         unset($params['source']);
     }
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     // 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($this->_params["billing_state_province_id-{$this->_bltID}"]);
     $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
     if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
     }
     $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
     $this->_params['amount'] = $this->_params['total_amount'];
     // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
     // function to get correct amount level consistently. Remove setting of the amount level in
     // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
     // to cover all variants.
     $this->_params['amount_level'] = 0;
     $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, $config->defaultCurrency);
     if (!empty($this->_params['trxn_date'])) {
         $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['trxn_date'], $this->_params['trxn_date_time']);
     }
     if (empty($this->_params['invoice_id'])) {
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
     } else {
         $this->_params['invoiceID'] = $this->_params['invoice_id'];
     }
     $this->assignBillingName($params);
     $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters($params, $this->_bltID));
     $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
     $date = CRM_Utils_Date::mysqlToIso($date);
     $this->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $params));
     $this->assign('credit_card_exp_date', $date);
     $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
     //Add common data to formatted params
     CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
     // 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
     // so we copy stuff over to first_name etc.
     $paymentParams = $this->_params;
     $paymentParams['contactID'] = $this->_contactId;
     CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
     // add some financial type details to the params list
     // if folks need to use it
     $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
     $paymentParams['contributionPageID'] = NULL;
     if (!empty($this->_params['is_email_receipt'])) {
         $paymentParams['email'] = $this->_contributorEmail;
         $paymentParams['is_email_receipt'] = 1;
     } else {
         $paymentParams['is_email_receipt'] = 0;
         $this->_params['is_email_receipt'] = 0;
     }
     if (!empty($this->_params['receive_date'])) {
         $paymentParams['receive_date'] = $this->_params['receive_date'];
     }
     if (!empty($this->_params['receive_date'])) {
         $paymentParams['receive_date'] = $this->_params['receive_date'];
     }
     $result = NULL;
     if ($paymentParams['amount'] > 0.0) {
         try {
             // force a reget of the payment processor in case the form changed it, CRM-7179
             $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
             $result = $payment->doPayment($paymentParams);
         } catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
             //set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactId}&id={$this->_id}&component={$this->_component}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/payment/add', $urlParams));
         }
     }
     if ($result) {
         $this->_params = array_merge($this->_params, $result);
     }
     if (empty($this->_params['receive_date'])) {
         $this->_params['receive_date'] = $now;
     }
     $this->set('params', $this->_params);
     // set source if not set
     if (empty($this->_params['source'])) {
         $userID = $session->get('userID');
         $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
         $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
     }
     // process the additional payment
     $participantId = NULL;
     if ($this->_component == 'event') {
         $participantId = $this->_id;
     }
     $trxnRecord = CRM_Contribute_BAO_Contribution::recordAdditionalPayment($this->_contributionId, $submittedValues, $this->_paymentType, $participantId);
     if ($trxnRecord->id && !empty($this->_params['is_email_receipt'])) {
         $sendReceipt = $this->emailReceipt($this->_params);
     }
     if ($trxnRecord->id) {
         $statusMsg = ts('The payment record has been processed.');
         if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
     }
 }
Example #8
0
 /**
  * Set variables up before form is built.
  */
 public function preProcess()
 {
     parent::preProcess();
     // lineItem isn't set until Register postProcess
     $this->_lineItem = $this->get('lineItem');
     $this->_params = $this->get('params');
     $this->_params[0]['tax_amount'] = $this->get('tax_amount');
     $this->_params[0]['is_pay_later'] = $this->get('is_pay_later');
     $this->assign('is_pay_later', $this->_params[0]['is_pay_later']);
     if ($this->_params[0]['is_pay_later']) {
         $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
     }
     CRM_Utils_Hook::eventDiscount($this, $this->_params);
     if (!empty($this->_params[0]['discount']) && !empty($this->_params[0]['discount']['applied'])) {
         $this->set('hookDiscount', $this->_params[0]['discount']);
         $this->assign('hookDiscount', $this->_params[0]['discount']);
     }
     // The concept of contributeMode is deprecated.
     if ($this->_contributeMode == 'express') {
         $params = array();
         // rfp == redirect from paypal
         // rfp is probably not required - the getPreApprovalDetails should deal with any payment-processor specific 'stuff'
         $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET');
         //we lost rfp in case of additional participant. So set it explicitly.
         if ($rfp || CRM_Utils_Array::value('additional_participants', $this->_params[0], FALSE)) {
             if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) {
                 $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
                 $params = array_merge($this->_params, $preApprovalParams);
             }
             CRM_Core_Payment_Form::mapParams($this->_bltID, $params, $params, FALSE);
             // set a few other parameters that are not really specific to this method because we don't know what
             // will break if we change this.
             $params['amount'] = $this->_params[0]['amount'];
             if (!empty($this->_params[0]['discount'])) {
                 $params['discount'] = $this->_params[0]['discount'];
                 $params['discountAmount'] = $this->_params[0]['discountAmount'];
                 $params['discountMessage'] = $this->_params[0]['discountMessage'];
             }
             $params['amount_level'] = $this->_params[0]['amount_level'];
             $params['currencyID'] = $this->_params[0]['currencyID'];
             // also merge all the other values from the profile fields
             $values = $this->controller->exportValues('Register');
             $skipFields = array('amount', "street_address-{$this->_bltID}", "city-{$this->_bltID}", "state_province_id-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}");
             foreach ($values as $name => $value) {
                 // skip amount field
                 if (!in_array($name, $skipFields)) {
                     $params[$name] = $value;
                 }
                 if (substr($name, 0, 6) == 'price_') {
                     $params[$name] = $this->_params[0][$name];
                 }
             }
             $this->set('getExpressCheckoutDetails', $params);
         }
         $this->_params[0] = array_merge($this->_params[0], $params);
         $this->_params[0]['is_primary'] = 1;
     } else {
         //process only primary participant params.
         $registerParams = $this->_params[0];
         if (isset($registerParams["billing_state_province_id-{$this->_bltID}"]) && $registerParams["billing_state_province_id-{$this->_bltID}"]) {
             $registerParams["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($registerParams["billing_state_province_id-{$this->_bltID}"]);
         }
         if (isset($registerParams["billing_country_id-{$this->_bltID}"]) && $registerParams["billing_country_id-{$this->_bltID}"]) {
             $registerParams["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($registerParams["billing_country_id-{$this->_bltID}"]);
         }
         if (isset($registerParams['credit_card_exp_date'])) {
             $registerParams['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($registerParams);
             $registerParams['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($registerParams);
         }
         if ($this->_values['event']['is_monetary']) {
             $registerParams['ip_address'] = CRM_Utils_System::ipAddress();
             $registerParams['currencyID'] = $this->_params[0]['currencyID'];
         }
         //assign back primary participant params.
         $this->_params[0] = $registerParams;
     }
     if ($this->_values['event']['is_monetary']) {
         $this->_params[0]['invoiceID'] = $this->get('invoiceID');
     }
     $this->assign('defaultRole', FALSE);
     if (CRM_Utils_Array::value('defaultRole', $this->_params[0]) == 1) {
         $this->assign('defaultRole', TRUE);
     }
     if (empty($this->_params[0]['participant_role_id']) && $this->_values['event']['default_role_id']) {
         $this->_params[0]['participant_role_id'] = $this->_values['event']['default_role_id'];
     }
     if (isset($this->_values['event']['confirm_title'])) {
         CRM_Utils_System::setTitle($this->_values['event']['confirm_title']);
     }
     if ($this->_pcpId) {
         $params = CRM_Contribute_Form_Contribution_Confirm::processPcp($this, $this->_params[0]);
         $this->_params[0] = $params;
     }
     $this->set('params', $this->_params);
 }
Example #9
0
 /** 
  * Function to set variables up before form is built 
  *                                                           
  * @return void 
  * @access public 
  */
 function preProcess()
 {
     parent::preProcess();
     // lineItem isn't set until Register postProcess
     $this->_lineItem = $this->get('lineItem');
     $this->_params = $this->get('params');
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::eventDiscount($this, $this->_params);
     if (CRM_Utils_Array::value('discount', $this->_params[0]) && CRM_Utils_Array::value('applied', $this->_params[0]['discount'])) {
         $this->set('hookDiscount', $this->_params[0]['discount']);
         $this->assign('hookDiscount', $this->_params[0]['discount']);
     }
     $config =& CRM_Core_Config::singleton();
     if ($this->_contributeMode == 'express') {
         $params = array();
         // rfp == redirect from paypal
         $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean', CRM_Core_DAO::$_nullObject, false, null, 'GET');
         //we lost rfp in case of additional participant. So set it explicitly.
         if ($rfp || CRM_Utils_Array::value('additional_participants', $this->_params[0], false)) {
             require_once 'CRM/Core/Payment.php';
             $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
             $expressParams = $payment->getExpressCheckoutDetails($this->get('token'));
             $params['payer'] = $expressParams['payer'];
             $params['payer_id'] = $expressParams['payer_id'];
             $params['payer_status'] = $expressParams['payer_status'];
             require_once 'CRM/Core/Payment/Form.php';
             CRM_Core_Payment_Form::mapParams($this->_bltID, $expressParams, $params, false);
             // fix state and country id if present
             if (isset($params["billing_state_province_id-{$this->_bltID}"])) {
                 $params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["billing_state_province_id-{$this->_bltID}"]);
             }
             if (isset($params['billing_country_id'])) {
                 $params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["billing_country_id-{$this->_bltID}"]);
             }
             // set a few other parameters for PayPal
             $params['token'] = $this->get('token');
             $params['amount'] = $this->_params[0]['amount'];
             if (CRM_Utils_Array::value('discount', $this->_params[0])) {
                 $params['discount'] = $this->_params[0]['discount'];
                 $params['discountAmount'] = $this->_params[0]['discountAmount'];
                 $params['discountMessage'] = $this->_params[0]['discountMessage'];
             }
             $params['amount_level'] = $this->_params[0]['amount_level'];
             $params['currencyID'] = $this->_params[0]['currencyID'];
             $params['payment_action'] = 'Sale';
             // also merge all the other values from the profile fields
             $values = $this->controller->exportValues('Register');
             $skipFields = array('amount', "street_address-{$this->_bltID}", "city-{$this->_bltID}", "state_province_id-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}");
             foreach ($values as $name => $value) {
                 // skip amount field
                 if (!in_array($name, $skipFields)) {
                     $params[$name] = $value;
                 }
             }
             $this->set('getExpressCheckoutDetails', $params);
         } else {
             $params = $this->get('getExpressCheckoutDetails');
         }
         $this->_params[0] = $params;
         $this->_params[0]['is_primary'] = 1;
     } else {
         //process only primary participant params.
         $registerParams = $this->_params[0];
         if (isset($registerParams["billing_state_province_id-{$this->_bltID}"]) && $registerParams["billing_state_province_id-{$this->_bltID}"]) {
             $registerParams["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($registerParams["billing_state_province_id-{$this->_bltID}"]);
         }
         if (isset($registerParams["billing_country_id-{$this->_bltID}"]) && $registerParams["billing_country_id-{$this->_bltID}"]) {
             $registerParams["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($registerParams["billing_country_id-{$this->_bltID}"]);
         }
         if (isset($registerParams['credit_card_exp_date'])) {
             $registerParams['year'] = $registerParams['credit_card_exp_date']['Y'];
             $registerParams['month'] = $registerParams['credit_card_exp_date']['M'];
         }
         if ($this->_values['event']['is_monetary']) {
             $registerParams['ip_address'] = CRM_Utils_System::ipAddress();
             $registerParams['currencyID'] = $this->_params[0]['currencyID'];
             $registerParams['payment_action'] = 'Sale';
         }
         //assign back primary participant params.
         $this->_params[0] = $registerParams;
     }
     if ($this->_values['event']['is_monetary']) {
         $this->_params[0]['invoiceID'] = $this->get('invoiceID');
     }
     $this->assign('defaultRole', false);
     if (CRM_Utils_Array::value('defaultRole', $this->_params[0]) == 1) {
         $this->assign('defaultRole', true);
     }
     if (!CRM_Utils_Array::value('participant_role_id', $this->_params[0]) && $this->_values['event']['default_role_id']) {
         $this->_params[0]['participant_role_id'] = $this->_values['event']['default_role_id'];
     }
     if (isset($this->_values['event']['confirm_title'])) {
         CRM_Utils_System::setTitle($this->_values['event']['confirm_title']);
     }
     $this->set('params', $this->_params);
 }
Example #10
0
 /**
  * @param array $params
  *
  * @return array|void
  * @throws Exception
  */
 public function make_payment(&$params)
 {
     $config = CRM_Core_Config::singleton();
     if (isset($params["billing_state_province_id-{$this->_bltID}"]) && $params["billing_state_province_id-{$this->_bltID}"]) {
         $params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["billing_state_province_id-{$this->_bltID}"]);
     }
     if (isset($params["billing_country_id-{$this->_bltID}"]) && $params["billing_country_id-{$this->_bltID}"]) {
         $params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["billing_country_id-{$this->_bltID}"]);
     }
     $params['ip_address'] = CRM_Utils_System::ipAddress();
     $params['currencyID'] = $config->defaultCurrency;
     $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
     CRM_Core_Payment_Form::mapParams($this->_bltID, $params, $params, TRUE);
     $params['month'] = $params['credit_card_exp_date']['M'];
     $params['year'] = $params['credit_card_exp_date']['Y'];
     try {
         $result = $payment->doPayment($params);
     } catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
         CRM_Core_Error::displaySessionError($result);
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/cart_checkout', "_qf_Payment_display=1&qfKey={$this->controller->_key}", TRUE, NULL, FALSE));
     }
     $trxnDetails = array('trxn_id' => $result['trxn_id'], 'trxn_date' => $result['now'], 'currency' => CRM_Utils_Array::value('currencyID', $result));
     return $trxnDetails;
 }
Example #11
0
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     //set as Primary participant
     $params['is_primary'] = 1;
     //hack to allow group to register w/ waiting
     if (!$this->_allowConfirmation && CRM_Utils_Array::value('bypass_payment', $params) && is_numeric($this->_availableRegistrations) && CRM_Utils_Array::value('additional_participants', $params) >= $this->_availableRegistrations) {
         $this->_allowWaitlist = true;
         $this->set('allowWaitlist', true);
     }
     //carry participant id if pre-registered.
     if ($this->_allowConfirmation && $this->_participantId) {
         $params['participant_id'] = $this->_participantId;
     }
     $params['defaultRole'] = 1;
     if (array_key_exists('participant_role_id', $params)) {
         $params['defaultRole'] = 0;
     }
     if (!CRM_Utils_Array::value('participant_role_id', $params) && $this->_values['event']['default_role_id']) {
         $params['participant_role_id'] = $this->_values['event']['default_role_id'];
     }
     if ($this->_values['event']['is_monetary']) {
         $config =& CRM_Core_Config::singleton();
         // we first reset the confirm page so it accepts new values
         $this->controller->resetPage('Confirm');
         // get the submitted form values.
         $params['currencyID'] = $config->defaultCurrency;
         //added for discount
         require_once 'CRM/Core/BAO/Discount.php';
         $discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
         if (!empty($this->_values['discount'][$discountId])) {
             $params['discount_id'] = $discountId;
             $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
         } else {
             if (empty($params['priceSetId'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
             } else {
                 $lineItem = array();
                 require_once "CRM/Price/BAO/Set.php";
                 CRM_Price_BAO_Set::processAmount($this->_values['fee']['fields'], $params, $lineItem);
                 $priceSet = array();
                 $priceSet[] = $lineItem;
                 $this->set('lineItem', $priceSet);
             }
         }
         $this->set('amount', $params['amount']);
         $this->set('amount_level', $params['amount_level']);
         // generate and set an invoiceID for this transaction
         $invoiceID = md5(uniqid(rand(), true));
         $this->set('invoiceID', $invoiceID);
         if (is_array($this->_paymentProcessor)) {
             $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
         }
         // default mode is direct
         $this->set('contributeMode', 'direct');
         if (isset($params["state_province_id-{$this->_bltID}"]) && $params["state_province_id-{$this->_bltID}"]) {
             $params["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["state_province_id-{$this->_bltID}"]);
         }
         if (isset($params["country_id-{$this->_bltID}"]) && $params["country_id-{$this->_bltID}"]) {
             $params["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["country_id-{$this->_bltID}"]);
         }
         if (isset($params['credit_card_exp_date'])) {
             $params['year'] = $params['credit_card_exp_date']['Y'];
             $params['month'] = $params['credit_card_exp_date']['M'];
         }
         if ($this->_values['event']['is_monetary']) {
             $params['ip_address'] = CRM_Utils_System::ipAddress();
             $params['currencyID'] = $config->defaultCurrency;
             $params['payment_action'] = 'Sale';
             $params['invoiceID'] = $invoiceID;
         }
         $this->_params = array();
         $this->_params[] = $params;
         $this->set('params', $this->_params);
         if ($this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) {
             //get the button name
             $buttonName = $this->controller->getButtonName();
             if (in_array($buttonName, array($this->_expressButtonName, $this->_expressButtonName . '_x', $this->_expressButtonName . '_y')) && !isset($params['is_pay_later']) && !$this->_allowWaitlist && !$this->_requireApproval) {
                 $this->set('contributeMode', 'express');
                 // Send Event Name & Id in Params
                 $params['eventName'] = $this->_values['event']['title'];
                 $params['eventId'] = $this->_values['event']['id'];
                 $params['cancelURL'] = CRM_Utils_System::url('civicrm/event/register', '_qf_Register_display=1', true, null, false);
                 if (CRM_Utils_Array::value('additional_participants', $params, false)) {
                     $urlArgs = "_qf_Participant_1_display=1&rfp=1&qfKey={$this->controller->_key}";
                 } else {
                     $urlArgs = '_qf_Confirm_display=1&rfp=1';
                 }
                 $params['returnURL'] = CRM_Utils_System::url('civicrm/event/register', $urlArgs, true, null, false);
                 $params['invoiceID'] = $invoiceID;
                 //default action is Sale
                 $params['payment_action'] = 'Sale';
                 $token = $payment->setExpressCheckout($params);
                 if (is_a($token, 'CRM_Core_Error')) {
                     CRM_Core_Error::displaySessionError($token);
                     CRM_Utils_System::redirect($params['cancelURL']);
                 }
                 $this->set('token', $token);
                 $paymentURL = $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token={$token}";
                 CRM_Utils_System::redirect($paymentURL);
             }
         } else {
             if ($this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY) {
                 $this->set('contributeMode', 'notify');
             }
         }
     } else {
         $session =& CRM_Core_Session::singleton();
         $contactID = $session->get('userID');
         $params['description'] = ts('Online Event Registration') . ' ' . $this->_values['event']['title'];
         $this->_params = array();
         $this->_params[] = $params;
         $this->set('params', $this->_params);
         if (!CRM_Utils_Array::value('additional_participants', $params)) {
             self::processRegistration($this->_params, $contactID);
         }
     }
     // If registering > 1 participant, give status message
     if (CRM_Utils_Array::value('additional_participants', $params, false)) {
         require_once "CRM/Core/Session.php";
         $statusMsg = ts('Registration information for participant 1 has been saved.');
         CRM_Core_Session::setStatus("{$statusMsg}");
     }
 }
 /**
  * Get options for credit card.
  *
  * Not yet implemented
  * - token
  *
  * @param array $params
  * @param string $component
  *
  * @return array
  */
 private function getCreditCardOptions($params, $component)
 {
     // Contribution page in 4.4 passes amount - not sure which passes total_amount if any.
     if (isset($params['total_amount'])) {
         $amount = (double) CRM_Utils_Rule::cleanMoney($params['total_amount']);
     } else {
         $amount = (double) CRM_Utils_Rule::cleanMoney($params['amount']);
     }
     $creditCardOptions = array('amount' => $amount, 'currency' => strtoupper(!empty($params['currencyID']) ? $params['currencyID'] : $params['currency']), 'description' => $this->getPaymentDescription($params), 'transactionId' => $this->transaction_id, 'clientIp' => CRM_Utils_System::ipAddress(), 'returnUrl' => $this->getNotifyUrl(TRUE), 'cancelUrl' => $this->getCancelUrl($params['qfKey'], CRM_Utils_Array::value('participantID', $params)), 'notifyUrl' => $this->getNotifyUrl(), 'card' => $this->getCreditCardObjectParams($params));
     CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $creditCardOptions);
     $creditCardOptions['card'] = array_merge($creditCardOptions['card'], $this->getSensitiveCreditCardObjectOptions($params));
     return $creditCardOptions;
 }
Example #13
0
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     require_once 'CRM/Member/BAO/Membership.php';
     require_once 'CRM/Member/BAO/MembershipType.php';
     require_once 'CRM/Member/BAO/MembershipStatus.php';
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Member_BAO_Membership::deleteRelatedMemberships($this->_id);
         CRM_Member_BAO_Membership::deleteMembership($this->_id);
         return;
     }
     $config =& CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $params = array();
     $ids = array();
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $formValues)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $formValues);
     }
     $params['contact_id'] = $this->_contactID;
     // we need to retrieve email address
     if ($this->_context == 'standalone' && CRM_Utils_Array::value('send_receipt', $formValues)) {
         require_once 'CRM/Contact/BAO/Contact/Location.php';
         list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
     }
     $fields = array('status_id', 'source', 'is_override');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (!CRM_Utils_Array::value('is_override', $params)) {
         $params['exclude_is_admin'] = true;
     }
     $params['membership_type_id'] = $formValues['membership_type_id'][1];
     $joinDate = CRM_Utils_Date::processDate($formValues['join_date']);
     $startDate = CRM_Utils_Date::processDate($formValues['start_date']);
     $endDate = CRM_Utils_Date::processDate($formValues['end_date']);
     $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($params['membership_type_id'], $joinDate, $startDate, $endDate);
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date', 'receive_date');
     $currentTime = getDate();
     foreach ($dates as $d) {
         if (isset($formValues[$d]) && !CRM_Utils_System::isNull($formValues[$d])) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d]);
         } else {
             if (isset($calcDates[$d])) {
                 $params[$d] = CRM_Utils_Date::processDate($calcDates[$d]);
             }
         }
     }
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $session = CRM_Core_Session::singleton();
     $ids['userId'] = $session->get('userID');
     // membership type custom data
     $customFields = CRM_Core_BAO_CustomField::getFields('Membership', false, false, CRM_Utils_Array::value('membership_type_id', $params));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', false, false, null, null, true));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     require_once 'CRM/Contact/BAO/Contact/Location.php';
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     if (CRM_Utils_Array::value('record_contribution', $formValues)) {
         $recordContribution = array('total_amount', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         $membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1]);
         if (!$this->_onlinePendingContributionId) {
             $params['contribution_source'] = "{$membershipType} Membership: Offline membership signup (by {$userName})";
         }
         if ($formValues['send_receipt']) {
             $params['receipt_date'] = $params['receive_date'];
         }
         //insert contribution type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $formValues['contribution_type_id']);
     }
     if ($this->_mode) {
         $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id'], 'minimum_fee');
         $params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id'], 'contribution_type_id');
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $formValues["email-5"] = $formValues["email-Primary"] = $this->_contributorEmail;
         $params['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;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $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;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contactID, null, null, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // 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
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Contribute', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $params['contribution_status_id'] = 1;
         $params['receive_date'] = $now;
         $params['invoice_id'] = $this->_params['invoiceID'];
         $params['contribution_source'] = ts('Online Membership: Admin Interface');
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = $result['trxn_id'];
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         $membership =& CRM_Member_BAO_Membership::create($params, $ids);
         $contribution = new CRM_Contribute_BAO_Contribution();
         $contribution->trxn_id = $result['trxn_id'];
         if ($contribution->find(true)) {
             // next create the transaction record
             $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['total_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['total_amount']), 'currency' => $config->defaultCurrency, 'payment_processor' => $this->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id']);
             require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
             $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($trxnParams);
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && CRM_Utils_Array::value('record_contribution', $formValues)) {
             // update membership as well as contribution object, CRM-4395
             require_once 'CRM/Contribute/Form/Contribution.php';
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, true);
             //carry updated membership object.
             $membership =& new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(true);
             $cancelled = true;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 require_once 'CRM/Member/PseudoConstant.php';
                 $membershipStatues = CRM_Member_PseudoConstant::membershipStatus();
                 if (!in_array($membership->status_id, array(array_search('Cancelled', $membershipStatues), array_search('Expired', $membershipStatues)))) {
                     $cancelled = false;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
         } else {
             $membership =& CRM_Member_BAO_Membership::create($params, $ids);
         }
     }
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         require_once 'CRM/Core/DAO.php';
         CRM_Core_DAO::setFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id'], 'receipt_text_signup', $formValues['receipt_text_signup']);
     }
     $receiptSend = false;
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         $receiptSend = true;
         $receiptFrom = "{$userName} <{$userEmail}>";
         if (CRM_Utils_Array::value('payment_instrument_id', $formValues)) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
         }
         // retrieve custom data
         require_once "CRM/Core/BAO/UFGroup.php";
         $customFields = $customValues = array();
         foreach ($this->_groupTree as $groupID => $group) {
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
         }
         $members = array(array('member_id', '=', $membership->id, 0, 0));
         // check whether its a test drive
         if ($this->_mode) {
             $members[] = array('member_test', '=', 1, 0, 0);
         }
         CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, false, $members);
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $this->_params)) {
                 $name = $this->_params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $this->_params)) {
                 $name .= " {$this->_params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $this->_params)) {
                 $name .= " {$this->_params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $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);
             $this->assign('isPrimary', 1);
         }
         $this->assign('module', 'Membership');
         $this->assign('contactID', $this->_contactID);
         $this->assign('membershipID', $params['membership_id']);
         $this->assign('receiptType', 'membership signup');
         $this->assign('receive_date', $params['receive_date']);
         $this->assign('formValues', $formValues);
         $this->assign('mem_start_date', CRM_Utils_Date::customFormat($calcDates['start_date']));
         $this->assign('mem_end_date', CRM_Utils_Date::customFormat($calcDates['end_date']));
         $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1]));
         $this->assign('customValues', $customValues);
         require_once 'CRM/Core/BAO/MessageTemplates.php';
         list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_offline_receipt', 'contactId' => $this->_contactID, 'from' => $receiptFrom, 'toName' => $this->_contributorDisplayName, 'toEmail' => $this->_contributorEmail, 'isTest' => (bool) ($this->_action & CRM_Core_Action::PREVIEW)));
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($endDate) {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend) {
             $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         require_once 'CRM/Core/DAO.php';
         $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id']);
         $statusMsg = ts('%1 membership for %2 has been added.', array(1 => $memType, 2 => $this->_contributorDisplayName));
         //get the end date from calculated dates.
         $endDate = $endDate ? $endDate : CRM_Utils_Array::value('end_date', $calcDates);
         if ($endDate) {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend && $mailSend) {
             $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     }
     CRM_Core_Session::setStatus($statusMsg);
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=member"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&context=membership&cid={$this->_contactID}"));
         }
     }
 }
Example #14
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  * @return None 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once 'CRM/Contribute/BAO/Contribution.php';
         CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
         return;
     }
     // get the submitted form values.
     $submittedValues = $this->controller->exportValues($this->_name);
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = null;
     if ($priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues)) {
         require_once 'CRM/Price/BAO/Set.php';
         CRM_Price_BAO_Set::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         $submittedValues['total_amount'] = $submittedValues['amount'];
     }
     if (!CRM_Utils_Array::value('total_amount', $submittedValues)) {
         $submittedValues['total_amount'] = $this->_values['total_amount'];
     }
     $this->assign('lineItem', !empty($lineItem) ? $lineItem : false);
     if (CRM_Utils_Array::value('soft_credit_to', $submittedValues)) {
         $submittedValues['soft_credit_to'] = $submittedValues['soft_contact_id'];
     }
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $submittedValues)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $submittedValues);
     }
     $config =& CRM_Core_Config::singleton();
     $session =& CRM_Core_Session::singleton();
     //Credit Card Contribution.
     if ($this->_mode) {
         $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'receive_date', 'cancel_date', 'cancel_reason');
         foreach ($unsetParams as $key) {
             if (isset($submittedValues[$key])) {
                 unset($submittedValues[$key]);
             }
         }
         //Get the rquire fields value only.
         $params = $this->_params = $submittedValues;
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // we need to retrieve email address
         if ($this->_context == 'standalone' && CRM_Utils_Array::value('is_email_receipt', $submittedValues)) {
             require_once 'CRM/Contact/BAO/Contact/Location.php';
             list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
             $this->assign('displayName', $this->userDisplayName);
         }
         //set email for primary location.
         $fields["email-Primary"] = 1;
         $params["email-Primary"] = $this->userEmail;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = true;
             }
         }
         if (CRM_Utils_Array::value('source', $params)) {
             unset($params['source']);
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, null, null, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
             $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
             $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         }
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $this->_params['total_amount'];
         $this->_params['amount_level'] = 0;
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         if (CRM_Utils_Array::value('soft_credit_to', $params)) {
             $this->_params['soft_credit_to'] = $params['soft_credit_to'];
             $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
         }
         $this->_params['pcp_display_in_roll'] = $params['pcp_display_in_roll'];
         $this->_params['pcp_roll_nickname'] = $params['pcp_roll_nickname'];
         $this->_params['pcp_personal_note'] = $params['pcp_personal_note'];
         //Add common data to formatted params
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params);
         if (empty($this->_params['invoice_id'])) {
             $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         } else {
             $this->_params['invoiceID'] = $this->_params['invoice_id'];
         }
         // 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
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $contributionType =& new CRM_Contribute_DAO_ContributionType();
         $contributionType->id = $params['contribution_type_id'];
         if (!$contributionType->find(true)) {
             CRM_Core_Error::fatal("Could not find a system table");
         }
         // add some contribution type details to the params list
         // if folks need to use it
         $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
         $paymentParams['contributionType_accounting_code'] = $this->_params['contributionType_accounting_code'] = $contributionType->accounting_code;
         $paymentParams['contributionPageID'] = null;
         if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $paymentParams['email'] = $this->userEmail;
         }
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Contribute', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             //set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactID}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             if (!CRM_Utils_System::isNull($this->_params['receipt_date'])) {
                 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date']);
             } else {
                 $this->_params['receipt_date'] = 'null';
             }
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         // result has all the stuff we need
         // lets archive it to a financial transaction
         if ($contributionType->is_deductible) {
             $this->assign('is_deductible', true);
             $this->set('is_deductible', true);
         }
         // set source if not set
         if (empty($this->_params['source'])) {
             $userID = $session->get('userID');
             $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
             $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
         }
         // build custom data getFields array
         $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', false, false, CRM_Utils_Array::value('contribution_type_id', $params));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', false, false, null, null, true));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution');
         require_once 'CRM/Contribute/Form/Contribution/Confirm.php';
         $contribution =& CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, false, false, false);
         // process line items, until no previous line items.
         if (empty($this->_lineItems) && $contribution->id && !empty($lineItem)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $lineItem);
         }
         //send receipt mail.
         if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
             $this->_params['contact_id'] = $this->_contactID;
             $this->_params['contribution_id'] = $contribution->id;
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, true);
         }
         //process the note
         if ($contribution->id && isset($params['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, null);
         }
         //process premium
         if ($contribution->id && isset($params['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, null, $this->_options);
         }
         //update pledge payment status.
         if ($this->_ppID && $contribution->id) {
             //store contribution id in payment record.
             CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Payment', $this->_ppID, 'contribution_id', $contribution->id);
             require_once 'CRM/Pledge/BAO/Payment.php';
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id);
         }
         if ($contribution->id) {
             $statusMsg = ts('The contribution record has been processed.');
             if (CRM_Utils_Array::value('is_email_receipt', $this->_params) && $sendReceipt) {
                 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
             }
             CRM_Core_Session::setStatus($statusMsg);
         }
         //submit credit card contribution ends.
     } else {
         //Offline Contribution.
         $unsetParams = array("payment_processor_id", "email-{$this->_bltID}", "hidden_buildCreditCard", "hidden_buildDirectDebit", "billing_first_name", "billing_middle_name", "billing_last_name", "street_address-5", "city-{$this->_bltID}", "state_province_id-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}", "credit_card_number", "cvv2", "credit_card_exp_date", "credit_card_type");
         foreach ($unsetParams as $key) {
             if (isset($submittedValues[$key])) {
                 unset($submittedValues[$key]);
             }
         }
         // get the required field value only.
         $formValues = $submittedValues;
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         $params['currency'] = $config->defaultCurrency;
         if ($currency = CRM_Utils_Array::value('currency', $this->_values)) {
             $params['currency'] = $currency;
         }
         $fields = array('contribution_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number', 'soft_credit_to', 'pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if ($softID = CRM_Utils_Array::value('softID', $this->_values)) {
             $params['softID'] = $softID;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             if (!CRM_Utils_System::isNull($formValues[$d])) {
                 $params[$d] = CRM_Utils_Date::processDate($formValues[$d]);
             } else {
                 if (array_key_exists($d, $formValues)) {
                     $params[$d] = 'null';
                 }
             }
         }
         if (CRM_Utils_Array::value('is_email_receipt', $formValues)) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params["contribution_status_id"] == 3) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date("Y-m-d");
             }
         } else {
             $params['cancel_date'] = 'null';
             $params['cancel_reason'] = 'null';
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         //Add Additinal common information  to formatted params
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params);
         //create contribution.
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contribution =& CRM_Contribute_BAO_Contribution::create($params, $ids);
         // process line items, until no previous line items.
         if (empty($this->_lineItems) && $contribution->id && !empty($lineItem)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $lineItem);
         }
         // process associated membership / participant, CRM-4395
         $relatedComponentStatusMsg = null;
         if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
             $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values));
         }
         //process  note
         if ($contribution->id && isset($formValues['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
         }
         //process premium
         if ($contribution->id && isset($formValues['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id, $this->_premiumID, $this->_options);
         }
         //send receipt mail.
         if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $formValues)) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
         }
         //update pledge payment status.
         if ($this->_ppID && $contribution->id && $this->_action & CRM_Core_Action::ADD) {
             //store contribution id in payment record.
             CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Payment', $this->_ppID, 'contribution_id', $contribution->id);
             require_once 'CRM/Pledge/BAO/Payment.php';
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id);
         }
         $statusMsg = ts('The contribution record has been saved.');
         if (CRM_Utils_Array::value('is_email_receipt', $formValues) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         if ($relatedComponentStatusMsg) {
             $statusMsg .= ' ' . $relatedComponentStatusMsg;
         }
         CRM_Core_Session::setStatus($statusMsg);
         //Offline Contribution ends.
     }
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context=contribution&cid={$this->_contactID}"));
         }
     }
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     //set as Primary participant
     $params['is_primary'] = 1;
     if ($this->_values['event']['is_pay_later'] && !array_key_exists('hidden_processor', $params)) {
         $params['is_pay_later'] = 1;
     } else {
         $params['is_pay_later'] = 0;
     }
     $this->set('is_pay_later', $params['is_pay_later']);
     // assign pay later stuff
     $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
     $this->assign('is_pay_later', $params['is_pay_later']);
     if ($params['is_pay_later']) {
         $this->assign('pay_later_text', $this->_values['event']['pay_later_text']);
         $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
     }
     if (!$this->_allowConfirmation) {
         // check if the participant is already registered
         if (!$this->_skipDupeRegistrationCheck) {
             $params['contact_id'] = self::checkRegistration($params, $this, FALSE, TRUE, TRUE);
         }
     }
     if (CRM_Utils_Array::value('image_URL', $params)) {
         CRM_Contact_BAO_Contact::processImageParams($params);
     }
     //carry campaign to partcipants.
     if (array_key_exists('participant_campaign_id', $params)) {
         $params['campaign_id'] = $params['participant_campaign_id'];
     } else {
         $params['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values['event']);
     }
     //hack to allow group to register w/ waiting
     $primaryParticipantCount = self::getParticipantCount($this, $params);
     $totalParticipants = $primaryParticipantCount;
     if (CRM_Utils_Array::value('additional_participants', $params)) {
         $totalParticipants += $params['additional_participants'];
     }
     if (!$this->_allowConfirmation && CRM_Utils_Array::value('bypass_payment', $params) && is_numeric($this->_availableRegistrations) && $totalParticipants > $this->_availableRegistrations) {
         $this->_allowWaitlist = TRUE;
         $this->set('allowWaitlist', TRUE);
     }
     //carry participant id if pre-registered.
     if ($this->_allowConfirmation && $this->_participantId) {
         $params['participant_id'] = $this->_participantId;
     }
     $params['defaultRole'] = 1;
     if (array_key_exists('participant_role', $params)) {
         $params['participant_role_id'] = $params['participant_role'];
     }
     if (array_key_exists('participant_role_id', $params)) {
         $params['defaultRole'] = 0;
     }
     if (!CRM_Utils_Array::value('participant_role_id', $params) && $this->_values['event']['default_role_id']) {
         $params['participant_role_id'] = $this->_values['event']['default_role_id'];
     }
     $config = CRM_Core_Config::singleton();
     $params['currencyID'] = $config->defaultCurrency;
     if ($this->_values['event']['is_monetary']) {
         // we first reset the confirm page so it accepts new values
         $this->controller->resetPage('Confirm');
         //added for discount
         $discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
         if (!empty($this->_values['discount'][$discountId])) {
             $params['discount_id'] = $discountId;
             $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
         } elseif (empty($params['priceSetId'])) {
             if (!empty($params['amount'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
             } else {
                 $params['amount_level'] = $params['amount'] = '';
             }
         } else {
             $lineItem = array();
             CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem);
             $this->set('lineItem', array($lineItem));
             $this->set('lineItemParticipantsCount', array($primaryParticipantCount));
         }
         $this->set('amount', $params['amount']);
         $this->set('amount_level', $params['amount_level']);
         // generate and set an invoiceID for this transaction
         $invoiceID = md5(uniqid(rand(), TRUE));
         $this->set('invoiceID', $invoiceID);
         if (is_array($this->_paymentProcessor)) {
             $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
         }
         // default mode is direct
         $this->set('contributeMode', 'direct');
         if (isset($params["state_province_id-{$this->_bltID}"]) && $params["state_province_id-{$this->_bltID}"]) {
             $params["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["state_province_id-{$this->_bltID}"]);
         }
         if (isset($params["country_id-{$this->_bltID}"]) && $params["country_id-{$this->_bltID}"]) {
             $params["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["country_id-{$this->_bltID}"]);
         }
         if (isset($params['credit_card_exp_date'])) {
             $params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($params);
             $params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($params);
         }
         if ($this->_values['event']['is_monetary']) {
             $params['ip_address'] = CRM_Utils_System::ipAddress();
             $params['currencyID'] = $config->defaultCurrency;
             $params['payment_action'] = 'Sale';
             $params['invoiceID'] = $invoiceID;
         }
         $this->_params = array();
         $this->_params[] = $params;
         $this->set('params', $this->_params);
         if ($this->_paymentProcessor && $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) {
             //get the button name
             $buttonName = $this->controller->getButtonName();
             if (in_array($buttonName, array($this->_expressButtonName, $this->_expressButtonName . '_x', $this->_expressButtonName . '_y')) && !CRM_Utils_Array::value('is_pay_later', $params) && !$this->_allowWaitlist && !$this->_requireApproval) {
                 $this->set('contributeMode', 'express');
                 // Send Event Name & Id in Params
                 $params['eventName'] = $this->_values['event']['title'];
                 $params['eventId'] = $this->_values['event']['id'];
                 $params['cancelURL'] = CRM_Utils_System::url('civicrm/event/register', "_qf_Register_display=1&qfKey={$this->controller->_key}", TRUE, NULL, FALSE);
                 if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
                     $urlArgs = "_qf_Participant_1_display=1&rfp=1&qfKey={$this->controller->_key}";
                 } else {
                     $urlArgs = "_qf_Confirm_display=1&rfp=1&qfKey={$this->controller->_key}";
                 }
                 $params['returnURL'] = CRM_Utils_System::url('civicrm/event/register', $urlArgs, TRUE, NULL, FALSE);
                 $params['invoiceID'] = $invoiceID;
                 //default action is Sale
                 $params['payment_action'] = 'Sale';
                 $token = $payment->setExpressCheckout($params);
                 if (is_a($token, 'CRM_Core_Error')) {
                     CRM_Core_Error::displaySessionError($token);
                     CRM_Utils_System::redirect($params['cancelURL']);
                 }
                 $this->set('token', $token);
                 $paymentURL = $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token={$token}";
                 CRM_Utils_System::redirect($paymentURL);
             }
         } elseif ($this->_paymentProcessor && $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY) {
             $this->set('contributeMode', 'notify');
         }
     } else {
         $session = CRM_Core_Session::singleton();
         $params['description'] = ts('Online Event Registration') . ' ' . $this->_values['event']['title'];
         $this->_params = array();
         $this->_params[] = $params;
         $this->set('params', $this->_params);
         if (!CRM_Utils_Array::value('additional_participants', $params)) {
             self::processRegistration($this->_params);
         }
     }
     // If registering > 1 participant, give status message
     if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
         $statusMsg = ts('Registration information for participant 1 has been saved.');
         CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     }
 }
 /**
  * Process form submission.
  *
  * This function is also accessed by a unit test.
  */
 protected function submit()
 {
     $this->storeContactFields($this->_params);
     $now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
     $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'])) {
         $this->_params['receipt_date'] = $now;
         $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($this->_params['receipt_date']));
     } else {
         $this->_params['receipt_date'] = NULL;
     }
     if ($this->_mode) {
         $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']));
         $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'] = $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
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         $paymentParams['contactID'] = $this->_contributorContactID;
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         $payment = $this->_paymentProcessor['object'];
         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);
         $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($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', $this->_params))) {
         $numRenewTerms = $this->_params['num_terms'];
     }
     //if contribution status is pending then set pay later
     $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;
     }
     // These variable sets prior to renewMembership may not be required for this form. They were in
     // a function this form shared with other forms.
     $contributionRecurID = isset($this->_params['contributionRecurID']) ? $this->_params['contributionRecurID'] : NULL;
     $membershipSource = NULL;
     if (!empty($this->_params['membership_source'])) {
         $membershipSource = $this->_params['membership_source'];
     }
     $isPending = $this->_params['contribution_status_id'] == 2 ? TRUE : FALSE;
     list($renewMembership) = CRM_Member_BAO_Membership::renewMembership($this->_contactID, $this->_params['membership_type_id'][1], $isTestMembership, $renewalDate, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId, $isPending, $contributionRecurID, $membershipSource, $this->_params['is_pay_later'], CRM_Utils_Array::value('campaign_id', $this->_params));
     $this->endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
     $this->membershipTypeName = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name');
     if (!empty($this->_params['record_contribution']) || $this->_mode) {
         // set the source
         $this->_params['contribution_source'] = "{$this->membershipTypeName} Membership: Offline membership renewal (by {$userName})";
         //create line items
         $lineItem = array();
         $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', $this->_params)) {
             foreach ($lineItem[$priceSetId] as &$li) {
                 $li['financial_type_id'] = $submittedFinancialType;
             }
         }
         $this->_params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
         if (!empty($lineItem)) {
             $this->_params['lineItems'] = $lineItem;
             $this->_params['processPriceSet'] = TRUE;
         }
         //assign contribution contact id to the field expected by recordMembershipContribution
         if ($this->_contributorContactID != $this->_contactID) {
             $this->_params['contribution_contact_id'] = $this->_contributorContactID;
             if (!empty($this->_params['soft_credit_type_id'])) {
                 $this->_params['soft_credit'] = array('soft_credit_type_id' => $this->_params['soft_credit_type_id'], '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($this->_params, array('membership_id' => $renewMembership->id));
         CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams);
     }
     if (!empty($this->_params['send_receipt'])) {
         $receiptFrom = $this->_params['from_email_address'];
         if (!empty($this->_params['payment_instrument_id'])) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             $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);
         // retrieve custom data
         $customFields = $customValues = $fo = array();
         foreach ($this->_groupTree as $groupID => $group) {
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
         }
         $members = array(array('member_id', '=', $this->_membershipId, 0, 0));
         // check whether its a test drive
         if ($this->_mode == 'test') {
             $members[] = array('member_test', '=', 1, 0, 0);
         }
         CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
         $this->assign_by_ref('formValues', $this->_params);
         if (!empty($this->_params['contribution_id'])) {
             $this->assign('contributionID', $this->_params['contribution_id']);
         }
         $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("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $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));
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
             $this->assign('receipt_text_renewal', $this->_params['receipt_text']);
             if ($this->_mode == 'test') {
                 $this->assign('action', '1024');
             }
         }
         list($this->isMailSent) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $this->_receiptContactId, 'from' => $receiptFrom, 'toName' => $this->_contributorDisplayName, 'toEmail' => $this->_contributorEmail, 'isTest' => $this->_mode == 'test'));
     }
 }
Example #17
0
 /**
  * Function to process the renewal form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     require_once 'CRM/Member/BAO/Membership.php';
     require_once 'CRM/Member/BAO/MembershipType.php';
     require_once 'CRM/Member/BAO/MembershipStatus.php';
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $params = array();
     $ids = array();
     $config =& CRM_Core_Config::singleton();
     $params['contact_id'] = $this->_contactID;
     if ($this->_mode) {
         $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee');
         $formValues['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'contribution_type_id');
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = CRM_Utils_Date::getToday($now, 'YmdHis');
         $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;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $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;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contactID, null, null, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $formValues['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // 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
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Contribute', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $formValues['contribution_status_id'] = 1;
         $formValues['receive_date'] = $now;
         $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;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $formValues['receipt_date'] = $now;
         } else {
             $formValues['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($formValues['receive_date']));
     }
     $renewalDate = null;
     if ($formValues['renewal_date']) {
         $this->set('renewDate', CRM_Utils_Date::processDate($formValues['renewal_date']));
     }
     $this->_membershipId = $this->_id;
     // check for test membership.
     $isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
     $renewMembership = CRM_Member_BAO_Membership::renewMembership($this->_contactID, $this->_memType, $isTestMembership, $this, null);
     $endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
     require_once 'CRM/Contact/BAO/Contact/Location.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session =& CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name');
     if (CRM_Utils_Array::value('record_contribution', $formValues) || $this->_mode) {
         //building contribution params
         $contributionParams = array();
         $config =& CRM_Core_Config::singleton();
         $contributionParams['currency'] = $config->defaultCurrency;
         $contributionParams['contact_id'] = $params['contact_id'];
         $contributionParams['source'] = "{$memType} Membership: Offline membership renewal (by {$userName})";
         $contributionParams['non_deductible_amount'] = 'null';
         $contributionParams['receive_date'] = date('Y-m-d H:i:s');
         $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $formValues) ? $contributionParams['receive_date'] : 'null';
         $recordContribution = array('total_amount', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'invoice_id', 'check_number', 'is_test');
         foreach ($recordContribution as $f) {
             $contributionParams[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contribution =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
         require_once 'CRM/Member/DAO/MembershipPayment.php';
         $mpDAO =& new CRM_Member_DAO_MembershipPayment();
         $mpDAO->membership_id = $renewMembership->id;
         $mpDAO->contribution_id = $contribution->id;
         $mpDAO->save();
         if ($this->_mode) {
             $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $formValues['total_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $formValues['total_amount']), 'currency' => $config->defaultCurrency, 'payment_processor' => $this->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id']);
             require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
             $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($trxnParams);
         }
     }
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         require_once 'CRM/Core/DAO.php';
         CRM_Core_DAO::setFieldValue('CRM_Member_DAO_MembershipType', CRM_Utils_Array::value('membership_type_id', $params), 'receipt_text_renewal', $formValues['receipt_text_renewal']);
     }
     $receiptSend = false;
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         $receiptSend = true;
         // Retrieve the name and email of the contact - this will be the TO for receipt email
         list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
         $receiptFrom = '"' . $userName . '" <' . $userEmail . '>';
         $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
         $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
         //get the group Tree
         $this->_groupTree =& CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $this->_id, false, $this->_memType);
         // retrieve custom data
         require_once "CRM/Core/BAO/UFGroup.php";
         $customFields = $customValues = $fo = array();
         foreach ($this->_groupTree as $groupID => $group) {
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
         }
         CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, false, array(array('member_id', '=', $renewMembership->id, 0, 0)));
         $this->assign_by_ref('formValues', $formValues);
         $this->assign('receive_date', $renewalDate);
         $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);
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $this->_params)) {
                 $name = $this->_params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $this->_params)) {
                 $name .= " {$this->_params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $this->_params)) {
                 $name .= " {$this->_params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $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);
             $this->assign('isPrimary', 1);
             if ($this->_mode == 'test') {
                 $this->assign('action', '1024');
             }
         }
         require_once 'CRM/Core/BAO/MessageTemplates.php';
         list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $this->_contactID, 'from' => $receiptFrom, 'toName' => $this->_contributorDisplayName, 'toEmail' => $this->_contributorEmail, 'isTest' => $this->_mode == 'test'));
     }
     $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $memType, 2 => $this->_contributorDisplayName));
     $endDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $this->_id, "end_date"));
     if ($endDate) {
         $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(1 => $endDate));
     }
     if ($receiptSend && $mailSend) {
         $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
     }
     CRM_Core_Session::setStatus($statusMsg);
 }
Example #18
0
 /**
  * Submit function.
  *
  * This is also accessed by unit tests.
  *
  * @param array $formValues
  *
  * @return array
  */
 public function submit($formValues)
 {
     $isTest = $this->_mode == 'test' ? 1 : 0;
     $joinDate = $startDate = $endDate = NULL;
     $membershipTypes = $membership = $calcDate = array();
     $membershipType = NULL;
     $mailSend = FALSE;
     $formValues = $this->setPriceSetParameters($formValues);
     $params = $softParams = $ids = array();
     $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus();
     $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $ids['userId'] = CRM_Core_Session::singleton()->get('userID');
     // Set variables that we normally get from context.
     // In form mode these are set in preProcess.
     //TODO: set memberships, fixme
     $this->setContextVariables($formValues);
     $this->_memTypeSelected = self::getSelectedMemberships($this->_priceSet, $formValues);
     if (empty($formValues['financial_type_id'])) {
         $formValues['financial_type_id'] = $this->_priceSet['financial_type_id'];
     }
     $config = CRM_Core_Config::singleton();
     $this->convertDateFieldsToMySQL($formValues);
     $membershipTypeValues = array();
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypeValues[$memType]['membership_type_id'] = $memType;
     }
     //take the required membership recur values.
     if ($this->_mode && !empty($formValues['auto_renew'])) {
         $params['is_recur'] = $formValues['is_recur'] = TRUE;
         $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit');
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array());
             foreach ($mapping as $mapVal => $mapParam) {
                 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 if (!$count) {
                     $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 }
             }
             $count++;
         }
     }
     $isQuickConfig = $this->_priceSet['is_quick_config'];
     $termsByType = array();
     $lineItem = array($this->_priceSetId => array());
     CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $formValues, $lineItem[$this->_priceSetId]);
     if (CRM_Utils_Array::value('tax_amount', $formValues)) {
         $params['tax_amount'] = $formValues['tax_amount'];
     }
     $params['total_amount'] = CRM_Utils_Array::value('amount', $formValues);
     $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
     if (!empty($lineItem[$this->_priceSetId])) {
         foreach ($lineItem[$this->_priceSetId] as &$li) {
             if (!empty($li['membership_type_id'])) {
                 if (!empty($li['membership_num_terms'])) {
                     $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
                 }
             }
             ///CRM-11529 for quick config backoffice transactions
             //when financial_type_id is passed in form, update the
             //lineitems with the financial type selected in form
             if ($isQuickConfig && $submittedFinancialType) {
                 $li['financial_type_id'] = $submittedFinancialType;
             }
         }
     }
     $this->storeContactFields($formValues);
     $params['contact_id'] = $this->_contactID;
     $fields = array('status_id', 'source', 'is_override', 'campaign_id');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (empty($params['is_override'])) {
         $params['exclude_is_admin'] = TRUE;
     }
     // process date params to mysql date format.
     $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
     foreach ($dateTypes as $dateField => $dateVariable) {
         ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]);
     }
     $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
     $calcDates = array();
     foreach ($this->_memTypeSelected as $memType) {
         if (empty($memTypeNumTerms)) {
             $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
         }
         $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate, $memTypeNumTerms);
     }
     foreach ($calcDates as $memType => $calcDate) {
         foreach (array_keys($dateTypes) as $d) {
             //first give priority to form values then calDates.
             $date = CRM_Utils_Array::value($d, $formValues);
             if (!$date) {
                 $date = CRM_Utils_Array::value($d, $calcDate);
             }
             $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
         }
     }
     // max related memberships - take from form or inherit from membership type
     foreach ($this->_memTypeSelected as $memType) {
         if (array_key_exists('max_related', $formValues)) {
             $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
         }
         $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $this->_id, 'Membership');
         $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType);
     }
     $membershipType = implode(', ', $membershipTypes);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     //CRM-13981, allow different person as a soft-contributor of chosen type
     if ($this->_contributorContactID != $this->_contactID) {
         $params['contribution_contact_id'] = $this->_contributorContactID;
         if (!empty($formValues['soft_credit_type_id'])) {
             $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
             $softParams['contact_id'] = $this->_contactID;
         }
     }
     if (!empty($formValues['record_contribution'])) {
         $recordContribution = array('total_amount', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!$this->_onlinePendingContributionId) {
             if (empty($formValues['source'])) {
                 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
             } else {
                 $params['contribution_source'] = $formValues['source'];
             }
         }
         if (empty($params['is_override']) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             $params['is_pay_later'] = 1;
             $this->assign('is_pay_later', 1);
         }
         if (!empty($formValues['send_receipt'])) {
             $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
         }
         //insert financial type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $formValues['financial_type_id']);
     }
     // process line items, until no previous line items.
     if (!empty($lineItem)) {
         $params['lineItems'] = $lineItem;
         $params['processPriceSet'] = TRUE;
     }
     $createdMemberships = array();
     if ($this->_mode) {
         $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
         if (!$isQuickConfig) {
             $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'financial_type_id');
         } else {
             $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
         }
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail;
         $params['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;
         //ensure we don't over-write the payer's email with the member's email
         if ($this->_contributorContactID == $this->_contactID) {
             $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;
             }
         }
         if ($this->_contributorContactID == $this->_contactID) {
             //see CRM-12869 for discussion of why we don't do this for separate payee payments
             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
         $formValues["state_province-{$this->_bltID}"] = $formValues["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($formValues["billing_state_province_id-{$this->_bltID}"]);
         $formValues["country-{$this->_bltID}"] = $formValues["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($formValues["billing_country_id-{$this->_bltID}"]);
         $formValues['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($formValues);
         $formValues['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($formValues);
         $formValues['ip_address'] = CRM_Utils_System::ipAddress();
         $formValues['amount'] = $params['total_amount'];
         $formValues['currencyID'] = $config->defaultCurrency;
         $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup");
         $formValues['invoiceID'] = md5(uniqid(rand(), TRUE));
         $formValues['financial_type_id'] = $params['financial_type_id'];
         // 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
         // so we copy stuff over to first_name etc.
         $paymentParams = $formValues;
         $paymentParams['contactID'] = $this->_contributorContactID;
         //CRM-10377 if payment is by an alternate contact then we need to set that person
         // as the contact in the payment params
         if ($this->_contributorContactID != $this->_contactID) {
             if (!empty($formValues['soft_credit_type_id'])) {
                 $softParams['contact_id'] = $params['contact_id'];
                 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
             }
         }
         if (!empty($formValues['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         CRM_Core_Payment_Form::mapParams($this->_bltID, $formValues, $paymentParams, TRUE);
         // CRM-7137 -for recurring membership,
         // we do need contribution and recurring records.
         $result = NULL;
         if (!empty($paymentParams['is_recur'])) {
             $financialType = new CRM_Financial_DAO_FinancialType();
             $financialType->id = $params['financial_type_id'];
             $financialType->find(TRUE);
             $this->_params = $formValues;
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this, $paymentParams, NULL, array('contact_id' => $this->_contributorContactID, 'line_item' => $lineItem, 'is_test' => $isTest, 'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams), 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $formValues), 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)), 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $paymentParams), 'payment_instrument_id' => $this->_paymentProcessor['payment_instrument_id']), $financialType, TRUE, FALSE, $this->_bltID);
             //create new soft-credit record, CRM-13981
             if ($softParams) {
                 $softParams['contribution_id'] = $contribution->id;
                 $softParams['currency'] = $contribution->currency;
                 $softParams['amount'] = $contribution->total_amount;
                 CRM_Contribute_BAO_ContributionSoft::add($softParams);
             }
             $paymentParams['contactID'] = $this->_contactID;
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             $ids['contribution'] = $contribution->id;
             $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
         }
         if ($params['total_amount'] > 0.0) {
             $payment = $this->_paymentProcessor['object'];
             try {
                 $result = $payment->doPayment($paymentParams);
                 $formValues = array_merge($formValues, $result);
                 // Assign amount to template if payment was successful.
                 $this->assign('amount', $params['total_amount']);
             } catch (PaymentProcessorException $e) {
                 if (!empty($paymentParams['contributionID'])) {
                     CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $this->_contactID, $e->getMessage());
                 }
                 if (!empty($paymentParams['contributionRecurID'])) {
                     CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
                 }
                 CRM_Core_Error::displaySessionError($result);
                 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
             }
         }
         if ($formValues['payment_status_id'] != array_search('Completed', $allContributionStatus)) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             // unset send-receipt option, since receipt will be sent when ipn is received.
             unset($formValues['send_receipt'], $formValues['send_receipt']);
             //as membership is pending set dates to null.
             $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
             foreach ($memberDates as $dv) {
                 ${$dv} = NULL;
                 foreach ($this->_memTypeSelected as $memType) {
                     $membershipTypeValues[$memType][$dv] = NULL;
                 }
             }
         }
         $params['receive_date'] = $now;
         $params['invoice_id'] = $formValues['invoiceID'];
         $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName));
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (!empty($formValues['send_receipt'])) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = NULL;
         }
         $this->set('params', $formValues);
         $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         //create membership record.
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
             }
             $membershipParams = array_merge($membershipTypeValues[$memType], $params);
             //CRM-15366
             if (!empty($softParams) && empty($paymentParams['is_recur'])) {
                 $membershipParams['soft_credit'] = $softParams;
             }
             // This is required to trigger the recording of the membership contribution in the
             // CRM_Member_BAO_Membership::Create function.
             // @todo stop setting this & 'teach' the create function to respond to something
             // appropriate as part of our 2-step always create the pending contribution & then finally add the payment
             // process -
             // @see http://wiki.civicrm.org/confluence/pages/viewpage.action?pageId=261062657#Payments&AccountsRoadmap-Movetowardsalwaysusinga2-steppaymentprocess
             $membershipParams['contribution_status_id'] = CRM_Utils_Array::value('payment_status_id', $result);
             if (!empty($paymentParams['is_recur'])) {
                 // The earlier process created the line items (although we want to get rid of the earlier one in favour
                 // of a single path!
                 unset($membershipParams['lineItems']);
             }
             $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
             $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
             unset($params['lineItems']);
             $this->_membershipIDs[] = $membership->id;
             $createdMemberships[$memType] = $membership;
             $count++;
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
             // update membership as well as contribution object, CRM-4395
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
             if (!empty($result) && !empty($params['contribution_id'])) {
                 $lineItem = array();
                 $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
                 $itemId = key($lineItems);
                 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
                 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
                 $lineItems[$itemId]['line_total'] = $params['total_amount'];
                 $lineItems[$itemId]['id'] = $itemId;
                 $lineItem[$priceSetId] = $lineItems;
                 $contributionBAO = new CRM_Contribute_BAO_Contribution();
                 $contributionBAO->id = $params['contribution_id'];
                 $contributionBAO->contact_id = $params['contact_id'];
                 $contributionBAO->find();
                 CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
                 //create new soft-credit record, CRM-13981
                 if ($softParams) {
                     $softParams['contribution_id'] = $params['contribution_id'];
                     while ($contributionBAO->fetch()) {
                         $softParams['currency'] = $contributionBAO->currency;
                         $softParams['amount'] = $contributionBAO->total_amount;
                     }
                     CRM_Contribute_BAO_ContributionSoft::add($softParams);
                 }
             }
             //carry updated membership object.
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(TRUE);
             $cancelled = TRUE;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 if (!in_array($membership->status_id, array(array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), array_search('Expired', CRM_Member_PseudoConstant::membershipStatus())))) {
                     $cancelled = FALSE;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
             $createdMemberships[] = $membership;
         } else {
             $count = 0;
             foreach ($this->_memTypeSelected as $memType) {
                 if ($count && !empty($formValues['record_contribution']) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                     $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
                 }
                 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
                 if (!empty($formValues['int_amount'])) {
                     $init_amount = array();
                     foreach ($formValues as $key => $value) {
                         if (strstr($key, 'txt-price')) {
                             $init_amount[$key] = $value;
                         }
                     }
                     $membershipParams['init_amount'] = $init_amount;
                 }
                 if (!empty($softParams)) {
                     $membershipParams['soft_credit'] = $softParams;
                 }
                 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
                 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
                 unset($params['lineItems']);
                 $this->_membershipIDs[] = $membership->id;
                 $createdMemberships[$memType] = $membership;
                 $count++;
             }
         }
     }
     if (!empty($lineItem[$this->_priceSetId])) {
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         $taxAmount = FALSE;
         $totalTaxAmount = 0;
         foreach ($lineItem[$this->_priceSetId] as &$priceFieldOp) {
             if (!empty($priceFieldOp['membership_type_id'])) {
                 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-';
                 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-';
             } else {
                 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
             }
             if ($invoicing && isset($priceFieldOp['tax_amount'])) {
                 $taxAmount = TRUE;
                 $totalTaxAmount += $priceFieldOp['tax_amount'];
             }
         }
         if ($invoicing) {
             $dataArray = array();
             foreach ($lineItem[$this->_priceSetId] as $key => $value) {
                 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
                     if (isset($dataArray[$value['tax_rate']])) {
                         $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                     } else {
                         $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                     }
                 }
             }
             if ($taxAmount) {
                 $this->assign('totalTaxAmount', $totalTaxAmount);
                 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
             }
             $this->assign('dataArray', $dataArray);
         }
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $receiptSend = FALSE;
     $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
     $membershipIds = $this->_membershipIDs;
     if ($contributionId && !empty($membershipIds)) {
         $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
         if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') {
             $receiptSend = TRUE;
         }
     }
     if (!empty($formValues['send_receipt']) && $receiptSend) {
         $formValues['contact_id'] = $this->_contactID;
         $formValues['contribution_id'] = $contributionId;
         // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
         // handled in the receipt. But by setting one we avoid breaking templates for now
         // although at some point we should switch in the templates.
         $formValues['receipt_text_signup'] = $formValues['receipt_text'];
         // send email receipt
         $mailSend = self::emailReceipt($this, $formValues, $membership);
     }
     // finally set membership id if already not set
     if (!$this->_id) {
         $this->_id = $membership->id;
     }
     $isRecur = CRM_Utils_Array::value('is_recur', $params);
     $this->setStatusMessage($membership, $endDate, $receiptSend, $membershipTypes, $createdMemberships, $isRecur, $calcDates, $mailSend);
     return $createdMemberships;
 }
Example #19
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     //set as Primary participant
     $params['is_primary'] = 1;
     if ($this->_values['event']['is_pay_later'] && (!array_key_exists('hidden_processor', $params) || $params['payment_processor_id'] == 0)) {
         $params['is_pay_later'] = 1;
     } else {
         $params['is_pay_later'] = 0;
     }
     $this->set('is_pay_later', $params['is_pay_later']);
     // assign pay later stuff
     $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
     $this->assign('is_pay_later', $params['is_pay_later']);
     if ($params['is_pay_later']) {
         $this->assign('pay_later_text', $this->_values['event']['pay_later_text']);
         $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
     }
     if (!$this->_allowConfirmation) {
         // check if the participant is already registered
         if (!$this->_skipDupeRegistrationCheck) {
             $params['contact_id'] = self::checkRegistration($params, $this, FALSE, TRUE, TRUE);
         }
     }
     if (!empty($params['image_URL'])) {
         CRM_Contact_BAO_Contact::processImageParams($params);
     }
     //carry campaign to partcipants.
     if (array_key_exists('participant_campaign_id', $params)) {
         $params['campaign_id'] = $params['participant_campaign_id'];
     } else {
         $params['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values['event']);
     }
     //hack to allow group to register w/ waiting
     $primaryParticipantCount = self::getParticipantCount($this, $params);
     $totalParticipants = $primaryParticipantCount;
     if (!empty($params['additional_participants'])) {
         $totalParticipants += $params['additional_participants'];
     }
     if (!$this->_allowConfirmation && !empty($params['bypass_payment']) && is_numeric($this->_availableRegistrations) && $totalParticipants > $this->_availableRegistrations) {
         $this->_allowWaitlist = TRUE;
         $this->set('allowWaitlist', TRUE);
     }
     //carry participant id if pre-registered.
     if ($this->_allowConfirmation && $this->_participantId) {
         $params['participant_id'] = $this->_participantId;
     }
     $params['defaultRole'] = 1;
     if (array_key_exists('participant_role', $params)) {
         $params['participant_role_id'] = $params['participant_role'];
     }
     if (array_key_exists('participant_role_id', $params)) {
         $params['defaultRole'] = 0;
     }
     if (empty($params['participant_role_id']) && $this->_values['event']['default_role_id']) {
         $params['participant_role_id'] = $this->_values['event']['default_role_id'];
     }
     $config = CRM_Core_Config::singleton();
     $params['currencyID'] = $config->defaultCurrency;
     if ($this->_values['event']['is_monetary']) {
         // we first reset the confirm page so it accepts new values
         $this->controller->resetPage('Confirm');
         //added for discount
         $discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
         $params['amount_level'] = $this->getAmountLevel($params, $discountId);
         if (!empty($this->_values['discount'][$discountId])) {
             $params['discount_id'] = $discountId;
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
         } elseif (empty($params['priceSetId'])) {
             if (!empty($params['amount'])) {
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
             } else {
                 $params['amount'] = '';
             }
         } else {
             $lineItem = array();
             CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem);
             if ($params['tax_amount']) {
                 $this->set('tax_amount', $params['tax_amount']);
             }
             $submittedLineItems = $this->get('lineItem');
             if (!empty($submittedLineItems) && is_array($submittedLineItems)) {
                 $submittedLineItems[0] = $lineItem;
             } else {
                 $submittedLineItems = array($lineItem);
             }
             $this->set('lineItem', $submittedLineItems);
             $this->set('lineItemParticipantsCount', array($primaryParticipantCount));
         }
         $this->set('amount', $params['amount']);
         $this->set('amount_level', $params['amount_level']);
         // generate and set an invoiceID for this transaction
         $invoiceID = md5(uniqid(rand(), TRUE));
         $this->set('invoiceID', $invoiceID);
         if ($this->_paymentProcessor) {
             $payment = $this->_paymentProcessor['object'];
             $payment->setBaseReturnUrl('civicrm/event/register');
         }
         // ContributeMode is a deprecated concept. It is short-hand for a bunch of
         // assumptions we are working to remove.
         $this->set('contributeMode', 'direct');
         // This code is duplicated multiple places and should be consolidated.
         if (isset($params["state_province_id-{$this->_bltID}"]) && $params["state_province_id-{$this->_bltID}"]) {
             $params["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["state_province_id-{$this->_bltID}"]);
         }
         if (isset($params["country_id-{$this->_bltID}"]) && $params["country_id-{$this->_bltID}"]) {
             $params["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["country_id-{$this->_bltID}"]);
         }
         if (isset($params['credit_card_exp_date'])) {
             $params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($params);
             $params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($params);
         }
         if ($this->_values['event']['is_monetary']) {
             $params['ip_address'] = CRM_Utils_System::ipAddress();
             $params['currencyID'] = $config->defaultCurrency;
             $params['invoiceID'] = $invoiceID;
         }
         $this->_params = $this->get('params');
         // Set the button so we know what
         $params['button'] = $this->controller->getButtonName();
         if (!empty($this->_params) && is_array($this->_params)) {
             $this->_params[0] = $params;
         } else {
             $this->_params = array();
             $this->_params[] = $params;
         }
         $this->set('params', $this->_params);
         if ($this->_paymentProcessor && $this->_paymentProcessor['object']->supports('preApproval') && !$this->_allowWaitlist && !$this->_requireApproval) {
             // The concept of contributeMode is deprecated - but still needs removal from the message templates.
             $this->set('contributeMode', 'express');
             // Send Event Name & Id in Params
             $params['eventName'] = $this->_values['event']['title'];
             $params['eventId'] = $this->_values['event']['id'];
             $params['cancelURL'] = CRM_Utils_System::url('civicrm/event/register', "_qf_Register_display=1&qfKey={$this->controller->_key}", TRUE, NULL, FALSE);
             if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
                 $urlArgs = "_qf_Participant_1_display=1&rfp=1&qfKey={$this->controller->_key}";
             } else {
                 $urlArgs = "_qf_Confirm_display=1&rfp=1&qfKey={$this->controller->_key}";
             }
             $params['returnURL'] = CRM_Utils_System::url('civicrm/event/register', $urlArgs, TRUE, NULL, FALSE);
             $params['invoiceID'] = $invoiceID;
             $params['component'] = 'event';
             $this->handlePreApproval($params);
         } elseif ($this->_paymentProcessor && $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY) {
             // The concept of contributeMode is deprecated - but still needs removal from the message templates.
             $this->set('contributeMode', 'notify');
         }
     } else {
         $params['description'] = ts('Online Event Registration') . ' ' . $this->_values['event']['title'];
         $this->_params = array();
         $this->_params[] = $params;
         $this->set('params', $this->_params);
         if (empty($params['additional_participants']) && !$this->_values['event']['is_confirm_enabled']) {
             $this->processRegistration($this->_params);
         }
     }
     // If registering > 1 participant, give status message
     if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
         $statusMsg = ts('Registration information for participant 1 has been saved.');
         CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     }
 }
 /**
  * Process credit card payment.
  *
  * @param array $submittedValues
  * @param array $lineItem
  *
  * @throws CRM_Core_Exception
  */
 protected function processCreditCard($submittedValues, $lineItem)
 {
     $sendReceipt = $contribution = FALSE;
     $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason');
     foreach ($unsetParams as $key) {
         if (isset($submittedValues[$key])) {
             unset($submittedValues[$key]);
         }
     }
     $isTest = $this->_mode == 'test' ? 1 : 0;
     // CRM-12680 set $_lineItem if its not set
     if (empty($this->_lineItem) && !empty($lineItem)) {
         $this->_lineItem = $lineItem;
     }
     //Get the require fields value only.
     $params = $this->_params = $submittedValues;
     $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
     // Get the payment processor id as per mode.
     $this->_params['payment_processor'] = $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
     $now = date('YmdHis');
     $fields = array();
     // we need to retrieve email address
     if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
         list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
         $this->assign('displayName', $this->userDisplayName);
     }
     // Set email for primary location.
     $fields['email-Primary'] = 1;
     $params['email-Primary'] = $this->userEmail;
     // now set the values for the billing location.
     foreach (array_keys($this->_fields) as $name) {
         $fields[$name] = 1;
     }
     // also add location name to the array
     $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
     $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
     $fields["address_name-{$this->_bltID}"] = 1;
     $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
     $nameFields = array('first_name', 'middle_name', 'last_name');
     foreach ($nameFields as $name) {
         $fields[$name] = 1;
         if (array_key_exists("billing_{$name}", $params)) {
             $params[$name] = $params["billing_{$name}"];
             $params['preserveDBName'] = TRUE;
         }
     }
     if (!empty($params['source'])) {
         unset($params['source']);
     }
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, NULL, NULL, $ctype);
     // add all the additional payment params we need
     if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
     }
     if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) {
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
     }
     $legacyCreditCardExpiryCheck = FALSE;
     if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD && !isset($this->_paymentFields)) {
         $legacyCreditCardExpiryCheck = TRUE;
     }
     if ($legacyCreditCardExpiryCheck || in_array('credit_card_exp_date', array_keys($this->_paymentFields))) {
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
     }
     $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
     $this->_params['amount'] = $this->_params['total_amount'];
     $this->_params['amount_level'] = 0;
     $this->_params['description'] = ts('Office Credit Card contribution');
     $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, CRM_Core_Config::singleton()->defaultCurrency);
     $this->_params['payment_action'] = 'Sale';
     if (!empty($this->_params['receive_date'])) {
         $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
     }
     if (!empty($params['soft_credit_to'])) {
         $this->_params['soft_credit_to'] = $params['soft_credit_to'];
         $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
     }
     $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
     $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
     $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
     //Add common data to formatted params
     CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
     if (empty($this->_params['invoice_id'])) {
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
     } else {
         $this->_params['invoiceID'] = $this->_params['invoice_id'];
     }
     // 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
     // so we copy stuff over to first_name etc.
     $paymentParams = $this->_params;
     $paymentParams['contactID'] = $this->_contactID;
     CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
     $contributionType = new CRM_Financial_DAO_FinancialType();
     $contributionType->id = $params['financial_type_id'];
     // Add some financial type details to the params list
     // if folks need to use it.
     $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
     $paymentParams['contributionPageID'] = NULL;
     if (!empty($this->_params['is_email_receipt'])) {
         $paymentParams['email'] = $this->userEmail;
         $paymentParams['is_email_receipt'] = 1;
     } else {
         $paymentParams['is_email_receipt'] = 0;
         $this->_params['is_email_receipt'] = 0;
     }
     if (!empty($this->_params['receive_date'])) {
         $paymentParams['receive_date'] = $this->_params['receive_date'];
     }
     // For recurring contribution, create Contribution Record first.
     // Contribution ID, Recurring ID and Contact ID needed
     // When we get a callback from the payment processor, CRM-7115
     if (!empty($paymentParams['is_recur'])) {
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, NULL, $this->_contactID, $contributionType, TRUE, FALSE, $isTest, $this->_lineItem);
         $paymentParams['contributionID'] = $contribution->id;
         $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
         $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
         $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
     }
     $result = array();
     if ($paymentParams['amount'] > 0.0) {
         // force a re-get of the payment processor in case the form changed it, CRM-7179
         $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
         try {
             $result = $payment->doPayment($paymentParams, 'contribute');
         } catch (CRM_Core_Exception $e) {
             $message = ts("Payment Processor Error message") . $e->getMessage();
             $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
             // Set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactID}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             if (!empty($this->_ppID)) {
                 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
             }
             CRM_Core_Error::statusBounce($message, $urlParams, ts('Payment Processor Error'));
         }
     }
     $this->_params = array_merge($this->_params, $result);
     $this->_params['receive_date'] = $now;
     if (!empty($this->_params['is_email_receipt'])) {
         $this->_params['receipt_date'] = $now;
     } else {
         $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'], $params['receipt_date_time'], TRUE);
     }
     $this->set('params', $this->_params);
     $this->assign('trxn_id', $result['trxn_id']);
     $this->assign('receive_date', $this->_params['receive_date']);
     // Result has all the stuff we need
     // lets archive it to a financial transaction
     if ($contributionType->is_deductible) {
         $this->assign('is_deductible', TRUE);
         $this->set('is_deductible', TRUE);
     }
     // Set source if not set
     if (empty($this->_params['source'])) {
         $userID = CRM_Core_Session::singleton()->get('userID');
         $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
         $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
     }
     // Build custom data getFields array
     $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, CRM_Utils_Array::value('financial_type_id', $params));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution');
     if (empty($paymentParams['is_recur'])) {
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, FALSE, $isTest, $this->_lineItem);
     }
     // Send receipt mail.
     if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
         $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $this->_params['contact_id'] = $this->_contactID;
         $this->_params['contribution_id'] = $contribution->id;
         $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
     }
     //process the note
     if ($contribution->id && isset($params['note'])) {
         CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
     }
     //process premium
     if ($contribution->id && isset($params['product_name'][0])) {
         CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
     }
     //update pledge payment status.
     if ($this->_ppID && $contribution->id) {
         // Store contribution id in payment record.
         CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
         CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount);
     }
     if ($contribution->id) {
         $statusMsg = ts('The contribution record has been processed.');
         if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
     }
 }
 /**
  * Begin post processing.
  *
  * This function aims to start to bring together common postProcessing functions.
  *
  * Eventually these are also shared with the front end forms & may need to be moved to where they can also
  * access this function.
  */
 protected function beginPostProcess()
 {
     if ($this->_mode) {
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode == 'test');
         if (in_array('credit_card_exp_date', array_keys($this->_params))) {
             $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']));
         $this->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $this->_params));
     }
     $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
 }
Example #22
0
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 public function preProcess()
 {
     $config = CRM_Core_Config::singleton();
     parent::preProcess();
     // lineItem isn't set until Register postProcess
     $this->_lineItem = $this->get('lineItem');
     $this->_paymentProcessor = $this->get('paymentProcessor');
     if ($this->_contributeMode == 'express') {
         // rfp == redirect from paypal
         $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET');
         if ($rfp) {
             $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
             $expressParams = $payment->getExpressCheckoutDetails($this->get('token'));
             $this->_params['payer'] = $expressParams['payer'];
             $this->_params['payer_id'] = $expressParams['payer_id'];
             $this->_params['payer_status'] = $expressParams['payer_status'];
             CRM_Core_Payment_Form::mapParams($this->_bltID, $expressParams, $this->_params, FALSE);
             // fix state and country id if present
             if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"]) && $this->_params["billing_state_province_id-{$this->_bltID}"]) {
                 $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
             }
             if (!empty($this->_params["billing_country_id-{$this->_bltID}"]) && $this->_params["billing_country_id-{$this->_bltID}"]) {
                 $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
             }
             // set a few other parameters for PayPal
             $this->_params['token'] = $this->get('token');
             $this->_params['amount'] = $this->get('amount');
             if (!empty($this->_membershipBlock)) {
                 $this->_params['selectMembership'] = $this->get('selectMembership');
             }
             // we use this here to incorporate any changes made by folks in hooks
             $this->_params['currencyID'] = $config->defaultCurrency;
             $this->_params['payment_action'] = 'Sale';
             // also merge all the other values from the profile fields
             $values = $this->controller->exportValues('Main');
             $skipFields = array('amount', 'amount_other', "billing_street_address-{$this->_bltID}", "billing_city-{$this->_bltID}", "billing_state_province_id-{$this->_bltID}", "billing_postal_code-{$this->_bltID}", "billing_country_id-{$this->_bltID}");
             foreach ($values as $name => $value) {
                 // skip amount field
                 if (!in_array($name, $skipFields)) {
                     $this->_params[$name] = $value;
                 }
             }
             $this->set('getExpressCheckoutDetails', $this->_params);
         } else {
             $this->_params = $this->get('getExpressCheckoutDetails');
         }
     } else {
         $this->_params = $this->controller->exportValues('Main');
         if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
             $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         }
         if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) {
             $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         }
         if (isset($this->_params['credit_card_exp_date'])) {
             $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
             $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         }
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $this->get('amount');
         $this->_useForMember = $this->get('useForMember');
         if (isset($this->_params['amount'])) {
             $priceField = new CRM_Price_DAO_PriceField();
             $priceField->price_set_id = $this->_params['priceSetId'];
             $priceField->orderBy('weight');
             $priceField->find();
             $contriPriceId = NULL;
             $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config');
             while ($priceField->fetch()) {
                 if ($priceField->name == "contribution_amount") {
                     $contriPriceId = $priceField->id;
                 }
                 if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) {
                     if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') {
                         $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_params["price_{$priceField->id}"], 'label');
                     }
                     if ($priceField->name == "membership_amount") {
                         $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_params["price_{$priceField->id}"], 'membership_type_id');
                     }
                 } elseif (CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) && !empty($this->_values['fee'][$priceField->id]) && $this->_values['fee'][$priceField->id]['name'] == "other_amount" && CRM_Utils_Array::value("price_{$contriPriceId}", $this->_params) < 1 && empty($this->_params["price_{$priceField->id}"])) {
                     $this->_params['amount'] = null;
                 }
             }
         }
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
     }
     $this->_params['is_pay_later'] = $this->get('is_pay_later');
     $this->assign('is_pay_later', $this->_params['is_pay_later']);
     if ($this->_params['is_pay_later']) {
         $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
     }
     // if onbehalf-of-organization
     if (!empty($this->_params['hidden_onbehalf_profile'])) {
         if (!empty($this->_params['org_option']) && !empty($this->_params['organization_id'])) {
             if (!empty($this->_params['onbehalfof_id'])) {
                 $this->_params['organization_id'] = $this->_params['onbehalfof_id'];
             }
         }
         $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name'];
         $addressBlocks = array('street_address', 'city', 'state_province', 'postal_code', 'country', 'supplemental_address_1', 'supplemental_address_2', 'supplemental_address_3', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'address_name');
         $blocks = array('email', 'phone', 'im', 'url', 'openid');
         foreach ($this->_params['onbehalf'] as $loc => $value) {
             $field = $typeId = NULL;
             if (strstr($loc, '-')) {
                 list($field, $locType) = explode('-', $loc);
             }
             if (in_array($field, $addressBlocks)) {
                 if ($locType == 'Primary') {
                     $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
                     $locType = $defaultLocationType->id;
                 }
                 if ($field == 'country') {
                     $value = CRM_Core_PseudoConstant::countryIsoCode($value);
                 } elseif ($field == 'state_province') {
                     $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
                 }
                 $isPrimary = 1;
                 if (isset($this->_params['onbehalf_location']['address']) && count($this->_params['onbehalf_location']['address']) > 0) {
                     $isPrimary = 0;
                 }
                 $this->_params['onbehalf_location']['address'][$locType][$field] = $value;
                 if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) {
                     $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
                 }
                 $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
             } elseif (in_array($field, $blocks)) {
                 if (!$typeId || is_numeric($typeId)) {
                     $blockName = $fieldName = $field;
                     $locationType = 'location_type_id';
                     if ($locType == 'Primary') {
                         $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
                         $locationValue = $defaultLocationType->id;
                     } else {
                         $locationValue = $locType;
                     }
                     $locTypeId = '';
                     $phoneExtField = array();
                     if ($field == 'url') {
                         $blockName = 'website';
                         $locationType = 'website_type_id';
                         $locationValue = CRM_Utils_Array::value("{$loc}-website_type_id", $this->_params['onbehalf']);
                     } elseif ($field == 'im') {
                         $fieldName = 'name';
                         $locTypeId = 'provider_id';
                         $typeId = $this->_params['onbehalf']["{$loc}-provider_id"];
                     } elseif ($field == 'phone') {
                         list($field, $locType, $typeId) = explode('-', $loc);
                         $locTypeId = 'phone_type_id';
                         //check if extension field exists
                         $extField = str_replace('phone', 'phone_ext', $loc);
                         if (isset($this->_params['onbehalf'][$extField])) {
                             $phoneExtField = array('phone_ext' => $this->_params['onbehalf'][$extField]);
                         }
                     }
                     $isPrimary = 1;
                     if (isset($this->_params['onbehalf_location'][$blockName]) && count($this->_params['onbehalf_location'][$blockName]) > 0) {
                         $isPrimary = 0;
                     }
                     if ($locationValue) {
                         $blockValues = array($fieldName => $value, $locationType => $locationValue, 'is_primary' => $isPrimary);
                         if ($locTypeId) {
                             $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
                         }
                         if (!empty($phoneExtField)) {
                             $blockValues = array_merge($blockValues, $phoneExtField);
                         }
                         $this->_params['onbehalf_location'][$blockName][] = $blockValues;
                     }
                 }
             } elseif (strstr($loc, 'custom')) {
                 if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) {
                     $value = $this->_params['onbehalf']["{$loc}_id"];
                 }
                 $this->_params['onbehalf_location']["{$loc}"] = $value;
             } else {
                 if ($loc == 'contact_sub_type') {
                     $this->_params['onbehalf_location'][$loc] = $value;
                 } else {
                     $this->_params['onbehalf_location'][$field] = $value;
                 }
             }
         }
     } elseif (!empty($this->_values['is_for_organization'])) {
         // no on behalf of an organization, CRM-5519
         // so reset loc blocks from main params.
         foreach (array('phone', 'email', 'address') as $blk) {
             if (isset($this->_params[$blk])) {
                 unset($this->_params[$blk]);
             }
         }
     }
     // if auto renew checkbox is set, initiate a open-ended recurring membership
     if ((!empty($this->_params['selectMembership']) || !empty($this->_params['priceSetId'])) && !empty($this->_paymentProcessor['is_recur']) && CRM_Utils_Array::value('auto_renew', $this->_params) && empty($this->_params['is_recur']) && empty($this->_params['frequency_interval'])) {
         $this->_params['is_recur'] = $this->_values['is_recur'] = 1;
         // check if price set is not quick config
         if (!empty($this->_params['priceSetId']) && !$isQuickConfig) {
             list($this->_params['frequency_interval'], $this->_params['frequency_unit']) = CRM_Price_BAO_PriceSet::getRecurDetails($this->_params['priceSetId']);
         } else {
             // FIXME: set interval and unit based on selected membership type
             $this->_params['frequency_interval'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'duration_interval');
             $this->_params['frequency_unit'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'duration_unit');
         }
     }
     if ($this->_pcpId) {
         $params = $this->processPcp($this, $this->_params);
         $this->_params = $params;
     }
     $this->_params['invoiceID'] = $this->get('invoiceID');
     //carry campaign from profile.
     if (array_key_exists('contribution_campaign_id', $this->_params)) {
         $this->_params['campaign_id'] = $this->_params['contribution_campaign_id'];
     }
     // assign contribution page id to the template so we can add css class for it
     $this->assign('contributionPageID', $this->_id);
     $this->set('params', $this->_params);
 }
Example #23
0
 /**
  * Process credit card payment.
  *
  * @param array $submittedValues
  * @param array $lineItem
  *
  * @param int $contactID
  *   Contact ID
  *
  * @return bool|\CRM_Contribute_DAO_Contribution
  * @throws \CiviCRM_API3_Exception
  * @throws \Civi\Payment\Exception\PaymentProcessorException
  */
 protected function processCreditCard($submittedValues, $lineItem, $contactID)
 {
     $contribution = FALSE;
     $isTest = $this->_mode == 'test' ? 1 : 0;
     // CRM-12680 set $_lineItem if its not set
     // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
     // It would be better to pass line item out to functions than $this->_lineItem as
     // we don't know what is being changed where.
     if (empty($this->_lineItem) && !empty($lineItem)) {
         $this->_lineItem = $lineItem;
     }
     $this->_paymentObject = Civi\Payment\System::singleton()->getById($submittedValues['payment_processor_id']);
     $this->_paymentProcessor = $this->_paymentObject->getPaymentProcessor();
     // Set source if not set
     if (empty($submittedValues['source'])) {
         $userID = CRM_Core_Session::singleton()->get('userID');
         $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
         $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
     }
     $params = $this->_params = $submittedValues;
     // Mapping requiring documentation.
     $this->_params['payment_processor'] = $submittedValues['payment_processor_id'];
     $now = date('YmdHis');
     $fields = array();
     // we need to retrieve email address
     if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
         list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
         $this->assign('displayName', $this->userDisplayName);
     }
     // Set email for primary location.
     $fields['email-Primary'] = 1;
     $params['email-Primary'] = $this->userEmail;
     // now set the values for the billing location.
     foreach (array_keys($this->_fields) as $name) {
         $fields[$name] = 1;
     }
     // also add location name to the array
     $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
     $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
     $fields["address_name-{$this->_bltID}"] = 1;
     $nameFields = array('first_name', 'middle_name', 'last_name');
     foreach ($nameFields as $name) {
         $fields[$name] = 1;
         if (array_key_exists("billing_{$name}", $params)) {
             $params[$name] = $params["billing_{$name}"];
             $params['preserveDBName'] = TRUE;
         }
     }
     if (!empty($params['source'])) {
         unset($params['source']);
     }
     CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $contactID, NULL, NULL, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type'));
     // add all the additional payment params we need
     if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
     }
     if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) {
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
     }
     if (in_array('credit_card_exp_date', array_keys($this->_paymentFields))) {
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
     }
     $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
     $this->_params['amount'] = $this->_params['total_amount'];
     $this->_params['amount_level'] = 0;
     $this->_params['description'] = ts('Office Credit Card contribution');
     $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, CRM_Core_Config::singleton()->defaultCurrency);
     if (!empty($this->_params['receive_date'])) {
         $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
     }
     if (!empty($params['soft_credit_to'])) {
         $this->_params['soft_credit_to'] = $params['soft_credit_to'];
         $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
     }
     $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
     $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
     $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
     //Add common data to formatted params
     CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
     if (empty($this->_params['invoice_id'])) {
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
     } else {
         $this->_params['invoiceID'] = $this->_params['invoice_id'];
     }
     // 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
     // so we copy stuff over to first_name etc.
     $paymentParams = $this->_params;
     $paymentParams['contactID'] = $contactID;
     CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
     $financialType = new CRM_Financial_DAO_FinancialType();
     $financialType->id = $params['financial_type_id'];
     // Add some financial type details to the params list
     // if folks need to use it.
     $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $financialType->name;
     $paymentParams['contributionPageID'] = NULL;
     if (!empty($this->_params['is_email_receipt'])) {
         $paymentParams['email'] = $this->userEmail;
         $paymentParams['is_email_receipt'] = 1;
     } else {
         $paymentParams['is_email_receipt'] = 0;
         $this->_params['is_email_receipt'] = 0;
     }
     if (!empty($this->_params['receive_date'])) {
         $paymentParams['receive_date'] = $this->_params['receive_date'];
     }
     $this->_params['receive_date'] = $now;
     if (!empty($this->_params['is_email_receipt'])) {
         $this->_params['receipt_date'] = $now;
     } else {
         $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'], $params['receipt_date_time'], TRUE);
     }
     $this->set('params', $this->_params);
     $this->assign('receive_date', $this->_params['receive_date']);
     // Result has all the stuff we need
     // lets archive it to a financial transaction
     if ($financialType->is_deductible) {
         $this->assign('is_deductible', TRUE);
         $this->set('is_deductible', TRUE);
     }
     $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this, $this->_params, NULL, $contactID, $financialType, TRUE, FALSE, $isTest, $lineItem, $this->_bltID);
     $paymentParams['contributionID'] = $contribution->id;
     $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
     $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
     $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
     if ($paymentParams['amount'] > 0.0) {
         // force a re-get of the payment processor in case the form changed it, CRM-7179
         // NOTE - I expect this is not obsolete.
         $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
         try {
             $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
             $result = $payment->doPayment($paymentParams, 'contribute');
             $this->assign('trxn_id', $result['trxn_id']);
             $contribution->trxn_id = $result['trxn_id'];
             /* Our scenarios here are
              *  1) the payment failed & an Exception should have been thrown
              *  2) the payment succeeded but the payment is not immediate (for example a recurring payment
              *     with a delayed start)
              *  3) the payment succeeded with an immediate payment.
              *
              * The doPayment function ensures that contribution_status_id is always set
              * as historically we have had to guess from the context - ie doDirectPayment
              * = error or success, unless it is a recurring contribution in which case it is pending.
              */
             if (!isset($result['contribution_status_id']) || $result['contribution_status_id'] == array_search('Completed', $statuses)) {
                 civicrm_api3('contribution', 'completetransaction', array('id' => $contribution->id, 'trxn_id' => $result['trxn_id']));
             } else {
                 // Save the trxn_id.
                 $contribution->save();
             }
         } catch (PaymentProcessorException $e) {
             CRM_Contribute_BAO_Contribution::failPayment($contribution->id, $paymentParams['contactID'], $e->getMessage());
             throw new PaymentProcessorException($e->getMessage());
         }
     }
     // Send receipt mail.
     if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
         $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $this->_params['contact_id'] = $contactID;
         $this->_params['contribution_id'] = $contribution->id;
         if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE)) {
             $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
         }
     }
     return $contribution;
 }
Example #24
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if ($this->_action & CRM_Core_Action::DELETE) {
         if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
             $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId);
         }
         if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
             $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             foreach ($additionalIds as $value) {
                 CRM_Event_BAO_Participant::deleteParticipant($value);
             }
         }
         CRM_Event_BAO_Participant::deleteParticipant($this->_id);
         CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
         if (!empty($participantLinks)) {
             $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
             CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
         }
         return;
     }
     // When adding a single contact, the formRule prevents you from adding duplicates
     // (See above in formRule()). When adding more than one contact, the duplicates are
     // removed automatically and the user receives one notification.
     if ($this->_action & CRM_Core_Action::ADD) {
         $event_id = $this->_eventId;
         if (empty($event_id) && !empty($params['event_id'])) {
             $event_id = $params['event_id'];
         }
         if (!$this->_single && !empty($event_id)) {
             $duplicateContacts = 0;
             while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
                 // Eliminate contacts that have already been assigned to this event.
                 $dupeCheck = new CRM_Event_BAO_Participant();
                 $dupeCheck->contact_id = $dupeCheckContactId;
                 $dupeCheck->event_id = $event_id;
                 $dupeCheck->find(TRUE);
                 if (!empty($dupeCheck->id)) {
                     $duplicateContacts++;
                     unset($this->_contactIds[$k]);
                 }
             }
             if ($duplicateContacts > 0) {
                 $msg = ts("%1 contacts have already been assigned to this event. They were not added a second time.", array(1 => $duplicateContacts));
                 CRM_Core_Session::setStatus($msg);
             }
             if (count($this->_contactIds) == 0) {
                 CRM_Core_Session::setStatus(ts("No participants were added."));
                 return;
             }
             // We have to re-key $this->_contactIds so each contact has the same
             // key as their corresponding record in the $participants array that
             // will be created below.
             $this->_contactIds = array_values($this->_contactIds);
         }
     }
     $participantStatus = CRM_Event_PseudoConstant::participantStatus();
     // set the contact, when contact is selected
     if (!empty($params['contact_id'])) {
         $this->_contactId = $params['contact_id'];
     }
     if ($this->_priceSetId && ($isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config'))) {
         $this->_quickConfig = $isQuickConfig;
     }
     if ($this->_id) {
         $params['id'] = $this->_id;
     }
     $config = CRM_Core_Config::singleton();
     if ($this->_isPaidEvent) {
         $contributionParams = array();
         $lineItem = array();
         $additionalParticipantDetails = array();
         if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
             $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
             if ($eventStartDate) {
                 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
             }
         }
         if ($this->_id && $this->_action & CRM_Core_Action::UPDATE && $this->_paymentId) {
             $participantBAO = new CRM_Event_BAO_Participant();
             $participantBAO->id = $this->_id;
             $participantBAO->find(TRUE);
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
             $params['discount_id'] = NULL;
             //re-enter the values for UPDATE mode
             $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
             $params['fee_amount'] = $participantBAO->fee_amount;
             if (isset($params['priceSetId'])) {
                 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
             }
             //also add additional participant's fee level/priceset
             if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
                 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
                 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds, $hasLineItems);
             }
         } else {
             //check if discount is selected
             if (!empty($params['discount_id'])) {
                 $discountId = $params['discount_id'];
             } else {
                 $discountId = $params['discount_id'] = 'null';
             }
             //lets carry currency, CRM-4453
             $params['fee_currency'] = $config->defaultCurrency;
             CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[0]);
             //CRM-11529 for quick config backoffice transactions
             //when financial_type_id is passed in form, update the
             //lineitems with the financial type selected in form
             $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
             $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
             if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
                 foreach ($lineItem[0] as &$values) {
                     $values['financial_type_id'] = $submittedFinancialType;
                 }
             }
             $params['fee_level'] = $params['amount_level'];
             $contributionParams['total_amount'] = $params['amount'];
             if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                 $params['fee_amount'] = $params['total_amount'];
             } else {
                 //fix for CRM-3086
                 $params['fee_amount'] = $params['amount'];
             }
         }
         if (isset($params['priceSetId'])) {
             if (!empty($lineItem[0])) {
                 $this->set('lineItem', $lineItem);
                 $this->_lineItem = $lineItem;
                 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
                 $participantCount = array();
                 foreach ($lineItem as $k) {
                     foreach ($k as $v) {
                         if (CRM_Utils_Array::value('participant_count', $v) > 0) {
                             $participantCount[] = $v['participant_count'];
                         }
                     }
                 }
             }
             if (isset($participantCount)) {
                 $this->assign('pricesetFieldsCount', $participantCount);
             }
             $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
         } else {
             $this->assign('amount_level', $params['amount_level']);
         }
     }
     $this->_params = $params;
     $amountOwed = NULL;
     if (isset($params['amount'])) {
         $amountOwed = $params['amount'];
         unset($params['amount']);
     }
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
     $params['contact_id'] = $this->_contactId;
     // overwrite actual payment amount if entered
     if (!empty($params['total_amount'])) {
         $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
     }
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
     if ($this->_contactId) {
         list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
     }
     //modify params according to parameter used in create
     //participant method (addParticipant)
     $this->_params['participant_status_id'] = $params['status_id'];
     $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
     $this->_params['participant_register_date'] = $params['register_date'];
     $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         // set source if not set
         if (empty($params['source'])) {
             $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(1 => $userName, 2 => $eventTitle));
         } else {
             $this->_params['participant_source'] = $params['source'];
         }
         $this->_params['description'] = $this->_params['participant_source'];
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['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
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = TRUE;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     }
     if (!empty($this->_params['participant_role_id'])) {
         $customFieldsRole = array();
         foreach ($this->_params['participant_role_id'] as $roleKey) {
             $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
         }
         $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
         $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $this->_eventTypeId, $this->_eventTypeCustomDataTypeID);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, 'Participant');
     }
     //do cleanup line  items if participant edit the Event Fee.
     if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
         CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
     }
     if ($this->_mode) {
         // 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($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         // 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
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         // The only reason for merging in the 'contact_id' rather than ensuring it is set
         // is that this patch is being done around the time of the stable release
         // so more conservative approach is called for.
         // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
         // needs rationalising.
         $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
         CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
         $payment = $this->_paymentProcessor['object'];
         // CRM-15622: fix for incorrect contribution.fee_amount
         $paymentParams['fee_amount'] = NULL;
         $result = $payment->doPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (!empty($this->_params['send_receipt'])) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         //add contribution record
         $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution record
         $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
         // add participant record
         $participants = array();
         if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
             $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['role_id']);
         }
         //CRM-15372 patch to fix fee amount replacing amount
         $this->_params['fee_amount'] = $this->_params['amount'];
         $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
         //add custom data for participant
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $this->_contactIds[] = $this->_contactId;
     } else {
         $participants = array();
         if ($this->_single) {
             if ($params['role_id']) {
                 $params['role_id'] = $roleIdWithSeparator;
             } else {
                 $params['role_id'] = 'NULL';
             }
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 if ($commonParams['role_id']) {
                     $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
                 } else {
                     $commonParams['role_id'] = 'NULL';
                 }
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactId;
         }
         $contributions = array();
         if (!empty($params['record_contribution'])) {
             if (!empty($params['id'])) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 if (empty($params['source'])) {
                     $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(1 => $eventTitle, 2 => $userName));
                 } else {
                     $contributionParams['source'] = $params['source'];
                 }
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number', 'campaign_id');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert financial type name in receipt.
             $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             // legacy support
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             $contributionParams['skipLineItem'] = 1;
             if ($this->_id) {
                 $contributionParams['contribution_mode'] = 'participant';
                 $contributionParams['participant_id'] = $this->_id;
             }
             // Set is_pay_later flag for back-office offline Pending status contributions
             if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
                 $contributionParams['is_pay_later'] = 1;
             } elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
                 $contributionParams['is_pay_later'] = 0;
             }
             if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
                 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
                     $amountOwed = $params['fee_amount'];
                 }
                 // if multiple participants are link, consider contribution total amount as the amount Owed
                 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                     $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'total_amount');
                 }
                 // CRM-13964 partial_payment_total
                 if ($amountOwed > $params['total_amount']) {
                     // the owed amount
                     $contributionParams['partial_payment_total'] = $amountOwed;
                     // the actual amount paid
                     $contributionParams['partial_amount_pay'] = $params['total_amount'];
                 }
             }
             if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
                 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
             }
             if ($this->_single) {
                 if (empty($ids)) {
                     $ids = array();
                 }
                 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (empty($ids['contribution'])) {
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO = new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
             // next create the transaction record
             $transaction = new CRM_Core_Transaction();
             // CRM-11124
             if ($this->_params['discount_id']) {
                 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params));
             }
             $transaction->commit();
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) {
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $lineKey => $line) {
                         //10117 update the line items for participants if contribution amount is recorded
                         if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                             $line['unit_price'] = $line['line_total'] = $params['total_amount'];
                             if (!empty($params['tax_amount'])) {
                                 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
                                 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
                             }
                         }
                         $lineItem[$this->_priceSetId][$lineKey] = $line;
                     }
                     CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
                     CRM_Contribute_BAO_Contribution::addPayments($value, $contributions);
                 }
             }
         }
     }
     $updateStatusMsg = NULL;
     //send mail when participant status changed, CRM-4326
     if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])) {
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId);
     }
     $sent = array();
     $notSent = array();
     if (!empty($params['send_receipt'])) {
         if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
             $receiptFrom = $params['from_email_address'];
         }
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $participantRoles = CRM_Utils_Array::value('role_id', $params);
         if (is_array($participantRoles)) {
             $selectedRoles = array();
             foreach ($participantRoles as $roleId) {
                 $selectedRoles[] = $role[$roleId];
             }
             $event['participant_role'] = implode(', ', $selectedRoles);
         } else {
             $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
         }
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 if (isset($params['payment_instrument_id'])) {
                     $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
                 }
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             if (isset($contributionParams['partial_payment_total'])) {
                 // balance amount
                 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
                 $this->assign('balanceAmount', $balanceAmount);
             }
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (!empty($params['billing_first_name'])) {
                 $name = $params['billing_first_name'];
             }
             if (!empty($params['billing_middle_name'])) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (!empty($params['billing_last_name'])) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = 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($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($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             // The concept of contributeMode is deprecated.
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (!empty($this->_defaultValues['is_test'])) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template = CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
                 $this->assign('isOnWaitlist', TRUE);
             }
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             $this->_id = $participants[$num]->id;
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
                 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
                 $totalTaxAmount = 0;
                 //add dataArray in the receipts in ADD and UPDATE condition
                 $dataArray = array();
                 if ($this->_action & CRM_Core_Action::ADD) {
                     $line = $lineItem[0];
                 } elseif ($this->_action & CRM_Core_Action::UPDATE) {
                     $line = $this->_values['line_items'];
                 }
                 if ($invoicing) {
                     foreach ($line as $key => $value) {
                         if (isset($value['tax_amount'])) {
                             $totalTaxAmount += $value['tax_amount'];
                             if (isset($dataArray[(string) $value['tax_rate']])) {
                                 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                             } else {
                                 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                             }
                         }
                     }
                     $this->assign('totalTaxAmount', $totalTaxAmount);
                     $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
                     $this->assign('dataArray', $dataArray);
                 }
                 if (!empty($additionalParticipantDetails)) {
                     $params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
                 }
                 $eventAmount[$num] = array('label' => preg_replace('//', '', $params['amount_level']), 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => !empty($this->_defaultValues['is_test']), 'PDFFilename' => ts('confirmation') . '.pdf');
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
             }
             //send email with pdf invoice
             $template = CRM_Core_Smarty::singleton();
             $taxAmt = $template->get_template_vars('dataArray');
             $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
             $prefixValue = Civi::settings()->get('contribution_invoice_settings');
             $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
             if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
                 $sendTemplateParams['isEmailPdf'] = TRUE;
                 $sendTemplateParams['contributionId'] = $contributionId;
             }
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
                 foreach ($participants as $ids => $values) {
                     if ($values->contact_id == $contactID) {
                         $values->details = CRM_Utils_Array::value('receipt_text', $params);
                         CRM_Activity_BAO_Activity::addActivity($values, 'Email');
                         break;
                     }
                 }
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     // set the participant id if it is not set
     if (!$this->_id) {
         $this->_id = $participants[0]->id;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if (!empty($params['send_receipt']) && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (!empty($params['send_receipt']) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $session = CRM_Core_Session::singleton();
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $urlParams = 'reset=1&action=add&context=standalone';
             if ($this->_mode) {
                 $urlParams .= '&mode=' . $this->_mode;
             }
             if ($this->_eID) {
                 $urlParams .= '&eid=' . $this->_eID;
             }
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"));
     }
 }
Example #25
0
 /**
  * Set variables up before form is built.
  *
  * @return void
  */
 public function preProcess()
 {
     parent::preProcess();
     // lineItem isn't set until Register postProcess
     $this->_lineItem = $this->get('lineItem');
     $this->_params = $this->get('params');
     $this->_params[0]['tax_amount'] = $this->get('tax_amount');
     $this->_params[0]['is_pay_later'] = $this->get('is_pay_later');
     $this->assign('is_pay_later', $this->_params[0]['is_pay_later']);
     if ($this->_params[0]['is_pay_later']) {
         $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
     }
     CRM_Utils_Hook::eventDiscount($this, $this->_params);
     if (!empty($this->_params[0]['discount']) && !empty($this->_params[0]['discount']['applied'])) {
         $this->set('hookDiscount', $this->_params[0]['discount']);
         $this->assign('hookDiscount', $this->_params[0]['discount']);
     }
     if ($this->_contributeMode == 'express') {
         $params = array();
         // rfp == redirect from paypal
         $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET');
         //we lost rfp in case of additional participant. So set it explicitly.
         if ($rfp || CRM_Utils_Array::value('additional_participants', $this->_params[0], FALSE)) {
             $payment = $this->_paymentProcessor['object'];
             $paymentObjError = ts('The system did not record payment details for this payment and so could not process the transaction. Please report this error to the site administrator.');
             if (is_object($payment)) {
                 $expressParams = $payment->getExpressCheckoutDetails($this->get('token'));
             } else {
                 CRM_Core_Error::fatal($paymentObjError);
             }
             $params['payer'] = CRM_Utils_Array::value('payer', $expressParams);
             $params['payer_id'] = $expressParams['payer_id'];
             $params['payer_status'] = $expressParams['payer_status'];
             CRM_Core_Payment_Form::mapParams($this->_bltID, $expressParams, $params, FALSE);
             // fix state and country id if present
             if (isset($params["billing_state_province_id-{$this->_bltID}"])) {
                 $params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["billing_state_province_id-{$this->_bltID}"]);
             }
             if (isset($params['billing_country_id'])) {
                 $params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["billing_country_id-{$this->_bltID}"]);
             }
             // set a few other parameters for PayPal
             $params['token'] = $this->get('token');
             $params['amount'] = $this->_params[0]['amount'];
             if (!empty($this->_params[0]['discount'])) {
                 $params['discount'] = $this->_params[0]['discount'];
                 $params['discountAmount'] = $this->_params[0]['discountAmount'];
                 $params['discountMessage'] = $this->_params[0]['discountMessage'];
             }
             if (!empty($this->_params[0]['amount_priceset_level_radio'])) {
                 $params['amount_priceset_level_radio'] = $this->_params[0]['amount_priceset_level_radio'];
             }
             $params['amount_level'] = $this->_params[0]['amount_level'];
             $params['currencyID'] = $this->_params[0]['currencyID'];
             // also merge all the other values from the profile fields
             $values = $this->controller->exportValues('Register');
             $skipFields = array('amount', "street_address-{$this->_bltID}", "city-{$this->_bltID}", "state_province_id-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}");
             foreach ($values as $name => $value) {
                 // skip amount field
                 if (!in_array($name, $skipFields)) {
                     $params[$name] = $value;
                 }
                 if (substr($name, 0, 6) == 'price_') {
                     $params[$name] = $this->_params[0][$name];
                 }
             }
             $this->set('getExpressCheckoutDetails', $params);
         } else {
             $params = $this->get('getExpressCheckoutDetails');
         }
         $this->_params[0] = $params;
         $this->_params[0]['is_primary'] = 1;
     } else {
         //process only primary participant params.
         $registerParams = $this->_params[0];
         if (isset($registerParams["billing_state_province_id-{$this->_bltID}"]) && $registerParams["billing_state_province_id-{$this->_bltID}"]) {
             $registerParams["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($registerParams["billing_state_province_id-{$this->_bltID}"]);
         }
         if (isset($registerParams["billing_country_id-{$this->_bltID}"]) && $registerParams["billing_country_id-{$this->_bltID}"]) {
             $registerParams["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($registerParams["billing_country_id-{$this->_bltID}"]);
         }
         if (isset($registerParams['credit_card_exp_date'])) {
             $registerParams['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($registerParams);
             $registerParams['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($registerParams);
         }
         if ($this->_values['event']['is_monetary']) {
             $registerParams['ip_address'] = CRM_Utils_System::ipAddress();
             $registerParams['currencyID'] = $this->_params[0]['currencyID'];
         }
         //assign back primary participant params.
         $this->_params[0] = $registerParams;
     }
     if ($this->_values['event']['is_monetary']) {
         $this->_params[0]['invoiceID'] = $this->get('invoiceID');
     }
     $this->assign('defaultRole', FALSE);
     if (CRM_Utils_Array::value('defaultRole', $this->_params[0]) == 1) {
         $this->assign('defaultRole', TRUE);
     }
     if (empty($this->_params[0]['participant_role_id']) && $this->_values['event']['default_role_id']) {
         $this->_params[0]['participant_role_id'] = $this->_values['event']['default_role_id'];
     }
     if (isset($this->_values['event']['confirm_title'])) {
         CRM_Utils_System::setTitle($this->_values['event']['confirm_title']);
     }
     if ($this->_pcpId) {
         $params = CRM_Contribute_Form_Contribution_Confirm::processPcp($this, $this->_params[0]);
         $this->_params[0] = $params;
     }
     $this->set('params', $this->_params);
 }
Example #26
0
 /**
  * @param array $params
  *
  * @return array|void
  * @throws Exception
  */
 public function make_payment(&$params)
 {
     $config = CRM_Core_Config::singleton();
     if (isset($params["billing_state_province_id-{$this->_bltID}"]) && $params["billing_state_province_id-{$this->_bltID}"]) {
         $params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["billing_state_province_id-{$this->_bltID}"]);
     }
     if (isset($params["billing_country_id-{$this->_bltID}"]) && $params["billing_country_id-{$this->_bltID}"]) {
         $params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["billing_country_id-{$this->_bltID}"]);
     }
     $params['ip_address'] = CRM_Utils_System::ipAddress();
     $params['currencyID'] = $config->defaultCurrency;
     $params['payment_action'] = 'Sale';
     $payment =& CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
     CRM_Core_Payment_Form::mapParams($this->_bltID, $params, $params, TRUE);
     $params['month'] = $params['credit_card_exp_date']['M'];
     $params['year'] = $params['credit_card_exp_date']['Y'];
     $result =& $payment->doDirectPayment($params);
     if (is_a($result, 'CRM_Core_Error')) {
         CRM_Core_Error::displaySessionError($result);
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/cart_checkout', "_qf_Payment_display=1&qfKey={$this->controller->_key}", TRUE, NULL, FALSE));
         return NULL;
     } elseif (!$result['trxn_id']) {
         CRM_Core_Error::fatal(ts("Financial institution didn't return a transaction id."));
     }
     $trxnDetails = array('trxn_id' => $result['trxn_id'], 'trxn_date' => $result['now'], 'currency' => CRM_Utils_Array::value('currencyID', $result));
     return $trxnDetails;
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     $session = CRM_Core_Session::singleton();
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute"));
         return;
     }
     // get the submitted form values.
     $submittedValues = $this->controller->exportValues($this->_name);
     if (CRM_Utils_Array::value('price_set_id', $submittedValues) && $this->_action & CRM_Core_Action::UPDATE) {
         $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
         $lineID = key($line);
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
         $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $priceSetId, 'is_quick_config');
         if ($quickConfig) {
             CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
         }
     }
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = $pId = NULL;
     $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
     if (empty($priceSetId) && !$this->_id) {
         $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', 'default_contribution_amount', 'id', 'name');
         $this->_priceSet = current(CRM_Price_BAO_Set::getSetDetail($priceSetId));
         $fieldID = key($this->_priceSet['fields']);
         $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
         $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
         $submittedValues['price_' . $fieldID] = 1;
     }
     if ($priceSetId) {
         CRM_Price_BAO_Set::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
     }
     if (!$priceSetId && CRM_Utils_Array::value('total_amount', $submittedValues) && $this->_id) {
         // 10117 update th line items for participants
         $pId = $this->_compId && $this->_context == 'participant' ? $this->_compId : CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
         //CRM-10964
         if ($pId) {
             $entityTable = 'participant';
             $entityID = $pId;
             $participantParams = array('fee_amount' => $submittedValues['total_amount'], 'id' => $entityID);
             CRM_Event_BAO_Participant::add($participantParams);
             if (empty($this->_lineItems)) {
                 $this->_lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
             }
         } else {
             $entityTable = 'contribution';
             $entityID = $this->_id;
         }
         $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable);
         $itemId = key($lineItems);
         $fieldType = NULL;
         if ($itemId && CRM_Utils_Array::value('price_field_id', $lineItems[$itemId])) {
             $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'html_type');
         }
         $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
         $lineItems[$itemId]['id'] = $itemId;
         // 10117 update th line items for participants
         $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'price_set_id');
         $lineItem[$this->_priceSetId] = $lineItems;
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     if (!CRM_Utils_Array::value('total_amount', $submittedValues)) {
         $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     if (CRM_Utils_Array::value('soft_credit_to', $submittedValues)) {
         $submittedValues['soft_credit_to'] = $submittedValues['soft_contact_id'];
     }
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $submittedValues)) {
         $this->_contactID = $submittedValues['contact_select_id'][1];
     }
     $config = CRM_Core_Config::singleton();
     //Credit Card Contribution.
     if ($this->_mode) {
         $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason');
         foreach ($unsetParams as $key) {
             if (isset($submittedValues[$key])) {
                 unset($submittedValues[$key]);
             }
         }
         //Get the rquire fields value only.
         $params = $this->_params = $submittedValues;
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // we need to retrieve email address
         if ($this->_context == 'standalone' && CRM_Utils_Array::value('is_email_receipt', $submittedValues)) {
             list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
             $this->assign('displayName', $this->userDisplayName);
         }
         //set email for primary location.
         $fields['email-Primary'] = 1;
         $params['email-Primary'] = $this->userEmail;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = TRUE;
             }
         }
         if (CRM_Utils_Array::value('source', $params)) {
             unset($params['source']);
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, NULL, NULL, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
             $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
             $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         }
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $this->_params['total_amount'];
         $this->_params['amount_level'] = 0;
         $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, $config->defaultCurrency);
         $this->_params['payment_action'] = 'Sale';
         if (CRM_Utils_Array::value('receive_date', $this->_params)) {
             $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
         }
         if (CRM_Utils_Array::value('soft_credit_to', $params)) {
             $this->_params['soft_credit_to'] = $params['soft_credit_to'];
             $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
         }
         $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
         $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
         $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
         //Add common data to formatted params
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params);
         if (empty($this->_params['invoice_id'])) {
             $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         } else {
             $this->_params['invoiceID'] = $this->_params['invoice_id'];
         }
         // 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
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         $paymentParams['contactID'] = $this->_contactID;
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         $contributionType = new CRM_Contribute_DAO_ContributionType();
         $contributionType->id = $params['contribution_type_id'];
         if (!$contributionType->find(TRUE)) {
             CRM_Core_Error::fatal('Could not find a system table');
         }
         // add some contribution type details to the params list
         // if folks need to use it
         $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
         $paymentParams['contributionType_accounting_code'] = $this->_params['contributionType_accounting_code'] = $contributionType->accounting_code;
         $paymentParams['contributionPageID'] = NULL;
         if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $paymentParams['email'] = $this->userEmail;
             $paymentParams['is_email_receipt'] = 1;
         } else {
             $paymentParams['is_email_receipt'] = 0;
             $this->_params['is_email_receipt'] = 0;
         }
         if (CRM_Utils_Array::value('receive_date', $this->_params)) {
             $paymentParams['receive_date'] = $this->_params['receive_date'];
         }
         if (CRM_Utils_Array::value('receive_date', $this->_params)) {
             $paymentParams['receive_date'] = $this->_params['receive_date'];
         }
         $result = NULL;
         // For recurring contribution, create Contribution Record first.
         // Contribution ID, Recurring ID and Contact ID needed
         // When we get a callback from the payment processor, CRM-7115
         if (CRM_Utils_Array::value('is_recur', $paymentParams)) {
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, TRUE, FALSE);
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->contribution_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
         }
         if ($paymentParams['amount'] > 0.0) {
             // force a reget of the payment processor in case the form changed it, CRM-7179
             $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
             $result = $payment->doDirectPayment($paymentParams);
         }
         if (is_a($result, 'CRM_Core_Error')) {
             //make sure to cleanup db for recurring case.
             if (CRM_Utils_Array::value('contributionID', $paymentParams)) {
                 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
                 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
             }
             if (CRM_Utils_Array::value('contributionRecurID', $paymentParams)) {
                 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
                 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
             }
             //set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactID}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             if (!empty($this->_ppID)) {
                 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'], $params['receipt_date_time'], TRUE);
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', $this->_params['receive_date']);
         // result has all the stuff we need
         // lets archive it to a financial transaction
         if ($contributionType->is_deductible) {
             $this->assign('is_deductible', TRUE);
             $this->set('is_deductible', TRUE);
         }
         // set source if not set
         if (empty($this->_params['source'])) {
             $userID = $session->get('userID');
             $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
             $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
         }
         // build custom data getFields array
         $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, CRM_Utils_Array::value('contribution_type_id', $params));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution');
         if (!CRM_Utils_Array::value('is_recur', $paymentParams)) {
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, FALSE, FALSE);
         }
         if ($this->_context != 'participant' && !$pId) {
             $entityID = $contribution->id;
             $entityTable = 'contribution';
         }
         // process line items, until no previous line items.
         if (empty($this->_lineItems) && $entityID && !empty($lineItem)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($entityID, $lineItem, 'civicrm_' . $entityTable);
         }
         //send receipt mail.
         if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
             $this->_params['contact_id'] = $this->_contactID;
             $this->_params['contribution_id'] = $contribution->id;
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
         }
         //process the note
         if ($contribution->id && isset($params['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
         }
         //process premium
         if ($contribution->id && isset($params['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
         }
         //update pledge payment status.
         if ($this->_ppID && $contribution->id) {
             //store contribution id in payment record.
             CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount);
         }
         if ($contribution->id) {
             $statusMsg = ts('The contribution record has been processed.');
             if (CRM_Utils_Array::value('is_email_receipt', $this->_params) && $sendReceipt) {
                 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
             }
             CRM_Core_Session::setStatus($statusMsg);
         }
         //submit credit card contribution ends.
     } else {
         //Offline Contribution.
         $unsetParams = array('payment_processor_id', "email-{$this->_bltID}", 'hidden_buildCreditCard', 'hidden_buildDirectDebit', 'billing_first_name', 'billing_middle_name', 'billing_last_name', 'street_address-5', "city-{$this->_bltID}", "state_province_id-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}", 'credit_card_number', 'cvv2', 'credit_card_exp_date', 'credit_card_type');
         foreach ($unsetParams as $key) {
             if (isset($submittedValues[$key])) {
                 unset($submittedValues[$key]);
             }
         }
         // get the required field value only.
         $formValues = $submittedValues;
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         // get current currency from DB or use default currency
         $currentCurrency = CRM_Utils_Array::value('currency', $this->_values, $config->defaultCurrency);
         // use submitted currency if present else use current currency
         $params['currency'] = CRM_Utils_Array::value('currency', $submittedValues, $currentCurrency);
         $fields = array('contribution_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number', 'soft_credit_to', 'pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if ($softID = CRM_Utils_Array::value('softID', $this->_values)) {
             $params['softID'] = $softID;
         }
         //if priceset is used, no need to cleanup money
         //CRM-5740
         if ($priceSetId) {
             $params['skipCleanMoney'] = 1;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
         }
         if (CRM_Utils_Array::value('is_email_receipt', $formValues)) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date("Y-m-d");
             }
         } else {
             $params['cancel_date'] = $params['cancel_reason'] = 'null';
         }
         // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
             $params['is_pay_later'] = 1;
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         //Add Additional common information  to formatted params
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params);
         //create contribution.
         $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
         // 10117 update th line items for participants
         if ($this->_context != 'participant' && !$pId) {
             $entityID = $contribution->id;
             $entityTable = 'contribution';
         }
         // process line items, until no previous line items.
         if (empty($this->_lineItems) && $entityID && !empty($lineItem)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($entityID, $lineItem, 'civicrm_' . $entityTable);
         }
         // process associated membership / participant, CRM-4395
         $relatedComponentStatusMsg = NULL;
         if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
             $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values));
         }
         //process  note
         if ($contribution->id && isset($formValues['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
         }
         //process premium
         if ($contribution->id && isset($formValues['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id, $this->_premiumID, $this->_options);
         }
         //send receipt mail.
         if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $formValues)) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             // to get 'from email id' for send receipt
             $this->fromEmailId = $formValues['from_email_address'];
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
         }
         $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id');
         //update pledge payment status.
         if ($this->_ppID && $contribution->id && $this->_action & CRM_Core_Action::ADD || $pledgePaymentId && $this->_action & CRM_Core_Action::UPDATE) {
             if ($this->_ppID) {
                 //store contribution id in payment record.
                 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
             } else {
                 $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id');
                 $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'pledge_id', 'contribution_id');
             }
             $adjustTotalAmount = FALSE;
             if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
                 $adjustTotalAmount = TRUE;
             }
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount, $adjustTotalAmount);
         }
         $statusMsg = ts('The contribution record has been saved.');
         if (CRM_Utils_Array::value('is_email_receipt', $formValues) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         if ($relatedComponentStatusMsg) {
             $statusMsg .= ' ' . $relatedComponentStatusMsg;
         }
         CRM_Core_Session::setStatus($statusMsg, FALSE);
         //Offline Contribution ends.
     }
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute"));
         }
     } elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"));
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"));
     }
 }