Exemple #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}"));
         }
     }
 }
Exemple #2
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 ($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));
     $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
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     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, $customFields, $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['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 (!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 = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
         // CRM-15622: fix for incorrect contribution.fee_amount
         $paymentParams['fee_amount'] = NULL;
         $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 (!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, CRM_Core_DAO::$_nullArray, '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('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->_quickConfig) {
                 if (!empty($this->_params['amount_priceset_level_radio'])) {
                     $feeLevel = $this->_params['amount_priceset_level_radio'];
                 } else {
                     $feeLevel[] = $this->_params['fee_level'];
                 }
                 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, $feeLevel);
             }
             $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');
                 }
             }
         }
     }
     $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']);
             $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) {
                 $customValue = array('data' => $fieldValue['value']);
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID], TRUE);
                 $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 = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, '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' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues), '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 = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, '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');
     $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}"));
     }
 }
Exemple #3
0
 /**
  * This function is called after the user submits the form.
  *
  * @access public
  *
  * @return none
  */
 public function postProcess()
 {
     global $user;
     $isAdmin = in_array('civihr_admin', $user->roles) ? true : false;
     $session = CRM_Core_Session::singleton();
     $submitValues = $this->_submitValues;
     if (!empty($submitValues['contacts_id'])) {
         $this->_targetContactID = $submitValues['contacts_id'];
     }
     $absentDateDurations = array();
     $activityStatus = CRM_HRAbsence_BAO_HRAbsenceType::getActivityStatus('name');
     $activityStatusId['status_id'] = CRM_Utils_Array::key('Completed', $activityStatus);
     if (!empty($submitValues['date_values'])) {
         foreach (explode('|', $submitValues['date_values']) as $key => $dateString) {
             if ($dateString) {
                 $values = explode('(', $dateString);
                 $date = CRM_Utils_Date::processDate($values[0]);
                 $valuesDate = explode(':', $dateString);
                 $absentDateDurations[$date]['duration'] = (int) $valuesDate[1];
                 if (isset($valuesDate[2]) && $valuesDate[2] == 1 && $this->_showhide == 1 && array_key_exists('_qf_AbsenceRequest_done_save', $submitValues) || isset($valuesDate[2]) && $valuesDate[2] == 0 && $this->_showhide == 0 && array_key_exists('_qf_AbsenceRequest_done_save', $submitValues)) {
                     $absentDateDurations[$date]['approval'] = CRM_Utils_Array::key('Scheduled', $activityStatus);
                 } elseif (isset($valuesDate[2]) && $valuesDate[2] == 0 && $this->_showhide == 1) {
                     $absentDateDurations[$date]['approval'] = CRM_Utils_Array::key('Rejected', $activityStatus);
                 } elseif (array_key_exists('_qf_AbsenceRequest_done_saveandapprove', $submitValues) || array_key_exists('_qf_AbsenceRequest_done_approve', $submitValues)) {
                     $absentDateDurations[$date]['approval'] = CRM_Utils_Array::key('Completed', $activityStatus);
                 }
             }
         }
     }
     // set email template values
     $taDays = explode('|', $submitValues['tot_app_days']);
     $totDays = $taDays[0];
     if (!empty($taDays[1])) {
         $appDays = $taDays[1];
     }
     $msgTempResult = civicrm_api3('MessageTemplate', 'get', array('msg_title' => "Absence Email"));
     $targetContactResult = civicrm_api3('contact', 'get', array('id' => $this->_targetContactID));
     $mailprm[$this->_targetContactID]['display_name'] = $targetContactResult['values'][$this->_targetContactID]['display_name'];
     $mailprm[$this->_targetContactID]['email'] = $targetContactResult['values'][$this->_targetContactID]['email'];
     $tplParams = array('messageTemplateID' => $msgTempResult['values'][$msgTempResult['id']]['id'], 'empName' => $mailprm[$this->_targetContactID]['display_name'], 'absenceType' => $this->_absenceType, 'absentDateDurations' => $absentDateDurations, 'startDate' => $submitValues['start_date'], 'endDate' => $submitValues['end_date'], 'empPosition' => $this->_empPosition, 'totDays' => $totDays, 'jobHoursTime' => $this->_jobHoursTime);
     if (!empty($appDays)) {
         $tplParams['appDays'] = $appDays;
     }
     $sendTemplateParams = array('messageTemplateID' => $tplParams['messageTemplateID'], 'contactId' => $this->_targetContactID, 'tplParams' => $tplParams);
     if ($this->_action & CRM_Core_Action::ADD) {
         $activityParam = array('sequential' => 1, 'source_contact_id' => $this->_loginUserID, 'target_contact_id' => $this->_targetContactID, 'assignee_contact_id' => $this->_managerContactID, 'activity_type_id' => $this->_activityTypeID);
         if (array_key_exists('_qf_AbsenceRequest_done_saveandapprove', $submitValues) || $isAdmin) {
             $activityParam['status_id'] = CRM_Utils_Array::key('Completed', $activityStatus);
         } else {
             //we want to keep the activity status in Scheduled for new absence if save button is clicked
             $activityParam['status_id'] = CRM_Utils_Array::key('Scheduled', $activityStatus);
         }
         $result = civicrm_api3('Activity', 'create', $activityParam);
         //save the custom data
         if (!empty($submitValues['hidden_custom'])) {
             $customFields = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeID), CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
             $customValues = CRM_Core_BAO_CustomField::postProcess($submitValues, $customFields, $result['id'], 'Activity');
             CRM_Core_BAO_CustomValueTable::store($customValues, 'civicrm_activity', $result['id']);
         }
         if (!empty($customValues)) {
             $customGroup = array();
             foreach ($customValues 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], TRUE);
                     $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
                 }
             }
             $sendTemplateParams['tplParams']['customGroup'] = $customGroup;
         }
         $activityLeavesParam = array('sequential' => 1, 'source_record_id' => $result['id'], 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Absence', 'name'));
         foreach ($absentDateDurations as $date => $duration) {
             $activityLeavesParam['activity_date_time'] = $date;
             $activityLeavesParam['duration'] = $duration['duration'];
             $activityLeavesParam['status_id'] = $duration['approval'];
             civicrm_api3('Activity', 'create', $activityLeavesParam);
         }
         if (array_key_exists('_qf_AbsenceRequest_done_save', $submitValues)) {
             $sendTemplateParams['from'] = $mailprm[$this->_targetContactID]['email'];
             CRM_Core_Session::setStatus(ts('Absence(s) have been applied.'), ts('Saved'), 'success');
         } elseif (array_key_exists('_qf_AbsenceRequest_done_saveandapprove', $submitValues) || $isAdmin) {
             if (!empty($this->_managerContactID)) {
                 $emailID = civicrm_api3('contact', 'get', array('id' => $this->_loginUserID));
                 $sendTemplateParams['from'] = $emailID['values'][$emailID['id']]['email'];
             }
             $sendTemplateParams['tplParams']['approval'] = TRUE;
             CRM_Core_Session::setStatus(ts('Absence(s) have been applied and approved.'), ts('Saved'), 'success');
         }
         $managerContactResult = array();
         if (!empty($this->_managerContactID)) {
             foreach ($this->_managerContactID as $key => $val) {
                 $managerContactResult = civicrm_api3('contact', 'get', array('id' => $val));
                 if (!empty($val) && !empty($managerContactResult['values'])) {
                     $mailprm[$val]['display_name'] = $managerContactResult['values'][$val]['display_name'];
                     $mailprm[$val]['email'] = $managerContactResult['values'][$val]['email'];
                 }
             }
         }
         self::sendAbsenceMail($mailprm, $sendTemplateParams);
         $session->pushUserContext(CRM_Utils_System::url('civicrm/absences', "reset=1&cid={$this->_targetContactID}#hrabsence/list"));
     } elseif ($this->_mode == 'edit') {
         if (array_key_exists('_qf_AbsenceRequest_done_cancelabsence', $submitValues)) {
             $statusId = CRM_Utils_Array::key('Cancelled', $activityStatus);
             $activityParam = array('sequential' => 1, 'id' => $this->_activityId, 'activity_type_id' => $this->_activityTypeID, 'status_id' => $statusId);
             $result = civicrm_api3('Activity', 'create', $activityParam);
             $subact = civicrm_api3('Activity', 'get', array('return' => "id", 'source_record_id' => $result['id']));
             foreach ($subact['values'] as $key => $val) {
                 civicrm_api3('Activity', 'create', array('id' => $val['id'], 'status_id' => $statusId));
             }
             $sendTemplateParams['from'] = $mailprm[$this->_targetContactID]['email'];
             $sendTemplateParams['tplParams']['cancel'] = $sendMail = TRUE;
             CRM_Core_Session::setStatus(ts('Absence(s) have been Cancelled.'), ts('Cancelled'), 'success');
             $session->pushUserContext(CRM_Utils_System::url('civicrm/absence/set', "reset=1&action=view&aid={$result['id']}"));
         } elseif (array_key_exists('_qf_AbsenceRequest_done_approve', $submitValues)) {
             $statusId = CRM_Utils_Array::key('Completed', $activityStatus);
             $activityParam = array('sequential' => 1, 'id' => $this->_activityId, 'activity_type_id' => $this->_activityTypeID, 'status_id' => $statusId);
             $result = civicrm_api3('Activity', 'get', array('source_record_id' => $submitValues['source_record_id'], 'option.limit' => 365));
             foreach ($result['values'] as $row_result) {
                 civicrm_api3('Activity', 'delete', array('id' => $row_result['id']));
             }
             foreach ($absentDateDurations as $date => $duration) {
                 $resultAct = civicrm_api3('Activity', 'create', array('activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Absence', 'name'), 'source_record_id' => $submitValues['source_record_id'], 'activity_date_time' => $date, 'duration' => $duration['duration'], 'status_id' => $duration['approval']));
             }
             $result = civicrm_api3('Activity', 'create', $activityParam);
             if (!empty($this->_managerContactID)) {
                 $emailID = civicrm_api3('contact', 'get', array('id' => $this->_loginUserID));
                 $sendTemplateParams['from'] = $emailID['values'][$emailID['id']]['email'];
             }
             $sendTemplateParams['tplParams']['approval'] = $sendMail = TRUE;
             CRM_Core_Session::setStatus(ts('Absence(s) have been Approved.'), ts('Approved'), 'success');
             $session->pushUserContext(CRM_Utils_System::url('civicrm/absence/set', "reset=1&action=view&aid={$result['id']}"));
         } elseif (array_key_exists('_qf_AbsenceRequest_done_reject', $submitValues)) {
             $statusId = CRM_Utils_Array::key('Rejected', $activityStatus);
             $activityParam = array('id' => $this->_activityId, 'activity_type_id' => $this->_activityTypeID, 'status_id' => $statusId);
             $result = civicrm_api3('Activity', 'create', $activityParam);
             $subact = civicrm_api3('Activity', 'get', array('return' => "id", 'source_record_id' => $result['id']));
             foreach ($subact['values'] as $key => $val) {
                 civicrm_api3('Activity', 'create', array('id' => $val['id'], 'status_id' => $statusId));
             }
             if (!empty($this->_managerContactID)) {
                 $emailID = civicrm_api3('contact', 'get', array('id' => $this->_loginUserID));
                 $sendTemplateParams['from'] = $emailID['values'][$emailID['id']]['email'];
             }
             $sendTemplateParams['tplParams']['reject'] = $sendMail = TRUE;
             CRM_Core_Session::setStatus(ts('Absence(s) have been Rejected.'), ts('Rejected'), 'success');
             $session->pushUserContext(CRM_Utils_System::url('civicrm/absence/set', "reset=1&action=view&aid={$result['id']}"));
         } elseif (array_key_exists('_qf_AbsenceRequest_done_cancel', $submitValues)) {
             $session->pushUserContext(CRM_Utils_System::url('civicrm/absences', "reset=1&cid={$this->_targetContactID}#hrabsence/list"));
         } else {
             $result = civicrm_api3('Activity', 'get', array('source_record_id' => $submitValues['source_record_id'], 'option.limit' => 365));
             foreach ($result['values'] as $row_result) {
                 civicrm_api3('Activity', 'delete', array('id' => $row_result['id']));
             }
             foreach ($absentDateDurations as $date => $duration) {
                 $result = civicrm_api3('Activity', 'create', array('activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Absence', 'name'), 'source_record_id' => $submitValues['source_record_id'], 'activity_date_time' => $date, 'duration' => $duration['duration'], 'status_id' => $duration['approval']));
             }
             $buttonName = $this->controller->getButtonName();
             if ($buttonName == "_qf_AbsenceRequest_done_save") {
                 $this->_aid = $submitValues['source_record_id'];
                 $sendTemplateParams['from'] = $mailprm[$this->_targetContactID]['email'];
                 $sendTemplateParams['tplParams']['save'] = $sendMail = TRUE;
                 $session->pushUserContext(CRM_Utils_System::url('civicrm/absences', "reset=1&cid={$this->_targetContactID}#hrabsence/list"));
             }
         }
         if (!empty($submitValues['hidden_custom'])) {
             $customFields = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeID), CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
             $customValues = CRM_Core_BAO_CustomField::postProcess($submitValues, $customFields, $result['id'], 'Activity');
             CRM_Core_BAO_CustomValueTable::store($customValues, 'civicrm_activity', $result['id']);
         }
         if (!empty($customValues)) {
             $customGroup = array();
             foreach ($customValues 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], TRUE);
                     $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
                 }
             }
             $sendTemplateParams['tplParams']['customGroup'] = $customGroup;
         }
         if ($sendMail) {
             //send mail to multiple manager
             $managerContactResult = array();
             if (!empty($this->_managerContactID)) {
                 foreach ($this->_managerContactID as $key => $val) {
                     $managerContactResult = civicrm_api3('contact', 'get', array('id' => $val));
                     if (!empty($val) && !empty($managerContactResult['values'])) {
                         $mailprm[$val]['display_name'] = $managerContactResult['values'][$val]['display_name'];
                         $mailprm[$val]['email'] = $managerContactResult['values'][$val]['email'];
                     }
                 }
             }
             self::sendAbsenceMail($mailprm, $sendTemplateParams);
         }
     } else {
         if (CRM_Utils_Request::retrieve('aid', 'Positive', $this)) {
             $activityIDs = CRM_Utils_Request::retrieve('aid', 'Positive', $this);
         }
         if (array_key_exists('_qf_AbsenceRequest_done_cancelabsence', $submitValues)) {
             $statusId = CRM_Utils_Array::key('Cancelled', $activityStatus);
             $statusMsg = ts('Absence(s) have been Cancelled');
         } elseif (array_key_exists('_qf_AbsenceRequest_done_cancel', $submitValues)) {
             $session->pushUserContext(CRM_Utils_System::url('civicrm/absences', "reset=1&cid={$this->_targetContactID}#hrabsence/list"));
         }
         civicrm_api3('Activity', 'create', array('id' => $this->_activityId, 'activity_type_id' => $this->_activityTypeID, 'status_id' => $statusId));
         CRM_Core_Session::setStatus($statusMsg, '', 'success');
         $session->pushUserContext(CRM_Utils_System::url('civicrm/absence/set', "reset=1&action=view&aid={$activityIDs}"));
     }
 }
 /**
  * A function to build an array of information required by merge function and the merge UI.
  *
  * @param int $mainId
  *   Main contact with whom merge has to happen.
  * @param int $otherId
  *   Duplicate contact which would be deleted after merge operation.
  *
  * @return array|bool|int
  */
 public static function getRowsElementsAndInfo($mainId, $otherId)
 {
     $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
     // Fetch contacts
     foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
         $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self::getContactFields()));
         $result = civicrm_api('contact', 'get', $params);
         if (empty($result['values'][$cid]['contact_type'])) {
             return FALSE;
         }
         ${$moniker} = $result['values'][$cid];
     }
     static $fields = array();
     if (empty($fields)) {
         $fields = CRM_Contact_DAO_Contact::fields();
         CRM_Core_DAO::freeResult();
     }
     // FIXME: there must be a better way
     foreach (array('main', 'other') as $moniker) {
         $contact =& ${$moniker};
         $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
         $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
         $specialValues[$moniker] = array('preferred_communication_method' => $value, 'communication_style_id' => $value);
         if (!empty($contact['preferred_communication_method'])) {
             // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
             $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
             $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
         }
         $names = array('preferred_communication_method' => array('newName' => 'preferred_communication_method_display', 'groupName' => 'preferred_communication_method'));
         CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
         if (!empty($contact['communication_style'])) {
             $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
         }
     }
     static $optionValueFields = array();
     if (empty($optionValueFields)) {
         $optionValueFields = CRM_Core_OptionValue::getFields();
     }
     foreach ($optionValueFields as $field => $params) {
         $fields[$field]['title'] = $params['title'];
     }
     $diffs = self::findDifferences($main, $other);
     $rows = $elements = $relTableElements = $migrationInfo = array();
     $genders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
     foreach ($diffs['contact'] as $field) {
         if ($field == 'contact_sub_type') {
             // CRM-15681 don't display sub-types in UI
             continue;
         }
         foreach (array('main', 'other') as $moniker) {
             $contact =& ${$moniker};
             $value = CRM_Utils_Array::value($field, $contact);
             if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
                 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
             }
             $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
             if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
                 if ($value) {
                     $value = str_replace('-', '', $value);
                     $label = CRM_Utils_Date::customFormat($label);
                 } else {
                     $value = "null";
                 }
             } elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
                 if ($label === '0') {
                     $label = ts('[ ]');
                 }
                 if ($label === '1') {
                     $label = ts('[x]');
                 }
             } elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
                 $label = CRM_Utils_Array::value('individual_prefix', $contact);
                 $value = CRM_Utils_Array::value('prefix_id', $contact);
                 $field = 'prefix_id';
             } elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
                 $label = CRM_Utils_Array::value('individual_suffix', $contact);
                 $value = CRM_Utils_Array::value('suffix_id', $contact);
                 $field = 'suffix_id';
             } elseif ($field == 'gender_id' && !empty($value)) {
                 $label = $genders[$value];
             } elseif ($field == 'current_employer_id' && !empty($value)) {
                 $label = "{$value} (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
             }
             $rows["move_{$field}"][$moniker] = $label;
             if ($moniker == 'other') {
                 //CRM-14334
                 if ($value === NULL || $value == '') {
                     $value = 'null';
                 }
                 if ($value === 0 or $value === '0') {
                     $value = $qfZeroBug;
                 }
                 if (is_array($value) && empty($value[1])) {
                     $value[1] = NULL;
                 }
                 $elements[] = array('advcheckbox', "move_{$field}", NULL, NULL, NULL, $value);
                 $migrationInfo["move_{$field}"] = $value;
             }
         }
         $rows["move_{$field}"]['title'] = $fields[$field]['title'];
     }
     // handle location blocks.
     $locationBlocks = array('email', 'phone', 'address');
     $locations = array();
     foreach ($locationBlocks as $block) {
         foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
             $cnt = 1;
             $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
             $count = $values['count'];
             if ($count) {
                 if ($count > $cnt) {
                     foreach ($values['values'] as $value) {
                         if ($block == 'address') {
                             CRM_Core_BAO_Address::fixAddress($value);
                             $display = CRM_Utils_Address::format($value);
                             $locations[$moniker][$block][$cnt] = $value;
                             $locations[$moniker][$block][$cnt]['display'] = $display;
                         } else {
                             $locations[$moniker][$block][$cnt] = $value;
                         }
                         $cnt++;
                     }
                 } else {
                     $id = $values['id'];
                     if ($block == 'address') {
                         CRM_Core_BAO_Address::fixAddress($values['values'][$id]);
                         $display = CRM_Utils_Address::format($values['values'][$id]);
                         $locations[$moniker][$block][$cnt] = $values['values'][$id];
                         $locations[$moniker][$block][$cnt]['display'] = $display;
                     } else {
                         $locations[$moniker][$block][$cnt] = $values['values'][$id];
                     }
                 }
             }
         }
     }
     $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $mainLocBlock = $locBlockIds = array();
     $locBlockIds['main'] = $locBlockIds['other'] = array();
     foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
         $name = strtolower($block);
         foreach (array('main', 'other') as $moniker) {
             $locIndex = CRM_Utils_Array::value($moniker, $locations);
             $blockValue = CRM_Utils_Array::value($name, $locIndex, array());
             if (empty($blockValue)) {
                 $locValue[$moniker][$name] = 0;
                 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
             } else {
                 $locValue[$moniker][$name] = TRUE;
                 foreach ($blockValue as $count => $blkValues) {
                     $fldName = $name;
                     $locTypeId = $blkValues['location_type_id'];
                     if ($name == 'im') {
                         $fldName = 'name';
                     }
                     if ($name == 'address') {
                         $fldName = 'display';
                     }
                     $locLabel[$moniker][$name][$count] = CRM_Utils_Array::value($fldName, $blkValues);
                     $locTypes[$moniker][$name][$count] = $locTypeId;
                     if ($moniker == 'main' && in_array($name, $locationBlocks)) {
                         $mainLocBlock["main_{$name}{$locTypeId}"] = CRM_Utils_Array::value($fldName, $blkValues);
                         $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
                     } else {
                         $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
                     }
                 }
             }
         }
         if ($locValue['other'][$name] != 0) {
             foreach ($locLabel['other'][$name] as $count => $value) {
                 $locTypeId = $locTypes['other'][$name][$count];
                 $rows["move_location_{$name}_{$count}"]['other'] = $value;
                 $rows["move_location_{$name}_{$count}"]['main'] = CRM_Utils_Array::value($count, $locLabel['main'][$name]);
                 $rows["move_location_{$name}_{$count}"]['title'] = ts('%1:%2:%3', array(1 => $block, 2 => $count, 3 => $allLocationTypes[$locTypeId]));
                 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
                 $migrationInfo["move_location_{$name}_{$count}"] = 1;
                 // make sure default location type is always on top
                 $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId);
                 $locTypeValues = $allLocationTypes;
                 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
                 unset($locTypeValues[$mainLocTypeId]);
                 // keep 1-1 mapping for address - location type.
                 $js = NULL;
                 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
                     $js = array('onChange' => "mergeBlock('{$name}', this, {$count} );");
                 }
                 $elements[] = array('select', "location[{$name}][{$count}][locTypeId]", NULL, $defaultLocType + $locTypeValues, $js);
                 // keep location-type-id same as that of other-contact
                 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
                 if ($name != 'address') {
                     $elements[] = array('advcheckbox', "location[{$name}][{$count}][operation]", NULL, ts('add new'));
                     // always use add operation
                     $migrationInfo['location'][$name][$count]['operation'] = 1;
                 }
             }
         }
     }
     // add the related tables and unset the ones that don't sport any of the duplicate contact's info
     $config = CRM_Core_Config::singleton();
     $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
     $mainUser = NULL;
     if ($mainUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
             $mainUser = user_load($mainUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $mainUser = JFactory::getUser($mainUfId);
         }
     }
     $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
     $otherUser = NULL;
     if ($otherUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
             $otherUser = user_load($otherUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $otherUser = JFactory::getUser($otherUfId);
         }
     }
     $relTables = CRM_Dedupe_Merger::relTables();
     $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
     $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
     foreach ($relTables as $name => $null) {
         if (!in_array($name, $activeRelTables) && !($name == 'rel_table_users' && in_array($name, $activeMainRelTables))) {
             unset($relTables[$name]);
             continue;
         }
         $relTableElements[] = array('checkbox', "move_{$name}");
         $migrationInfo["move_{$name}"] = 1;
         $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
         $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
         if ($name == 'rel_table_users') {
             $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
             $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
             $find = array('$ufid', '$ufname');
             if ($mainUser) {
                 $replace = array($mainUfId, $mainUser->name);
                 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
             }
             if ($otherUser) {
                 $replace = array($otherUfId, $otherUser->name);
                 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
             }
         }
         if ($name == 'rel_table_memberships') {
             $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
             $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
         }
     }
     foreach ($relTables as $name => $null) {
         $relTables["move_{$name}"] = $relTables[$name];
         unset($relTables[$name]);
     }
     // handle custom fields
     $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1, CRM_Utils_Array::value('contact_sub_type', $main));
     $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1, CRM_Utils_Array::value('contact_sub_type', $other));
     CRM_Core_DAO::freeResult();
     foreach ($otherTree as $gid => $group) {
         $foundField = FALSE;
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             if (in_array($fid, $diffs['custom'])) {
                 if (!$foundField) {
                     $rows["custom_group_{$gid}"]['title'] = $group['title'];
                     $foundField = TRUE;
                 }
                 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE);
                     }
                 }
                 $value = "null";
                 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE);
                         if ($values['data'] === 0 || $values['data'] === '0') {
                             $values['data'] = $qfZeroBug;
                         }
                         $value = $values['data'] ? $values['data'] : $value;
                     }
                 }
                 $rows["move_custom_{$fid}"]['title'] = $field['label'];
                 $elements[] = array('advcheckbox', "move_custom_{$fid}", NULL, NULL, NULL, $value);
                 $migrationInfo["move_custom_{$fid}"] = $value;
             }
         }
     }
     $result = array('rows' => $rows, 'elements' => $elements, 'rel_table_elements' => $relTableElements, 'main_loc_block' => $mainLocBlock, 'rel_tables' => $relTables, 'main_details' => $main, 'other_details' => $other, 'migration_info' => $migrationInfo);
     $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
     $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
     return $result;
 }
Exemple #5
0
 function preProcess()
 {
     require_once 'api/v2/Contact.php';
     require_once 'CRM/Core/BAO/CustomGroup.php';
     require_once 'CRM/Core/OptionGroup.php';
     require_once 'CRM/Core/OptionValue.php';
     if (!CRM_Core_Permission::check('administer CiviCRM')) {
         CRM_Core_Error::fatal(ts('You do not have access to this page'));
     }
     $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, true);
     $oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, true);
     $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, false);
     $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, false);
     $session =& CRM_Core_Session::singleton();
     // context fixed.
     if ($rgid) {
         $urlParam = "reset=1&action=browse&rgid={$rgid}";
         if ($gid) {
             $urlParam .= "&gid={$gid}";
         }
         $session->pushUserContext(CRM_Utils_system::url('civicrm/admin/dedupefind', $urlParam));
     }
     // ensure that oid is not the current user, if so refuse to do the merge
     if ($session->get('userID') == $oid) {
         $display_name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $oid, 'display_name');
         $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.', array(1 => $display_name));
         CRM_Core_Error::statusBounce($message);
     }
     $diffs = CRM_Dedupe_Merger::findDifferences($cid, $oid);
     $mainParams = array('contact_id' => $cid, 'return.display_name' => 1);
     $otherParams = array('contact_id' => $oid, 'return.display_name' => 1);
     // API 2 has to have the requested fields spelt-out for it
     foreach (CRM_Dedupe_Merger::$validFields as $field) {
         $mainParams["return.{$field}"] = $otherParams["return.{$field}"] = 1;
     }
     $main =& civicrm_contact_get($mainParams);
     //CRM-4524
     $main = reset($main);
     if ($main['contact_id'] != $cid) {
         CRM_Core_Error::fatal(ts('The main contact record does not exist'));
     }
     $other =& civicrm_contact_get($otherParams);
     //CRM-4524
     $other = reset($other);
     if ($other['contact_id'] != $oid) {
         CRM_Core_Error::fatal(ts('The other contact record does not exist'));
     }
     $this->assign('contact_type', $main['contact_type']);
     $this->assign('main_name', $main['display_name']);
     $this->assign('other_name', $other['display_name']);
     $this->assign('main_cid', $main['contact_id']);
     $this->assign('other_cid', $other['contact_id']);
     $this->_cid = $cid;
     $this->_oid = $oid;
     $this->_rgid = $rgid;
     $this->_contactType = $main['contact_type'];
     $this->addElement('checkbox', 'toggleSelect', null, null, array('onclick' => "return toggleCheckboxVals('move_',this);"));
     require_once "CRM/Contact/DAO/Contact.php";
     $fields =& CRM_Contact_DAO_Contact::fields();
     // FIXME: there must be a better way
     foreach (array('main', 'other') as $moniker) {
         $contact =& ${$moniker};
         $specialValues[$moniker] = array('preferred_communication_method' => $contact['preferred_communication_method']);
         $names = array('preferred_communication_method' => array('newName' => 'preferred_communication_method_display', 'groupName' => 'preferred_communication_method'));
         CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
     }
     foreach (CRM_Core_OptionValue::getFields() as $field => $params) {
         $fields[$field]['title'] = $params['title'];
     }
     if (!isset($diffs['contact'])) {
         $diffs['contact'] = array();
     }
     foreach ($diffs['contact'] as $field) {
         foreach (array('main', 'other') as $moniker) {
             $contact =& ${$moniker};
             $value = CRM_Utils_Array::value($field, $contact);
             $label = isset($specialValues[$moniker][$field]) ? $specialValues[$moniker]["{$field}_display"] : $value;
             if ($fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
                 if ($value) {
                     $value = str_replace('-', '', $value);
                     $label = CRM_Utils_Date::customFormat($label);
                 } else {
                     $value = "null";
                 }
             } elseif ($fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
                 if ($label === '0') {
                     $label = ts('[ ]');
                 }
                 if ($label === '1') {
                     $label = ts('[x]');
                 }
             }
             $rows["move_{$field}"][$moniker] = $label;
             if ($moniker == 'other') {
                 if ($value === null) {
                     $value = 'null';
                 }
                 if ($value === 0 or $value === '0') {
                     $value = $this->_qfZeroBug;
                 }
                 $this->addElement('advcheckbox', "move_{$field}", null, null, null, $value);
             }
         }
         $rows["move_{$field}"]['title'] = $fields[$field]['title'];
     }
     // handle location blocks.
     require_once 'api/v2/Location.php';
     $mainParams['version'] = $otherParams['version'] = '3.0';
     $locations['main'] =& civicrm_location_get($mainParams);
     $locations['other'] =& civicrm_location_get($otherParams);
     $allLocationTypes = CRM_Core_PseudoConstant::locationType();
     $mainLocAddress = array();
     foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
         $name = strtolower($block);
         foreach (array('main', 'other') as $moniker) {
             $blockValue = CRM_Utils_Array::value($name, $locations[$moniker], array());
             if (empty($blockValue)) {
                 $locValue[$moniker][$name] = 0;
                 $locLabel[$moniker][$name] = array();
                 $locTypes[$moniker][$name] = array();
             } else {
                 $locValue[$moniker][$name] = true;
                 foreach ($blockValue as $count => $blkValues) {
                     $fldName = $name;
                     $locTypeId = $blkValues['location_type_id'];
                     if ($name == 'im') {
                         $fldName = 'name';
                     }
                     if ($name == 'address') {
                         $fldName = 'display';
                     }
                     $locLabel[$moniker][$name][$count] = $blkValues[$fldName];
                     $locTypes[$moniker][$name][$count] = $locTypeId;
                     if ($moniker == 'main' && $name == 'address') {
                         $mainLocAddress["main_{$locTypeId}"] = $blkValues[$fldName];
                         $this->_locBlockIds['main']['address'][$locTypeId] = $blkValues['id'];
                     } else {
                         $this->_locBlockIds[$moniker][$name][$count] = $blkValues['id'];
                     }
                 }
             }
         }
         if ($locValue['other'][$name] != 0) {
             foreach ($locLabel['other'][$name] as $count => $value) {
                 $locTypeId = $locTypes['other'][$name][$count];
                 $rows["move_location_{$name}_{$count}"]['other'] = $value;
                 $rows["move_location_{$name}_{$count}"]['main'] = $locLabel['main'][$name][$count];
                 $rows["move_location_{$name}_{$count}"]['title'] = ts('%1:%2:%3', array(1 => $block, 2 => $count, 3 => $allLocationTypes[$locTypeId]));
                 $this->addElement('advcheckbox', "move_location_{$name}_{$count}");
                 // make sure default location type is always on top
                 $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId);
                 $locTypeValues = $allLocationTypes;
                 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
                 unset($locTypeValues[$mainLocTypeId]);
                 // keep 1-1 mapping for address - location type.
                 $js = null;
                 if ($name == 'address' && !empty($mainLocAddress)) {
                     $js = array('onChange' => "mergeAddress( this, {$count} );");
                 }
                 $this->addElement('select', "location[{$name}][{$count}][locTypeId]", null, $defaultLocType + $locTypeValues, $js);
                 if ($name != 'address') {
                     $this->addElement('advcheckbox', "location[{$name}][{$count}][operation]", null, ts('add new'));
                 }
             }
         }
     }
     $this->assign('mainLocAddress', json_encode($mainLocAddress));
     // handle custom fields
     $mainTree =& CRM_Core_BAO_CustomGroup::getTree($this->_contactType, $this, $this->_cid, -1);
     $otherTree =& CRM_Core_BAO_CustomGroup::getTree($this->_contactType, $this, $this->_oid, -1);
     if (!isset($diffs['custom'])) {
         $diffs['custom'] = array();
     }
     foreach ($otherTree as $gid => $group) {
         $foundField = false;
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             if (in_array($fid, $diffs['custom'])) {
                 if (!$foundField) {
                     $rows["custom_group_{$gid}"]['title'] = $group['title'];
                     $foundField = true;
                 }
                 if (is_array($mainTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field);
                     }
                 }
                 if (is_array($otherTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field);
                         $value = $values['data'] ? $values['data'] : $this->_qfZeroBug;
                     }
                 }
                 $rows["move_custom_{$fid}"]['title'] = $field['label'];
                 $this->addElement('advcheckbox', "move_custom_{$fid}", null, null, null, $value);
             }
         }
     }
     $this->assign('rows', $rows);
     // add the related tables and unset the ones that don't sport any of the duplicate contact's info
     $relTables = CRM_Dedupe_Merger::relTables();
     $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($oid);
     foreach ($relTables as $name => $null) {
         if (!in_array($name, $activeRelTables)) {
             unset($relTables[$name]);
             continue;
         }
         $this->addElement('checkbox', "move_{$name}");
         $relTables[$name]['main_url'] = str_replace('$cid', $cid, $relTables[$name]['url']);
         $relTables[$name]['other_url'] = str_replace('$cid', $oid, $relTables[$name]['url']);
     }
     foreach ($relTables as $name => $null) {
         $relTables["move_{$name}"] = $relTables[$name];
         unset($relTables[$name]);
     }
     $this->assign('rel_tables', $relTables);
 }
Exemple #6
0
 /**
  * A function to build an array of information required by merge function and the merge UI.
  *
  * @param int $mainId
  *   Main contact with whom merge has to happen.
  * @param int $otherId
  *   Duplicate contact which would be deleted after merge operation.
  *
  * @return array|bool|int
  *   'main_loc_block' => Stores all location blocks associated with the 'main' contact
  */
 public static function getRowsElementsAndInfo($mainId, $otherId)
 {
     $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
     // Fetch contacts
     foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
         $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self::getContactFields()));
         $result = civicrm_api('contact', 'get', $params);
         if (empty($result['values'][$cid]['contact_type'])) {
             return FALSE;
         }
         ${$moniker} = $result['values'][$cid];
     }
     static $fields = array();
     if (empty($fields)) {
         $fields = CRM_Contact_DAO_Contact::fields();
         CRM_Core_DAO::freeResult();
     }
     // FIXME: there must be a better way
     foreach (array('main', 'other') as $moniker) {
         $contact =& ${$moniker};
         $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
         $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
         $specialValues[$moniker] = array('preferred_communication_method' => $value, 'communication_style_id' => $value);
         if (!empty($contact['preferred_communication_method'])) {
             // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
             $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
             $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
         }
         $names = array('preferred_communication_method' => array('newName' => 'preferred_communication_method_display', 'groupName' => 'preferred_communication_method'));
         CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
         if (!empty($contact['communication_style'])) {
             $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
         }
     }
     static $optionValueFields = array();
     if (empty($optionValueFields)) {
         $optionValueFields = CRM_Core_OptionValue::getFields();
     }
     foreach ($optionValueFields as $field => $params) {
         $fields[$field]['title'] = $params['title'];
     }
     $compareFields = self::retrieveFields($main, $other);
     $rows = $elements = $relTableElements = $migrationInfo = array();
     foreach ($compareFields['contact'] as $field) {
         if ($field == 'contact_sub_type') {
             // CRM-15681 don't display sub-types in UI
             continue;
         }
         foreach (array('main', 'other') as $moniker) {
             $contact =& ${$moniker};
             $value = CRM_Utils_Array::value($field, $contact);
             if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
                 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
             }
             $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
             if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
                 if ($value) {
                     $value = str_replace('-', '', $value);
                     $label = CRM_Utils_Date::customFormat($label);
                 } else {
                     $value = "null";
                 }
             } elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
                 if ($label === '0') {
                     $label = ts('[ ]');
                 }
                 if ($label === '1') {
                     $label = ts('[x]');
                 }
             } elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
                 $label = CRM_Utils_Array::value('individual_prefix', $contact);
                 $value = CRM_Utils_Array::value('prefix_id', $contact);
                 $field = 'prefix_id';
             } elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
                 $label = CRM_Utils_Array::value('individual_suffix', $contact);
                 $value = CRM_Utils_Array::value('suffix_id', $contact);
                 $field = 'suffix_id';
             } elseif ($field == 'gender_id' && !empty($value)) {
                 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
                 $label = $genderOptions['values'][$value];
             } elseif ($field == 'current_employer_id' && !empty($value)) {
                 $label = "{$value} (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
             }
             $rows["move_{$field}"][$moniker] = $label;
             if ($moniker == 'other') {
                 //CRM-14334
                 if ($value === NULL || $value == '') {
                     $value = 'null';
                 }
                 if ($value === 0 or $value === '0') {
                     $value = $qfZeroBug;
                 }
                 if (is_array($value) && empty($value[1])) {
                     $value[1] = NULL;
                 }
                 // Display a checkbox to migrate, only if the values are different
                 if ($value != $main[$field]) {
                     $elements[] = array('advcheckbox', "move_{$field}", NULL, NULL, NULL, $value);
                 }
                 $migrationInfo["move_{$field}"] = $value;
             }
         }
         $rows["move_{$field}"]['title'] = $fields[$field]['title'];
     }
     // Handle location blocks.
     // @todo OpenID not in API yet, so is not supported here.
     // Set up useful information about the location blocks
     $locationBlocks = self::getLocationBlockInfo();
     $locations = array('main' => array(), 'other' => array());
     $mainLocBlock = array();
     // @todo This could probably be defined and used earlier
     $mergeTargets = array('main' => $mainId, 'other' => $otherId);
     foreach ($locationBlocks as $blockName => $blockInfo) {
         // Collect existing fields from both 'main' and 'other' contacts first
         // This allows us to match up location/types when building the table rows
         foreach ($mergeTargets as $moniker => $cid) {
             $cnt = 1;
             $searchParams = array('version' => 3, 'contact_id' => $cid, 'options' => array('sort' => $blockInfo['sortString']));
             $values = civicrm_api($blockName, 'get', $searchParams);
             if ($values['count']) {
                 $cnt = 0;
                 foreach ($values['values'] as $index => $value) {
                     $locations[$moniker][$blockName][$cnt] = $value;
                     // Fix address display
                     $display = '';
                     if ($blockName == 'address') {
                         CRM_Core_BAO_Address::fixAddress($value);
                         $display = CRM_Utils_Address::format($value);
                         $locations[$moniker][$blockName][$cnt]['display'] = $display;
                     }
                     // Add any 'main' contact block values to an array for the JS
                     // @todo The JS should just access the main_details to find this info?
                     if ($moniker == 'main') {
                         if ($blockInfo['hasType']) {
                             // Handle websites, no location type ID
                             // @todo Remove the need for this specific 'if'
                             if ($blockName == 'website') {
                                 $value['location_type_id'] = 0;
                             }
                             $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id'] . "_" . $value[$blockInfo['hasType']]]['display'] = $value[$blockInfo['displayField']];
                             $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id'] . "_" . $value[$blockInfo['hasType']]]['id'] = $value['id'];
                         } else {
                             // Get the correct display value for addresses
                             // @todo Remove the need for this if...
                             if ($blockName == 'address') {
                                 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['display'] = $display;
                                 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['id'] = $value['id'];
                             } else {
                                 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['display'] = $value[$blockInfo['displayField']];
                                 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['id'] = $value['id'];
                             }
                         }
                     }
                     $cnt++;
                 }
             }
         }
         // Now, build the table rows appropriately, based off the information on
         // the 'other' contact
         if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
             foreach ($locations['other'][$blockName] as $count => $value) {
                 $displayValue = $value[$blockInfo['displayField']];
                 // Add this value to the table rows
                 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
                 // CRM-17556 Only display 'main' contact value if it's the same location + type
                 // Look it up from main values...
                 $lookupLocation = FALSE;
                 if ($blockInfo['hasLocation']) {
                     $lookupLocation = $value['location_type_id'];
                 }
                 $lookupType = FALSE;
                 if ($blockInfo['hasType']) {
                     $lookupType = $value[$blockInfo['hasType']];
                 }
                 // Hold ID of main contact's matching block
                 $mainContactBlockId = 0;
                 if (!empty($locations['main'][$blockName])) {
                     foreach ($locations['main'][$blockName] as $mainValueCheck) {
                         // No location/type, or matching location and type
                         if ((empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id']) && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])) {
                             // Set this value as the default against the 'other' contact value
                             $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
                             $mainContactBlockId = $mainValueCheck['id'];
                             break;
                         }
                     }
                 }
                 // Add checkbox to migrate data from 'other' to 'main'
                 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
                 // Flag up this field to skipMerge function (@todo: do we need to?)
                 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
                 // Add a hidden field to store the ID of the target main contact block
                 $elements[] = array('hidden', "location[{$blockName}][{$count}][mainContactBlockId]", $mainContactBlockId);
                 // Setup variables
                 $thisTypeId = FALSE;
                 $thisLocId = FALSE;
                 // Provide a select drop-down for the location's location type
                 // eg: Home, Work...
                 $js = NULL;
                 if ($blockInfo['hasLocation']) {
                     // Load the location options for this entity
                     $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
                     // JS lookup 'main' contact's location (if there are any)
                     if (!empty($locations['main'][$blockName])) {
                         $js = array('onChange' => "mergeBlock('{$blockName}', this, {$count}, 'locTypeId' );");
                     }
                     $thisLocId = $value['location_type_id'];
                     // Put this field's location type at the top of the list
                     $tmpIdList = $locationOptions['values'];
                     $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
                     unset($tmpIdList[$thisLocId]);
                     // Add the element
                     $elements[] = array('select', "location[{$blockName}][{$count}][locTypeId]", NULL, $defaultLocId + $tmpIdList, $js);
                     // Add the relevant information to the $migrationInfo
                     // Keep location-type-id same as that of other-contact
                     // @todo Check this logic out
                     $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
                     if ($blockName != 'address') {
                         $elements[] = array('advcheckbox', "location[{$blockName}][{$count}][operation]", NULL, ts('add new'));
                         // always use add operation
                         $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
                     }
                 }
                 // Provide a select drop-down for the location's type/provider
                 // eg websites: Google+, Facebook...
                 $js = NULL;
                 if ($blockInfo['hasType']) {
                     // Load the type options for this entity
                     $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
                     // CRM-17556 Set up JS lookup of 'main' contact's value by type
                     if (!empty($locations['main'][$blockName])) {
                         $js = array('onChange' => "mergeBlock('{$blockName}', this, {$count}, 'typeTypeId' );");
                     }
                     $thisTypeId = $value[$blockInfo['hasType']];
                     // Put this field's location type at the top of the list
                     $tmpIdList = $typeOptions['values'];
                     $defaultTypeId = array($thisTypeId => $tmpIdList[$thisTypeId]);
                     unset($tmpIdList[$thisTypeId]);
                     // Add the element
                     $elements[] = array('select', "location[{$blockName}][{$count}][typeTypeId]", NULL, $defaultTypeId + $tmpIdList, $js);
                     // Add the information to the migrationInfo (@todo Why?)
                     $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
                 }
                 // Set the label for this row
                 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
                 if (!empty($thisLocId)) {
                     $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
                 }
                 if (!empty($thisTypeId)) {
                     $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
                 }
                 $rows["move_location_{$blockName}_{$count}"]['title'] = $rowTitle;
             }
             // End loop through 'other' locations of this type
         }
         // End if 'other' location for this type exists
     }
     // End loop through each location block entity
     // add the related tables and unset the ones that don't sport any of the duplicate contact's info
     $config = CRM_Core_Config::singleton();
     $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
     $mainUser = NULL;
     if ($mainUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
             $mainUser = user_load($mainUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $mainUser = JFactory::getUser($mainUfId);
         }
     }
     $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
     $otherUser = NULL;
     if ($otherUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
             $otherUser = user_load($otherUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $otherUser = JFactory::getUser($otherUfId);
         }
     }
     $relTables = CRM_Dedupe_Merger::relTables();
     $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
     $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
     foreach ($relTables as $name => $null) {
         if (!in_array($name, $activeRelTables) && !($name == 'rel_table_users' && in_array($name, $activeMainRelTables))) {
             unset($relTables[$name]);
             continue;
         }
         $relTableElements[] = array('checkbox', "move_{$name}");
         $migrationInfo["move_{$name}"] = 1;
         $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
         $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
         if ($name == 'rel_table_users') {
             $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
             $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
             $find = array('$ufid', '$ufname');
             if ($mainUser) {
                 $replace = array($mainUfId, $mainUser->name);
                 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
             }
             if ($otherUser) {
                 $replace = array($otherUfId, $otherUser->name);
                 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
             }
         }
         if ($name == 'rel_table_memberships') {
             $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
             $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
         }
     }
     foreach ($relTables as $name => $null) {
         $relTables["move_{$name}"] = $relTables[$name];
         unset($relTables[$name]);
     }
     // handle custom fields
     $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1, CRM_Utils_Array::value('contact_sub_type', $main));
     $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1, CRM_Utils_Array::value('contact_sub_type', $other));
     CRM_Core_DAO::freeResult();
     foreach ($otherTree as $gid => $group) {
         $foundField = FALSE;
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             if (in_array($fid, $compareFields['custom'])) {
                 if (!$foundField) {
                     $rows["custom_group_{$gid}"]['title'] = $group['title'];
                     $foundField = TRUE;
                 }
                 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE);
                     }
                 }
                 $value = "null";
                 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
                     foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
                         $rows["move_custom_{$fid}"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE);
                         if ($values['data'] === 0 || $values['data'] === '0') {
                             $values['data'] = $qfZeroBug;
                         }
                         $value = $values['data'] ? $values['data'] : $value;
                     }
                 }
                 $rows["move_custom_{$fid}"]['title'] = $field['label'];
                 $elements[] = array('advcheckbox', "move_custom_{$fid}", NULL, NULL, NULL, $value);
                 $migrationInfo["move_custom_{$fid}"] = $value;
             }
         }
     }
     $result = array('rows' => $rows, 'elements' => $elements, 'rel_table_elements' => $relTableElements, 'main_loc_block' => $mainLocBlock, 'rel_tables' => $relTables, 'main_details' => $main, 'other_details' => $other, 'migration_info' => $migrationInfo);
     $result['main_details']['location_blocks'] = $locations['main'];
     $result['other_details']['location_blocks'] = $locations['other'];
     return $result;
 }