/**
  * Method to check if the user is already registered for the event
  * and if result found redirect to the event info page
  *
  * @param array $fields  the input form values(anonymous user)
  * @param array $self    event data
  *
  * @return void
  * @access public
  */
 function checkRegistration($fields, &$self, $isAdditional = FALSE, $returnContactId = FALSE, $useDedupeRules = FALSE)
 {
     // CRM-3907, skip check for preview registrations
     // CRM-4320 participant need to walk wizard
     if (!$returnContactId && ($self->_mode == 'test' || $self->_allowConfirmation)) {
         return FALSE;
     }
     $contactID = NULL;
     $session = CRM_Core_Session::singleton();
     if (!$isAdditional) {
         $contactID = parent::getContactID();
     }
     if (!$contactID && is_array($fields) && !empty($fields)) {
         //CRM-6996
         //as we are allowing w/ same email address,
         //lets check w/ other contact params.
         if ($self->_values['event']['allow_same_participant_emails'] || $useDedupeRules) {
             $params = $fields;
             $level = $isAdditional ? 'Fuzzy' : 'Strict';
             $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
             // disable permission based on cache since event registration is public page/feature.
             $dedupeParams['check_permission'] = FALSE;
             $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', $level);
             $contactID = CRM_Utils_Array::value(0, $ids);
         } else {
             foreach ($fields as $fieldname => $fieldvalue) {
                 if (substr($fieldname, 0, 6) == 'email-') {
                     $emailString = trim($fieldvalue);
                     if (!empty($emailString)) {
                         $match = CRM_Contact_BAO_Contact::matchContactOnEmail($emailString, 'Individual');
                         if (!empty($match)) {
                             $contactID = $match->contact_id;
                         }
                     }
                 }
             }
         }
     }
     if ($returnContactId) {
         // CRM-7377
         // return contactID if contact already exists
         return $contactID;
     }
     if ($contactID) {
         $participant = new CRM_Event_BAO_Participant();
         $participant->contact_id = $contactID;
         $participant->event_id = $self->_values['event']['id'];
         $participant->role_id = $self->_values['event']['default_role_id'];
         $participant->is_test = 0;
         $participant->find();
         $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
         while ($participant->fetch()) {
             if (array_key_exists($participant->status_id, $statusTypes)) {
                 if (!$isAdditional && !$self->_values['event']['allow_same_participant_emails']) {
                     $registerUrl = CRM_Utils_System::url('civicrm/event/register', "reset=1&id={$self->_values['event']['id']}&cid=0");
                     if ($self->_pcpId) {
                         $registerUrl .= '&pcpId=' . $self->_pcpId;
                     }
                     $status = ts("Oops. It looks like you are already registered for this event. If you want to change your registration, or you feel that you've gotten this message in error, please contact the site administrator.") . ' ' . ts('You can also <a href="%1">register another participant</a>.', array(1 => $registerUrl));
                     $session->setStatus($status);
                     $url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$self->_values['event']['id']}&noFullMsg=true");
                     if ($self->_action & CRM_Core_Action::PREVIEW) {
                         $url .= '&action=preview';
                     }
                     if ($self->_pcpId) {
                         $url .= '&pcpId=' . $self->_pcpId;
                     }
                     CRM_Utils_System::redirect($url);
                 }
                 if ($isAdditional) {
                     $status = ts("Oops. It looks like this participant is already registered for this event. If you want to change your registration, or you feel that you've gotten this message in error, please contact the site administrator.");
                     $session->setStatus($status);
                     return $participant->id;
                 }
             }
         }
     }
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     $now = date('YmdHis');
     $config = CRM_Core_Config::singleton();
     $session = CRM_Core_Session::singleton();
     $this->_params = $this->get('params');
     if (CRM_Utils_Array::value('contact_id', $this->_params[0])) {
         $contactID = $this->_params[0]['contact_id'];
     } else {
         $contactID = parent::getContactID();
     }
     // if a discount has been applied, lets now deduct it from the amount
     // and fix the fee level
     if (CRM_Utils_Array::value('discount', $this->_params[0]) && CRM_Utils_Array::value('applied', $this->_params[0]['discount'])) {
         foreach ($this->_params as $k => $v) {
             if (CRM_Utils_Array::value('amount', $this->_params[$k]) > 0 && CRM_Utils_Array::value('discountAmount', $this->_params[$k])) {
                 $this->_params[$k]['amount'] -= $this->_params[$k]['discountAmount'];
                 $this->_params[$k]['amount_level'] .= CRM_Utils_Array::value('discountMessage', $this->_params[$k]);
             }
         }
         $this->set('params', $this->_params);
     }
     // CRM-4320, lets build array of cancelled additional participant ids
     // those are drop or skip by primary at the time of confirmation.
     // get all in and then unset those we want to process.
     $cancelledIds = $this->_additionalParticipantIds;
     $params = $this->_params;
     $this->set('finalAmount', $this->_amount);
     $participantCount = array();
     //unset the skip participant from params.
     //build the $participantCount array.
     //maintain record for all participants.
     foreach ($params as $participantNum => $record) {
         if ($record == 'skip') {
             unset($params[$participantNum]);
             $participantCount[$participantNum] = 'skip';
         } elseif ($participantNum) {
             $participantCount[$participantNum] = 'participant';
         }
         //lets get additional participant id to cancel.
         if ($this->_allowConfirmation && is_array($cancelledIds)) {
             $additonalId = CRM_Utils_Array::value('participant_id', $record);
             if ($additonalId && ($key = array_search($additonalId, $cancelledIds))) {
                 unset($cancelledIds[$key]);
             }
         }
     }
     $payment = $registerByID = $primaryCurrencyID = $contribution = NULL;
     $paymentObjError = ts('The system did not record payment details for this payment and so could not process the transaction. Please report this error to the site administrator.');
     $this->participantIDS = array();
     foreach ($params as $key => $value) {
         $this->fixLocationFields($value, $fields);
         //unset the billing parameters if it is pay later mode
         //to avoid creation of billing location
         if ($this->_allowWaitlist || $this->_requireApproval || CRM_Utils_Array::value('is_pay_later', $value) || !CRM_Utils_Array::value('is_primary', $value)) {
             $billingFields = array("email-{$this->_bltID}", "billing_first_name", "billing_middle_name", "billing_last_name", "billing_street_address-{$this->_bltID}", "billing_city-{$this->_bltID}", "billing_state_province-{$this->_bltID}", "billing_state_province_id-{$this->_bltID}", "billing_postal_code-{$this->_bltID}", "billing_country-{$this->_bltID}", "billing_country_id-{$this->_bltID}", "address_name-{$this->_bltID}");
             foreach ($billingFields as $field) {
                 unset($value[$field]);
             }
             if (CRM_Utils_Array::value('is_pay_later', $value)) {
                 $this->_values['params']['is_pay_later'] = TRUE;
             }
         }
         //Unset ContactID for additional participants and set RegisterBy Id.
         if (!CRM_Utils_Array::value('is_primary', $value)) {
             $contactID = CRM_Utils_Array::value('contact_id', $value);
             $registerByID = $this->get('registerByID');
             if ($registerByID) {
                 $value['registered_by_id'] = $registerByID;
             }
         } else {
             $value['amount'] = $this->_totalAmount;
         }
         $contactID =& $this->updateContactFields($contactID, $value, $fields);
         // lets store the contactID in the session
         // we dont store in userID in case the user is doing multiple
         // transactions etc
         // for things like tell a friend
         if (!parent::getContactID() && CRM_Utils_Array::value('is_primary', $value)) {
             $session->set('transaction.userID', $contactID);
         }
         $value['description'] = ts('Online Event Registration') . ': ' . $this->_values['event']['title'];
         $value['accountingCode'] = CRM_Utils_Array::value('accountingCode', $this->_values['event']);
         // required only if paid event
         if ($this->_values['event']['is_monetary']) {
             if (is_array($this->_paymentProcessor)) {
                 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
             }
             $pending = FALSE;
             $result = NULL;
             if ($this->_allowWaitlist || $this->_requireApproval) {
                 //get the participant statuses.
                 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
                 if ($this->_allowWaitlist) {
                     $value['participant_status_id'] = $value['participant_status'] = array_search('On waitlist', $waitingStatuses);
                 } else {
                     $value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
                 }
                 //there might be case user seleted pay later and
                 //now becomes part of run time waiting list.
                 $value['is_pay_later'] = FALSE;
             } elseif (CRM_Utils_Array::value('is_pay_later', $value) || $value['amount'] == 0 || $this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') {
                 if ($value['amount'] != 0) {
                     $pending = TRUE;
                     //get the participant statuses.
                     $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'");
                     $status = CRM_Utils_Array::value('is_pay_later', $value) ? 'Pending from pay later' : 'Pending from incomplete transaction';
                     $value['participant_status_id'] = $value['participant_status'] = array_search($status, $pendingStatuses);
                 }
             } elseif ($this->_contributeMode == 'express' && CRM_Utils_Array::value('is_primary', $value)) {
                 if (is_object($payment)) {
                     $result =& $payment->doExpressCheckout($value);
                 } else {
                     CRM_Core_Error::fatal($paymentObjError);
                 }
             } elseif (CRM_Utils_Array::value('is_primary', $value)) {
                 CRM_Core_Payment_Form::mapParams($this->_bltID, $value, $value, TRUE);
                 if (is_object($payment)) {
                     $result =& $payment->doDirectPayment($value);
                 } else {
                     CRM_Core_Error::fatal($paymentObjError);
                 }
             }
             if (is_a($result, 'CRM_Core_Error')) {
                 CRM_Core_Error::displaySessionError($result);
                 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "id={$this->_eventId}"));
             }
             if ($result) {
                 $value = array_merge($value, $result);
             }
             $value['receive_date'] = $now;
             if ($this->_allowConfirmation) {
                 $value['participant_register_date'] = $this->_values['participant']['register_date'];
             }
             $createContrib = $value['amount'] != 0 ? TRUE : FALSE;
             // force to create zero amount contribution, CRM-5095
             if (!$createContrib && $value['amount'] == 0 && $this->_priceSetId && $this->_lineItem) {
                 $createContrib = TRUE;
             }
             if ($createContrib && CRM_Utils_Array::value('is_primary', $value) && !$this->_allowWaitlist && !$this->_requireApproval) {
                 // if paid event add a contribution record
                 //if primary participant contributing additional amount
                 //append (multiple participants) to its fee level. CRM-4196.
                 $isAdditionalAmount = FALSE;
                 if (count($params) > 1) {
                     $isAdditionalAmount = TRUE;
                 }
                 //passing contribution id is already registered.
                 $contribution =& self::processContribution($this, $value, $result, $contactID, $pending, $isAdditionalAmount);
                 $value['contributionID'] = $contribution->id;
                 $value['contributionTypeID'] = $contribution->contribution_type_id;
                 $value['receive_date'] = $contribution->receive_date;
                 $value['trxn_id'] = $contribution->trxn_id;
                 $value['contributionID'] = $contribution->id;
                 $value['contributionTypeID'] = $contribution->contribution_type_id;
             }
             $value['contactID'] = $contactID;
             $value['eventID'] = $this->_eventId;
             $value['item_name'] = $value['description'];
         }
         //CRM-4453.
         if (CRM_Utils_Array::value('is_primary', $value)) {
             $primaryCurrencyID = CRM_Utils_Array::value('currencyID', $value);
         }
         if (!CRM_Utils_Array::value('currencyID', $value)) {
             $value['currencyID'] = $primaryCurrencyID;
         }
         if (!$pending && CRM_Utils_Array::value('is_primary', $value) && !$this->_allowWaitlist && !$this->_requireApproval) {
             // transactionID & receive date required while building email template
             $this->assign('trxn_id', $value['trxn_id']);
             $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($value['receive_date']));
             $this->set('receiveDate', CRM_Utils_Date::mysqlToIso($value['receive_date']));
             $this->set('trxnId', CRM_Utils_Array::value('trxn_id', $value));
         }
         $value['fee_amount'] = $value['amount'];
         $this->set('value', $value);
         // handle register date CRM-4320
         if ($this->_allowConfirmation) {
             $registerDate = CRM_Utils_Array::value('participant_register_date', $params);
         } elseif (CRM_Utils_Array::value('participant_register_date', $params) && is_array($params['participant_register_date']) && !empty($params['participant_register_date'])) {
             $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
         } else {
             $registerDate = date('YmdHis');
         }
         $this->assign('register_date', $registerDate);
         $this->confirmPostProcess($contactID, $contribution, $payment);
     }
     //handle if no additional participant.
     if (!$registerByID) {
         $registerByID = $this->get('registerByID');
     }
     $this->set('participantIDs', $this->_participantIDS);
     // create line items, CRM-5313
     if ($this->_priceSetId && !empty($this->_lineItem)) {
         // take all processed participant ids.
         $allParticipantIds = $this->_participantIDS;
         // when participant re-walk wizard.
         if ($this->_allowConfirmation && !empty($this->_additionalParticipantIds)) {
             $allParticipantIds = array_merge(array($registerByID), $this->_additionalParticipantIds);
         }
         $entityTable = 'civicrm_participant';
         foreach ($this->_lineItem as $key => $value) {
             if ($value != 'skip' && ($entityId = CRM_Utils_Array::value($key, $allParticipantIds))) {
                 // do cleanup line  items if participant re-walking wizard.
                 if ($this->_allowConfirmation) {
                     CRM_Price_BAO_LineItem::deleteLineItems($entityId, $entityTable);
                 }
                 // create line.
                 foreach ($value as $line) {
                     $line['entity_id'] = $entityId;
                     $line['entity_table'] = $entityTable;
                     CRM_Price_BAO_LineItem::create($line);
                 }
             }
         }
     }
     //update status and send mail to cancelled additonal participants, CRM-4320
     if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
         $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
         CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
     }
     $isTest = FALSE;
     if ($this->_action & CRM_Core_Action::PREVIEW) {
         $isTest = TRUE;
     }
     // for Transfer checkout.
     if (($this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') && !CRM_Utils_Array::value('is_pay_later', $params[0]) && !$this->_allowWaitlist && !$this->_requireApproval && $this->_totalAmount > 0) {
         $primaryParticipant = $this->get('primaryParticipant');
         if (!CRM_Utils_Array::value('participantID', $primaryParticipant)) {
             $primaryParticipant['participantID'] = $registerByID;
         }
         //build an array of custom profile and assigning it to template
         $customProfile = CRM_Event_BAO_Event::buildCustomProfile($registerByID, $this->_values, NULL, $isTest);
         if (count($customProfile)) {
             $this->assign('customProfile', $customProfile);
             $this->set('customProfile', $customProfile);
         }
         // do a transfer only if a monetary payment greater than 0
         if ($this->_values['event']['is_monetary'] && $primaryParticipant) {
             if ($payment && is_object($payment)) {
                 $payment->doTransferCheckout($primaryParticipant, 'event');
             } else {
                 CRM_Core_Error::fatal($paymentObjError);
             }
         }
     } else {
         //otherwise send mail Confirmation/Receipt
         $primaryContactId = $this->get('primaryContactId');
         //build an array of cId/pId of participants
         $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL, $primaryContactId, $isTest, TRUE);
         //lets send  mails to all with meaningful text, CRM-4320.
         $this->assign('isOnWaitlist', $this->_allowWaitlist);
         $this->assign('isRequireApproval', $this->_requireApproval);
         //need to copy, since we are unsetting on the way.
         $copyParticipantCount = $participantCount;
         //lets carry all paticipant params w/ values.
         foreach ($additionalIDs as $participantID => $contactId) {
             $participantNum = NULL;
             if ($participantID == $registerByID) {
                 $participantNum = 0;
             } else {
                 if ($participantNum = array_search('participant', $copyParticipantCount)) {
                     unset($copyParticipantCount[$participantNum]);
                 }
             }
             if ($participantNum === NULL) {
                 break;
             }
             //carry the participant submitted values.
             $this->_values['params'][$participantID] = $params[$participantNum];
         }
         foreach ($additionalIDs as $participantID => $contactId) {
             $participantNum = 0;
             if ($participantID == $registerByID) {
                 //set as Primary Participant
                 $this->assign('isPrimary', 1);
                 //build an array of custom profile and assigning it to template.
                 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
                 if (count($customProfile)) {
                     $this->assign('customProfile', $customProfile);
                     $this->set('customProfile', $customProfile);
                 }
                 $this->_values['params']['additionalParticipant'] = FALSE;
             } else {
                 //take the Additional participant number.
                 if ($participantNum = array_search('participant', $participantCount)) {
                     unset($participantCount[$participantNum]);
                 }
                 $this->assign('isPrimary', 0);
                 $this->assign('customProfile', NULL);
                 //Additional Participant should get only it's payment information
                 if ($this->_amount) {
                     $amount = array();
                     $params = $this->get('params');
                     $amount[$participantNum]['label'] = $params[$participantNum]['amount_level'];
                     $amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
                     $this->assign('amount', $amount);
                 }
                 if ($this->_lineItem) {
                     $lineItems = $this->_lineItem;
                     $lineItem = array();
                     $lineItem[] = CRM_Utils_Array::value($participantNum, $lineItems);
                     $this->assign('lineItem', $lineItem);
                 }
                 $this->_values['params']['additionalParticipant'] = TRUE;
             }
             //pass these variables since these are run time calculated.
             $this->_values['params']['isOnWaitlist'] = $this->_allowWaitlist;
             $this->_values['params']['isRequireApproval'] = $this->_requireApproval;
             //send mail to primary as well as additional participants.
             $this->assign('contactID', $contactId);
             $this->assign('participantID', $participantID);
             CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
         }
     }
 }