public static function find_all_by_params($params)
 {
     $participant = new CRM_Event_BAO_Participant();
     $participant->copyValues($params);
     $result = array();
     if ($participant->find()) {
         while ($participant->fetch()) {
             $result[] = new CRM_Event_Cart_BAO_MerParticipant(clone $participant);
         }
     }
     return $result;
 }
Пример #2
0
 /**
  * Given the list of params in the params array, fetch the object
  * and store the values in the values array
  *
  * @param array $params
  *   Input parameters to find object.
  * @param array $values
  *   Output values of the object.
  *
  * @param $ids
  *
  * @return CRM_Event_BAO_Participant|null the found object or null
  */
 public static function getValues(&$params, &$values, &$ids)
 {
     if (empty($params)) {
         return NULL;
     }
     $participant = new CRM_Event_BAO_Participant();
     $participant->copyValues($params);
     $participant->find();
     $participants = array();
     while ($participant->fetch()) {
         $ids['participant'] = $participant->id;
         CRM_Core_DAO::storeValues($participant, $values[$participant->id]);
         $participants[$participant->id] = $participant;
     }
     return $participants;
 }
Пример #3
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if ($this->_action & CRM_Core_Action::DELETE) {
         if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
             $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId);
         }
         if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
             $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             foreach ($additionalIds as $value) {
                 CRM_Event_BAO_Participant::deleteParticipant($value);
             }
         }
         CRM_Event_BAO_Participant::deleteParticipant($this->_id);
         CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
         if (!empty($participantLinks)) {
             $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
             CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
         }
         return;
     }
     // When adding a single contact, the formRule prevents you from adding duplicates
     // (See above in formRule()). When adding more than one contact, the duplicates are
     // removed automatically and the user receives one notification.
     if ($this->_action & CRM_Core_Action::ADD) {
         $event_id = $this->_eventId;
         if (empty($event_id) && !empty($params['event_id'])) {
             $event_id = $params['event_id'];
         }
         if (!$this->_single && !empty($event_id)) {
             $duplicateContacts = 0;
             while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
                 // Eliminate contacts that have already been assigned to this event.
                 $dupeCheck = new CRM_Event_BAO_Participant();
                 $dupeCheck->contact_id = $dupeCheckContactId;
                 $dupeCheck->event_id = $event_id;
                 $dupeCheck->find(TRUE);
                 if (!empty($dupeCheck->id)) {
                     $duplicateContacts++;
                     unset($this->_contactIds[$k]);
                 }
             }
             if ($duplicateContacts > 0) {
                 $msg = ts("%1 contacts have already been assigned to this event. They were not added a second time.", array(1 => $duplicateContacts));
                 CRM_Core_Session::setStatus($msg);
             }
             if (count($this->_contactIds) == 0) {
                 CRM_Core_Session::setStatus(ts("No participants were added."));
                 return;
             }
             // We have to re-key $this->_contactIds so each contact has the same
             // key as their corresponding record in the $participants array that
             // will be created below.
             $this->_contactIds = array_values($this->_contactIds);
         }
     }
     $participantStatus = CRM_Event_PseudoConstant::participantStatus();
     // set the contact, when contact is selected
     if (!empty($params['contact_id'])) {
         $this->_contactId = $params['contact_id'];
     }
     if ($this->_priceSetId && ($isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config'))) {
         $this->_quickConfig = $isQuickConfig;
     }
     if ($this->_id) {
         $params['id'] = $this->_id;
     }
     $config = CRM_Core_Config::singleton();
     if ($this->_isPaidEvent) {
         $contributionParams = array();
         $lineItem = array();
         $additionalParticipantDetails = array();
         if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
             $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
             if ($eventStartDate) {
                 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
             }
         }
         if ($this->_id && $this->_action & CRM_Core_Action::UPDATE && $this->_paymentId) {
             $participantBAO = new CRM_Event_BAO_Participant();
             $participantBAO->id = $this->_id;
             $participantBAO->find(TRUE);
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
             $params['discount_id'] = NULL;
             //re-enter the values for UPDATE mode
             $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
             $params['fee_amount'] = $participantBAO->fee_amount;
             if (isset($params['priceSetId'])) {
                 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
             }
             //also add additional participant's fee level/priceset
             if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
                 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
                 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds, $hasLineItems);
             }
         } else {
             //check if discount is selected
             if (!empty($params['discount_id'])) {
                 $discountId = $params['discount_id'];
             } else {
                 $discountId = $params['discount_id'] = 'null';
             }
             //lets carry currency, CRM-4453
             $params['fee_currency'] = $config->defaultCurrency;
             CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[0]);
             //CRM-11529 for quick config backoffice transactions
             //when financial_type_id is passed in form, update the
             //lineitems with the financial type selected in form
             $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
             $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
             if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
                 foreach ($lineItem[0] as &$values) {
                     $values['financial_type_id'] = $submittedFinancialType;
                 }
             }
             $params['fee_level'] = $params['amount_level'];
             $contributionParams['total_amount'] = $params['amount'];
             if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                 $params['fee_amount'] = $params['total_amount'];
             } else {
                 //fix for CRM-3086
                 $params['fee_amount'] = $params['amount'];
             }
         }
         if (isset($params['priceSetId'])) {
             if (!empty($lineItem[0])) {
                 $this->set('lineItem', $lineItem);
                 $this->_lineItem = $lineItem;
                 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
                 $participantCount = array();
                 foreach ($lineItem as $k) {
                     foreach ($k as $v) {
                         if (CRM_Utils_Array::value('participant_count', $v) > 0) {
                             $participantCount[] = $v['participant_count'];
                         }
                     }
                 }
             }
             if (isset($participantCount)) {
                 $this->assign('pricesetFieldsCount', $participantCount);
             }
             $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
         } else {
             $this->assign('amount_level', $params['amount_level']);
         }
     }
     $this->_params = $params;
     $amountOwed = NULL;
     if (isset($params['amount'])) {
         $amountOwed = $params['amount'];
         unset($params['amount']);
     }
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
     $params['contact_id'] = $this->_contactId;
     // overwrite actual payment amount if entered
     if (!empty($params['total_amount'])) {
         $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
     }
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
     if ($this->_contactId) {
         list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
     }
     //modify params according to parameter used in create
     //participant method (addParticipant)
     $this->_params['participant_status_id'] = $params['status_id'];
     $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
     $this->_params['participant_register_date'] = $params['register_date'];
     $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         // set source if not set
         if (empty($params['source'])) {
             $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(1 => $userName, 2 => $eventTitle));
         } else {
             $this->_params['participant_source'] = $params['source'];
         }
         $this->_params['description'] = $this->_params['participant_source'];
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = TRUE;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     }
     if (!empty($this->_params['participant_role_id'])) {
         $customFieldsRole = array();
         foreach ($this->_params['participant_role_id'] as $roleKey) {
             $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
         }
         $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
         $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $this->_eventTypeId, $this->_eventTypeCustomDataTypeID);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, 'Participant');
     }
     //do cleanup line  items if participant edit the Event Fee.
     if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
         CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
     }
     if ($this->_mode) {
         // add all the additional payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         // The only reason for merging in the 'contact_id' rather than ensuring it is set
         // is that this patch is being done around the time of the stable release
         // so more conservative approach is called for.
         // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
         // needs rationalising.
         $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
         CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
         $payment = $this->_paymentProcessor['object'];
         // CRM-15622: fix for incorrect contribution.fee_amount
         $paymentParams['fee_amount'] = NULL;
         $result = $payment->doPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (!empty($this->_params['send_receipt'])) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         //add contribution record
         $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution record
         $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
         // add participant record
         $participants = array();
         if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
             $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['role_id']);
         }
         //CRM-15372 patch to fix fee amount replacing amount
         $this->_params['fee_amount'] = $this->_params['amount'];
         $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
         //add custom data for participant
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $this->_contactIds[] = $this->_contactId;
     } else {
         $participants = array();
         if ($this->_single) {
             if ($params['role_id']) {
                 $params['role_id'] = $roleIdWithSeparator;
             } else {
                 $params['role_id'] = 'NULL';
             }
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 if ($commonParams['role_id']) {
                     $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
                 } else {
                     $commonParams['role_id'] = 'NULL';
                 }
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactId;
         }
         $contributions = array();
         if (!empty($params['record_contribution'])) {
             if (!empty($params['id'])) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 if (empty($params['source'])) {
                     $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(1 => $eventTitle, 2 => $userName));
                 } else {
                     $contributionParams['source'] = $params['source'];
                 }
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number', 'campaign_id');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert financial type name in receipt.
             $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             // legacy support
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             $contributionParams['skipLineItem'] = 1;
             if ($this->_id) {
                 $contributionParams['contribution_mode'] = 'participant';
                 $contributionParams['participant_id'] = $this->_id;
             }
             // Set is_pay_later flag for back-office offline Pending status contributions
             if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
                 $contributionParams['is_pay_later'] = 1;
             } elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
                 $contributionParams['is_pay_later'] = 0;
             }
             if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
                 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
                     $amountOwed = $params['fee_amount'];
                 }
                 // if multiple participants are link, consider contribution total amount as the amount Owed
                 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                     $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'total_amount');
                 }
                 // CRM-13964 partial_payment_total
                 if ($amountOwed > $params['total_amount']) {
                     // the owed amount
                     $contributionParams['partial_payment_total'] = $amountOwed;
                     // the actual amount paid
                     $contributionParams['partial_amount_pay'] = $params['total_amount'];
                 }
             }
             if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
                 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
             }
             if ($this->_single) {
                 if (empty($ids)) {
                     $ids = array();
                 }
                 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (empty($ids['contribution'])) {
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO = new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
             // next create the transaction record
             $transaction = new CRM_Core_Transaction();
             // CRM-11124
             if ($this->_params['discount_id']) {
                 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params));
             }
             $transaction->commit();
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) {
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $lineKey => $line) {
                         //10117 update the line items for participants if contribution amount is recorded
                         if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                             $line['unit_price'] = $line['line_total'] = $params['total_amount'];
                             if (!empty($params['tax_amount'])) {
                                 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
                                 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
                             }
                         }
                         $lineItem[$this->_priceSetId][$lineKey] = $line;
                     }
                     CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
                     CRM_Contribute_BAO_Contribution::addPayments($value, $contributions);
                 }
             }
         }
     }
     $updateStatusMsg = NULL;
     //send mail when participant status changed, CRM-4326
     if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])) {
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId);
     }
     $sent = array();
     $notSent = array();
     if (!empty($params['send_receipt'])) {
         if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
             $receiptFrom = $params['from_email_address'];
         }
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $participantRoles = CRM_Utils_Array::value('role_id', $params);
         if (is_array($participantRoles)) {
             $selectedRoles = array();
             foreach ($participantRoles as $roleId) {
                 $selectedRoles[] = $role[$roleId];
             }
             $event['participant_role'] = implode(', ', $selectedRoles);
         } else {
             $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
         }
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 if (isset($params['payment_instrument_id'])) {
                     $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
                 }
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             if (isset($contributionParams['partial_payment_total'])) {
                 // balance amount
                 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
                 $this->assign('balanceAmount', $balanceAmount);
             }
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (!empty($params['billing_first_name'])) {
                 $name = $params['billing_first_name'];
             }
             if (!empty($params['billing_middle_name'])) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (!empty($params['billing_last_name'])) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             // The concept of contributeMode is deprecated.
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (!empty($this->_defaultValues['is_test'])) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template = CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
                 $this->assign('isOnWaitlist', TRUE);
             }
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             $this->_id = $participants[$num]->id;
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
                 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
                 $totalTaxAmount = 0;
                 //add dataArray in the receipts in ADD and UPDATE condition
                 $dataArray = array();
                 if ($this->_action & CRM_Core_Action::ADD) {
                     $line = $lineItem[0];
                 } elseif ($this->_action & CRM_Core_Action::UPDATE) {
                     $line = $this->_values['line_items'];
                 }
                 if ($invoicing) {
                     foreach ($line as $key => $value) {
                         if (isset($value['tax_amount'])) {
                             $totalTaxAmount += $value['tax_amount'];
                             if (isset($dataArray[(string) $value['tax_rate']])) {
                                 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                             } else {
                                 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                             }
                         }
                     }
                     $this->assign('totalTaxAmount', $totalTaxAmount);
                     $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
                     $this->assign('dataArray', $dataArray);
                 }
                 if (!empty($additionalParticipantDetails)) {
                     $params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
                 }
                 $eventAmount[$num] = array('label' => preg_replace('//', '', $params['amount_level']), 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => !empty($this->_defaultValues['is_test']), 'PDFFilename' => ts('confirmation') . '.pdf');
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
             }
             //send email with pdf invoice
             $template = CRM_Core_Smarty::singleton();
             $taxAmt = $template->get_template_vars('dataArray');
             $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
             $prefixValue = Civi::settings()->get('contribution_invoice_settings');
             $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
             if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
                 $sendTemplateParams['isEmailPdf'] = TRUE;
                 $sendTemplateParams['contributionId'] = $contributionId;
             }
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
                 foreach ($participants as $ids => $values) {
                     if ($values->contact_id == $contactID) {
                         $values->details = CRM_Utils_Array::value('receipt_text', $params);
                         CRM_Activity_BAO_Activity::addActivity($values, 'Email');
                         break;
                     }
                 }
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     // set the participant id if it is not set
     if (!$this->_id) {
         $this->_id = $participants[0]->id;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if (!empty($params['send_receipt']) && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (!empty($params['send_receipt']) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $session = CRM_Core_Session::singleton();
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $urlParams = 'reset=1&action=add&context=standalone';
             if ($this->_mode) {
                 $urlParams .= '&mode=' . $this->_mode;
             }
             if ($this->_eID) {
                 $urlParams .= '&eid=' . $this->_eID;
             }
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"));
     }
 }
Пример #4
0
 /**
  * Load objects relations to contribution object.
  * Objects are stored in the $_relatedObjects property
  * In the first instance we are just moving functionality from BASEIpn -
  * @see http://issues.civicrm.org/jira/browse/CRM-9996
  *
  * Note that the unit test for the BaseIPN class tests this function
  *
  * @param array $input
  *   Input as delivered from Payment Processor.
  * @param array $ids
  *   Ids as Loaded by Payment Processor.
  * @param bool $loadAll
  *   Load all related objects - even where id not passed in? (allows API to call this).
  *
  * @return bool
  * @throws Exception
  */
 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE)
 {
     if ($loadAll) {
         $ids = array_merge($this->getComponentDetails($this->id), $ids);
         if (empty($ids['contact']) && isset($this->contact_id)) {
             $ids['contact'] = $this->contact_id;
         }
     }
     if (empty($this->_component)) {
         if (!empty($ids['event'])) {
             $this->_component = 'event';
         } else {
             $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
         }
     }
     // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
     // refactoring than anything else, and has unit test coverage.
     if (empty($this->financial_type_id)) {
         $this->find(TRUE);
     }
     $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value('paymentProcessor', $ids));
     if (!$paymentProcessorID && $this->contribution_page_id) {
         $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->contribution_page_id, 'payment_processor');
         if ($paymentProcessorID) {
             $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
         }
     }
     $ids['contributionType'] = $this->financial_type_id;
     $ids['financialType'] = $this->financial_type_id;
     $entities = array('contact' => 'CRM_Contact_BAO_Contact', 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur', 'contributionType' => 'CRM_Financial_BAO_FinancialType', 'financialType' => 'CRM_Financial_BAO_FinancialType');
     foreach ($entities as $entity => $bao) {
         if (!empty($ids[$entity])) {
             $this->_relatedObjects[$entity] = new $bao();
             $this->_relatedObjects[$entity]->id = $ids[$entity];
             if (!$this->_relatedObjects[$entity]->find(TRUE)) {
                 throw new CRM_Core_Exception($entity . ' could not be loaded');
             }
         }
     }
     if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
         $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id;
     }
     if (!empty($ids['pledge_payment'])) {
         foreach ($ids['pledge_payment'] as $key => $paymentID) {
             if (empty($paymentID)) {
                 continue;
             }
             $payment = new CRM_Pledge_BAO_PledgePayment();
             $payment->id = $paymentID;
             if (!$payment->find(TRUE)) {
                 throw new Exception("Could not find pledge payment record: " . $paymentID);
             }
             $this->_relatedObjects['pledge_payment'][] = $payment;
         }
     }
     if ($this->_component == 'contribute') {
         // retrieve the other optional objects first so
         // stuff down the line can use this info and do things
         // CRM-6056
         //in any case get the memberships associated with the contribution
         //because we now support multiple memberships w/ price set
         // see if there are any other memberships to be considered for same contribution.
         $query = "\n            SELECT membership_id\n            FROM   civicrm_membership_payment\nWHERE  contribution_id = %1 ";
         $params = array(1 => array($this->id, 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($query, $params);
         while ($dao->fetch()) {
             if ($dao->membership_id) {
                 if (!is_array($ids['membership'])) {
                     $ids['membership'] = array();
                 }
                 $ids['membership'][] = $dao->membership_id;
             }
         }
         if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
             foreach ($ids['membership'] as $id) {
                 if (!empty($id)) {
                     $membership = new CRM_Member_BAO_Membership();
                     $membership->id = $id;
                     if (!$membership->find(TRUE)) {
                         throw new Exception("Could not find membership record: {$id}");
                     }
                     $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
                     $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
                     $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
                     $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                     $membership->free();
                 }
             }
         }
     } else {
         // we are in event mode
         // make sure event exists and is valid
         $event = new CRM_Event_BAO_Event();
         $event->id = $ids['event'];
         if ($ids['event'] && !$event->find(TRUE)) {
             throw new Exception("Could not find event: " . $ids['event']);
         }
         $this->_relatedObjects['event'] =& $event;
         $participant = new CRM_Event_BAO_Participant();
         $participant->id = $ids['participant'];
         if ($ids['participant'] && !$participant->find(TRUE)) {
             throw new Exception("Could not find participant: " . $ids['participant']);
         }
         $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
         $this->_relatedObjects['participant'] =& $participant;
         // get the payment processor id from event - this is inaccurate see CRM-16923
         // in future we should look at throwing an exception here rather than an dubious guess.
         if (!$paymentProcessorID) {
             $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
             if ($paymentProcessorID) {
                 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
             }
         }
     }
     if ($paymentProcessorID) {
         $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $this->is_test ? 'test' : 'live');
         $ids['paymentProcessor'] = $paymentProcessorID;
         $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
     }
     return TRUE;
 }
Пример #5
0
 /**
  * Handle the values in import mode.
  *
  * @param int $onDuplicate
  *   The code for what action to take on duplicates.
  * @param array $values
  *   The array of values belonging to this line.
  *
  * @return bool
  *   the result of this processing
  */
 public function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $formatted = array('version' => 3);
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = TRUE;
     foreach ($params as $key => $val) {
         if ($val) {
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
             if ($key == 'participant_register_date') {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, 'participant_register_date');
                 $formatted['participant_register_date'] = CRM_Utils_Date::processDate($params['participant_register_date']);
             }
         }
     }
     if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) {
         if (!empty($params['event_id'])) {
             $params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id');
         } else {
             $eventTitle = $params['event_title'];
             $qParams = array();
             $dao = new CRM_Core_DAO();
             $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams);
         }
     }
     //date-Format part ends
     static $indieFields = NULL;
     if ($indieFields == NULL) {
         $indieFields = CRM_Event_BAO_Participant::import();
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_api3_deprecated_participant_formatted_param($formatValues, $formatted, TRUE);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Import_Parser::ERROR;
     }
     if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
         array_unshift($values, ts('Invalid value for Event ID'));
         return CRM_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Participant');
     } else {
         if ($formatValues['participant_id']) {
             $dao = new CRM_Event_BAO_Participant();
             $dao->id = $formatValues['participant_id'];
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatValues['participant_id'], 'Participant');
             if ($dao->find(TRUE)) {
                 $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID'));
                 $participantValues = array();
                 //@todo calling api functions directly is not supported
                 $newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE);
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Import_Parser::ERROR;
                 }
                 $newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
                 if (!empty($formatted['fee_level'])) {
                     $otherParams = array('fee_label' => $formatted['fee_level'], 'event_id' => $newParticipant->event_id);
                     CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
                 }
                 $this->_newParticipant[] = $newParticipant->id;
                 return CRM_Import_Parser::VALID;
             } else {
                 array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $formatValues['version'] = 3;
         $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 foreach ($matchedIDs as $contactId) {
                     $formatted['contact_id'] = $contactId;
                     $formatted['version'] = 3;
                     $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
                 }
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             $disp = '';
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (!empty($params['external_identifier'])) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, 'No matching Contact found for (' . $disp . ')');
             return CRM_Import_Parser::ERROR;
         }
     } else {
         if (!empty($formatValues['external_identifier'])) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(TRUE);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
     }
     if (is_array($newParticipant) && civicrm_error($newParticipant)) {
         if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
             $contactID = CRM_Utils_Array::value('contactID', $newParticipant);
             $participantID = CRM_Utils_Array::value('participantID', $newParticipant);
             $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE);
             if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) {
                 array_unshift($values, $url);
                 return CRM_Import_Parser::DUPLICATE;
             } elseif ($newParticipant['error_message']) {
                 array_unshift($values, $newParticipant['error_message']);
                 return CRM_Import_Parser::ERROR;
             }
             return CRM_Import_Parser::ERROR;
         }
     }
     if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
         $this->_newParticipants[] = CRM_Utils_Array::value('id', $newParticipant);
     }
     return CRM_Import_Parser::VALID;
 }
Пример #6
0
 /**
  * Load objects relations to contribution object.
  * Objects are stored in the $_relatedObjects property
  * In the first instance we are just moving functionality from BASEIpn -
  * @see http://issues.civicrm.org/jira/browse/CRM-9996
  *
  * Note that the unit test for the BaseIPN class tests this function
  *
  * @param array $input
  *   Input as delivered from Payment Processor.
  * @param array $ids
  *   Ids as Loaded by Payment Processor.
  * @param bool $required
  *   Is Payment processor / contribution page required.
  * @param bool $loadAll
  *   Load all related objects - even where id not passed in? (allows API to call this).
  *
  * @return bool
  * @throws Exception
  */
 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE)
 {
     if ($loadAll) {
         $ids = array_merge($this->getComponentDetails($this->id), $ids);
         if (empty($ids['contact']) && isset($this->contact_id)) {
             $ids['contact'] = $this->contact_id;
         }
     }
     if (empty($this->_component)) {
         if (!empty($ids['event'])) {
             $this->_component = 'event';
         } else {
             $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
         }
     }
     $paymentProcessorID = CRM_Utils_Array::value('paymentProcessor', $ids);
     $contributionType = new CRM_Financial_BAO_FinancialType();
     $contributionType->id = $this->financial_type_id;
     $contributionType->find(TRUE);
     if (!empty($ids['contact'])) {
         $this->_relatedObjects['contact'] = new CRM_Contact_BAO_Contact();
         $this->_relatedObjects['contact']->id = $ids['contact'];
         $this->_relatedObjects['contact']->find(TRUE);
     }
     $this->_relatedObjects['contributionType'] = $contributionType;
     if ($this->_component == 'contribute') {
         // retrieve the other optional objects first so
         // stuff down the line can use this info and do things
         // CRM-6056
         //in any case get the memberships associated with the contribution
         //because we now support multiple memberships w/ price set
         // see if there are any other memberships to be considered for same contribution.
         $query = "\n            SELECT membership_id\n            FROM   civicrm_membership_payment\nWHERE  contribution_id = %1 ";
         $params = array(1 => array($this->id, 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($query, $params);
         while ($dao->fetch()) {
             if ($dao->membership_id) {
                 if (!is_array($ids['membership'])) {
                     $ids['membership'] = array();
                 }
                 $ids['membership'][] = $dao->membership_id;
             }
         }
         if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
             foreach ($ids['membership'] as $id) {
                 if (!empty($id)) {
                     $membership = new CRM_Member_BAO_Membership();
                     $membership->id = $id;
                     if (!$membership->find(TRUE)) {
                         throw new Exception("Could not find membership record: {$id}");
                     }
                     $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
                     $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
                     $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
                     $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                     $membership->free();
                 }
             }
         }
         if (!empty($ids['pledge_payment'])) {
             foreach ($ids['pledge_payment'] as $key => $paymentID) {
                 if (empty($paymentID)) {
                     continue;
                 }
                 $payment = new CRM_Pledge_BAO_PledgePayment();
                 $payment->id = $paymentID;
                 if (!$payment->find(TRUE)) {
                     throw new Exception("Could not find pledge payment record: " . $paymentID);
                 }
                 $this->_relatedObjects['pledge_payment'][] = $payment;
             }
         }
         if (!empty($ids['contributionRecur'])) {
             $recur = new CRM_Contribute_BAO_ContributionRecur();
             $recur->id = $ids['contributionRecur'];
             if (!$recur->find(TRUE)) {
                 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
             }
             $this->_relatedObjects['contributionRecur'] =& $recur;
             //get payment processor id from recur object.
             $paymentProcessorID = $recur->payment_processor_id;
         }
         //for normal contribution get the payment processor id.
         if (!$paymentProcessorID) {
             if ($this->contribution_page_id) {
                 // get the payment processor id from contribution page
                 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->contribution_page_id, 'payment_processor');
             } elseif (empty($ids['pledge_payment'])) {
                 $loadObjectSuccess = TRUE;
                 if ($required) {
                     throw new Exception("Could not find contribution page for contribution record: " . $this->id);
                 }
                 return $loadObjectSuccess;
             }
         }
     } else {
         // we are in event mode
         // make sure event exists and is valid
         $event = new CRM_Event_BAO_Event();
         $event->id = $ids['event'];
         if ($ids['event'] && !$event->find(TRUE)) {
             throw new Exception("Could not find event: " . $ids['event']);
         }
         $this->_relatedObjects['event'] =& $event;
         $participant = new CRM_Event_BAO_Participant();
         $participant->id = $ids['participant'];
         if ($ids['participant'] && !$participant->find(TRUE)) {
             throw new Exception("Could not find participant: " . $ids['participant']);
         }
         $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
         $this->_relatedObjects['participant'] =& $participant;
         if (!$paymentProcessorID) {
             $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
         }
     }
     if ($paymentProcessorID) {
         $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $this->is_test ? 'test' : 'live');
         $ids['paymentProcessor'] = $paymentProcessorID;
         $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
     } elseif ($required) {
         throw new Exception("Could not find payment processor for contribution record: " . $this->id);
     }
     return TRUE;
 }
Пример #7
0
 /**
  * Load objects relations to contribution object.
  * Objects are stored in the $_relatedObjects property
  * In the first instance we are just moving functionality from BASEIpn -
  * @see http://issues.civicrm.org/jira/browse/CRM-9996
  *
  * Note that the unit test for the BaseIPN class tests this function
  *
  * @param array $input
  *   Input as delivered from Payment Processor.
  * @param array $ids
  *   Ids as Loaded by Payment Processor.
  * @param bool $loadAll
  *   Load all related objects - even where id not passed in? (allows API to call this).
  *
  * @return bool
  * @throws Exception
  */
 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE)
 {
     if ($loadAll) {
         $ids = array_merge($this->getComponentDetails($this->id), $ids);
         if (empty($ids['contact']) && isset($this->contact_id)) {
             $ids['contact'] = $this->contact_id;
         }
     }
     if (empty($this->_component)) {
         if (!empty($ids['event'])) {
             $this->_component = 'event';
         } else {
             $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
         }
     }
     // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
     // refactoring than anything else, and has unit test coverage.
     if (empty($this->financial_type_id)) {
         $this->find(TRUE);
     }
     $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value('paymentProcessor', $ids));
     if (!$paymentProcessorID && $this->contribution_page_id) {
         $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->contribution_page_id, 'payment_processor');
         if ($paymentProcessorID) {
             $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
         }
     }
     $ids['contributionType'] = $this->financial_type_id;
     $ids['financialType'] = $this->financial_type_id;
     $entities = array('contact' => 'CRM_Contact_BAO_Contact', 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur', 'contributionType' => 'CRM_Financial_BAO_FinancialType', 'financialType' => 'CRM_Financial_BAO_FinancialType');
     foreach ($entities as $entity => $bao) {
         if (!empty($ids[$entity])) {
             $this->_relatedObjects[$entity] = new $bao();
             $this->_relatedObjects[$entity]->id = $ids[$entity];
             if (!$this->_relatedObjects[$entity]->find(TRUE)) {
                 throw new CRM_Core_Exception($entity . ' could not be loaded');
             }
         }
     }
     if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
         $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id;
     }
     if (!empty($ids['pledge_payment'])) {
         foreach ($ids['pledge_payment'] as $key => $paymentID) {
             if (empty($paymentID)) {
                 continue;
             }
             $payment = new CRM_Pledge_BAO_PledgePayment();
             $payment->id = $paymentID;
             if (!$payment->find(TRUE)) {
                 throw new Exception("Could not find pledge payment record: " . $paymentID);
             }
             $this->_relatedObjects['pledge_payment'][] = $payment;
         }
     }
     $this->loadRelatedMembershipObjects($ids);
     if ($this->_component != 'contribute') {
         // we are in event mode
         // make sure event exists and is valid
         $event = new CRM_Event_BAO_Event();
         $event->id = $ids['event'];
         if ($ids['event'] && !$event->find(TRUE)) {
             throw new Exception("Could not find event: " . $ids['event']);
         }
         $this->_relatedObjects['event'] =& $event;
         $participant = new CRM_Event_BAO_Participant();
         $participant->id = $ids['participant'];
         if ($ids['participant'] && !$participant->find(TRUE)) {
             throw new Exception("Could not find participant: " . $ids['participant']);
         }
         $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
         $this->_relatedObjects['participant'] =& $participant;
         // get the payment processor id from event - this is inaccurate see CRM-16923
         // in future we should look at throwing an exception here rather than an dubious guess.
         if (!$paymentProcessorID) {
             $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
             if ($paymentProcessorID) {
                 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
             }
         }
     }
     if ($paymentProcessorID) {
         $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $this->is_test ? 'test' : 'live');
         $ids['paymentProcessor'] = $paymentProcessorID;
         $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
     }
     return TRUE;
 }
Пример #8
0
/**
 *
 * @param array $params
 *
 * @param bool $checkDuplicate
 *
 * @return array|bool
 *   <type>
 */
function _civicrm_api3_deprecated_participant_check_params($params, $checkDuplicate = FALSE)
{
    // check if participant id is valid or not
    if (!empty($params['id'])) {
        $participant = new CRM_Event_BAO_Participant();
        $participant->id = $params['id'];
        if (!$participant->find(TRUE)) {
            return civicrm_api3_create_error(ts('Participant  id is not valid'));
        }
    }
    require_once 'CRM/Contact/BAO/Contact.php';
    // check if contact id is valid or not
    if (!empty($params['contact_id'])) {
        $contact = new CRM_Contact_BAO_Contact();
        $contact->id = $params['contact_id'];
        if (!$contact->find(TRUE)) {
            return civicrm_api3_create_error(ts('Contact id is not valid'));
        }
    }
    // check that event id is not an template
    if (!empty($params['event_id'])) {
        $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'is_template');
        if (!empty($isTemplate)) {
            return civicrm_api3_create_error(ts('Event templates are not meant to be registered.'));
        }
    }
    $result = array();
    if ($checkDuplicate) {
        if (CRM_Event_BAO_Participant::checkDuplicate($params, $result)) {
            $participantID = array_pop($result);
            $error = CRM_Core_Error::createError("Found matching participant record.", CRM_Core_Error::DUPLICATE_PARTICIPANT, 'Fatal', $participantID);
            return civicrm_api3_create_error($error->pop(), array('contactID' => $params['contact_id'], 'participantID' => $participantID));
        }
    }
    return TRUE;
}
Пример #9
0
 function validate()
 {
     parent::validate();
     if ($this->_errors) {
         return FALSE;
     }
     $this->cart->load_associations();
     $fields = $this->_submitValues;
     foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
         $price_set_id = CRM_Event_BAO_Event::usesPriceSet($event_in_cart->event_id);
         if ($price_set_id) {
             $priceField = new CRM_Price_DAO_PriceField();
             $priceField->price_set_id = $price_set_id;
             $priceField->find();
             $check = array();
             while ($priceField->fetch()) {
                 if (!empty($fields["event_{$event_in_cart->event_id}_price_{$priceField->id}"])) {
                     $check[] = $priceField->id;
                 }
             }
             //XXX
             if (empty($check)) {
                 $this->_errors['_qf_default'] = ts("Select at least one option from Price Levels.");
             }
             $lineItem = array();
             if (is_array($this->_values['fee']['fields'])) {
                 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee']['fields'], $fields, $lineItem);
                 //XXX total...
                 if ($fields['amount'] < 0) {
                     $this->_errors['_qf_default'] = ts("Price Levels can not be less than zero. Please select the options accordingly");
                 }
             }
         }
         foreach ($event_in_cart->participants as $mer_participant) {
             $participant_fields = $fields['event'][$event_in_cart->event_id]['participant'][$mer_participant->id];
             //TODO what to do when profile responses differ for the same contact?
             $contact_id = self::find_contact($participant_fields);
             if ($contact_id) {
                 $participant = new CRM_Event_BAO_Participant();
                 $participant->event_id = $event_in_cart->event_id;
                 $participant->contact_id = $contact_id;
                 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
                 $participant->find();
                 while ($participant->fetch()) {
                     if (array_key_exists($participant->status_id, $statusTypes)) {
                         $form = $mer_participant->get_form();
                         $this->_errors[$form->html_field_name('email')] = ts("The participant %1 is already registered for %2 (%3).", array(1 => $participant_fields['email'], 2 => $event_in_cart->event->title, 3 => $event_in_cart->event->start_date));
                     }
                 }
             }
         }
     }
     return empty($this->_errors);
 }
Пример #10
0
 /**
  * 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
  * @param boolean $isAdditional treat isAdditional participants a bit differently
  * @param boolean $returnContactId just find and return the contactID match to use
  * @param boolean $useDedupeRules force usage of dedupe rules
  *
  * @return void
  * @access public
  */
 static 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 = $self->getContactID();
     }
     if (!$contactID && is_array($fields) && $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']) {
             $params = $fields;
             $level = $isAdditional ? 'Supervised' : 'Unsupervised';
             $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'];
         if (!empty($fields['participant_role']) && is_numeric($fields['participant_role'])) {
             $participant->role_id = $fields['participant_role'];
         } else {
             $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("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, ts('Oops.'), 'alert');
                     $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("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, ts('Oops.'), 'alert');
                     return $participant->id;
                 }
             }
         }
     }
 }
Пример #11
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Event_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $formatted = array();
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = true;
     foreach ($params as $key => $val) {
         if ($val) {
             if ($key == 'participant_register_date') {
                 if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                     if (!CRM_Utils_Rule::date($params[$key])) {
                         CRM_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage);
                     }
                 } else {
                     CRM_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage);
                 }
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } else {
                     if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                         $params[$key] = CRM_Utils_String::strtoboolstr($val);
                     }
                 }
             }
         }
     }
     if (!($params['participant_role_id'] || $params['participant_role'])) {
         if ($params['event_id']) {
             $params['participant_role_id'] = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $params['event_id'], 'default_role_id');
         } else {
             $eventTitle = $params['event_title'];
             $qParams = array();
             $dao = new CRM_Core_DAO();
             $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams);
         }
     }
     //date-Format part ends
     static $indieFields = null;
     if ($indieFields == null) {
         require_once 'CRM/Event/BAO/Participant.php';
         $indieFields =& CRM_Event_BAO_Participant::import();
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_participant_formatted_param($formatValues, $formatted, true);
     require_once "api/v2/Participant.php";
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Event_Import_Parser::ERROR;
     }
     if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
         array_unshift($values, ts('Invalid value for Event ID'));
         return CRM_Event_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Event_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, null, 'Participant');
     } else {
         if ($formatValues['participant_id']) {
             require_once 'CRM/Event/BAO/Participant.php';
             $dao = new CRM_Event_BAO_Participant();
             $dao->id = $formatValues['participant_id'];
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['participant_id'], 'Participant');
             if ($dao->find(true)) {
                 $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID'));
                 $newParticipant = civicrm_participant_check_params($formatted, false);
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Event_Import_Parser::ERROR;
                 }
                 $newParticipant =& CRM_Event_BAO_Participant::create($formatted, $ids);
                 $this->_newParticipant[] = $newParticipant->id;
                 return CRM_Event_Import_Parser::VALID;
             } else {
                 array_unshift($values, "Matching Participant record not found for Participant ID " . $formatValues['participant_id'] . ". Row was skipped.");
                 return CRM_Event_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $error = civicrm_check_contact_dedupe($formatValues);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 foreach ($matchedIDs as $contactId) {
                     $formatted['contact_id'] = $contactId;
                     $newParticipant = civicrm_create_participant_formatted($formatted, $onDuplicate);
                 }
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Event_Import_Parser::ERROR;
         }
     } else {
         if ($formatValues['external_identifier']) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(true);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, "Mismatch of External identifier :" . $formatValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']);
                 return CRM_Event_Import_Parser::ERROR;
             }
         }
         $newParticipant = civicrm_create_participant_formatted($formatted, $onDuplicate);
     }
     if (is_array($newParticipant) && civicrm_error($newParticipant)) {
         if ($onDuplicate == CRM_Event_Import_Parser::DUPLICATE_SKIP) {
             $contactID = CRM_Utils_Array::value('contactID', $newParticipant['error_data']);
             $participantID = CRM_Utils_Array::value('participantID', $newParticipant['error_data']);
             $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", true);
             if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) {
                 array_unshift($values, $url);
                 return CRM_Event_Import_Parser::DUPLICATE;
             } else {
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Event_Import_Parser::ERROR;
                 }
             }
             return CRM_Event_Import_Parser::ERROR;
         }
     }
     if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
         $this->_newParticipants[] = $newParticipant['id'];
     }
     return CRM_Event_Import_Parser::VALID;
 }
Пример #12
0
 /**
  * takes an associative array and creates a participant object
  *
  * the function extract all the params it needs to initialize the create a
  * participant object. the params array could contain additional unused name/value
  * pairs
  *
  * @param array  $params (reference ) an assoc array of name/value pairs
  * @param array $ids    the array that holds all the db ids
  *
  * @return object CRM_Event_BAO_Participant object
  * @access public
  * @static
  */
 static function &add(&$params)
 {
     require_once 'CRM/Utils/Hook.php';
     if (CRM_Utils_Array::value('id', $params)) {
         CRM_Utils_Hook::pre('edit', 'Participant', $params['id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Participant', null, $params);
     }
     // converting dates to mysql format
     if (CRM_Utils_Array::value('register_date', $params)) {
         $params['register_date'] = CRM_Utils_Date::isoToMysql($params['register_date']);
     }
     if (CRM_Utils_Array::value('participant_fee_amount', $params)) {
         $params['participant_fee_amount'] = CRM_Utils_Rule::cleanMoney($params['participant_fee_amount']);
     }
     $participantBAO = new CRM_Event_BAO_Participant();
     if (CRM_Utils_Array::value('id', $params)) {
         $participantBAO->id = CRM_Utils_Array::value('id', $params);
         $participantBAO->find(true);
         $participantBAO->register_date = CRM_Utils_Date::isoToMysql($participantBAO->register_date);
     }
     $participantBAO->copyValues($params);
     //make sure we have currency when amount is not null CRM-4453
     require_once 'CRM/Utils/Rule.php';
     if (!CRM_Utils_System::isNull($participantBAO->fee_amount) && !CRM_Utils_Rule::currencyCode($participantBAO->fee_currency)) {
         require_once 'CRM/Core/Config.php';
         $config =& CRM_Core_Config::singleton();
         $participantBAO->fee_currency = $config->defaultCurrency;
     }
     $participantBAO->save();
     $session =& CRM_Core_Session::singleton();
     // reset the group contact cache for this group
     require_once 'CRM/Contact/BAO/GroupContactCache.php';
     CRM_Contact_BAO_GroupContactCache::remove();
     if (CRM_Utils_Array::value('id', $params)) {
         CRM_Utils_Hook::post('edit', 'Participant', $participantBAO->id, $participantBAO);
     } else {
         CRM_Utils_Hook::post('create', 'Participant', $participantBAO->id, $participantBAO);
     }
     return $participantBAO;
 }
Пример #13
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once "CRM/Event/BAO/Participant.php";
         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);
         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;
         } else {
             $status = "Selected Participants was deleted sucessfully.";
         }
         CRM_Core_Session::setStatus($status);
         return;
     }
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $params)) {
         $this->_contactId = $params['contact_select_id'][1];
     }
     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'])) {
                 require_once 'CRM/Price/BAO/LineItem.php';
                 $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 (CRM_Utils_Array::value('discount_id', $params)) {
                 $discountId = $params['discount_id'];
             } else {
                 $discountId = $params['discount_id'] = 'null';
             }
             //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'];
             } else {
                 if (!isset($params['priceSetId']) && CRM_Utils_Array::value('amount', $params)) {
                     $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                     $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
                 } else {
                     CRM_Price_BAO_Set::processAmount($this->_values['fee'], $params, $lineItem[0]);
                 }
             }
             $params['fee_level'] = $params['amount_level'];
             $contributionParams['total_amount'] = $params['amount'];
             //fix for CRM-3086
             $params['fee_amount'] = $params['amount'];
         }
         if (isset($params['priceSetId'])) {
             $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 ($participantCount) {
                 $this->assign('pricesetFieldsCount', $participantCount);
             }
             $this->assign('lineItem', empty($lineItem[0]) ? false : $lineItem);
         } else {
             $this->assign('amount_level', $params['amount_level']);
         }
     }
     $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;
     // overwrite actual payment amount if entered
     if (CRM_Utils_Array::value('total_amount', $params)) {
         $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
     }
     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)
         $this->_params['participant_status_id'] = $params['status_id'];
         $this->_params['participant_role_id'] = $params['role_id'];
         $this->_params['participant_register_date'] = $params['register_date'];
         $this->_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;
         list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
         $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);
     }
     $roleAllIds = CRM_Utils_Array::value('role_id', $params);
     if ($roleAllIds) {
         foreach ($roleAllIds as $rkey => $rvalue) {
             $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, $rkey, $this->_roleCustomDataTypeID);
             $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');
         }
     }
     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, $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();
         if (CRM_Utils_Array::value('participant_role_id', $this->_params) && is_array($this->_params['participant_role_id'])) {
             $this->_params['participant_role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($this->_params['participant_role_id']));
         }
         $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) {
             if ($params['role_id']) {
                 foreach ($params['role_id'] as $k => $v) {
                     $rolesIDS[] = $k;
                 }
                 require_once 'CRM/Core/DAO.php';
                 $seperator = CRM_Core_DAO::VALUE_SEPARATOR;
                 $params['role_id'] = implode($seperator, $rolesIDS);
             } 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']) {
                     $rolesIDS = array();
                     foreach ($commonParams['role_id'] as $k => $v) {
                         $rolesIDS[] = $k;
                     }
                     require_once 'CRM/Core/DAO.php';
                     $seperator = CRM_Core_DAO::VALUE_SEPARATOR;
                     $commonParams['role_id'] = implode($seperator, $rolesIDS);
                     $commonParams['participant_role_id'] = implode($seperator, $rolesIDS);
                 } 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;
         }
         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();
                 }
             }
         }
     }
     //do cleanup line  items if participant edit the Event Fee.
     if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId) {
         require_once 'CRM/Price/BAO/LineItem.php';
         CRM_Price_BAO_LineItem::deleteLineItems($params['participant_id'], 'civicrm_participant');
     }
     // also store lineitem stuff here
     if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) {
         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->_id && $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->_id, $params['status_id'], $this->_statusId);
     }
     if (CRM_Utils_Array::value('send_receipt', $params)) {
         $receiptFrom = CRM_Utils_Array::value($params['from_email_address'], $this->_fromEmails['name']);
         $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();
         if (is_array($params['role_id'])) {
             $selectedRoles = array();
             foreach (array_keys($params['role_id']) as $roleId) {
                 $selectedRoles[] = $role[$roleId];
             }
             $event['participant_role'] = implode(', ', $selectedRoles);
         } else {
             $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], 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;
             $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();
                 if (!empty($additionalParticipantDetails)) {
                     $params['amount_level'] = $params['amount_level'] . ' - ' . $this->_contributorDisplayName;
                 }
                 $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.
                 $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));
             // 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);
             }
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
                 require_once 'CRM/Activity/BAO/Activity.php';
                 foreach ($participants as $ids => $values) {
                     CRM_Activity_BAO_Activity::addActivity($values, 'Email');
                 }
             } 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 (CRM_Utils_Array::value('send_receipt', $params) && 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(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');
             }
         }
     }
     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={$this->_context}&cid={$this->_contactId}"));
         }
     }
 }
Пример #14
0
 /** 
  * 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)
 {
     // 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']) {
             $params = $fields;
             $level = $isAdditional ? 'Fuzzy' : 'Strict';
             require_once 'CRM/Dedupe/Finder.php';
             $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 {
             if (isset($fields["email-{$self->_bltID}"])) {
                 $emailString = trim($fields["email-{$self->_bltID}"]);
                 if (!empty($emailString)) {
                     $contactID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $emailString, 'contact_Id', 'email');
                 }
             }
         }
     }
     if ($returnContactId) {
         // CRM-7377
         // return contactID if contact already exists
         return $contactID;
     }
     if ($contactID) {
         require_once 'CRM/Event/BAO/Participant.php';
         $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();
         require_once 'CRM/Event/PseudoConstant.php';
         $statusTypes = CRM_Event_PseudoConstant::participantStatus(null, "is_counted = 1");
         while ($participant->fetch()) {
             if (array_key_exists($participant->status_id, $statusTypes)) {
                 if (!$isAdditional) {
                     $registerUrl = CRM_Utils_System::url('civicrm/event/register', "reset=1&id={$self->_values['event']['id']}&cid=0");
                     $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';
                     }
                     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;
                 }
             }
         }
     }
 }