Esempio n. 1
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}"));
         }
     }
 }
 /**
  * Process the form.
  *
  * @return void
  */
 public function postProcess()
 {
     // Process / save custom data
     // Get the form values and groupTree
     $params = $this->controller->exportValues($this->_name);
     CRM_Core_BAO_CustomValueTable::postProcess($params, 'civicrm_contact', $this->_contactId, $this->_entityType);
     $this->log();
     // reset the group contact cache for this group
     CRM_Contact_BAO_GroupContactCache::remove();
     $this->response();
 }
Esempio n. 3
0
 /**
  * Process the user submitted custom data values.
  */
 public function postProcess()
 {
     // Get the form values and groupTree
     //CRM-18183
     $params = $this->controller->exportValues($this->_name);
     CRM_Core_BAO_CustomValueTable::postProcess($params, 'civicrm_contact', $this->_tableID, $this->_entityType);
     $table = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_groupID, 'table_name');
     $cgcount = CRM_Core_BAO_CustomGroup::customGroupDataExistsForEntity($this->_tableID, $table, TRUE);
     $cgcount += 1;
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->getButtonName('upload', 'new')) {
         CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/contact/view/cd/edit', "reset=1&type={$this->_contactType}&groupID={$this->_groupID}&entityID={$this->_tableID}&cgcount={$cgcount}&multiRecordDisplay=single&mode=add"));
     }
     // Add entry in the log table
     CRM_Core_BAO_Log::register($this->_tableID, 'civicrm_contact', $this->_tableID);
     if (CRM_Core_Resources::isAjaxMode()) {
         $this->ajaxResponse += CRM_Contact_Form_Inline::renderFooter($this->_tableID);
     }
     // reset the group contact cache for this group
     CRM_Contact_BAO_GroupContactCache::remove();
 }
Esempio n. 4
0
 /**
  * Test multi-record custom fields
  */
 public function testMultiRecordFieldList()
 {
     //create multi record custom group
     $ids = $this->CustomGroupMultipleCreateWithFields(array('style' => 'Tab with table'));
     $params = array('contact_type' => 'Individual', 'first_name' => 'Test', 'last_name' => 'Contact');
     $customFields = $ids['custom_field_id'];
     $result = $this->callAPISuccess('contact', 'create', $params);
     $contactId = $result['id'];
     //enter values for custom fields
     $customParams = array("custom_{$customFields[0]}_-1" => "test value {$customFields[0]} one", "custom_{$customFields[0]}_-2" => "test value {$customFields[0]} two", "custom_{$customFields[0]}_-3" => "test value {$customFields[0]} three", "custom_{$customFields[1]}_-1" => "test value {$customFields[1]} one", "custom_{$customFields[1]}_-2" => "test value {$customFields[1]} two", "custom_{$customFields[1]}_-3" => "test value {$customFields[1]} three", "custom_{$customFields[2]}_-1" => "test value {$customFields[2]} one", "custom_{$customFields[2]}_-2" => "test value {$customFields[2]} two", "custom_{$customFields[2]}_-3" => "test value {$customFields[2]} three");
     CRM_Core_BAO_CustomValueTable::postProcess($customParams, "civicrm_contact", $contactId, NULL);
     $_GET = array('cid' => $contactId, 'cgid' => $ids['custom_group_id'], 'is_unit_test' => TRUE);
     $multiRecordFields = CRM_Custom_Page_AJAX::getMultiRecordFieldList();
     //check sorting
     foreach ($customFields as $fieldId) {
         $columnName = "field_{$fieldId}{$ids['custom_group_id']}_{$fieldId}";
         $_GET['columns'][] = array('data' => $columnName);
     }
     // get the results in descending order
     $_GET['order'] = array('0' => array('column' => 0, 'dir' => 'desc'));
     $sortedRecords = CRM_Custom_Page_AJAX::getMultiRecordFieldList();
     $this->assertEquals(3, $sortedRecords['recordsTotal']);
     $this->assertEquals(3, $multiRecordFields['recordsTotal']);
     foreach ($customFields as $fieldId) {
         $columnName = "field_{$fieldId}{$ids['custom_group_id']}_{$fieldId}";
         $this->assertEquals("test value {$fieldId} one", $multiRecordFields['data'][0][$columnName]['data']);
         $this->assertEquals("test value {$fieldId} two", $multiRecordFields['data'][1][$columnName]['data']);
         $this->assertEquals("test value {$fieldId} three", $multiRecordFields['data'][2][$columnName]['data']);
         // this should be sorted in descending order.
         $this->assertEquals("test value {$fieldId} two", $sortedRecords['data'][0][$columnName]['data']);
         $this->assertEquals("test value {$fieldId} three", $sortedRecords['data'][1][$columnName]['data']);
         $this->assertEquals("test value {$fieldId} one", $sortedRecords['data'][2][$columnName]['data']);
     }
     $sorted = FALSE;
     // sorted order result should be two, three, one
     $sortedCount = array(1 => 2, 2 => 3, 3 => 1);
     foreach (array($multiRecordFields, $sortedRecords) as $records) {
         $count = 1;
         foreach ($records['data'] as $key => $val) {
             //check links for result sorted in descending order
             if ($sorted) {
                 $initialCount = $count;
                 $count = $sortedCount[$count];
             }
             // extract view, edit, copy links and assert the recId, cgcount.
             preg_match_all('!https?://\\S+!', $val['action'], $matches);
             foreach ($matches[0] as $match) {
                 $parts = parse_url($match);
                 $parts['query'] = str_replace('&amp;', '&', $parts['query']);
                 parse_str($parts['query'], $query);
                 switch (trim($query['mode'], '"')) {
                     case 'view':
                         $this->assertEquals($count, $query['recId']);
                         break;
                     case 'edit':
                         $this->assertEquals($count, $query['cgcount']);
                         break;
                     case 'copy':
                         $this->assertEquals(4, $query['cgcount']);
                         break;
                 }
             }
             if (!empty($initialCount)) {
                 $count = $initialCount;
             }
             $count++;
         }
         $sorted = TRUE;
     }
 }
Esempio n. 5
0
 /**
  * Process the Memberships.
  *
  * @param array $membershipParams
  *   Array of membership fields.
  * @param int $contactID
  *   Contact id.
  * @param CRM_Contribute_Form_Contribution_Confirm $form
  *   Confirmation form object.
  *
  * @param array $premiumParams
  * @param null $customFieldsFormatted
  * @param null $includeFieldTypes
  *
  * @param array $membershipDetails
  *
  * @param array $membershipTypeIDs
  *
  * @param bool $isPaidMembership
  * @param array $membershipID
  *
  * @param $isProcessSeparateMembershipTransaction
  *
  * @param int $defaultContributionTypeID
  * @param array $membershipLineItems
  *   Line items specific to membership payment that is separate to contribution.
  * @param $isPayLater
  *
  * @throws \CRM_Core_Exception
  */
 public static function postProcessMembership($membershipParams, $contactID, &$form, $premiumParams, $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID, $isProcessSeparateMembershipTransaction, $defaultContributionTypeID, $membershipLineItems, $isPayLater)
 {
     $result = $membershipContribution = NULL;
     $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE);
     $errors = $createdMemberships = array();
     //@todo move this into the calling function & pass in the correct financialTypeID
     if (isset($paymentParams['financial_type'])) {
         $financialTypeID = $paymentParams['financial_type'];
     } else {
         $financialTypeID = $defaultContributionTypeID;
     }
     if (CRM_Utils_Array::value('membership_source', $form->_params)) {
         $membershipParams['contribution_source'] = $form->_params['membership_source'];
     }
     if ($isPaidMembership) {
         $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $premiumParams, $contactID, $financialTypeID, 'membership', array(), $isTest, $isPayLater);
         if (is_a($result[1], 'CRM_Core_Error')) {
             $errors[1] = CRM_Core_Error::getMessages($result[1]);
         } elseif (!empty($result[1])) {
             // Save the contribution ID so that I can be used in email receipts
             // For example, if you need to generate a tax receipt for the donation only.
             $form->_values['contribution_other_id'] = $result[1]->id;
             //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
             $membershipContribution = $result[1];
         }
     }
     if ($isProcessSeparateMembershipTransaction) {
         try {
             $lineItems = $form->_lineItem = $membershipLineItems;
             if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) {
                 unset($membershipParams['is_recur']);
             }
             $membershipContribution = self::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array::value('financial_type_id', $membershipDetails));
         } catch (CRM_Core_Exception $e) {
             $errors[2] = $e->getMessage();
             $membershipContribution = NULL;
         }
     }
     $membership = NULL;
     if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
         $membershipContributionID = $membershipContribution->id;
     }
     //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
     if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
         $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
     }
     //@todo it should no longer be possible for it to get to this point & membership to not be an array
     if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
         $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
         foreach ($membershipTypeIDs as $memType) {
             $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
             $createdMemberships[$memType] = self::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form);
         }
         if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
             foreach ($form->_lineItem[$form->_priceSetId] as &$priceFieldOp) {
                 if (!empty($priceFieldOp['membership_type_id']) && isset($createdMemberships[$priceFieldOp['membership_type_id']])) {
                     $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
                     $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%B %E%f, %Y') : '-';
                     $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%B %E%f, %Y') : '-';
                 } else {
                     $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
                 }
             }
             $form->_values['lineItem'] = $form->_lineItem;
             $form->assign('lineItem', $form->_lineItem);
         }
     }
     if (!empty($errors)) {
         $message = self::compileErrorMessage($errors);
         throw new CRM_Core_Exception($message);
     }
     $form->_params['createdMembershipIDs'] = array();
     // CRM-7851 - Moved after processing Payment Errors
     //@todo - the reasoning for this being here seems a little outdated
     foreach ($createdMemberships as $createdMembership) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_membership', $createdMembership->id, 'Membership');
         $form->_params['createdMembershipIDs'][] = $createdMembership->id;
     }
     if (count($createdMemberships) == 1) {
         //presumably this is only relevant for exactly 1 membership
         $form->_params['membershipID'] = $createdMembership->id;
     }
     //CRM-15232: Check if membership is created and on the basis of it use
     //membership reciept template to send payment reciept
     if (count($createdMemberships)) {
         $form->_values['isMembership'] = TRUE;
     }
     if ($form->_contributeMode == 'notify') {
         if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
             // call postProcess hook before leaving
             $form->postProcessHook();
             // this does not return
             $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             $payment->doTransferCheckout($form->_params, 'contribute');
         }
     }
     if (isset($membershipContributionID)) {
         $form->_values['contribution_id'] = $membershipContributionID;
     }
     // Refer to CRM-16737. Payment processors 'should' return payment_status_id
     // to denote the outcome of the transaction.
     //
     // In 4.7 trxn_id will no longer denote the outcome & all processor transactions must return an array
     // containing payment_status_id.
     // In 4.6 support (such as there was) for other ways of denoting payment outcome is retained but the use
     // of payment_status_id is strongly encouraged.
     if (!empty($form->_params['is_recur']) && $form->_contributeMode == 'direct') {
         if (!empty($membershipContribution->trxn_id) && !isset($membershipContribution->payment_status_id) || !empty($membershipContribution->payment_status_id) && $membershipContribution->payment_status_id == 1) {
             try {
                 civicrm_api3('contribution', 'completetransaction', array('id' => $membershipContribution->id, 'trxn_id' => $membershipContribution->trxn_id));
             } catch (CiviCRM_API3_Exception $e) {
                 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
                 // so let's be gentle here
                 CRM_Core_Error::debug_log_message('contribution ' . $membershipContribution->id . ' not completed with trxn_id ' . $membershipContribution->trxn_id . ' and message ' . $e->getMessage());
             }
         }
         // Do not send an email if Recurring transaction is done via Direct Mode
         // Email will we sent when the IPN is received.
         return;
     }
     //finally send an email receipt
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $isTest, FALSE, $includeFieldTypes);
 }
Esempio n. 6
0
 /**
  * Process the Memberships.
  *
  * @param array $membershipParams
  *   Array of membership fields.
  * @param int $contactID
  *   Contact id.
  * @param CRM_Contribute_Form_Contribution_Confirm $form
  *   Confirmation form object.
  *
  * @param array $premiumParams
  * @param null $customFieldsFormatted
  * @param null $includeFieldTypes
  *
  * @param array $membershipDetails
  *
  * @param array $membershipTypeIDs
  *
  * @param bool $isPaidMembership
  * @param array $membershipID
  *
  * @param bool $isProcessSeparateMembershipTransaction
  *
  * @param int $financialTypeID
  * @param array $membershipLineItems
  *   Line items specific to membership payment that is separate to contribution.
  * @param bool $isPayLater
  * @param bool $isPending
  *
  * @throws \CRM_Core_Exception
  */
 protected function postProcessMembership($membershipParams, $contactID, &$form, $premiumParams, $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID, $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending)
 {
     $membershipContribution = NULL;
     $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE);
     $errors = $createdMemberships = $paymentResults = array();
     $form->_values['isMembership'] = TRUE;
     $isRecurForFirstTransaction = CRM_Utils_Array::value('is_recur', $form->_values, CRM_Utils_Array::value('is_recur', $membershipParams));
     $totalAmount = $membershipParams['amount'];
     if ($isPaidMembership) {
         if ($isProcessSeparateMembershipTransaction) {
             // If we have 2 transactions only one can use the invoice id.
             $membershipParams['invoiceID'] .= '-2';
             if (!empty($membershipParams['auto_renew'])) {
                 $isRecurForFirstTransaction = FALSE;
             }
         }
         $paymentResult = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $contactID, $financialTypeID, 'membership', $isTest, $isRecurForFirstTransaction);
         if (!empty($paymentResult['contribution'])) {
             $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
             //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
             $membershipContribution = $paymentResult['contribution'];
             // Save the contribution ID so that I can be used in email receipts
             // For example, if you need to generate a tax receipt for the donation only.
             $form->_values['contribution_other_id'] = $membershipContribution->id;
         }
     }
     if ($isProcessSeparateMembershipTransaction) {
         try {
             $form->_lineItem = $membershipLineItems;
             if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) {
                 unset($membershipParams['is_recur']);
             }
             list($membershipContribution, $secondPaymentResult) = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array::value('financial_type_id', $membershipDetails));
             $paymentResults[] = array('contribution_id' => $membershipContribution->id, 'result' => $secondPaymentResult);
         } catch (CRM_Core_Exception $e) {
             $errors[2] = $e->getMessage();
             $membershipContribution = NULL;
         }
     }
     $membership = NULL;
     if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
         $membershipContributionID = $membershipContribution->id;
     }
     //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
     if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
         $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
     }
     //@todo it should no longer be possible for it to get to this point & membership to not be an array
     if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
         $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
         foreach ($membershipTypeIDs as $memType) {
             $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
             if (!empty($membershipContribution)) {
                 $pendingStatus = CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name');
                 $pending = $membershipContribution->contribution_status_id == $pendingStatus ? TRUE : FALSE;
             } else {
                 $pending = $isPending;
             }
             $contributionRecurID = isset($form->_params['contributionRecurID']) ? $form->_params['contributionRecurID'] : NULL;
             $membershipSource = NULL;
             if (!empty($form->_params['membership_source'])) {
                 $membershipSource = $form->_params['membership_source'];
             } elseif (isset($form->_values['title']) && !empty($form->_values['title'])) {
                 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values['title'];
             }
             $isPayLater = NULL;
             if (isset($form->_params)) {
                 $isPayLater = CRM_Utils_Array::value('is_pay_later', $form->_params);
             }
             $campaignId = NULL;
             if (isset($form->_values) && is_array($form->_values) && !empty($form->_values)) {
                 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_params);
                 if (!array_key_exists('campaign_id', $form->_params)) {
                     $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
                 }
             }
             list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership::renewMembership($contactID, $memType, $isTest, date('YmdHis'), CRM_Utils_Array::value('cms_contactID', $membershipParams), $customFieldsFormatted, $numTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId);
             $form->set('renewal_mode', $renewalMode);
             if (!empty($dates)) {
                 $form->assign('mem_start_date', CRM_Utils_Date::customFormat($dates['start_date'], '%Y%m%d'));
                 $form->assign('mem_end_date', CRM_Utils_Date::customFormat($dates['end_date'], '%Y%m%d'));
             }
             if (!empty($membershipContribution)) {
                 // update recurring id for membership record
                 CRM_Member_BAO_Membership::updateRecurMembership($membership, $membershipContribution);
                 CRM_Member_BAO_Membership::linkMembershipPayment($membership, $membershipContribution);
             }
         }
         if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
             foreach ($form->_lineItem[$form->_priceSetId] as &$priceFieldOp) {
                 if (!empty($priceFieldOp['membership_type_id']) && isset($createdMemberships[$priceFieldOp['membership_type_id']])) {
                     $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
                     $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%B %E%f, %Y') : '-';
                     $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%B %E%f, %Y') : '-';
                 } else {
                     $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
                 }
             }
             $form->_values['lineItem'] = $form->_lineItem;
             $form->assign('lineItem', $form->_lineItem);
         }
     }
     if (!empty($errors)) {
         $message = $this->compileErrorMessage($errors);
         throw new CRM_Core_Exception($message);
     }
     $form->_params['createdMembershipIDs'] = array();
     // CRM-7851 - Moved after processing Payment Errors
     //@todo - the reasoning for this being here seems a little outdated
     foreach ($createdMemberships as $createdMembership) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, 'civicrm_membership', $createdMembership->id, 'Membership');
         $form->_params['createdMembershipIDs'][] = $createdMembership->id;
     }
     if (count($createdMemberships) == 1) {
         //presumably this is only relevant for exactly 1 membership
         $form->_params['membershipID'] = $createdMembership->id;
     }
     //CRM-15232: Check if membership is created and on the basis of it use
     //membership receipt template to send payment receipt
     if (count($createdMemberships)) {
         $form->_values['isMembership'] = TRUE;
     }
     if (isset($membershipContributionID)) {
         $form->_values['contribution_id'] = $membershipContributionID;
     }
     if ($form->_paymentProcessor) {
         // the is_monetary concept probably should be deprecated as it can be calculated from
         // the existence of 'amount' & seems fragile.
         if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
             // call postProcess hook before leaving
             $form->postProcessHook();
         }
         $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
         // The contribution_other_id is effectively the ID for the only contribution or the non-membership contribution.
         // Since we have called the membership contribution (in a 2 contribution scenario) this is out
         // primary-contribution compared to that - but let's face it - it's all just too hard & confusing at the moment!
         $paymentParams = array_merge($form->_params, array('contributionID' => $form->_values['contribution_other_id']));
         $paymentActionResult = $payment->doPayment($paymentParams, 'contribute');
         $paymentResults[] = array('contribution_id' => $paymentResult['contribution']->id, 'result' => $paymentActionResult);
         // Do not send an email if Recurring transaction is done via Direct Mode
         // Email will we sent when the IPN is received.
         foreach ($paymentResults as $result) {
             $this->completeTransaction($result['result'], $result['contribution_id']);
         }
         return;
     }
     $emailValues = $form->_values;
     // Finally send an email receipt for pay-later scenario (although it might sometimes be caught above!)
     if ($totalAmount == 0) {
         // This feels like a bizarre hack as the variable name doesn't seem to be directly connected to it's use in the template.
         $emailValues['useForMember'] = 0;
         $emailValues['membership_assign'] = 1;
         $emailValues['amount'] = 0;
     }
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $emailValues, $isTest, FALSE, $includeFieldTypes);
 }
Esempio n. 7
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}"));
     }
 }
Esempio n. 8
0
 /**
  * Process the contribution
  *
  * @return void
  * @access public
  */
 static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = true, $pending = false, $online = true)
 {
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $honorCId = $recurringContributionID = null;
     if ($online) {
         if ($form->get('honor_block_is_active')) {
             $honorCId = $form->createHonorContact();
         }
         $recurringContributionID = $form->processRecurringContribution($params, $contactID);
     } else {
         if (!$online && isset($params['honor_contact_id'])) {
             $honorCId = $params['honor_contact_id'];
         }
     }
     $config =& CRM_Core_Config::singleton();
     if (!$online && isset($params['non_deductible_amount'])) {
         $nonDeductibleAmount = $params['non_deductible_amount'];
     } else {
         $nonDeductibleAmount = $params['amount'];
     }
     if ($online && $contributionType->is_deductible && $deductibleMode) {
         $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
         if ($selectProduct && $selectProduct != 'no_thanks') {
             require_once 'CRM/Contribute/DAO/Product.php';
             $productDAO =& new CRM_Contribute_DAO_Product();
             $productDAO->id = $selectProduct;
             $productDAO->find(true);
             if ($params['amount'] < $productDAO->price) {
                 $nonDeductibleAmount = $params['amount'];
             } else {
                 $nonDeductibleAmount = $productDAO->price;
             }
         } else {
             $nonDeductibleAmount = '0.00';
         }
     }
     $now = date('YmdHis');
     $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
     if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) {
         $receiptDate = $now;
     }
     // check contribution Type
     // first create the contribution record
     $contribParams = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'contribution_page_id' => $online ? $form->_id : null, 'receive_date' => $now, 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $params['amount'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || CRM_Utils_Array::value('source', $params) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0), 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : null, 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : null);
     if (!$online && isset($params['thankyou_date'])) {
         $contribParams['thankyou_date'] = $params['thankyou_date'];
     }
     if (!$online || $form->_values['is_monetary']) {
         if (!CRM_Utils_Array::value('is_pay_later', $params)) {
             $contribParams['payment_instrument_id'] = 1;
         }
     }
     if (!$pending && $result) {
         $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => $result['trxn_result_code'], 'payment_processor' => $result['payment_processor']);
     }
     if (isset($honorCId)) {
         $contribParams["honor_contact_id"] = $honorCId;
         $contribParams["honor_type_id"] = $params['honor_type_id'];
     }
     if ($recurringContributionID) {
         $contribParams['contribution_recur_id'] = $recurringContributionID;
     }
     $contribParams["contribution_status_id"] = $pending ? 2 : 1;
     if ($form->_mode == 'test') {
         $contribParams["is_test"] = 1;
     }
     $ids = array();
     if (isset($contribParams['invoice_id'])) {
         $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id');
         if (isset($contribID)) {
             $ids['contribution'] = $contribID;
             $contribParams['id'] = $contribID;
         }
     }
     foreach (array('pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note') as $val) {
         if (CRM_Utils_Array::value($val, $params)) {
             $contribSoftParams[$val] = $params[$val];
         }
     }
     require_once 'CRM/Contribute/BAO/Contribution.php';
     //create an contribution address
     if ($form->_contributeMode != 'notify' && !CRM_Utils_Array::value('is_pay_later', $params)) {
         $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
     }
     // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
     require_once 'CRM/Utils/Money.php';
     $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' '));
     $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' '));
     //add contribution record
     $contribution =& CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
     // process price set, CRM-5095
     if ($contribution->id && $form->_priceSetId) {
         require_once 'CRM/Contribute/Form/AdditionalInfo.php';
         CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $form->_lineItem);
     }
     //add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
     if (CRM_Utils_Array::value('pcp_made_through_id', $params) || CRM_Utils_Array::value('soft_credit_to', $params)) {
         $contribSoftParams['contribution_id'] = $contribution->id;
         $contribSoftParams['amount'] = $params['amount'];
         //if its due to pcp
         if (CRM_Utils_Array::value('pcp_made_through_id', $params)) {
             $contribSoftParams['pcp_id'] = $params['pcp_made_through_id'];
             $contribSoftParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_PCP', $params['pcp_made_through_id'], 'contact_id');
         } else {
             $contribSoftParams['contact_id'] = CRM_Utils_Array::value('soft_credit_to', $params);
         }
         $softContribution = CRM_Contribute_BAO_Contribution::addSoftContribution($contribSoftParams);
     }
     //handle pledge stuff.
     if (!CRM_Utils_Array::value('separate_membership_payment', $form->_params) && CRM_Utils_Array::value('pledge_block_id', $form->_values) && (CRM_Utils_Array::value('is_pledge', $form->_params) || CRM_Utils_Array::value('pledge_id', $form->_values))) {
         if (CRM_Utils_Array::value('pledge_id', $form->_values)) {
             //when user doing pledge payments.
             //update the schedule when payment(s) are made
             require_once 'CRM/Pledge/BAO/Payment.php';
             foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
                 $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id);
                 CRM_Pledge_BAO_Payment::add($pledgePaymentParams);
             }
             //update pledge status according to the new payment statuses
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($form->_values['pledge_id']);
         } else {
             //when user creating pledge record.
             $pledgeParams = array();
             $pledgeParams['contact_id'] = $contribution->contact_id;
             $pledgeParams['installment_amount'] = $contribution->total_amount;
             $pledgeParams['contribution_id'] = $contribution->id;
             $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
             $pledgeParams['contribution_type_id'] = $contribution->contribution_type_id;
             $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
             $pledgeParams['installments'] = $params['pledge_installments'];
             $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
             $pledgeParams['frequency_day'] = 1;
             $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
             $pledgeParams['status_id'] = $contribution->contribution_status_id;
             $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
             $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
             $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
             $pledgeParams['is_test'] = $contribution->is_test;
             $pledgeParams['acknowledge_date'] = date('Ymd');
             require_once 'CRM/Pledge/BAO/Pledge.php';
             $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
             $form->_params['pledge_id'] = $pledge->id;
             //send acknowledgment email. only when pledge is created
             if ($pledge->id) {
                 //build params to send acknowledgment.
                 $pledgeParams['id'] = $pledge->id;
                 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
                 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
                 //scheduled amount will be same as installment_amount.
                 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
                 //get total pledge amount.
                 $pledgeParams['total_pledge_amount'] = $pledge->amount;
                 require_once 'CRM/Pledge/BAO/Pledge.php';
                 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
             }
         }
     }
     if ($online) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution');
     } else {
         //handle custom data.
         $params['contribution_id'] = $contribution->id;
         if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) {
             require_once 'CRM/Core/BAO/CustomValueTable.php';
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
         }
     }
     require_once "CRM/Contribute/BAO/Contribution/Utils.php";
     if (isset($params['related_contact'])) {
         $contactID = $params['related_contact'];
     } else {
         if (isset($params['cms_contactID'])) {
             $contactID = $params['cms_contactID'];
         }
     }
     CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID);
     // return if pending
     if ($pending) {
         return $contribution;
     }
     // next create the transaction record
     if ((!$online || $form->_values['is_monetary']) && $result['trxn_id']) {
         $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'currency' => $params['currencyID'], 'payment_processor' => $form->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id'], 'trxn_result_code' => $result['trxn_result_code']);
         require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
         $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($trxnParams);
     }
     //create contribution activity w/ individual and target
     //activity w/ organisation contact id when onbelf, CRM-4027
     $targetContactID = null;
     if (CRM_Utils_Array::value('is_for_organization', $params)) {
         $targetContactID = $contribution->contact_id;
         $contribution->contact_id = $contactID;
     }
     // create an activity record
     require_once 'CRM/Activity/BAO/Activity.php';
     CRM_Activity_BAO_Activity::addActivity($contribution, null, $targetContactID);
     $transaction->commit();
     return $contribution;
 }
 /**
  * Process the Memberships
  *
  * @param array  $membershipParams array of membership fields
  * @param int    $contactID        contact id
  * @param object $form             form object
  *
  * @return void
  * @access public
  */
 public static function postProcessMembership($membershipParams, $contactID, &$form, &$premiumParams, $customFieldsFormatted = NULL, $includeFieldTypes = NULL)
 {
     $tempParams = $membershipParams;
     $paymentDone = FALSE;
     $result = NULL;
     $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE);
     $form->assign('membership_assign', TRUE);
     $form->set('membershipTypeID', $membershipParams['selectMembership']);
     $singleMembershipTypeID = $membershipTypeID = $membershipParams['selectMembership'];
     if (is_array($membershipTypeID) && count($membershipTypeID) == 1) {
         $singleMembershipTypeID = $membershipTypeID[0];
     }
     $membershipDetails = self::buildMembershipTypeValues($form, $singleMembershipTypeID);
     $form->assign('membership_name', CRM_Utils_Array::value('name', $membershipDetails));
     $minimumFee = CRM_Utils_Array::value('minimum_fee', $membershipDetails);
     $contributionTypeId = NULL;
     if ($form->_values['amount_block_is_active']) {
         $contributionTypeId = $form->_values['financial_type_id'];
     } else {
         $paymentDone = TRUE;
         $params['amount'] = $minimumFee;
         $contributionTypeId = CRM_Utils_Array::value('financial_type_id', $membershipDetails);
         if (!$contributionTypeId) {
             $contributionTypeId = CRM_Utils_Array::value('financial_type_id', $membershipParams);
         }
     }
     //amount must be greater than zero for
     //adding contribution record  to contribution table.
     //this condition arises when separate membership payment is
     //enabled and contribution amount is not selected. fix for CRM-3010
     if ($form->_amount > 0.0 && $membershipParams['amount']) {
         $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $premiumParams, $contactID, $contributionTypeId, 'membership');
     } else {
         // we need to explicitly create a CMS user in case of free memberships
         // since the below has already been done under processConfirm for paid memberships
         CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams, $membershipParams['cms_contactID'], 'email-' . $form->_bltID);
     }
     $errors = array();
     if (is_a($result[1], 'CRM_Core_Error')) {
         $errors[1] = CRM_Core_Error::getMessages($result[1]);
     } elseif (CRM_Utils_Array::value(1, $result)) {
         // Save the contribution ID so that I can be used in email receipts
         // For example, if you need to generate a tax receipt for the donation only.
         $form->_values['contribution_other_id'] = $result[1]->id;
         $contribution[1] = $result[1];
     }
     $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($form->_id);
     if (CRM_Utils_Array::value('is_separate_payment', $memBlockDetails) && !$paymentDone) {
         $form->_lineItem = $form->_memLineItem;
         $contributionType = new CRM_Financial_DAO_FinancialType();
         $contributionType->id = CRM_Utils_Array::value('financial_type_id', $membershipDetails);
         if (!$contributionType->find(TRUE)) {
             CRM_Core_Error::fatal(ts("Could not find a system table"));
         }
         $tempParams['amount'] = $minimumFee;
         $invoiceID = md5(uniqid(rand(), TRUE));
         $tempParams['invoiceID'] = $invoiceID;
         //we don't allow recurring membership.CRM-3781.
         if (CRM_Utils_Array::value('is_recur', $tempParams)) {
             $tempParams['is_recur'] = 0;
         }
         $result = NULL;
         if ($form->_values['is_monetary'] && !$form->_params['is_pay_later'] && $minimumFee > 0.0) {
             $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             if ($form->_contributeMode == 'express') {
                 $result =& $payment->doExpressCheckout($tempParams);
             } else {
                 $result =& $payment->doDirectPayment($tempParams);
             }
         }
         if (is_a($result, 'CRM_Core_Error')) {
             $errors[2] = CRM_Core_Error::getMessages($result);
         } else {
             //assign receive date when separate membership payment
             //and contribution amount not selected.
             if ($form->_amount == 0) {
                 $now = date('YmdHis');
                 $form->_params['receive_date'] = $now;
                 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
                 $form->set('params', $form->_params);
                 $form->assign('receive_date', $receiveDate);
             }
             $form->set('membership_trx_id', $result['trxn_id']);
             $form->set('membership_amount', $minimumFee);
             $form->assign('membership_trx_id', $result['trxn_id']);
             $form->assign('membership_amount', $minimumFee);
             // we dont need to create the user twice, so lets disable cms_create_account
             // irrespective of the value, CRM-2888
             $tempParams['cms_create_account'] = 0;
             $pending = $form->_params['is_pay_later'] ? CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0) > 0.0 ? TRUE : FALSE : FALSE;
             //set this variable as we are not creating pledge for
             //separate membership payment contribution.
             //so for differentiating membership contributon from
             //main contribution.
             $form->_params['separate_membership_payment'] = 1;
             $contribution[2] = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $tempParams, $result, $contactID, $contributionType, TRUE, $pending);
         }
     }
     $index = CRM_Utils_Array::value('is_separate_payment', $memBlockDetails) ? 2 : 1;
     if (!CRM_Utils_Array::value($index, $errors)) {
         if (isset($membershipParams['onbehalf']) && CRM_Utils_Array::value('member_campaign_id', $membershipParams['onbehalf'])) {
             $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
         }
         if (is_array($membershipTypeID)) {
             $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
             $createdMemberships = array();
             foreach ($membershipTypeID as $memType) {
                 $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
                 $membership = self::renewMembership($contactID, $memType, $isTest, $form, NULL, CRM_Utils_Array::value('cms_contactID', $membershipParams), $customFieldsFormatted, CRM_Utils_Array::value($memType, $typesTerms, 1));
                 $createdMemberships[$memType] = $membership;
                 if (isset($contribution[$index])) {
                     //insert payment record
                     $dao = new CRM_Member_DAO_MembershipPayment();
                     $dao->membership_id = $membership->id;
                     $dao->contribution_id = $contribution[$index]->id;
                     //Fixed for avoiding duplicate entry error when user goes
                     //back and forward during payment mode is notify
                     if (!$dao->find(TRUE)) {
                         CRM_Utils_Hook::pre('create', 'MembershipPayment', NULL, $dao);
                         $dao->save();
                         CRM_Utils_Hook::post('create', 'MembershipPayment', $dao->id, $dao);
                     }
                 }
             }
             if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
                 foreach ($form->_lineItem[$form->_priceSetId] as &$priceFieldOp) {
                     if (CRM_Utils_Array::value('membership_type_id', $priceFieldOp) && isset($createdMemberships[$priceFieldOp['membership_type_id']])) {
                         $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
                         $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%d%f %b, %Y') : '-';
                         $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%d%f %b, %Y') : '-';
                     } else {
                         $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
                     }
                 }
                 $form->_values['lineItem'] = $form->_lineItem;
                 $form->assign('lineItem', $form->_lineItem);
             }
         } else {
             $membership = self::renewMembership($contactID, $membershipTypeID, $isTest, $form, NULL, CRM_Utils_Array::value('cms_contactID', $membershipParams), $customFieldsFormatted, CRM_Utils_Array::value('types_terms', $membershipParams, 1), CRM_Utils_Array::value('contribution_status_id', $result) == 2 ? TRUE : FALSE);
             if (isset($contribution[$index])) {
                 //insert payment record
                 $dao = new CRM_Member_DAO_MembershipPayment();
                 $dao->membership_id = $membership->id;
                 $dao->contribution_id = $contribution[$index]->id;
                 //Fixed for avoiding duplicate entry error when user goes
                 //back and forward during payment mode is notify
                 if (!$dao->find(TRUE)) {
                     CRM_Utils_Hook::pre('create', 'MembershipPayment', NULL, $dao);
                     $dao->save();
                     CRM_Utils_Hook::post('create', 'MembershipPayment', $dao->id, $dao);
                 }
             }
         }
     }
     if (!empty($errors)) {
         foreach ($errors as $error) {
             if (is_string($error)) {
                 $message[] = $error;
             }
         }
         $message = ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
         throw new CRM_Core_Exception($message);
     }
     // CRM-7851
     CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_membership', $membership->id, 'Membership');
     $form->_params['membershipID'] = $membership->id;
     if ($form->_contributeMode == 'notify') {
         if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
             // call postprocess hook before leaving
             $form->postProcessHook();
             // this does not return
             $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             $payment->doTransferCheckout($form->_params, 'contribute');
         }
     }
     $form->_values['membership_id'] = $membership->id;
     if (isset($contribution[$index]->id)) {
         $form->_values['contribution_id'] = $contribution[$index]->id;
     }
     // Do not send an email if Recurring transaction is done via Direct Mode
     // Email will we sent when the IPN is received.
     if (CRM_Utils_Array::value('is_recur', $form->_params) && $form->_contributeMode == 'direct') {
         return TRUE;
     }
     //finally send an email receipt
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $isTest, FALSE, $includeFieldTypes);
 }
Esempio n. 10
0
 /**
  * Process the Memberships.
  *
  * @param array $membershipParams
  *   Array of membership fields.
  * @param int $contactID
  *   Contact id.
  * @param CRM_Contribute_Form_Contribution_Confirm $form
  *   Confirmation form object.
  *
  * @param array $premiumParams
  * @param null $customFieldsFormatted
  * @param null $includeFieldTypes
  *
  * @param array $membershipDetails
  *
  * @param array $membershipTypeIDs
  *
  * @param bool $isPaidMembership
  * @param array $membershipID
  *
  * @param bool $isProcessSeparateMembershipTransaction
  *
  * @param int $financialTypeID
  * @param array $membershipLineItems
  *   Line items specific to membership payment that is separate to contribution.
  * @param bool $isPayLater
  * @param bool $isPending
  *
  * @throws \CRM_Core_Exception
  */
 protected function postProcessMembership($membershipParams, $contactID, &$form, $premiumParams, $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID, $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending)
 {
     $membershipContribution = NULL;
     $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE);
     $errors = $createdMemberships = $paymentResult = array();
     if ($isPaidMembership) {
         if ($isProcessSeparateMembershipTransaction) {
             // If we have 2 transactions only one can use the invoice id.
             $membershipParams['invoiceID'] .= '-2';
         }
         $paymentResult = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $contactID, $financialTypeID, 'membership', array(), $isTest, $isPayLater);
         if (!empty($paymentResult['contribution'])) {
             $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
             //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
             $membershipContribution = $paymentResult['contribution'];
             // Save the contribution ID so that I can be used in email receipts
             // For example, if you need to generate a tax receipt for the donation only.
             $form->_values['contribution_other_id'] = $membershipContribution->id;
         }
     }
     if ($isProcessSeparateMembershipTransaction) {
         try {
             $form->_lineItem = $membershipLineItems;
             if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) {
                 unset($membershipParams['is_recur']);
             }
             $membershipContribution = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array::value('financial_type_id', $membershipDetails));
         } catch (CRM_Core_Exception $e) {
             $errors[2] = $e->getMessage();
             $membershipContribution = NULL;
         }
     }
     $membership = NULL;
     if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
         $membershipContributionID = $membershipContribution->id;
     }
     //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
     if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
         $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
     }
     //@todo it should no longer be possible for it to get to this point & membership to not be an array
     if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
         $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
         foreach ($membershipTypeIDs as $memType) {
             $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
             if (!empty($membershipContribution)) {
                 $pendingStatus = CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name');
                 $pending = $membershipContribution->contribution_status_id == $pendingStatus ? TRUE : FALSE;
             } else {
                 $pending = $isPending;
             }
             $contributionRecurID = isset($form->_params['contributionRecurID']) ? $form->_params['contributionRecurID'] : NULL;
             $membershipSource = NULL;
             if (!empty($form->_params['membership_source'])) {
                 $membershipSource = $form->_params['membership_source'];
             } elseif (isset($form->_values['title']) && !empty($form->_values['title'])) {
                 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values['title'];
             }
             $isPayLater = NULL;
             if (isset($form->_params)) {
                 $isPayLater = CRM_Utils_Array::value('is_pay_later', $form->_params);
             }
             $campaignId = NULL;
             if (isset($form->_values) && is_array($form->_values) && !empty($form->_values)) {
                 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_params);
                 if (!array_key_exists('campaign_id', $form->_params)) {
                     $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
                 }
             }
             list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership::renewMembership($contactID, $memType, $isTest, date('YmdHis'), CRM_Utils_Array::value('cms_contactID', $membershipParams), $customFieldsFormatted, $numTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId);
             $form->set('renewal_mode', $renewalMode);
             if (!empty($dates)) {
                 $form->assign('mem_start_date', CRM_Utils_Date::customFormat($dates['start_date'], '%Y%m%d'));
                 $form->assign('mem_end_date', CRM_Utils_Date::customFormat($dates['end_date'], '%Y%m%d'));
             }
             if (!empty($membershipContribution)) {
                 // update recurring id for membership record
                 CRM_Member_BAO_Membership::updateRecurMembership($membership, $membershipContribution);
                 CRM_Member_BAO_Membership::linkMembershipPayment($membership, $membershipContribution);
             }
         }
         if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
             foreach ($form->_lineItem[$form->_priceSetId] as &$priceFieldOp) {
                 if (!empty($priceFieldOp['membership_type_id']) && isset($createdMemberships[$priceFieldOp['membership_type_id']])) {
                     $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
                     $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%B %E%f, %Y') : '-';
                     $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%B %E%f, %Y') : '-';
                 } else {
                     $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
                 }
             }
             $form->_values['lineItem'] = $form->_lineItem;
             $form->assign('lineItem', $form->_lineItem);
         }
     }
     if (!empty($errors)) {
         $message = $this->compileErrorMessage($errors);
         throw new CRM_Core_Exception($message);
     }
     $form->_params['createdMembershipIDs'] = array();
     // CRM-7851 - Moved after processing Payment Errors
     //@todo - the reasoning for this being here seems a little outdated
     foreach ($createdMemberships as $createdMembership) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, 'civicrm_membership', $createdMembership->id, 'Membership');
         $form->_params['createdMembershipIDs'][] = $createdMembership->id;
     }
     if (count($createdMemberships) == 1) {
         //presumably this is only relevant for exactly 1 membership
         $form->_params['membershipID'] = $createdMembership->id;
     }
     //CRM-15232: Check if membership is created and on the basis of it use
     //membership receipt template to send payment receipt
     if (count($createdMemberships)) {
         $form->_values['isMembership'] = TRUE;
     }
     if (isset($membershipContributionID)) {
         $form->_values['contribution_id'] = $membershipContributionID;
     }
     if ($form->_contributeMode) {
         if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
             // call postProcess hook before leaving
             $form->postProcessHook();
         }
         $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
         $result = $payment->doPayment($form->_params, 'contribute');
         if (CRM_Utils_Array::value('payment_status_id', $result) == 1) {
             // Refer to CRM-16737. Payment processors 'should' return payment_status_id
             // to denote the outcome of the transaction.
             try {
                 civicrm_api3('contribution', 'completetransaction', array('id' => $paymentResult['contribution']->id, 'trxn_id' => $paymentResult['contribution']->trxn_id, 'is_transactional' => FALSE));
             } catch (CiviCRM_API3_Exception $e) {
                 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
                 // so let's be gentle here
                 CRM_Core_Error::debug_log_message('contribution ' . $membershipContribution->id . ' not completed with trxn_id ' . $membershipContribution->trxn_id . ' and message ' . $e->getMessage());
             }
         }
         // Do not send an email if Recurring transaction is done via Direct Mode
         // Email will we sent when the IPN is received.
         return;
     }
     //finally send an email receipt
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $isTest, FALSE, $includeFieldTypes);
 }
Esempio n. 11
0
 /**  
  * Function to handle  process after the confirmation of payment by User
  *  
  * @return None  
  * @access public  
  */
 function confirmPostProcess($contactID = null, $contribution = null, $payment = null)
 {
     // add/update contact information
     $fields = array();
     unset($this->_params['note']);
     //to avoid conflict overwrite $this->_params
     $this->_params = $this->get('value');
     // create CMS user
     if (CRM_Utils_Array::value('cms_create_account', $this->_params)) {
         $this->_params['contactID'] = $contactID;
         $mail = 'email-5';
         // we should use primary email for
         // 1. free event registration.
         // 2. pay later participant.
         // 3. waiting list participant.
         // 4. require approval participant.
         if (CRM_Utils_Array::value('is_pay_later', $this->_params) || $this->_allowWaitlist || $this->_requireApproval || !CRM_Utils_Array::value('is_monetary', $this->_values['event'])) {
             $mail = 'email-Primary';
         }
         require_once "CRM/Core/BAO/CMSUser.php";
         if (!CRM_Core_BAO_CMSUser::create($this->_params, $mail)) {
             CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
         }
     }
     //get the amount of primary participant
     if (CRM_Utils_Array::value('is_primary', $this->_params)) {
         $this->_params['fee_amount'] = $this->get('primaryParticipantAmount');
     }
     // add participant record
     $participant = $this->addParticipant($this->_params, $contactID);
     $this->_participantIDS[] = $participant->id;
     //setting register_by_id field and primaryContactId
     if (CRM_Utils_Array::value('is_primary', $this->_params)) {
         $this->set('registerByID', $participant->id);
         $this->set('primaryContactId', $contactID);
     }
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participant->id, 'Participant');
     $createPayment = $this->_params['amount'] != 0 ? true : false;
     // force to create zero amount payment, CRM-5095
     if (!$createPayment && $contribution->id && $this->_params['amount'] == 0 && $this->_priceSetId && $this->_lineItem) {
         $createPayment = true;
     }
     if ($createPayment && $this->_values['event']['is_monetary'] && CRM_Utils_Array::value('contributionID', $this->_params)) {
         require_once 'CRM/Event/BAO/ParticipantPayment.php';
         $paymentParams = array('participant_id' => $participant->id, 'contribution_id' => $contribution->id);
         $ids = array();
         $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams, $ids);
     }
     //set only primary participant's params for transfer checkout.
     if (($this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') && CRM_Utils_Array::value('is_primary', $this->_params)) {
         $this->_params['participantID'] = $participant->id;
         $this->set('primaryParticipant', $this->_params);
     }
     $this->assign('action', $this->_action);
 }
 /**
  * Process the contribution
  *
  * @return void
  * @access public
  */
 static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = TRUE, $pending = FALSE, $online = TRUE)
 {
     $transaction = new CRM_Core_Transaction();
     $className = get_class($form);
     $honorCId = $recurringContributionID = NULL;
     if ($online && $form->get('honor_block_is_active')) {
         $honorCId = $form->createHonorContact();
     }
     // add these values for the recurringContrib function ,CRM-10188
     $params['contribution_type_id'] = $contributionType->id;
     $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $form->_values);
     $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online);
     if (!$online && isset($params['honor_contact_id'])) {
         $honorCId = $params['honor_contact_id'];
     }
     $config = CRM_Core_Config::singleton();
     if (!$online && isset($params['non_deductible_amount'])) {
         $nonDeductibleAmount = $params['non_deductible_amount'];
     } else {
         $nonDeductibleAmount = $params['amount'];
     }
     if ($online && $contributionType->is_deductible && $deductibleMode) {
         $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
         if ($selectProduct && $selectProduct != 'no_thanks') {
             $productDAO = new CRM_Contribute_DAO_Product();
             $productDAO->id = $selectProduct;
             $productDAO->find(TRUE);
             if ($params['amount'] < $productDAO->price) {
                 $nonDeductibleAmount = $params['amount'];
             } else {
                 $nonDeductibleAmount = $productDAO->price;
             }
         } else {
             $nonDeductibleAmount = '0.00';
         }
     }
     $now = date('YmdHis');
     $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
     if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) {
         $receiptDate = $now;
     }
     //get the contrib page id.
     $campaignId = $contributionPageId = NULL;
     if ($online) {
         $contributionPageId = $form->_id;
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
         if (!array_key_exists('campaign_id', $params)) {
             $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
         }
     } else {
         //also for offline we do support - CRM-7290
         $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
     }
     // first create the contribution record
     $contribParams = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'contribution_page_id' => $contributionPageId, 'receive_date' => CRM_Utils_Array::value('receive_date', $params) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'), 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $params['amount'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || CRM_Utils_Array::value('source', $params) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0), 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : NULL, 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : NULL, 'campaign_id' => $campaignId);
     if (!$online && isset($params['thankyou_date'])) {
         $contribParams['thankyou_date'] = $params['thankyou_date'];
     }
     if (!$online || $form->_values['is_monetary']) {
         if (!CRM_Utils_Array::value('is_pay_later', $params)) {
             $contribParams['payment_instrument_id'] = 1;
         }
     }
     if (!$pending && $result) {
         $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $result), 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result));
     }
     if (isset($honorCId)) {
         $contribParams['honor_contact_id'] = $honorCId;
         $contribParams['honor_type_id'] = $params['honor_type_id'];
     }
     if ($recurringContributionID) {
         $contribParams['contribution_recur_id'] = $recurringContributionID;
     }
     $contribParams['contribution_status_id'] = $pending ? 2 : 1;
     $contribParams['is_test'] = 0;
     if ($form->_mode == 'test') {
         $contribParams['is_test'] = 1;
     }
     $ids = array();
     if (isset($contribParams['invoice_id'])) {
         $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id');
         if (isset($contribID)) {
             $ids['contribution'] = $contribID;
             $contribParams['id'] = $contribID;
         }
     }
     //create an contribution address
     if ($form->_contributeMode != 'notify' && !CRM_Utils_Array::value('is_pay_later', $params) && CRM_Utils_Array::value('is_monetary', $form->_values)) {
         $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
     }
     // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
     $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' '));
     $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' '));
     // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
     if (CRM_Utils_Array::value('pcp_made_through_id', $params) || CRM_Utils_Array::value('soft_credit_to', $params)) {
         // if its due to pcp
         if (CRM_Utils_Array::value('pcp_made_through_id', $params)) {
             $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id');
         } else {
             $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
         }
         // Pass these details onto with the contribution to make them
         // available at hook_post_process, CRM-8908
         $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId;
     }
     if ($params['amount']) {
         //add contribution record
         $contribution =& CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
     }
     // process soft credit / pcp pages
     CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
     // process price set, CRM-5095
     if ($contribution && $contribution->id && $form->_priceSetId) {
         if (CRM_Utils_Array::value('is_quick_config', $form->_params)) {
             $temp = array();
             foreach ($form->_lineItem as $key => $val) {
                 foreach ($val as $k => $v) {
                     if (CRM_Utils_Money::format($v['line_total']) == CRM_Utils_Money::format($contribution->total_amount)) {
                         $temp[$key][$k] = $form->_lineItem[$key][$k];
                         CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $temp);
                     }
                 }
             }
         } elseif (!CRM_Utils_Array::value('is_quick_config', $form->_params)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $form->_lineItem);
         }
         if (!$form->_separateMembershipPayment && CRM_Utils_Array::value('is_quick_config', $form->_params)) {
             $form->_lineItem = null;
         }
     }
     //handle pledge stuff.
     if (!CRM_Utils_Array::value('separate_membership_payment', $form->_params) && CRM_Utils_Array::value('pledge_block_id', $form->_values) && (CRM_Utils_Array::value('is_pledge', $form->_params) || CRM_Utils_Array::value('pledge_id', $form->_values))) {
         if (CRM_Utils_Array::value('pledge_id', $form->_values)) {
             //when user doing pledge payments.
             //update the schedule when payment(s) are made
             foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
                 $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id');
                 $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount);
                 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
             }
             //update pledge status according to the new payment statuses
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']);
         } else {
             //when user creating pledge record.
             $pledgeParams = array();
             $pledgeParams['contact_id'] = $contribution->contact_id;
             $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
             $pledgeParams['contribution_id'] = $contribution->id;
             $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
             $pledgeParams['contribution_type_id'] = $contribution->contribution_type_id;
             $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
             $pledgeParams['installments'] = $params['pledge_installments'];
             $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
             if ($pledgeParams['frequency_unit'] == 'month') {
                 $pledgeParams['frequency_day'] = intval(date("d"));
             } else {
                 $pledgeParams['frequency_day'] = 1;
             }
             $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
             $pledgeParams['status_id'] = $contribution->contribution_status_id;
             $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
             $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
             $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
             $pledgeParams['is_test'] = $contribution->is_test;
             $pledgeParams['acknowledge_date'] = date('Ymd');
             $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
             //inherit campaign from contirb page.
             $pledgeParams['campaign_id'] = $campaignId;
             $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
             $form->_params['pledge_id'] = $pledge->id;
             //send acknowledgment email. only when pledge is created
             if ($pledge->id) {
                 //build params to send acknowledgment.
                 $pledgeParams['id'] = $pledge->id;
                 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
                 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
                 //scheduled amount will be same as installment_amount.
                 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
                 //get total pledge amount.
                 $pledgeParams['total_pledge_amount'] = $pledge->amount;
                 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
             }
         }
     }
     if ($online && $contribution) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution');
     } elseif ($contribution) {
         //handle custom data.
         $params['contribution_id'] = $contribution->id;
         if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) {
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
         }
     }
     if (isset($params['related_contact'])) {
         $contactID = $params['related_contact'];
     } elseif (isset($params['cms_contactID'])) {
         $contactID = $params['cms_contactID'];
     }
     CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID);
     // return if pending
     if ($pending) {
         return $contribution;
     }
     // next create the transaction record
     if ($contribution && (!$online || $form->_values['is_monetary']) && $result['trxn_id']) {
         $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'currency' => $params['currencyID'], 'payment_processor' => $form->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id'], 'trxn_result_code' => isset($result['trxn_result_code']) ? $result['trxn_result_code'] : FALSE);
         $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
     }
     //create contribution activity w/ individual and target
     //activity w/ organisation contact id when onbelf, CRM-4027
     $targetContactID = NULL;
     if (CRM_Utils_Array::value('hidden_onbehalf_profile', $params)) {
         $targetContactID = $contribution->contact_id;
         $contribution->contact_id = $contactID;
     }
     // create an activity record
     if ($contribution) {
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
     }
     $transaction->commit();
     return $contribution;
 }
 /**
  * process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // need to process / save custom data
     // Get the form values and groupTree
     $params = $this->controller->exportValues($this->_name);
     CRM_Core_BAO_CustomValueTable::postProcess($params, $this->_groupTree[$this->_groupID]['fields'], 'civicrm_contact', $this->_contactId, $this->_entityType);
     // reset the group contact cache for this group
     CRM_Contact_BAO_GroupContactCache::remove();
     $response = array('status' => 'save');
     $this->postProcessHook();
     echo json_encode($response);
     CRM_Utils_System::civiExit();
 }
Esempio n. 14
0
 /**
  * Process the contribution.
  *
  * @param CRM_Core_Form $form
  * @param array $params
  * @param array $result
  * @param int $contactID
  * @param CRM_Financial_DAO_FinancialType $financialType
  * @param bool $pending
  * @param bool $online
  *
  * @param bool $isTest
  * @param array $lineItems
  *
  * @param int $billingLocationID
  *   ID of billing location type.
  *
  * @return \CRM_Contribute_DAO_Contribution
  * @throws \Exception
  */
 public static function processFormContribution(&$form, $params, $result, $contactID, $financialType, $pending, $online, $isTest, $lineItems, $billingLocationID)
 {
     $transaction = new CRM_Core_Transaction();
     $contribSoftContactId = $addressID = NULL;
     $contributeMode = $form->_contributeMode;
     $isMonetary = !empty($form->_values['is_monetary']);
     $isEmailReceipt = !empty($form->_values['is_email_receipt']);
     // How do these vary from params? These are currently passed to
     // - custom data function....
     $formParams = $form->_params;
     $isSeparateMembershipPayment = empty($formParams['separate_membership_payment']) ? FALSE : TRUE;
     $pledgeID = empty($formParams['pledge_id']) ? NULL : $formParams['pledge_id'];
     if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) && (!empty($formParams['is_pledge']) || $pledgeID)) {
         $isPledge = TRUE;
     } else {
         $isPledge = FALSE;
     }
     // add these values for the recurringContrib function ,CRM-10188
     $params['financial_type_id'] = $financialType->id;
     //create an contribution address
     if ($contributeMode != 'notify' && empty($params['is_pay_later']) && $isMonetary) {
         $addressID = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID);
     }
     //@todo - this is being set from the form to resolve CRM-10188 - an
     // eNotice caused by it not being set @ the front end
     // however, we then get it being over-written with null for backend contributions
     // a better fix would be to set the values in the respective forms rather than require
     // a function being shared by two forms to deal with their respective values
     // moving it to the BAO & not taking the $form as a param would make sense here.
     if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
         $params['is_email_receipt'] = $isEmailReceipt;
     }
     $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType, $online);
     $nonDeductibleAmount = self::getNonDeductibleAmount($params, $financialType, $online);
     $now = date('YmdHis');
     $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
     if ($isEmailReceipt) {
         $receiptDate = $now;
     }
     //get the contrib page id.
     $contributionPageId = NULL;
     if ($online) {
         $contributionPageId = $form->_id;
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
         if (!array_key_exists('campaign_id', $params)) {
             $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
         }
     } else {
         //also for offline we do support - CRM-7290
         $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
     }
     // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
     if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
         // if its due to pcp
         if (!empty($params['pcp_made_through_id'])) {
             $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id');
         } else {
             $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
         }
         // Pass these details onto with the contribution to make them
         // available at hook_post_process, CRM-8908
         $params['soft_credit_to'] = $contribSoftContactId;
     }
     if (isset($params['amount'])) {
         $contribParams = self::getContributionParams($params, $contactID, $financialType->id, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending, $result, $receiptDate, $recurringContributionID, $isTest, $addressID, $contribSoftContactId, $lineItems);
         $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         if ($invoicing) {
             $dataArray = array();
             foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
                 foreach ($lineItemValue 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);
                         }
                     }
                 }
             }
             $smarty = CRM_Core_Smarty::singleton();
             $smarty->assign('dataArray', $dataArray);
             $smarty->assign('totalTaxAmount', $params['tax_amount']);
         }
         if (is_a($contribution, 'CRM_Core_Error')) {
             $message = CRM_Core_Error::getMessages($contribution);
             CRM_Core_Error::fatal($message);
         }
         // lets store it in the form variable so postProcess hook can get to this and use it
         $form->_contributionID = $contribution->id;
     }
     //CRM-13981, processing honor contact into soft-credit contribution
     CRM_Contact_Form_ProfileContact::postProcess($form);
     // process soft credit / pcp pages
     CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
     //handle pledge stuff.
     if ($isPledge) {
         if ($pledgeID) {
             //when user doing pledge payments.
             //update the schedule when payment(s) are made
             foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
                 $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id');
                 $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount);
                 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
             }
             //update pledge status according to the new payment statuses
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID);
         } else {
             //when user creating pledge record.
             $pledgeParams = array();
             $pledgeParams['contact_id'] = $contribution->contact_id;
             $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
             $pledgeParams['contribution_id'] = $contribution->id;
             $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
             $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
             $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
             $pledgeParams['installments'] = $params['pledge_installments'];
             $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
             if ($pledgeParams['frequency_unit'] == 'month') {
                 $pledgeParams['frequency_day'] = intval(date("d"));
             } else {
                 $pledgeParams['frequency_day'] = 1;
             }
             $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
             $pledgeParams['status_id'] = $contribution->contribution_status_id;
             $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
             $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
             $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
             $pledgeParams['is_test'] = $contribution->is_test;
             $pledgeParams['acknowledge_date'] = date('Ymd');
             $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
             //inherit campaign from contirb page.
             $pledgeParams['campaign_id'] = $campaignId;
             $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
             $form->_params['pledge_id'] = $pledge->id;
             //send acknowledgment email. only when pledge is created
             if ($pledge->id) {
                 //build params to send acknowledgment.
                 $pledgeParams['id'] = $pledge->id;
                 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
                 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
                 //scheduled amount will be same as installment_amount.
                 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
                 //get total pledge amount.
                 $pledgeParams['total_pledge_amount'] = $pledge->amount;
                 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
             }
         }
     }
     if ($online && $contribution) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, 'civicrm_contribution', $contribution->id, 'Contribution');
     } elseif ($contribution) {
         //handle custom data.
         $params['contribution_id'] = $contribution->id;
         if (!empty($params['custom']) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) {
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
         }
     }
     // Save note
     if ($contribution && !empty($params['contribution_note'])) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['contribution_note'], 'entity_id' => $contribution->id, 'contact_id' => $contribution->contact_id, 'modified_date' => date('Ymd'));
         CRM_Core_BAO_Note::add($noteParams, array());
     }
     if (isset($params['related_contact'])) {
         $contactID = $params['related_contact'];
     } elseif (isset($params['cms_contactID'])) {
         $contactID = $params['cms_contactID'];
     }
     //create contribution activity w/ individual and target
     //activity w/ organisation contact id when onbelf, CRM-4027
     $targetContactID = NULL;
     if (!empty($params['hidden_onbehalf_profile'])) {
         $targetContactID = $contribution->contact_id;
         $contribution->contact_id = $contactID;
     }
     // create an activity record
     if ($contribution) {
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
     }
     $transaction->commit();
     // CRM-13074 - create the CMSUser after the transaction is completed as it
     // is not appropriate to delete a valid contribution if a user create problem occurs
     CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $billingLocationID);
     return $contribution;
 }
Esempio n. 15
0
 /**
  * Process the Memberships
  *
  * @param array  $membershipParams array of membership fields
  * @param int    $contactID        contact id 
  * @param object $form             form object  
  *
  * @return void
  * @access public
  */
 public function postProcessMembership($membershipParams, $contactID, &$form, &$premiumParams)
 {
     $tempParams = $membershipParams;
     $paymentDone = false;
     $result = null;
     $isTest = CRM_Utils_Array::value('is_test', $membershipParams, false);
     $form->assign('membership_assign', true);
     $form->set('membershipTypeID', $membershipParams['selectMembership']);
     require_once 'CRM/Member/BAO/MembershipType.php';
     require_once 'CRM/Member/BAO/Membership.php';
     $membershipTypeID = $membershipParams['selectMembership'];
     $membershipDetails = self::buildMembershipTypeValues($form, $membershipTypeID);
     $form->assign('membership_name', $membershipDetails['name']);
     $minimumFee = CRM_Utils_Array::value('minimum_fee', $membershipDetails);
     $contributionTypeId = null;
     if ($form->_values['amount_block_is_active']) {
         $contributionTypeId = $form->_values['contribution_type_id'];
     } else {
         $paymentDone = true;
         $params['amount'] = $minimumFee;
         $contributionTypeId = $membershipDetails['contribution_type_id'];
     }
     //amount must be greater than zero for
     //adding contribution record  to contribution table.
     //this condition is arises when separate membership payment is
     //enable and contribution amount is not selected. fix for CRM-3010
     require_once 'CRM/Contribute/BAO/Contribution/Utils.php';
     if ($form->_amount > 0.0) {
         $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $premiumParams, $contactID, $contributionTypeId, 'membership');
     } else {
         // create the CMS contact here since we normally do this under processConfirm
         CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams, $membershipParams['cms_contactID'], 'email-' . $form->_bltID);
     }
     $errors = array();
     if (is_a($result[1], 'CRM_Core_Error')) {
         $errors[1] = CRM_Core_Error::getMessages($result[1]);
     } else {
         $contribution[1] = $result[1];
     }
     $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($form->_id);
     if ($memBlockDetails['is_separate_payment'] && !$paymentDone) {
         require_once 'CRM/Contribute/DAO/ContributionType.php';
         $contributionType = new CRM_Contribute_DAO_ContributionType();
         $contributionType->id = $membershipDetails['contribution_type_id'];
         if (!$contributionType->find(true)) {
             CRM_Core_Error::fatal("Could not find a system table");
         }
         $tempParams['amount'] = $minimumFee;
         $invoiceID = md5(uniqid(rand(), true));
         $tempParams['invoiceID'] = $invoiceID;
         //we don't allow recurring membership.CRM-3781.
         if (CRM_Utils_Array::value('is_recur', $tempParams)) {
             $tempParams['is_recur'] = 0;
         }
         $result = null;
         if ($form->_values['is_monetary'] && !$form->_params['is_pay_later']) {
             require_once 'CRM/Core/Payment.php';
             $payment =& CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             if ($form->_contributeMode == 'express') {
                 $result =& $payment->doExpressCheckout($tempParams);
             } else {
                 $result =& $payment->doDirectPayment($tempParams);
             }
         }
         if (is_a($result, 'CRM_Core_Error')) {
             $errors[2] = CRM_Core_Error::getMessages($result);
         } else {
             //assign receive date when separate membership payment
             //and contribution amount not selected.
             if ($form->_amount == 0) {
                 $now = date('YmdHis');
                 $form->_params['receive_date'] = $now;
                 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
                 $form->set('params', $form->_params);
                 $form->assign('receive_date', $receiveDate);
             }
             $form->set('membership_trx_id', $result['trxn_id']);
             $form->set('membership_amount', $minimumFee);
             $form->assign('membership_trx_id', $result['trxn_id']);
             $form->assign('membership_amount', $minimumFee);
             // we dont need to create the user twice, so lets disable cms_create_account
             // irrespective of the value, CRM-2888
             $tempParams['cms_create_account'] = 0;
             $pending = $form->_params['is_pay_later'] ? true : false;
             //set this variable as we are not creating pledge for
             //separate membership payment contribution.
             //so for differentiating membership contributon from
             //main contribution.
             $form->_params['separate_membership_payment'] = 1;
             $contribution[2] = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $tempParams, $result, $contactID, $contributionType, false, $pending);
         }
     }
     $index = $memBlockDetails['is_separate_payment'] ? 2 : 1;
     if (!CRM_Utils_Array::value($index, $errors)) {
         $membership = self::renewMembership($contactID, $membershipTypeID, $isTest, $form, null, CRM_Utils_Array::value('cms_contactID', $membershipParams));
         if (isset($contribution[$index])) {
             //insert payment record
             require_once 'CRM/Member/DAO/MembershipPayment.php';
             $dao = new CRM_Member_DAO_MembershipPayment();
             $dao->membership_id = $membership->id;
             $dao->contribution_id = $contribution[$index]->id;
             //Fixed for avoiding duplicate entry error when user goes
             //back and forward during payment mode is notify
             if (!$dao->find(true)) {
                 CRM_Utils_Hook::pre('create', 'MembershipPayment', null, $dao);
                 $dao->save();
                 CRM_Utils_Hook::post('create', 'MembershipPayment', $dao->id, $dao);
             }
         }
     }
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_membership', $membership->id, 'Membership');
     if (!empty($errors)) {
         foreach ($errors as $error) {
             if (is_string($error)) {
                 $message[] = $error;
             }
         }
         $message = ts("Payment Processor Error message") . ": " . implode('<br/>', $message);
         $session = CRM_Core_Session::singleton();
         $session->setStatus($message);
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$form->_params['qfKey']}"));
     }
     $form->_params['membershipID'] = $membership->id;
     if ($form->_contributeMode == 'notify') {
         if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
             // this does not return
             require_once 'CRM/Core/Payment.php';
             $payment =& CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             $payment->doTransferCheckout($form->_params, 'contribute');
         }
     }
     $form->_values['membership_id'] = $membership->id;
     if (isset($contribution[$index]->id)) {
         $form->_values['contribution_id'] = $contribution[$index]->id;
     }
     // Do not send an email if Recurring transaction is done via Direct Mode
     // Email will we sent when the IPN is received.
     if ($form->_params['is_recur'] && $form->_contributeMode == 'direct') {
         return true;
     }
     //finally send an email receipt
     require_once "CRM/Contribute/BAO/ContributionPage.php";
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $isTest);
 }
Esempio n. 16
0
 /**
  * Process the user submitted custom data values.
  *
  * @access public
  * @return void
  */
 public function postProcess()
 {
     // Get the form values and groupTree
     $params = $this->controller->exportValues($this->_name);
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     CRM_Core_BAO_CustomValueTable::postProcess($params, $this->_groupTree[$this->_groupID]['fields'], 'civicrm_contact', $this->_tableID, $this->_entityType);
     // reset the group contact cache for this group
     require_once 'CRM/Contact/BAO/GroupContactCache.php';
     CRM_Contact_BAO_GroupContactCache::remove();
 }
Esempio n. 17
0
 /**
  * Process the contribution
  *
  * @param $form
  * @param $params
  * @param $result
  * @param $contactID
  * @param $contributionType
  * @param bool $deductibleMode
  * @param bool $pending
  * @param bool $online
  *
  * @return CRM_Contribute_DAO_Contribution
  * @access public
  */
 static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = TRUE, $pending = FALSE, $online = TRUE)
 {
     $transaction = new CRM_Core_Transaction();
     $className = get_class($form);
     $recurringContributionID = NULL;
     // add these values for the recurringContrib function ,CRM-10188
     $params['financial_type_id'] = $contributionType->id;
     //@todo - this is being set from the form to resolve CRM-10188 - an
     // eNotice caused by it not being set @ the front end
     // however, we then get it being over-written with null for backend contributions
     // a better fix would be to set the values in the respective forms rather than require
     // a function being shared by two forms to deal with their respective values
     // moving it to the BAO & not taking the $form as a param would make sense here.
     if (!isset($params['is_email_receipt'])) {
         $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $form->_values);
     }
     $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online);
     $config = CRM_Core_Config::singleton();
     // CRM-11885
     // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
     if (isset($params['non_deductible_amount']) && !empty($params['non_deductible_amount'])) {
         $nonDeductibleAmount = $params['non_deductible_amount'];
     } else {
         //if ($contributionType->is_deductible && $deductibleMode) {
         if ($contributionType->is_deductible) {
             if ($online && isset($params['selectProduct'])) {
                 $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
             }
             if (!$online && isset($params['product_name'][0])) {
                 $selectProduct = $params['product_name'][0];
             }
             // if there is a product - compare the value to the contribution amount
             if (isset($selectProduct) && $selectProduct != 'no_thanks') {
                 $productDAO = new CRM_Contribute_DAO_Product();
                 $productDAO->id = $selectProduct;
                 $productDAO->find(TRUE);
                 // product value exceeds contribution amount
                 if ($params['amount'] < $productDAO->price) {
                     $nonDeductibleAmount = $params['amount'];
                 } else {
                     $nonDeductibleAmount = $productDAO->price;
                 }
             } else {
                 $nonDeductibleAmount = '0.00';
             }
         } else {
             $nonDeductibleAmount = $params['amount'];
         }
     }
     $now = date('YmdHis');
     $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
     if (!empty($form->_values['is_email_receipt'])) {
         $receiptDate = $now;
     }
     //get the contrib page id.
     $campaignId = $contributionPageId = NULL;
     if ($online) {
         $contributionPageId = $form->_id;
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
         if (!array_key_exists('campaign_id', $params)) {
             $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
         }
     } else {
         //also for offline we do support - CRM-7290
         $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
     }
     // first create the contribution record
     $contribParams = array('contact_id' => $contactID, 'financial_type_id' => $contributionType->id, 'contribution_page_id' => $contributionPageId, 'receive_date' => CRM_Utils_Array::value('receive_date', $params) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'), 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $params['amount'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || !empty($params['source']) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0), 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : NULL, 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : NULL, 'campaign_id' => $campaignId);
     if (!$online && isset($params['thankyou_date'])) {
         $contribParams['thankyou_date'] = $params['thankyou_date'];
     }
     if (!$online || $form->_values['is_monetary']) {
         if (empty($params['is_pay_later'])) {
             $contribParams['payment_instrument_id'] = 1;
         }
     }
     if (!$pending && $result) {
         $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $result), 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result));
     }
     if ($recurringContributionID) {
         $contribParams['contribution_recur_id'] = $recurringContributionID;
     }
     $contribParams['contribution_status_id'] = $pending ? 2 : 1;
     $contribParams['is_test'] = 0;
     if ($form->_mode == 'test') {
         $contribParams['is_test'] = 1;
     }
     $ids = array();
     if (isset($contribParams['invoice_id'])) {
         $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id');
         if (isset($contribID)) {
             $ids['contribution'] = $contribID;
             $contribParams['id'] = $contribID;
         }
     }
     //create an contribution address
     if ($form->_contributeMode != 'notify' && empty($params['is_pay_later']) && !empty($form->_values['is_monetary'])) {
         $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
     }
     // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
     $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' '));
     $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' '));
     // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
     if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
         // if its due to pcp
         if (!empty($params['pcp_made_through_id'])) {
             $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id');
         } else {
             $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
         }
         // Pass these details onto with the contribution to make them
         // available at hook_post_process, CRM-8908
         $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId;
     }
     if (isset($params['amount'])) {
         $contribParams['line_item'] = $form->_lineItem;
         //add contribution record
         $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
         if (is_a($contribution, 'CRM_Core_Error')) {
             $message = CRM_Core_Error::getMessages($contribution);
             CRM_Core_Error::fatal($message);
         }
         // lets store it in the form variable so postProcess hook can get to this and use it
         $form->_contributionID = $contribution->id;
     }
     //CRM-13981, processing honor contact into soft-credit contribution
     CRM_Contact_Form_ProfileContact::postProcess($form);
     // process soft credit / pcp pages
     CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
     //handle pledge stuff.
     if (empty($form->_params['separate_membership_payment']) && !empty($form->_values['pledge_block_id']) && (!empty($form->_params['is_pledge']) || !empty($form->_values['pledge_id']))) {
         if (!empty($form->_values['pledge_id'])) {
             //when user doing pledge payments.
             //update the schedule when payment(s) are made
             foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
                 $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id');
                 $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount);
                 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
             }
             //update pledge status according to the new payment statuses
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']);
         } else {
             //when user creating pledge record.
             $pledgeParams = array();
             $pledgeParams['contact_id'] = $contribution->contact_id;
             $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
             $pledgeParams['contribution_id'] = $contribution->id;
             $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
             $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
             $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
             $pledgeParams['installments'] = $params['pledge_installments'];
             $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
             if ($pledgeParams['frequency_unit'] == 'month') {
                 $pledgeParams['frequency_day'] = intval(date("d"));
             } else {
                 $pledgeParams['frequency_day'] = 1;
             }
             $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
             $pledgeParams['status_id'] = $contribution->contribution_status_id;
             $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
             $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
             $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
             $pledgeParams['is_test'] = $contribution->is_test;
             $pledgeParams['acknowledge_date'] = date('Ymd');
             $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
             //inherit campaign from contirb page.
             $pledgeParams['campaign_id'] = $campaignId;
             $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
             $form->_params['pledge_id'] = $pledge->id;
             //send acknowledgment email. only when pledge is created
             if ($pledge->id) {
                 //build params to send acknowledgment.
                 $pledgeParams['id'] = $pledge->id;
                 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
                 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
                 //scheduled amount will be same as installment_amount.
                 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
                 //get total pledge amount.
                 $pledgeParams['total_pledge_amount'] = $pledge->amount;
                 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
             }
         }
     }
     if ($online && $contribution) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution');
     } elseif ($contribution) {
         //handle custom data.
         $params['contribution_id'] = $contribution->id;
         if (!empty($params['custom']) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) {
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
         }
     }
     // Save note
     if ($contribution && !empty($params['contribution_note'])) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['contribution_note'], 'entity_id' => $contribution->id, 'contact_id' => $contribution->contact_id, 'modified_date' => date('Ymd'));
         CRM_Core_BAO_Note::add($noteParams, array());
     }
     if (isset($params['related_contact'])) {
         $contactID = $params['related_contact'];
     } elseif (isset($params['cms_contactID'])) {
         $contactID = $params['cms_contactID'];
     }
     //create contribution activity w/ individual and target
     //activity w/ organisation contact id when onbelf, CRM-4027
     $targetContactID = NULL;
     if (!empty($params['hidden_onbehalf_profile'])) {
         $targetContactID = $contribution->contact_id;
         $contribution->contact_id = $contactID;
     }
     // create an activity record
     if ($contribution) {
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
     }
     $transaction->commit();
     // CRM-13074 - create the CMSUser after the transaction is completed as it
     // is not appropriate to delete a valid contribution if a user create problem occurs
     CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID);
     return $contribution;
 }
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     //get the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     require_once 'CRM/Activity/BAO/Activity.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     require_once 'CRM/Core/BAO/CustomField.php';
     require_once 'CRM/Core/BAO/CustomGroup.php';
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     $this->_groupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', 'civicrm_value_survey_activity_details', 'id', 'table_name');
     $groupTree = CRM_Core_BAO_CustomGroup::getTree('Activity', $this, null, $this->_groupId);
     $this->_surveyId = CRM_Utils_Array::value('survey_id', $params);
     $activityGroupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, $this);
     $fieldMapper = array();
     foreach ($activityGroupTree[$this->_groupId]['fields'] as $fieldId => $field) {
         $fieldMapper[$field['column_name']] = $field['element_name'];
     }
     $duplicateContacts = array();
     $query = "SELECT DISTINCT(target.target_contact_id) as contact_id FROM " . self::ACTIVITY_SURVEY_DETAIL_TABLE . " survey INNER JOIN civicrm_activity_target target ON ( target.activity_id = survey.entity_id ) WHERE survey.status_id = 'H' AND survey.survey_id = %1  AND target.target_contact_id IN (" . implode(',', $this->_contactIds) . ") ";
     $findDuplicate = CRM_Core_DAO::executeQuery($query, array(1 => array($this->_surveyId, 'Integer')));
     while ($findDuplicate->fetch()) {
         $duplicateContacts[$findDuplicate->contact_id] = $findDuplicate->contact_id;
     }
     $customFields = CRM_Core_BAO_CustomField::getFields('Activity');
     $surveyDetails = $this->_surveyDetails;
     $maxVoters = $surveyDetails->max_number_of_contacts;
     list($cName, $cEmail, $doNotEmail, $onHold, $isDeceased) = CRM_Contact_BAO_Contact::getContactDetails($this->_interviewerId);
     $fieldParams[$fieldMapper['survey_id']] = $this->_surveyId;
     $fieldParams[$fieldMapper['status_id']] = 'H';
     $fieldParams[$fieldMapper['interviewer_id']] = $this->_interviewerId;
     $fieldParams[$fieldMapper['interviewer_display_name']] = CRM_Utils_Type::escape($cName, 'String');
     $fieldParams[$fieldMapper['interviewer_email']] = CRM_Utils_Type::escape($cEmail, 'String');
     $fieldParams[$fieldMapper['interviewer_ip']] = CRM_Utils_Type::escape($_SERVER['REMOTE_ADDR'], 'String');
     $countVoters = 0;
     foreach ($this->_contactIds as $cid) {
         if ($maxVoters && $maxVoters <= $this->_numVoters + $countVoters) {
             break;
         }
         if (in_array($cid, $duplicateContacts)) {
             continue;
         }
         $countVoters++;
         $activityParams = array();
         $activityParams['source_contact_id'] = $this->_interviewerId;
         $activityParams['assignee_contact_id'] = array($this->_interviewerId);
         $activityParams['target_contact_id'] = array($cid);
         $activityParams['activity_type_id'] = $surveyDetails->survey_type_id;
         $activityParams['subject'] = ts('Voter Reservation');
         $activityParams['status_id'] = 1;
         $activityParams['campaign_id'] = $surveyDetails->campaign_id;
         $result = CRM_Activity_BAO_Activity::create($activityParams);
         $fieldParams[$fieldMapper['subject_display_name']] = CRM_Contact_BAO_Contact::displayName($cid);
         if ($result) {
             CRM_Core_BAO_CustomValueTable::postProcess($fieldParams, $customFields, 'civicrm_activity', $result->id, 'Activity');
         }
     }
     $status = array();
     if ($countVoters > 0) {
         $status[] = ts('Voter Reservation has been added for %1 Contact(s).', array(1 => $countVoters));
     }
     if (count($this->_contactIds) > $countVoters) {
         $status[] = ts('Voter Reservation did not add for %1 Contact(s).', array(1 => count($this->_contactIds) - $countVoters));
     }
     if (!empty($status)) {
         CRM_Core_Session::setStatus(implode('&nbsp;', $status));
     }
 }
Esempio n. 19
0
 /**
  * Copy custom fields and attachments from an existing activity to another.
  *
  * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
  *
  * @param array $params
  */
 public static function copyExtendedActivityData($params)
 {
     // attach custom data to the new activity
     $customParams = $htmlType = array();
     $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
     if (!empty($customValues)) {
         $fieldIds = implode(', ', array_keys($customValues));
         $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
         $result = CRM_Core_DAO::executeQuery($sql);
         while ($result->fetch()) {
             $htmlType[] = $result->id;
         }
         foreach ($customValues as $key => $value) {
             if ($value !== NULL) {
                 // CRM-10542
                 if (in_array($key, $htmlType)) {
                     $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
                     $customParams["custom_{$key}_-1"] = array('name' => $fileValues[0], 'path' => $fileValues[1]);
                 } else {
                     $customParams["custom_{$key}_-1"] = $value;
                 }
             }
         }
         CRM_Core_BAO_CustomValueTable::postProcess($customParams, 'civicrm_activity', $params['mainActivityId'], 'Activity');
     }
     // copy activity attachments ( if any )
     CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
 }
Esempio n. 20
0
 /**
  * Process the user submitted custom data values.
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     $transaction = new CRM_Core_Transaction();
     CRM_Core_BAO_CustomValueTable::postProcess($params, 'civicrm_case', $this->_entityID, 'Case');
     $session = CRM_Core_Session::singleton();
     $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/view/case', "reset=1&id={$this->_entityID}&cid={$this->_contactID}&action=view"));
     $session = CRM_Core_Session::singleton();
     $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Change Custom Data', 'name');
     $activityParams = array('activity_type_id' => $activityTypeID, 'source_contact_id' => $session->get('userID'), 'is_auto' => TRUE, 'subject' => $this->_customTitle . " : change data", 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'), 'target_contact_id' => $this->_contactID, 'details' => json_encode($this->_defaults), 'activity_date_time' => date('YmdHis'));
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
     $caseParams = array('activity_id' => $activity->id, 'case_id' => $this->_entityID);
     CRM_Case_BAO_Case::processCaseActivity($caseParams);
     $transaction->commit();
 }
Esempio n. 21
0
 /**
  * Handle process after the confirmation of payment by User.
  *
  * @param int $contactID
  * @param null $contribution
  * @param null $payment
  */
 public function confirmPostProcess($contactID = NULL, $contribution = NULL, $payment = NULL)
 {
     // add/update contact information
     $fields = array();
     unset($this->_params['note']);
     //to avoid conflict overwrite $this->_params
     $this->_params = $this->get('value');
     //get the amount of primary participant
     if (!empty($this->_params['is_primary'])) {
         $this->_params['fee_amount'] = $this->get('primaryParticipantAmount');
     }
     // add participant record
     $participant = CRM_Event_Form_Registration::addParticipant($this, $contactID);
     $this->_participantIDS[] = $participant->id;
     //setting register_by_id field and primaryContactId
     if (!empty($this->_params['is_primary'])) {
         $this->set('registerByID', $participant->id);
         $this->set('primaryContactId', $contactID);
         // CRM-10032
         $this->processFirstParticipant($participant->id);
     }
     CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participant->id, 'Participant');
     $createPayment = CRM_Utils_Array::value('amount', $this->_params, 0) != 0 ? TRUE : FALSE;
     // force to create zero amount payment, CRM-5095
     // we know the amout is zero since createPayment is false
     if (!$createPayment && (isset($contribution) && $contribution->id) && $this->_priceSetId && $this->_lineItem) {
         $createPayment = TRUE;
     }
     if ($createPayment && $this->_values['event']['is_monetary'] && !empty($this->_params['contributionID'])) {
         $paymentParams = array('participant_id' => $participant->id, 'contribution_id' => $contribution->id);
         $ids = array();
         $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams, $ids);
     }
     //set only primary participant's params for transfer checkout.
     // The concept of contributeMode is deprecated.
     if (($this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') && !empty($this->_params['is_primary'])) {
         $this->_params['participantID'] = $participant->id;
         $this->set('primaryParticipant', $this->_params);
     }
     $this->assign('action', $this->_action);
     // create CMS user
     if (!empty($this->_params['cms_create_account'])) {
         $this->_params['contactID'] = $contactID;
         if (array_key_exists('email-5', $this->_params)) {
             $mail = 'email-5';
         } else {
             foreach ($this->_params as $name => $dontCare) {
                 if (substr($name, 0, 5) == 'email') {
                     $mail = $name;
                     break;
                 }
             }
         }
         // we should use primary email for
         // 1. free event registration.
         // 2. pay later participant.
         // 3. waiting list participant.
         // 4. require approval participant.
         if (!empty($this->_params['is_pay_later']) || $this->_allowWaitlist || $this->_requireApproval || empty($this->_values['event']['is_monetary'])) {
             $mail = 'email-Primary';
         }
         if (!CRM_Core_BAO_CMSUser::create($this->_params, $mail)) {
             CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
         }
     }
 }
Esempio n. 22
0
 /**
  * process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // Process / save custom data
     // Get the form values and groupTree
     $params = $this->controller->exportValues($this->_name);
     CRM_Core_BAO_CustomValueTable::postProcess($params, $this->_groupTree[$this->_groupID]['fields'], 'civicrm_contact', $this->_contactId, $this->_entityType);
     // reset the group contact cache for this group
     CRM_Contact_BAO_GroupContactCache::remove();
     $customGroupResult = civicrm_api3('CustomGroup', 'get', array('id' => $this->_groupID, 'sequential' => 1));
     if ($customGroupResult['count']) {
         $customGroup = CRM_Utils_Array::first($customGroupResult['values']);
         if ($customGroup['name'] === 'HRJobContract_Summary') {
             $jobContractsResult = civicrm_api3('HRJobContract', 'get', array('sequential' => 1, 'contact_id' => $this->_contactId, 'return' => "period_start_date,period_end_date"));
             foreach ($jobContractsResult['values'] as $jobContract) {
                 if ($jobContract['is_current'] && !$jobContract['deleted']) {
                     $jobContractSummaryDates = $this->_getJobContractSummaryDates($this->_groupTree[$this->_groupID]['fields'], $params);
                     $createParams = array('sequential' => 1, 'jobcontract_id' => $jobContract['id']);
                     if (empty($jobContract['period_start_date']) && !empty($jobContractSummaryDates['startDate'])) {
                         $createParams['period_start_date'] = $jobContractSummaryDates['startDate'];
                     }
                     if ((empty($jobContract['period_end_date']) || $jobContract['period_end_date'] > $jobContractSummaryDates['endDate']) && !empty($jobContractSummaryDates['endDate'])) {
                         $createParams['period_end_date'] = $jobContractSummaryDates['endDate'];
                     }
                     $result = civicrm_api3('HRJobDetails', 'create', $createParams);
                 }
             }
         }
     }
     $this->response();
 }