3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Event_BAO_Participant
extends CRM_Event_DAO_Participant
{
20 * Static field for all the participant information that we can potentially import.
24 public static $_importableFields = NULL;
27 * Static field for all the participant information that we can potentially export.
31 public static $_exportableFields = NULL;
34 * Static array for valid status transitions rules.
38 public static $_statusTransitionsRules = [
39 'Pending from pay later' => ['Registered', 'Cancelled'],
40 'Pending from incomplete transaction' => ['Registered', 'Cancelled'],
41 'On waitlist' => ['Cancelled', 'Pending from waitlist'],
42 'Pending from waitlist' => ['Registered', 'Cancelled'],
43 'Awaiting approval' => ['Cancelled', 'Pending from approval'],
44 'Pending from approval' => ['Registered', 'Cancelled'],
49 public function __construct() {
50 parent
::__construct();
54 * Takes an associative array and creates a participant object.
56 * the function extract all the params it needs to initialize the create a
57 * participant object. the params array could contain additional unused name/value
60 * @param array $params
61 * (reference ) an assoc array of name/value pairs.
63 * @return CRM_Event_BAO_Participant
65 public static function &add(&$params) {
67 if (!empty($params['id'])) {
68 CRM_Utils_Hook
::pre('edit', 'Participant', $params['id'], $params);
71 CRM_Utils_Hook
::pre('create', 'Participant', NULL, $params);
74 // converting dates to mysql format
75 if (!empty($params['register_date'])) {
76 $params['register_date'] = CRM_Utils_Date
::isoToMysql($params['register_date']);
79 if (!empty($params['participant_fee_amount'])) {
80 $params['participant_fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['participant_fee_amount']);
83 if (!empty($params['fee_amount'])) {
84 $params['fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['fee_amount']);
87 // ensure that role ids are encoded as a string
88 if (isset($params['role_id']) && is_array($params['role_id'])) {
89 if (in_array(key($params['role_id']), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
90 $op = key($params['role_id']);
91 $params['role_id'] = $params['role_id'][$op];
94 $params['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['role_id']);
98 $participantBAO = new CRM_Event_BAO_Participant();
99 if (!empty($params['id'])) {
100 $participantBAO->id
= $params['id'] ??
NULL;
101 $participantBAO->find(TRUE);
102 $participantBAO->register_date
= CRM_Utils_Date
::isoToMysql($participantBAO->register_date
);
105 $participantBAO->copyValues($params);
108 //1. If currency present, it should be valid one.
109 //2. We should have currency when amount is not null.
110 $currency = $participantBAO->fee_currency
;
112 !CRM_Utils_System
::isNull($participantBAO->fee_amount
)
114 if (!CRM_Utils_Rule
::currencyCode($currency)) {
115 $config = CRM_Core_Config
::singleton();
116 $currency = $config->defaultCurrency
;
119 $participantBAO->fee_currency
= $currency;
121 $participantBAO->save();
123 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
125 if (!empty($params['id'])) {
126 CRM_Utils_Hook
::post('edit', 'Participant', $participantBAO->id
, $participantBAO);
129 CRM_Utils_Hook
::post('create', 'Participant', $participantBAO->id
, $participantBAO);
132 return $participantBAO;
136 * Given the list of params in the params array, fetch the object
137 * and store the values in the values array
139 * @param array $params
140 * Input parameters to find object.
141 * @param array $values
142 * Output values of the object.
146 * @return CRM_Event_BAO_Participant|null the found object or null
148 public static function getValues(&$params, &$values = [], &$ids = []) {
149 if (empty($params)) {
152 $participant = new CRM_Event_BAO_Participant();
153 $participant->copyValues($params);
154 $participant->find();
156 while ($participant->fetch()) {
157 $ids['participant'] = $participant->id
;
158 CRM_Core_DAO
::storeValues($participant, $values[$participant->id
]);
159 $participants[$participant->id
] = $participant;
161 return $participants;
165 * Takes an associative array and creates a participant object.
167 * @param array $params
168 * (reference ) an assoc array of name/value pairs.
170 * @return CRM_Event_BAO_Participant
172 public static function create(&$params) {
174 $transaction = new CRM_Core_Transaction();
177 if (!empty($params['id'])) {
178 $status = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
181 $participant = self
::add($params);
183 if (is_a($participant, 'CRM_Core_Error')) {
184 $transaction->rollback();
188 // Log activity when creating new participant or changing status
189 if (empty($params['id']) ||
190 (isset($params['status_id']) && $params['status_id'] != $status)
192 // Default status if not specified
193 $participant->status_id
= $participant->status_id ?
: self
::fields()['participant_status_id']['default'];
194 CRM_Activity_BAO_Activity
::addActivity($participant, 'Event Registration');
199 if (self
::isPrimaryParticipant($participant->id
) && $status) {
200 self
::updateParticipantStatus($participant->id
, $status, $participant->status_id
);
203 $session = CRM_Core_Session
::singleton();
204 $id = $session->get('userID');
206 $id = $params['contact_id'] ??
NULL;
209 // add custom field values
210 if (!empty($params['custom']) &&
211 is_array($params['custom'])
213 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_participant', $participant->id
);
216 //process note, CRM-7634
218 if (!empty($params['id'])) {
219 $note = CRM_Core_BAO_Note
::getNote($params['id'], 'civicrm_participant');
220 $noteId = key($note);
223 $hasNoteField = FALSE;
228 if (array_key_exists($noteFld, $params)) {
229 $noteValue = $params[$noteFld];
230 $hasNoteField = TRUE;
234 if ($noteId ||
$noteValue) {
237 'entity_table' => 'civicrm_participant',
238 'note' => $noteValue,
239 'entity_id' => $participant->id
,
244 $noteIDs['id'] = $noteId;
246 CRM_Core_BAO_Note
::add($noteParams, $noteIDs);
248 elseif ($noteId && $hasNoteField) {
249 CRM_Core_BAO_Note
::del($noteId, FALSE);
253 // Log the information on successful add/edit of Participant data.
255 'entity_table' => 'civicrm_participant',
256 'entity_id' => $participant->id
,
257 'data' => CRM_Event_PseudoConstant
::participantStatus($participant->status_id
),
258 'modified_id' => $id,
259 'modified_date' => date('Ymd'),
262 CRM_Core_BAO_Log
::add($logParams);
264 $params['participant_id'] = $participant->id
;
266 $transaction->commit();
268 // do not add to recent items for import, CRM-4399
269 if (empty($params['skipRecentView'])) {
271 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
272 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
276 if (CRM_Core_Permission
::check('edit event participants')) {
277 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
278 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
281 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
282 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
283 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
287 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
289 if ($participant->role_id
) {
290 $role = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participant->role_id
);
292 foreach ($role as & $roleValue) {
293 if (isset($roleValue)) {
294 $roleValue = $participantRoles[$roleValue];
297 $roles = implode(', ', $role);
300 $roleString = empty($roles) ?
'' : $roles;
301 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $participant->event_id
, 'title');
302 $title = CRM_Contact_BAO_Contact
::displayName($participant->contact_id
) . ' (' . $roleString . ' - ' . $eventTitle . ')';
304 // add the recently created Participant
305 CRM_Utils_Recent
::add($title,
309 $participant->contact_id
,
319 * Check whether the event is full for participation and return as.
322 * @param int $eventId
324 * @param bool $returnEmptySeats
325 * Are we require number if empty seats.
326 * @param bool $includeWaitingList
327 * Consider waiting list in event full.
328 * calculation or not. (it is for cron job purpose)
330 * @param bool $returnWaitingCount
331 * @param bool $considerTestParticipant
332 * When TRUE, include participant records where is_test = 1.
333 * @param bool $onlyPositiveStatuses
334 * When FALSE, count all participant statuses where is_counted = 1. This includes
335 * both "Positive" participants (Registered, Attended, etc.) and waitlisted
336 * (and some pending) participants.
337 * When TRUE, count only participants with statuses of "Positive".
339 * @return bool|int|null|string
340 * 1. false => If event having some empty spaces.
342 public static function eventFull(
344 $returnEmptySeats = FALSE,
345 $includeWaitingList = TRUE,
346 $returnWaitingCount = FALSE,
347 $considerTestParticipant = FALSE,
348 $onlyPositiveStatuses = FALSE
355 // consider event is full when.
356 // 1. (count(is_counted) >= event_size) or
357 // 2. (count(participants-with-status-on-waitlist) > 0)
358 // It might be case there are some empty spaces and still event
359 // is full, as waitlist might represent group require spaces > empty.
361 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
362 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
363 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
364 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
365 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
367 $where = [' event.id = %1 '];
368 if (!$considerTestParticipant) {
369 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
372 // Only count Participant Roles with the "Counted?" flag.
373 if (!empty($participantRoles)) {
375 foreach (array_keys($participantRoles) as $participantRole) {
376 $escapedRoles[] = CRM_Utils_Type
::escape($participantRole, 'String');
379 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', $escapedRoles) . "([[:cntrl:]]|$)";
380 $where[] = " participant.role_id REGEXP '{$regexp}'";
383 $eventParams = [1 => [$eventId, 'Positive']];
385 //in case any waiting, straight forward event is full.
386 if ($includeWaitingList && $onWaitlistStatusId) {
388 //build the where clause.
389 $whereClause = ' WHERE ' . implode(' AND ', $where);
390 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
391 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
394 SELECT participant.id id,
395 event.event_full_text as event_full_text
396 FROM civicrm_participant participant
397 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
400 $eventFullText = ts('This event is full.');
401 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
402 while ($participants->fetch()) {
403 //oops here event is full and we don't want waiting count.
404 if ($returnWaitingCount) {
405 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
408 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
413 //Consider only counted participants, or alternatively only registered (not on waitlist) participants.
414 if ($onlyPositiveStatuses) {
415 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($positiveStatuses)) . ' ) ';
418 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
420 $whereClause = ' WHERE ' . implode(' AND ', $where);
421 $eventSeatsWhere = implode(' AND ', $where);
424 SELECT participant.id id,
425 event.event_full_text as event_full_text,
426 event.max_participants as max_participants
427 FROM civicrm_participant participant
428 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
431 $eventMaxSeats = NULL;
432 $eventFullText = ts('This event is full.');
433 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
434 while ($participants->fetch()) {
435 if ($participants->event_full_text
) {
436 $eventFullText = $participants->event_full_text
;
438 $eventMaxSeats = $participants->max_participants
;
439 //don't have limit for event seats.
440 if ($participants->max_participants
== NULL) {
445 //get the total event seats occupied by these participants.
446 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
448 if ($eventRegisteredSeats) {
449 if ($eventRegisteredSeats >= $eventMaxSeats) {
450 $result = $eventFullText;
452 elseif ($returnEmptySeats) {
453 $result = $eventMaxSeats - $eventRegisteredSeats;
459 SELECT event.event_full_text,
460 event.max_participants
461 FROM civicrm_event event
462 WHERE event.id = %1';
463 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
464 while ($event->fetch()) {
465 $eventFullText = $event->event_full_text
;
466 $eventMaxSeats = $event->max_participants
;
470 // no limit for registration.
471 if ($eventMaxSeats == NULL) {
474 if ($eventMaxSeats) {
475 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
478 return $eventFullText;
482 * Return the array of all price set field options,
483 * with total participant count that field going to carry.
485 * @param int $eventId
487 * @param array $skipParticipantIds
488 * An array of participant ids those we should skip.
489 * @param bool $considerCounted
490 * @param bool $considerWaiting
491 * @param bool $considerTestParticipants
494 * an array of each option id and total count
496 public static function priceSetOptionsCount(
498 $skipParticipantIds = [],
499 $considerCounted = TRUE,
500 $considerWaiting = TRUE,
501 $considerTestParticipants = FALSE
505 return $optionsCount;
509 if ($considerCounted) {
510 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
511 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
513 if ($considerWaiting) {
514 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
515 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
517 $statusIdClause = NULL;
518 if (!empty($allStatusIds)) {
519 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
522 $isTestClause = NULL;
523 if (!$considerTestParticipants) {
524 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
527 $skipParticipantClause = NULL;
528 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
529 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
533 SELECT line.id as lineId,
534 line.entity_id as entity_id,
539 FROM civicrm_line_item line
540 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
541 AND participant.id = line.entity_id )
542 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
543 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
544 WHERE participant.event_id = %1
548 {$skipParticipantClause}";
550 $lineItem = CRM_Core_DAO
::executeQuery($sql, [1 => [$eventId, 'Positive']]);
551 while ($lineItem->fetch()) {
552 $count = $lineItem->count
;
556 if ($lineItem->html_type
== 'Text') {
557 $count *= $lineItem->qty
;
559 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
562 return $optionsCount;
566 * Get the empty spaces for event those we can allocate
567 * to pending participant to become confirm.
571 * @param int $eventId
575 * $spaces Number of Empty Seats/null.
577 public static function pendingToConfirmSpaces($eventId) {
578 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Event_BAO_Participant::eventFull');
579 return CRM_Event_BAO_Participant
::eventFull($eventId, TRUE, FALSE, TRUE, FALSE, TRUE);
583 * Combine all the importable fields from the lower levels object.
585 * @param string $contactType
586 * @param bool $status
587 * @param bool $onlyParticipant
588 * @param bool $checkPermission
589 * Is this a permissioned retrieval?
592 * array of importable Fields
594 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE) {
595 if (!self
::$_importableFields) {
596 if (!$onlyParticipant) {
598 $fields = ['' => ['title' => ts('- do not import -')]];
601 $fields = ['' => ['title' => ts('- Participant Fields -')]];
608 $tmpFields = CRM_Event_DAO_Participant
::import();
611 'participant_note' => [
612 'title' => ts('Participant Note'),
613 'name' => 'participant_note',
614 'headerPattern' => '/(participant.)?note$/i',
615 'data_type' => CRM_Utils_Type
::T_TEXT
,
619 // Split status and status id into 2 fields
620 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
621 $participantStatus = [
622 'participant_status' => [
623 'title' => ts('Participant Status'),
624 'name' => 'participant_status',
625 'data_type' => CRM_Utils_Type
::T_STRING
,
628 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
630 // Split role and role id into 2 fields
631 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
633 'participant_role' => [
634 'title' => ts('Participant Role'),
635 'name' => 'participant_role',
636 'data_type' => CRM_Utils_Type
::T_STRING
,
639 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
643 'title' => ts('Event Type'),
644 'name' => 'event_type',
645 'data_type' => CRM_Utils_Type
::T_STRING
,
649 $tmpContactField = $contactFields = [];
651 if (!$onlyParticipant) {
652 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
654 // Using new Dedupe rule.
656 'contact_type' => $contactType,
657 'used' => 'Unsupervised',
659 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
661 if (is_array($fieldsArray)) {
662 foreach ($fieldsArray as $value) {
663 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
668 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
669 $tmpContactField[trim($value)] = $contactFields[trim($value)] ??
NULL;
671 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
674 $title = $tmpContactField[trim($value)]['title'];
677 $tmpContactField[trim($value)]['title'] = $title;
681 $extIdentifier = $contactFields['external_identifier'] ??
NULL;
682 if ($extIdentifier) {
683 $tmpContactField['external_identifier'] = $extIdentifier;
684 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
686 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
688 $fields = array_merge($fields, $tmpContactField);
689 $fields = array_merge($fields, $tmpFields);
690 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
691 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
693 self
::$_importableFields = $fields;
696 return self
::$_importableFields;
700 * Combine all the exportable fields from the lower level objects.
702 * @param bool $checkPermission
705 * array of exportable Fields
707 public static function &exportableFields($checkPermission = TRUE) {
708 if (!self
::$_exportableFields) {
709 if (!self
::$_exportableFields) {
710 self
::$_exportableFields = [];
713 $participantFields = CRM_Event_DAO_Participant
::export();
714 $eventFields = CRM_Event_DAO_Event
::export();
716 'participant_note' => [
717 'title' => ts('Participant Note'),
718 'name' => 'participant_note',
719 'type' => CRM_Utils_Type
::T_STRING
,
723 $participantStatus = [
724 'participant_status' => [
725 'title' => ts('Participant Status (label)'),
726 'name' => 'participant_status',
727 'type' => CRM_Utils_Type
::T_STRING
,
732 'participant_role' => [
733 'title' => ts('Participant Role (label)'),
734 'name' => 'participant_role',
735 'type' => CRM_Utils_Type
::T_STRING
,
739 $participantFields['participant_status_id']['title'] .= ' (ID)';
740 $participantFields['participant_role_id']['title'] .= ' (ID)';
742 $discountFields = CRM_Core_DAO_Discount
::export();
744 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
747 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
748 self
::$_exportableFields = $fields;
751 return self
::$_exportableFields;
755 * Get the event name/sort name for a particular participation / participant
757 * @param int $participantId
758 * Id of the participant.
761 * associated array with sort_name and event title
763 public static function participantDetails($participantId) {
765 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
766 FROM civicrm_participant
767 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
768 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
769 WHERE civicrm_participant.id = {$participantId}
771 $dao = CRM_Core_DAO
::executeQuery($query);
774 while ($dao->fetch()) {
775 $details['name'] = $dao->name
;
776 $details['title'] = $dao->title
;
777 $details['cid'] = $dao->cid
;
784 * Get the values for pseudoconstants for name->value and reverse.
786 * @param array $defaults
787 * (reference) the default values, some of which need to be resolved.
788 * @param bool $reverse
789 * True if we want to resolve the values in the reverse direction (value -> name).
791 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
792 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
793 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
794 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
798 * Convert associative array names to values and vice-versa.
800 * This function is used by both the web form layer and the api. Note that
801 * the api needs the name => value conversion, also the view layer typically
802 * requires value => name conversion
804 * @param array $defaults
805 * @param string $property
806 * @param string $lookup
807 * @param bool $reverse
811 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
812 $id = $property . '_id';
814 $src = $reverse ?
$property : $id;
815 $dst = $reverse ?
$id : $property;
817 if (!array_key_exists($src, $defaults)) {
821 $look = $reverse ?
array_flip($lookup) : $lookup;
823 if (is_array($look)) {
824 if (!array_key_exists($defaults[$src], $look)) {
828 $defaults[$dst] = $look[$defaults[$src]];
833 * Delete the records that are associated with this participation.
836 * Id of the participation to delete.
838 * @return \CRM_Event_DAO_Participant
840 public static function deleteParticipant($id) {
841 $participant = new CRM_Event_DAO_Participant();
842 $participant->id
= $id;
843 if (!$participant->find()) {
846 CRM_Utils_Hook
::pre('delete', 'Participant', $id);
848 $transaction = new CRM_Core_Transaction();
850 //delete activity record
852 'source_record_id' => $id,
853 // activity type id for event registration
854 'activity_type_id' => 5,
857 CRM_Activity_BAO_Activity
::deleteActivity($params);
859 // delete the participant payment record
860 // we need to do this since the cascaded constraints
861 // dont work with join tables
862 $p = ['participant_id' => $id];
863 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
865 // cleanup line items.
866 $participantsId = [];
867 $participantsId = self
::getAdditionalParticipantIds($id);
868 $participantsId[] = $id;
869 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
871 //delete note when participant deleted.
872 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
873 $noteId = key($note);
875 CRM_Core_BAO_Note
::del($noteId, FALSE);
878 $participant->delete();
880 $transaction->commit();
882 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
884 // delete the recently created Participant
885 $participantRecent = [
887 'type' => 'Participant',
890 CRM_Utils_Recent
::del($participantRecent);
896 * Checks duplicate participants.
898 * @param array $input
899 * An assosiative array of name /value pairs.
900 * from other function
901 * @param array $duplicates
902 * (reference ) an assoc array of name/value pairs.
904 * @return CRM_Contribute_BAO_Contribution
906 public static function checkDuplicate($input, &$duplicates) {
907 $eventId = $input['event_id'] ??
NULL;
908 $contactId = $input['contact_id'] ??
NULL;
914 $clause[] = "event_id = %1";
915 $input[1] = [$eventId, 'Integer'];
919 $clause[] = "contact_id = %2";
920 $input[2] = [$contactId, 'Integer'];
923 if (empty($clause)) {
927 $clause = implode(' AND ', $clause);
929 $query = "SELECT id FROM civicrm_participant WHERE $clause";
930 $dao = CRM_Core_DAO
::executeQuery($query, $input);
932 while ($dao->fetch()) {
933 $duplicates[] = $dao->id
;
940 * Fix the event level.
942 * When price sets are used as event fee, fee_level is set as ^A
943 * separated string. We need to change that string to comma
944 * separated string before using fee_level in view mode.
946 * @param string $eventLevel
947 * Event_level string from db.
949 public static function fixEventLevel(&$eventLevel) {
950 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
951 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
953 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
954 $pos = strrpos($eventLevel, '(multiple participants)', 0);
956 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
959 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
960 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
961 substr($eventLevel, 0, 1)
964 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
965 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
966 substr($eventLevel, 0, -1)
972 * Get the ID of the default (first) participant role
975 * @throws \CiviCRM_API3_Exception
977 public static function getDefaultRoleID() {
978 return (int) civicrm_api3('OptionValue', 'getvalue', [
980 'option_group_id' => 'participant_role',
982 'options' => ['limit' => 1, 'sort' => 'is_default DESC'],
987 * Get the additional participant ids.
989 * @param int $primaryParticipantId
990 * Primary partycipant Id.
991 * @param bool $excludeCancel
992 * Do not include participant those are cancelled.
994 * @param int $oldStatusId
998 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
999 $additionalParticipantIds = [];
1000 if (!$primaryParticipantId) {
1001 return $additionalParticipantIds;
1004 $where = "participant.registered_by_id={$primaryParticipantId}";
1005 if ($excludeCancel) {
1006 $cancelStatusId = 0;
1007 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1008 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1009 $where .= " AND participant.status_id != {$cancelStatusId}";
1013 $where .= " AND participant.status_id = {$oldStatusId}";
1017 SELECT participant.id
1018 FROM civicrm_participant participant
1021 $dao = CRM_Core_DAO
::executeQuery($query);
1022 while ($dao->fetch()) {
1023 $additionalParticipantIds[$dao->id
] = $dao->id
;
1025 return $additionalParticipantIds;
1029 * Get the amount for the undiscounted version of the field.
1031 * Note this function is part of the refactoring process rather than the best approach.
1033 * @param int $eventID
1034 * @param int $discountedPriceFieldOptionID
1035 * @param string $feeLevel (deprecated)
1037 * @return null|string
1039 public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
1040 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1042 1 => [$priceSetId, 'Integer'],
1044 if ($discountedPriceFieldOptionID) {
1045 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1046 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1047 WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
1048 $params[2] = [$discountedPriceFieldOptionID, 'Integer'];
1051 $feeLevel = current($feeLevel);
1052 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1053 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1054 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1055 $params[2] = [$feeLevel, 'String'];
1057 return CRM_Core_DAO
::singleValueQuery($query, $params);
1061 * Retrieve additional participants display-names and URL to view their participant records.
1062 * (excludes cancelled participants automatically)
1064 * @param int $primaryParticipantID
1065 * Id of primary participant record.
1068 * $displayName => $viewUrl
1070 public static function getAdditionalParticipants($primaryParticipantID) {
1071 $additionalParticipantIDs = [];
1072 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1073 if (!empty($additionalParticipantIDs)) {
1074 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1075 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1076 $additionalParticipantID,
1079 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1080 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1081 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1084 $additionalParticipants[$additionalContactName] = $pViewURL;
1087 return $additionalParticipants;
1091 * Function for update primary and additional participant status.
1093 * @param int $participantID
1094 * Primary participant's id.
1095 * @param int $oldStatusID
1096 * @param int $newStatusID
1097 * @param bool $updatePrimaryStatus
1101 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1102 if (!$participantID ||
!$oldStatusID) {
1106 if (!$newStatusID) {
1107 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1109 elseif ($updatePrimaryStatus) {
1110 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1113 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1115 if (!empty($cascadeAdditionalIds)) {
1117 foreach ($cascadeAdditionalIds as $id) {
1118 $participantParams = [
1120 'status_id' => $newStatusID,
1122 civicrm_api3('Participant', 'create', $participantParams);
1126 catch (CiviCRM_API3_Exception
$e) {
1127 throw new CRM_Core_Exception('Failed to update additional participant status in database');
1134 * Function for update status for given participant ids.
1136 * @param int $participantIds
1137 * Array of participant ids.
1138 * @param int $statusId
1139 * Status id for participant.
1140 * @param bool $updateRegisterDate
1142 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1143 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1147 //lets update register date as we update status to keep track
1148 //when we did update status, useful for moving participant
1149 //from pending to expired.
1150 $setClause = "status_id = {$statusId}";
1151 if ($updateRegisterDate) {
1152 $setClause .= ", register_date = NOW()";
1155 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1158 UPDATE civicrm_participant
1160 WHERE id IN {$participantIdClause}";
1162 $dao = CRM_Core_DAO
::executeQuery($query);
1166 * Function takes participant ids and statuses
1167 * update status from $fromStatusId to $toStatusId
1168 * and send mail + create activities.
1170 * @param array $participantIds
1172 * @param int $toStatusId
1174 * @param int $fromStatusId
1176 * @param bool $returnResult
1177 * @param bool $skipCascadeRule
1179 * @return array|NULL
1181 public static function transitionParticipants(
1182 $participantIds, $toStatusId,
1183 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1185 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1189 //thumb rule is if we triggering primary participant need to triggered additional
1190 $allParticipantIds = $primaryANDAdditonalIds = [];
1191 foreach ($participantIds as $id) {
1192 $allParticipantIds[] = $id;
1193 if (self
::isPrimaryParticipant($id)) {
1194 //filter additional as per status transition rules, CRM-5403
1195 if ($skipCascadeRule) {
1196 $additionalIds = self
::getAdditionalParticipantIds($id);
1199 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1201 if (!empty($additionalIds)) {
1202 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1203 $primaryANDAdditonalIds[$id] = $additionalIds;
1208 //get the unique participant ids,
1209 $allParticipantIds = array_unique($allParticipantIds);
1211 //pull required participants, contacts, events data, if not in hand
1212 static $eventDetails = [];
1213 static $domainValues = [];
1214 static $contactDetails = [];
1216 $contactIds = $eventIds = $participantDetails = [];
1218 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1219 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1220 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1224 //first thing is pull all necessory data from db.
1225 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1227 //get all participants data.
1228 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1229 $dao = CRM_Core_DAO
::executeQuery($query);
1230 while ($dao->fetch()) {
1231 $participantDetails[$dao->id
] = [
1233 'role' => $participantRoles[$dao->role_id
],
1234 'is_test' => $dao->is_test
,
1235 'event_id' => $dao->event_id
,
1236 'status_id' => $dao->status_id
,
1237 'fee_amount' => $dao->fee_amount
,
1238 'contact_id' => $dao->contact_id
,
1239 'register_date' => $dao->register_date
,
1240 'registered_by_id' => $dao->registered_by_id
,
1242 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1243 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1246 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1247 $eventIds[$dao->event_id
] = $dao->event_id
;
1251 //get the domain values.
1252 if (empty($domainValues)) {
1253 // making all tokens available to templates.
1254 $domain = CRM_Core_BAO_Domain
::getDomain();
1256 'domain' => ['name', 'phone', 'address', 'email'],
1257 'contact' => CRM_Core_SelectValues
::contactTokens(),
1260 foreach ($tokens['domain'] as $token) {
1261 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1265 //get all required contacts detail.
1266 if (!empty($contactIds)) {
1267 // get the contact details.
1268 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1271 'CRM_Event_BAO_Participant'
1273 foreach ($currentContactDetails as $contactId => $contactValues) {
1274 $contactDetails[$contactId] = $contactValues;
1278 //get all required events detail.
1279 if (!empty($eventIds)) {
1280 foreach ($eventIds as $eventId) {
1281 //retrieve event information
1282 $eventParams = ['id' => $eventId];
1283 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1285 //get default participant role.
1286 $eventDetails[$eventId]['participant_role'] = $participantRoles[$eventDetails[$eventId]['default_role_id']] ??
NULL;
1288 //get the location info
1289 $locParams = ['entity_id' => $eventId, 'entity_table' => 'civicrm_event'];
1290 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1294 //now we are ready w/ all required data.
1295 //take a decision as per statuses.
1298 $toStatus = $statusTypes[$toStatusId];
1299 $fromStatus = $statusTypes[$fromStatusId] ??
NULL;
1301 switch ($toStatus) {
1302 case 'Pending from waitlist':
1303 case 'Pending from approval':
1304 switch ($fromStatus) {
1306 case 'Awaiting approval':
1307 $emailType = 'Confirm';
1313 //no matter from where u come send expired mail.
1314 $emailType = $toStatus;
1318 //no matter from where u come send cancel mail.
1319 $emailType = $toStatus;
1323 //as we process additional w/ primary, there might be case if user
1324 //select primary as well as additionals, so avoid double processing.
1325 $processedParticipantIds = [];
1326 $mailedParticipants = [];
1328 //send mails and update status.
1329 foreach ($participantDetails as $participantId => $participantValues) {
1330 $updateParticipantIds = [];
1331 if (in_array($participantId, $processedParticipantIds)) {
1335 //check is it primary and has additional.
1336 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1337 foreach ($primaryANDAdditonalIds[$participantId] as $additionalId) {
1340 $mail = self
::sendTransitionParticipantMail($additionalId,
1341 $participantDetails[$additionalId],
1342 $eventDetails[$participantDetails[$additionalId]['event_id']],
1343 $contactDetails[$participantDetails[$additionalId]['contact_id']],
1348 //get the mail participant ids
1350 $mailedParticipants[$additionalId] = $contactDetails[$participantDetails[$additionalId]['contact_id']]['display_name'];
1353 $updateParticipantIds[] = $additionalId;
1354 $processedParticipantIds[] = $additionalId;
1358 //now send email appropriate mail to primary.
1360 $mail = self
::sendTransitionParticipantMail($participantId,
1362 $eventDetails[$participantValues['event_id']],
1363 $contactDetails[$participantValues['contact_id']],
1368 //get the mail participant ids
1370 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1374 //now update status of group/one at once.
1375 $updateParticipantIds[] = $participantId;
1377 //update the register date only when we,
1378 //move participant to pending class, CRM-6496
1379 $updateRegisterDate = FALSE;
1380 if (array_key_exists($toStatusId, $pendingStatuses)) {
1381 $updateRegisterDate = TRUE;
1383 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1384 $processedParticipantIds[] = $participantId;
1387 //return result for cron.
1388 if ($returnResult) {
1390 'mailedParticipants' => $mailedParticipants,
1391 'updatedParticipantIds' => $processedParticipantIds,
1399 * Send mail and create activity
1400 * when participant status changed.
1402 * @param int $participantId
1404 * @param array $participantValues
1405 * Participant detail values. status id for participants.
1406 * @param array $eventDetails
1407 * Required event details.
1408 * @param array $contactDetails
1409 * Required contact details.
1410 * @param array $domainValues
1411 * Required domain values.
1412 * @param string $mailType
1413 * (eg 'approval', 'confirm', 'expired' ).
1417 public static function sendTransitionParticipantMail(
1428 //don't send confirmation mail to additional
1429 //since only primary able to confirm registration.
1430 if (!empty($participantValues['registered_by_id']) &&
1431 $mailType == 'Confirm'
1435 $toEmail = $contactDetails['email'] ??
NULL;
1438 $contactId = $participantValues['contact_id'];
1439 $participantName = $contactDetails['display_name'];
1441 //calculate the checksum value.
1442 $checksumValue = NULL;
1443 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1444 $checksumLife = 'inf';
1445 $endDate = $eventDetails['end_date'] ??
NULL;
1447 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1449 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1452 //take a receipt from as event else domain.
1453 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1454 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1455 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1458 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1460 'groupName' => 'msg_tpl_workflow_event',
1461 'valueName' => 'participant_' . strtolower($mailType),
1462 'contactId' => $contactId,
1464 'contact' => $contactDetails,
1465 'domain' => $domainValues,
1466 'participant' => $participantValues,
1467 'event' => $eventDetails,
1468 'paidEvent' => $eventDetails['is_monetary'] ??
NULL,
1469 'isShowLocation' => $eventDetails['is_show_location'] ??
NULL,
1470 'isAdditional' => $participantValues['registered_by_id'],
1471 'isExpired' => $mailType == 'Expired',
1472 'isConfirm' => $mailType == 'Confirm',
1473 'checksumValue' => $checksumValue,
1475 'from' => $receiptFrom,
1476 'toName' => $participantName,
1477 'toEmail' => $toEmail,
1478 'cc' => $eventDetails['cc_confirm'] ??
NULL,
1479 'bcc' => $eventDetails['bcc_confirm'] ??
NULL,
1483 // 3. create activity record.
1485 $now = date('YmdHis');
1486 $activityType = 'Event Registration';
1488 'subject' => $subject,
1489 'source_contact_id' => $contactId,
1490 'source_record_id' => $participantId,
1491 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1492 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1493 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1494 'is_test' => $participantValues['is_test'],
1498 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1499 throw new CRM_Core_Exception('Failed creating Activity for expiration mail');
1508 * Get participant status change message.
1510 * @param int $participantId
1511 * @param $statusChangeTo
1512 * @param int $fromStatusId
1516 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1518 $results = self
::transitionParticipants([$participantId],
1519 $statusChangeTo, $fromStatusId, TRUE
1522 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1523 //give user message only when mail has sent.
1524 if (is_array($results) && !empty($results)) {
1525 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1526 foreach ($results['updatedParticipantIds'] as $processedId) {
1527 if (is_array($results['mailedParticipants']) &&
1528 array_key_exists($processedId, $results['mailedParticipants'])
1530 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1532 1 => $allStatuses[$statusChangeTo],
1533 2 => $results['mailedParticipants'][$processedId],
1545 * Get event full and waiting list message.
1547 * @param int $eventId
1548 * @param int $participantId
1552 public static function eventFullMessage($eventId, $participantId = NULL) {
1553 $eventfullMsg = $dbStatusId = NULL;
1554 $checkEventFull = TRUE;
1555 if ($participantId) {
1556 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1557 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1558 //participant already in counted status no need to check for event full messages.
1559 $checkEventFull = FALSE;
1564 if (!$eventId ||
!$checkEventFull) {
1565 return $eventfullMsg;
1568 //event is truly full.
1569 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1570 if (is_string($emptySeats) && $emptySeats !== NULL) {
1571 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1572 $eventfullMsg = ts("This event currently has the maximum number of participants registered (%1). However, you can still override this limit and register additional participants using this form.", [
1573 1 => $maxParticipants,
1577 $hasWaiting = FALSE;
1578 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1579 if (is_numeric($waitListedCount)) {
1581 //only current processing participant is on waitlist.
1582 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1583 $hasWaiting = FALSE;
1588 $waitingStatusId = array_search('On waitlist',
1589 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1591 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1592 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1595 $eventfullMsg .= ts("There are %2 people currently on the waiting list for this event. You can <a href='%1'>view waitlisted registrations here</a>, or you can continue and register additional participants using this form.",
1597 1 => $viewWaitListUrl,
1598 2 => $waitListedCount,
1603 return $eventfullMsg;
1607 * Check for whether participant is primary or not.
1609 * @param int $participantId
1612 * true if participant is primary
1614 public static function isPrimaryParticipant($participantId) {
1616 $participant = new CRM_Event_DAO_Participant();
1617 $participant->registered_by_id
= $participantId;
1619 if ($participant->find(TRUE)) {
1626 * Get additional participant Ids for cascading with primary participant status.
1628 * @param int $participantId
1630 * @param int $oldStatusId
1632 * @param int $newStatusId
1638 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1640 $additionalParticipantIds = [];
1642 static $participantStatuses = [];
1644 if (empty($participantStatuses)) {
1645 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1648 if (!empty(self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]]) &&
1649 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1651 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1654 return $additionalParticipantIds;
1658 * Get participant record count for a Contact.
1660 * @param int $contactID
1663 * count of participant records
1665 public static function getContactParticipantCount($contactID) {
1666 $query = "SELECT count(*)
1667 FROM civicrm_participant
1668 WHERE civicrm_participant.contact_id = {$contactID} AND
1669 civicrm_participant.is_test = 0";
1670 return CRM_Core_DAO
::singleValueQuery($query);
1674 * Get participant ids by contribution id.
1676 * @param int $contributionId
1678 * @param bool $excludeCancelled
1679 * Exclude cancelled additional participant.
1683 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1686 if (!$contributionId) {
1690 // get primary participant id
1691 $query = "SELECT participant_id
1692 FROM civicrm_participant cp
1693 LEFT JOIN civicrm_participant_payment cpp ON cp.id = cpp.participant_id
1694 WHERE cpp.contribution_id = {$contributionId}
1695 AND cp.registered_by_id IS NULL";
1696 $participantPayment = CRM_Core_DAO
::executeQuery($query);
1698 // get additional participant ids (including cancelled)
1699 while ($participantPayment->fetch()) {
1700 $ids = array_merge($ids, array_merge([
1701 $participantPayment->participant_id
,
1702 ], self
::getAdditionalParticipantIds($participantPayment->participant_id
,
1711 * Get additional Participant edit & view url .
1713 * @param array $participantIds
1714 * An array of additional participant ids.
1719 public static function getAdditionalParticipantUrl($participantIds) {
1720 foreach ($participantIds as $value) {
1722 $details = self
::participantDetails($value);
1723 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1724 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1726 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1727 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1729 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1730 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1736 * create trxn entry if an event has discount.
1738 * @param int $eventID
1740 * @param array $contributionParams
1741 * Contribution params.
1743 * @param string $feeLevel (deprecated)
1744 * @param int $discountedPriceFieldOptionID
1745 * ID of the civicrm_price_field_value field for the discount id.
1747 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID = NULL) {
1748 $financialTypeID = $contributionParams['contribution']->financial_type_id
;
1749 $total_amount = $contributionParams['total_amount'];
1751 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID, 'civicrm_event');
1752 if (!empty($checkDiscount)) {
1753 $mainAmount = self
::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
1754 $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
1755 $financialTypeID, 'Discounts Account is');
1756 if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
1757 $transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
1758 $transactionParams['trxnParams']['payment_processor_id'] = NULL;
1759 $transactionParams['trxnParams']['payment_instrument_id'] = NULL;
1760 $transactionParams['trxnParams']['check_number'] = NULL;
1761 $transactionParams['trxnParams']['trxn_id'] = NULL;
1762 $transactionParams['trxnParams']['net_amount'] = NULL;
1763 $transactionParams['trxnParams']['fee_amount'] = NULL;
1764 CRM_Core_BAO_FinancialTrxn
::create($transactionParams);
1770 * Delete participants of contact.
1772 * @see https://issues.civicrm.org/jira/browse/CRM-12155
1774 * @param int $contactId
1778 public static function deleteContactParticipant($contactId) {
1779 $participant = new CRM_Event_DAO_Participant();
1780 $participant->contact_id
= $contactId;
1781 $participant->find();
1782 while ($participant->fetch()) {
1783 self
::deleteParticipant($participant->id
);
1788 * @param int $participantId
1789 * @param $activityType
1791 * @throws CRM_Core_Exception
1793 public static function addActivityForSelection($participantId, $activityType) {
1794 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
1795 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
1797 $date = CRM_Utils_Date
::currentDBDate();
1798 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
1799 $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array
::value($eventId, $event));
1803 'source_contact_id' => $contactId,
1804 'source_record_id' => $participantId,
1805 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1806 'subject' => $subject,
1807 'activity_date_time' => $date,
1808 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1809 'skipRecentView' => TRUE,
1812 // create activity with target contacts
1813 $id = CRM_Core_Session
::getLoggedInContactID();
1815 $activityParams['source_contact_id'] = $id;
1816 $activityParams['target_contact_id'][] = $contactId;
1818 // @todo use api & also look at duplication of similar methods.
1819 CRM_Activity_BAO_Activity
::create($activityParams);
1823 * Get options for a given field.
1824 * @see CRM_Core_DAO::buildOptions
1826 * @param string $fieldName
1827 * @param string $context
1828 * @see CRM_Core_DAO::buildOptionsContext
1829 * @param array $props
1830 * whatever is known about this dao object.
1832 * @return array|bool
1834 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1835 $params = ['condition' => []];
1837 if ($fieldName == 'status_id' && $context != 'validate') {
1838 // Get rid of cart-related option if disabled
1839 // FIXME: Why does this option even exist if cart is disabled?
1840 if (!Civi
::settings()->get('enable_cart')) {
1841 $params['condition'][] = "name <> 'Pending in cart'";
1845 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
1849 * CRM-17797 -- Format fields and setDefaults for primary and additional participants profile
1850 * @param int $contactId
1851 * @param CRM_Core_Form $form
1853 public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
1858 if (!empty($form->_fields
)) {
1859 $removeCustomFieldTypes = ['Participant'];
1861 foreach ($form->_fields
as $name => $fieldInfo) {
1862 if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
1863 && !CRM_Core_BAO_CustomGroup
::checkCustomField(substr($name, 7), $removeCustomFieldTypes))
1864 ||
substr($name, 0, 12) == 'participant_') {
1867 $fields[$name] = $fieldInfo;
1870 if (!empty($fields)) {
1871 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $fields, $form->_defaults
);
1877 * Evaluate whether a participant record is eligible for self-service transfer/cancellation. If so,
1878 * return additional participant/event details.
1880 * @param int $participantId
1881 * @param string $url
1882 * @param bool $isBackOffice
1884 public static function getSelfServiceEligibility(int $participantId, string $url, bool $isBackOffice) : array {
1885 $optionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'participant_role', 'id', 'name');
1887 SELECT cpst.name as status, cov.name as role, cp.fee_level, cp.fee_amount, cp.register_date, cp.status_id, ce.start_date, ce.title, cp.event_id, ce.allow_selfcancelxfer
1888 FROM civicrm_participant cp
1889 LEFT JOIN civicrm_participant_status_type cpst ON cpst.id = cp.status_id
1890 LEFT JOIN civicrm_option_value cov ON cov.value = cp.role_id and cov.option_group_id = {$optionGroupId}
1891 LEFT JOIN civicrm_event ce ON ce.id = cp.event_id
1892 WHERE cp.id = {$participantId}";
1893 $dao = CRM_Core_DAO
::executeQuery($query);
1894 while ($dao->fetch()) {
1895 $details['eligible'] = TRUE;
1896 $details['status'] = $dao->status
;
1897 $details['role'] = $dao->role
;
1898 $details['fee_level'] = trim($dao->fee_level
, CRM_Core_DAO
::VALUE_SEPARATOR
);
1899 $details['fee_amount'] = $dao->fee_amount
;
1900 $details['register_date'] = $dao->register_date
;
1901 $details['event_start_date'] = $dao->start_date
;
1902 $details['allow_selfcancelxfer'] = $dao->allow_selfcancelxfer
;
1903 $eventTitle = $dao->title
;
1904 $eventId = $dao->event_id
;
1906 if (!$details['allow_selfcancelxfer']) {
1907 $details['eligible'] = FALSE;
1908 $details['ineligible_message'] = ts('This event registration can not be transferred or cancelled. Contact the event organizer if you have questions.');
1911 //verify participant status is still Registered
1912 if ($details['status'] != 'Registered') {
1913 $details['eligible'] = FALSE;
1914 $details['ineligible_message'] = "You cannot transfer or cancel your registration for " . $eventTitle . ' as you are not currently registered for this event.';
1917 // Determine if it's too late to self-service cancel/transfer.
1918 $query = "select start_date as start, selfcancelxfer_time as time from civicrm_event where id = " . $eventId;
1919 $dao = CRM_Core_DAO
::executeQuery($query);
1920 while ($dao->fetch()) {
1921 $time_limit = $dao->time
;
1922 $start_date = $dao->start
;
1924 $timenow = new Datetime();
1925 if (!$isBackOffice && isset($time_limit)) {
1926 $cancelHours = abs($time_limit);
1927 $cancelInterval = new DateInterval("PT${cancelHours}H");
1928 $cancelInterval->invert
= $time_limit < 0 ?
1 : 0;
1929 $cancelDeadline = (new Datetime($start_date))->sub($cancelInterval);
1930 if ($timenow > $cancelDeadline) {
1931 $details['eligible'] = FALSE;
1932 // Change the language of the status message based on whether the waitlist time limit is positive or negative.
1933 $afterOrPrior = $time_limit <= 0 ?
'after' : 'prior to';
1934 $moreOrLess = $time_limit <= 0 ?
'more' : 'fewer';
1935 $details['ineligible_message'] = ts("Registration for this event cannot be cancelled or transferred %1 than %2 hours %3 the event's start time. Contact the event organizer if you have questions.",
1936 [1 => $moreOrLess, 2 => $cancelHours, 3 => $afterOrPrior]);