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
= CRM_Utils_Array
::value('id', $params);
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);
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 = CRM_Utils_Array
::value('contact_id', $params);
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
,
241 'modified_date' => date('Ymd'),
245 $noteIDs['id'] = $noteId;
247 CRM_Core_BAO_Note
::add($noteParams, $noteIDs);
249 elseif ($noteId && $hasNoteField) {
250 CRM_Core_BAO_Note
::del($noteId, FALSE);
254 // Log the information on successful add/edit of Participant data.
256 'entity_table' => 'civicrm_participant',
257 'entity_id' => $participant->id
,
258 'data' => CRM_Event_PseudoConstant
::participantStatus($participant->status_id
),
259 'modified_id' => $id,
260 'modified_date' => date('Ymd'),
263 CRM_Core_BAO_Log
::add($logParams);
265 $params['participant_id'] = $participant->id
;
267 $transaction->commit();
269 // do not add to recent items for import, CRM-4399
270 if (empty($params['skipRecentView'])) {
272 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
273 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
277 if (CRM_Core_Permission
::check('edit event participants')) {
278 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
279 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
282 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
283 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
284 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
288 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
290 if ($participant->role_id
) {
291 $role = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participant->role_id
);
293 foreach ($role as & $roleValue) {
294 if (isset($roleValue)) {
295 $roleValue = $participantRoles[$roleValue];
298 $roles = implode(', ', $role);
301 $roleString = empty($roles) ?
'' : $roles;
302 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $participant->event_id
, 'title');
303 $title = CRM_Contact_BAO_Contact
::displayName($participant->contact_id
) . ' (' . $roleString . ' - ' . $eventTitle . ')';
305 // add the recently created Participant
306 CRM_Utils_Recent
::add($title,
310 $participant->contact_id
,
320 * Check whether the event is full for participation and return as.
323 * @param int $eventId
325 * @param bool $returnEmptySeats
326 * Are we require number if empty seats.
327 * @param bool $includeWaitingList
328 * Consider waiting list in event full.
329 * calculation or not. (it is for cron job purpose)
331 * @param bool $returnWaitingCount
332 * @param bool $considerTestParticipant
333 * When TRUE, include participant records where is_test = 1.
334 * @param bool $onlyPositiveStatuses
335 * When FALSE, count all participant statuses where is_counted = 1. This includes
336 * both "Positive" participants (Registered, Attended, etc.) and waitlisted
337 * (and some pending) participants.
338 * When TRUE, count only participants with statuses of "Positive".
340 * @return bool|int|null|string
341 * 1. false => If event having some empty spaces.
343 public static function eventFull(
345 $returnEmptySeats = FALSE,
346 $includeWaitingList = TRUE,
347 $returnWaitingCount = FALSE,
348 $considerTestParticipant = FALSE,
349 $onlyPositiveStatuses = FALSE
356 // consider event is full when.
357 // 1. (count(is_counted) >= event_size) or
358 // 2. (count(participants-with-status-on-waitlist) > 0)
359 // It might be case there are some empty spaces and still event
360 // is full, as waitlist might represent group require spaces > empty.
362 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
363 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
364 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
365 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
366 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
368 $where = [' event.id = %1 '];
369 if (!$considerTestParticipant) {
370 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
373 // Only count Participant Roles with the "Counted?" flag.
374 if (!empty($participantRoles)) {
376 foreach (array_keys($participantRoles) as $participantRole) {
377 $escapedRoles[] = CRM_Utils_Type
::escape($participantRole, 'String');
380 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', $escapedRoles) . "([[:cntrl:]]|$)";
381 $where[] = " participant.role_id REGEXP '{$regexp}'";
384 $eventParams = [1 => [$eventId, 'Positive']];
386 //in case any waiting, straight forward event is full.
387 if ($includeWaitingList && $onWaitlistStatusId) {
389 //build the where clause.
390 $whereClause = ' WHERE ' . implode(' AND ', $where);
391 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
392 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
395 SELECT participant.id id,
396 event.event_full_text as event_full_text
397 FROM civicrm_participant participant
398 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
401 $eventFullText = ts('This event is full.');
402 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
403 while ($participants->fetch()) {
404 //oops here event is full and we don't want waiting count.
405 if ($returnWaitingCount) {
406 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
409 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
414 //Consider only counted participants, or alternatively only registered (not on waitlist) participants.
415 if ($onlyPositiveStatuses) {
416 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($positiveStatuses)) . ' ) ';
419 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
421 $whereClause = ' WHERE ' . implode(' AND ', $where);
422 $eventSeatsWhere = implode(' AND ', $where);
425 SELECT participant.id id,
426 event.event_full_text as event_full_text,
427 event.max_participants as max_participants
428 FROM civicrm_participant participant
429 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
432 $eventMaxSeats = NULL;
433 $eventFullText = ts('This event is full.');
434 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
435 while ($participants->fetch()) {
436 if ($participants->event_full_text
) {
437 $eventFullText = $participants->event_full_text
;
439 $eventMaxSeats = $participants->max_participants
;
440 //don't have limit for event seats.
441 if ($participants->max_participants
== NULL) {
446 //get the total event seats occupied by these participants.
447 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
449 if ($eventRegisteredSeats) {
450 if ($eventRegisteredSeats >= $eventMaxSeats) {
451 $result = $eventFullText;
453 elseif ($returnEmptySeats) {
454 $result = $eventMaxSeats - $eventRegisteredSeats;
460 SELECT event.event_full_text,
461 event.max_participants
462 FROM civicrm_event event
463 WHERE event.id = %1';
464 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
465 while ($event->fetch()) {
466 $eventFullText = $event->event_full_text
;
467 $eventMaxSeats = $event->max_participants
;
471 // no limit for registration.
472 if ($eventMaxSeats == NULL) {
475 if ($eventMaxSeats) {
476 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
479 return $eventFullText;
483 * Return the array of all price set field options,
484 * with total participant count that field going to carry.
486 * @param int $eventId
488 * @param array $skipParticipantIds
489 * An array of participant ids those we should skip.
490 * @param bool $considerCounted
491 * @param bool $considerWaiting
492 * @param bool $considerTestParticipants
495 * an array of each option id and total count
497 public static function priceSetOptionsCount(
499 $skipParticipantIds = [],
500 $considerCounted = TRUE,
501 $considerWaiting = TRUE,
502 $considerTestParticipants = FALSE
506 return $optionsCount;
510 if ($considerCounted) {
511 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
512 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
514 if ($considerWaiting) {
515 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
516 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
518 $statusIdClause = NULL;
519 if (!empty($allStatusIds)) {
520 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
523 $isTestClause = NULL;
524 if (!$considerTestParticipants) {
525 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
528 $skipParticipantClause = NULL;
529 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
530 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
534 SELECT line.id as lineId,
535 line.entity_id as entity_id,
540 FROM civicrm_line_item line
541 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
542 AND participant.id = line.entity_id )
543 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
544 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
545 WHERE participant.event_id = %1
549 {$skipParticipantClause}";
551 $lineItem = CRM_Core_DAO
::executeQuery($sql, [1 => [$eventId, 'Positive']]);
552 while ($lineItem->fetch()) {
553 $count = $lineItem->count
;
557 if ($lineItem->html_type
== 'Text') {
558 $count *= $lineItem->qty
;
560 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
563 return $optionsCount;
567 * Get the empty spaces for event those we can allocate
568 * to pending participant to become confirm.
572 * @param int $eventId
576 * $spaces Number of Empty Seats/null.
578 public static function pendingToConfirmSpaces($eventId) {
579 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Event_BAO_Participant::eventFull');
580 return CRM_Event_BAO_Participant
::eventFull($eventId, TRUE, FALSE, TRUE, FALSE, TRUE);
584 * Combine all the importable fields from the lower levels object.
586 * @param string $contactType
587 * @param bool $status
588 * @param bool $onlyParticipant
589 * @param bool $checkPermission
590 * Is this a permissioned retrieval?
593 * array of importable Fields
595 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE) {
596 if (!self
::$_importableFields) {
597 if (!$onlyParticipant) {
599 $fields = ['' => ['title' => ts('- do not import -')]];
602 $fields = ['' => ['title' => ts('- Participant Fields -')]];
609 $tmpFields = CRM_Event_DAO_Participant
::import();
612 'participant_note' => [
613 'title' => ts('Participant Note'),
614 'name' => 'participant_note',
615 'headerPattern' => '/(participant.)?note$/i',
616 'data_type' => CRM_Utils_Type
::T_TEXT
,
620 // Split status and status id into 2 fields
621 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
622 $participantStatus = [
623 'participant_status' => [
624 'title' => ts('Participant Status'),
625 'name' => 'participant_status',
626 'data_type' => CRM_Utils_Type
::T_STRING
,
629 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
631 // Split role and role id into 2 fields
632 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
634 'participant_role' => [
635 'title' => ts('Participant Role'),
636 'name' => 'participant_role',
637 'data_type' => CRM_Utils_Type
::T_STRING
,
640 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
644 'title' => ts('Event Type'),
645 'name' => 'event_type',
646 'data_type' => CRM_Utils_Type
::T_STRING
,
650 $tmpContactField = $contactFields = [];
652 if (!$onlyParticipant) {
653 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
655 // Using new Dedupe rule.
657 'contact_type' => $contactType,
658 'used' => 'Unsupervised',
660 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
662 if (is_array($fieldsArray)) {
663 foreach ($fieldsArray as $value) {
664 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
669 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
670 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
672 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
675 $title = $tmpContactField[trim($value)]['title'];
678 $tmpContactField[trim($value)]['title'] = $title;
682 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
683 if ($extIdentifier) {
684 $tmpContactField['external_identifier'] = $extIdentifier;
685 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
687 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
689 $fields = array_merge($fields, $tmpContactField);
690 $fields = array_merge($fields, $tmpFields);
691 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
692 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
694 self
::$_importableFields = $fields;
697 return self
::$_importableFields;
701 * Combine all the exportable fields from the lower level objects.
703 * @param bool $checkPermission
706 * array of exportable Fields
708 public static function &exportableFields($checkPermission = TRUE) {
709 if (!self
::$_exportableFields) {
710 if (!self
::$_exportableFields) {
711 self
::$_exportableFields = [];
714 $participantFields = CRM_Event_DAO_Participant
::export();
715 $eventFields = CRM_Event_DAO_Event
::export();
717 'participant_note' => [
718 'title' => ts('Participant Note'),
719 'name' => 'participant_note',
720 'type' => CRM_Utils_Type
::T_STRING
,
724 $participantStatus = [
725 'participant_status' => [
726 'title' => ts('Participant Status (label)'),
727 'name' => 'participant_status',
728 'type' => CRM_Utils_Type
::T_STRING
,
733 'participant_role' => [
734 'title' => ts('Participant Role (label)'),
735 'name' => 'participant_role',
736 'type' => CRM_Utils_Type
::T_STRING
,
740 $participantFields['participant_status_id']['title'] .= ' (ID)';
741 $participantFields['participant_role_id']['title'] .= ' (ID)';
743 $discountFields = CRM_Core_DAO_Discount
::export();
745 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
748 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
749 self
::$_exportableFields = $fields;
752 return self
::$_exportableFields;
756 * Get the event name/sort name for a particular participation / participant
758 * @param int $participantId
759 * Id of the participant.
762 * associated array with sort_name and event title
764 public static function participantDetails($participantId) {
766 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
767 FROM civicrm_participant
768 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
769 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
770 WHERE civicrm_participant.id = {$participantId}
772 $dao = CRM_Core_DAO
::executeQuery($query);
775 while ($dao->fetch()) {
776 $details['name'] = $dao->name
;
777 $details['title'] = $dao->title
;
778 $details['cid'] = $dao->cid
;
785 * Get the values for pseudoconstants for name->value and reverse.
787 * @param array $defaults
788 * (reference) the default values, some of which need to be resolved.
789 * @param bool $reverse
790 * True if we want to resolve the values in the reverse direction (value -> name).
792 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
793 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
794 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
795 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
799 * Convert associative array names to values and vice-versa.
801 * This function is used by both the web form layer and the api. Note that
802 * the api needs the name => value conversion, also the view layer typically
803 * requires value => name conversion
805 * @param array $defaults
806 * @param string $property
807 * @param string $lookup
808 * @param bool $reverse
812 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
813 $id = $property . '_id';
815 $src = $reverse ?
$property : $id;
816 $dst = $reverse ?
$id : $property;
818 if (!array_key_exists($src, $defaults)) {
822 $look = $reverse ?
array_flip($lookup) : $lookup;
824 if (is_array($look)) {
825 if (!array_key_exists($defaults[$src], $look)) {
829 $defaults[$dst] = $look[$defaults[$src]];
834 * Delete the records that are associated with this participation.
837 * Id of the participation to delete.
839 * @return \CRM_Event_DAO_Participant
841 public static function deleteParticipant($id) {
842 $participant = new CRM_Event_DAO_Participant();
843 $participant->id
= $id;
844 if (!$participant->find()) {
847 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
849 $transaction = new CRM_Core_Transaction();
851 //delete activity record
853 'source_record_id' => $id,
854 // activity type id for event registration
855 'activity_type_id' => 5,
858 CRM_Activity_BAO_Activity
::deleteActivity($params);
860 // delete the participant payment record
861 // we need to do this since the cascaded constraints
862 // dont work with join tables
863 $p = ['participant_id' => $id];
864 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
866 // cleanup line items.
867 $participantsId = [];
868 $participantsId = self
::getAdditionalParticipantIds($id);
869 $participantsId[] = $id;
870 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
872 //delete note when participant deleted.
873 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
874 $noteId = key($note);
876 CRM_Core_BAO_Note
::del($noteId, FALSE);
879 $participant->delete();
881 $transaction->commit();
883 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
885 // delete the recently created Participant
886 $participantRecent = [
888 'type' => 'Participant',
891 CRM_Utils_Recent
::del($participantRecent);
897 * Checks duplicate participants.
899 * @param array $input
900 * An assosiative array of name /value pairs.
901 * from other function
902 * @param array $duplicates
903 * (reference ) an assoc array of name/value pairs.
905 * @return CRM_Contribute_BAO_Contribution
907 public static function checkDuplicate($input, &$duplicates) {
908 $eventId = CRM_Utils_Array
::value('event_id', $input);
909 $contactId = CRM_Utils_Array
::value('contact_id', $input);
915 $clause[] = "event_id = %1";
916 $input[1] = [$eventId, 'Integer'];
920 $clause[] = "contact_id = %2";
921 $input[2] = [$contactId, 'Integer'];
924 if (empty($clause)) {
928 $clause = implode(' AND ', $clause);
930 $query = "SELECT id FROM civicrm_participant WHERE $clause";
931 $dao = CRM_Core_DAO
::executeQuery($query, $input);
933 while ($dao->fetch()) {
934 $duplicates[] = $dao->id
;
941 * Fix the event level.
943 * When price sets are used as event fee, fee_level is set as ^A
944 * separated string. We need to change that string to comma
945 * separated string before using fee_level in view mode.
947 * @param string $eventLevel
948 * Event_level string from db.
950 public static function fixEventLevel(&$eventLevel) {
951 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
952 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
954 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
955 $pos = strrpos($eventLevel, '(multiple participants)', 0);
957 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
960 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
961 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
962 substr($eventLevel, 0, 1)
965 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
966 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
967 substr($eventLevel, 0, -1)
973 * Get the additional participant ids.
975 * @param int $primaryParticipantId
976 * Primary partycipant Id.
977 * @param bool $excludeCancel
978 * Do not include participant those are cancelled.
980 * @param int $oldStatusId
984 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
985 $additionalParticipantIds = [];
986 if (!$primaryParticipantId) {
987 return $additionalParticipantIds;
990 $where = "participant.registered_by_id={$primaryParticipantId}";
991 if ($excludeCancel) {
993 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
994 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
995 $where .= " AND participant.status_id != {$cancelStatusId}";
999 $where .= " AND participant.status_id = {$oldStatusId}";
1003 SELECT participant.id
1004 FROM civicrm_participant participant
1007 $dao = CRM_Core_DAO
::executeQuery($query);
1008 while ($dao->fetch()) {
1009 $additionalParticipantIds[$dao->id
] = $dao->id
;
1011 return $additionalParticipantIds;
1015 * Get the amount for the undiscounted version of the field.
1017 * Note this function is part of the refactoring process rather than the best approach.
1019 * @param int $eventID
1020 * @param int $discountedPriceFieldOptionID
1021 * @param string $feeLevel (deprecated)
1023 * @return null|string
1025 public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
1026 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1028 1 => [$priceSetId, 'Integer'],
1030 if ($discountedPriceFieldOptionID) {
1031 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1032 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1033 WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
1034 $params[2] = [$discountedPriceFieldOptionID, 'Integer'];
1037 $feeLevel = current($feeLevel);
1038 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1039 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1040 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1041 $params[2] = [$feeLevel, 'String'];
1043 return CRM_Core_DAO
::singleValueQuery($query, $params);
1047 * Retrieve additional participants display-names and URL to view their participant records.
1048 * (excludes cancelled participants automatically)
1050 * @param int $primaryParticipantID
1051 * Id of primary participant record.
1054 * $displayName => $viewUrl
1056 public static function getAdditionalParticipants($primaryParticipantID) {
1057 $additionalParticipantIDs = [];
1058 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1059 if (!empty($additionalParticipantIDs)) {
1060 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1061 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1062 $additionalParticipantID,
1065 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1066 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1067 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1070 $additionalParticipants[$additionalContactName] = $pViewURL;
1073 return $additionalParticipants;
1077 * Function for update primary and additional participant status.
1079 * @param int $participantID
1080 * Primary participant's id.
1081 * @param int $oldStatusID
1082 * @param int $newStatusID
1083 * @param bool $updatePrimaryStatus
1087 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1088 if (!$participantID ||
!$oldStatusID) {
1092 if (!$newStatusID) {
1093 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1095 elseif ($updatePrimaryStatus) {
1096 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1099 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1101 if (!empty($cascadeAdditionalIds)) {
1103 foreach ($cascadeAdditionalIds as $id) {
1104 $participantParams = [
1106 'status_id' => $newStatusID,
1108 civicrm_api3('Participant', 'create', $participantParams);
1112 catch (CiviCRM_API3_Exception
$e) {
1113 throw new CRM_Core_Exception('Failed to update additional participant status in database');
1120 * Function for update status for given participant ids.
1122 * @param int $participantIds
1123 * Array of participant ids.
1124 * @param int $statusId
1125 * Status id for participant.
1126 * @param bool $updateRegisterDate
1128 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1129 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1133 //lets update register date as we update status to keep track
1134 //when we did update status, useful for moving participant
1135 //from pending to expired.
1136 $setClause = "status_id = {$statusId}";
1137 if ($updateRegisterDate) {
1138 $setClause .= ", register_date = NOW()";
1141 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1144 UPDATE civicrm_participant
1146 WHERE id IN {$participantIdClause}";
1148 $dao = CRM_Core_DAO
::executeQuery($query);
1152 * Function takes participant ids and statuses
1153 * update status from $fromStatusId to $toStatusId
1154 * and send mail + create activities.
1156 * @param array $participantIds
1158 * @param int $toStatusId
1160 * @param int $fromStatusId
1162 * @param bool $returnResult
1163 * @param bool $skipCascadeRule
1165 * @return array|NULL
1167 public static function transitionParticipants(
1168 $participantIds, $toStatusId,
1169 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1171 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1175 //thumb rule is if we triggering primary participant need to triggered additional
1176 $allParticipantIds = $primaryANDAdditonalIds = [];
1177 foreach ($participantIds as $id) {
1178 $allParticipantIds[] = $id;
1179 if (self
::isPrimaryParticipant($id)) {
1180 //filter additional as per status transition rules, CRM-5403
1181 if ($skipCascadeRule) {
1182 $additionalIds = self
::getAdditionalParticipantIds($id);
1185 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1187 if (!empty($additionalIds)) {
1188 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1189 $primaryANDAdditonalIds[$id] = $additionalIds;
1194 //get the unique participant ids,
1195 $allParticipantIds = array_unique($allParticipantIds);
1197 //pull required participants, contacts, events data, if not in hand
1198 static $eventDetails = [];
1199 static $domainValues = [];
1200 static $contactDetails = [];
1202 $contactIds = $eventIds = $participantDetails = [];
1204 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1205 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1206 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1210 //first thing is pull all necessory data from db.
1211 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1213 //get all participants data.
1214 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1215 $dao = CRM_Core_DAO
::executeQuery($query);
1216 while ($dao->fetch()) {
1217 $participantDetails[$dao->id
] = [
1219 'role' => $participantRoles[$dao->role_id
],
1220 'is_test' => $dao->is_test
,
1221 'event_id' => $dao->event_id
,
1222 'status_id' => $dao->status_id
,
1223 'fee_amount' => $dao->fee_amount
,
1224 'contact_id' => $dao->contact_id
,
1225 'register_date' => $dao->register_date
,
1226 'registered_by_id' => $dao->registered_by_id
,
1228 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1229 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1232 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1233 $eventIds[$dao->event_id
] = $dao->event_id
;
1237 //get the domain values.
1238 if (empty($domainValues)) {
1239 // making all tokens available to templates.
1240 $domain = CRM_Core_BAO_Domain
::getDomain();
1242 'domain' => ['name', 'phone', 'address', 'email'],
1243 'contact' => CRM_Core_SelectValues
::contactTokens(),
1246 foreach ($tokens['domain'] as $token) {
1247 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1251 //get all required contacts detail.
1252 if (!empty($contactIds)) {
1253 // get the contact details.
1254 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1257 'CRM_Event_BAO_Participant'
1259 foreach ($currentContactDetails as $contactId => $contactValues) {
1260 $contactDetails[$contactId] = $contactValues;
1264 //get all required events detail.
1265 if (!empty($eventIds)) {
1266 foreach ($eventIds as $eventId) {
1267 //retrieve event information
1268 $eventParams = ['id' => $eventId];
1269 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1271 //get default participant role.
1272 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1274 //get the location info
1275 $locParams = ['entity_id' => $eventId, 'entity_table' => 'civicrm_event'];
1276 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1280 //now we are ready w/ all required data.
1281 //take a decision as per statuses.
1284 $toStatus = $statusTypes[$toStatusId];
1285 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1287 switch ($toStatus) {
1288 case 'Pending from waitlist':
1289 case 'Pending from approval':
1290 switch ($fromStatus) {
1292 case 'Awaiting approval':
1293 $emailType = 'Confirm';
1299 //no matter from where u come send expired mail.
1300 $emailType = $toStatus;
1304 //no matter from where u come send cancel mail.
1305 $emailType = $toStatus;
1309 //as we process additional w/ primary, there might be case if user
1310 //select primary as well as additionals, so avoid double processing.
1311 $processedParticipantIds = [];
1312 $mailedParticipants = [];
1314 //send mails and update status.
1315 foreach ($participantDetails as $participantId => $participantValues) {
1316 $updateParticipantIds = [];
1317 if (in_array($participantId, $processedParticipantIds)) {
1321 //check is it primary and has additional.
1322 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1323 foreach ($primaryANDAdditonalIds[$participantId] as $additionalId) {
1326 $mail = self
::sendTransitionParticipantMail($additionalId,
1327 $participantDetails[$additionalId],
1328 $eventDetails[$participantDetails[$additionalId]['event_id']],
1329 $contactDetails[$participantDetails[$additionalId]['contact_id']],
1334 //get the mail participant ids
1336 $mailedParticipants[$additionalId] = $contactDetails[$participantDetails[$additionalId]['contact_id']]['display_name'];
1339 $updateParticipantIds[] = $additionalId;
1340 $processedParticipantIds[] = $additionalId;
1344 //now send email appropriate mail to primary.
1346 $mail = self
::sendTransitionParticipantMail($participantId,
1348 $eventDetails[$participantValues['event_id']],
1349 $contactDetails[$participantValues['contact_id']],
1354 //get the mail participant ids
1356 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1360 //now update status of group/one at once.
1361 $updateParticipantIds[] = $participantId;
1363 //update the register date only when we,
1364 //move participant to pending class, CRM-6496
1365 $updateRegisterDate = FALSE;
1366 if (array_key_exists($toStatusId, $pendingStatuses)) {
1367 $updateRegisterDate = TRUE;
1369 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1370 $processedParticipantIds[] = $participantId;
1373 //return result for cron.
1374 if ($returnResult) {
1376 'mailedParticipants' => $mailedParticipants,
1377 'updatedParticipantIds' => $processedParticipantIds,
1385 * Send mail and create activity
1386 * when participant status changed.
1388 * @param int $participantId
1390 * @param array $participantValues
1391 * Participant detail values. status id for participants.
1392 * @param array $eventDetails
1393 * Required event details.
1394 * @param array $contactDetails
1395 * Required contact details.
1396 * @param array $domainValues
1397 * Required domain values.
1398 * @param string $mailType
1399 * (eg 'approval', 'confirm', 'expired' ).
1403 public static function sendTransitionParticipantMail(
1414 //don't send confirmation mail to additional
1415 //since only primary able to confirm registration.
1416 if (!empty($participantValues['registered_by_id']) &&
1417 $mailType == 'Confirm'
1421 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1424 $contactId = $participantValues['contact_id'];
1425 $participantName = $contactDetails['display_name'];
1427 //calculate the checksum value.
1428 $checksumValue = NULL;
1429 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1430 $checksumLife = 'inf';
1431 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1433 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1435 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1438 //take a receipt from as event else domain.
1439 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1440 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1441 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1444 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1446 'groupName' => 'msg_tpl_workflow_event',
1447 'valueName' => 'participant_' . strtolower($mailType),
1448 'contactId' => $contactId,
1450 'contact' => $contactDetails,
1451 'domain' => $domainValues,
1452 'participant' => $participantValues,
1453 'event' => $eventDetails,
1454 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1455 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1456 'isAdditional' => $participantValues['registered_by_id'],
1457 'isExpired' => $mailType == 'Expired',
1458 'isConfirm' => $mailType == 'Confirm',
1459 'checksumValue' => $checksumValue,
1461 'from' => $receiptFrom,
1462 'toName' => $participantName,
1463 'toEmail' => $toEmail,
1464 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1465 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1469 // 3. create activity record.
1471 $now = date('YmdHis');
1472 $activityType = 'Event Registration';
1474 'subject' => $subject,
1475 'source_contact_id' => $contactId,
1476 'source_record_id' => $participantId,
1477 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1478 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1479 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1480 'is_test' => $participantValues['is_test'],
1484 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1485 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1494 * Get participant status change message.
1496 * @param int $participantId
1497 * @param $statusChangeTo
1498 * @param int $fromStatusId
1502 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1504 $results = self
::transitionParticipants([$participantId],
1505 $statusChangeTo, $fromStatusId, TRUE
1508 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1509 //give user message only when mail has sent.
1510 if (is_array($results) && !empty($results)) {
1511 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1512 foreach ($results['updatedParticipantIds'] as $processedId) {
1513 if (is_array($results['mailedParticipants']) &&
1514 array_key_exists($processedId, $results['mailedParticipants'])
1516 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1518 1 => $allStatuses[$statusChangeTo],
1519 2 => $results['mailedParticipants'][$processedId],
1531 * Get event full and waiting list message.
1533 * @param int $eventId
1534 * @param int $participantId
1538 public static function eventFullMessage($eventId, $participantId = NULL) {
1539 $eventfullMsg = $dbStatusId = NULL;
1540 $checkEventFull = TRUE;
1541 if ($participantId) {
1542 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1543 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1544 //participant already in counted status no need to check for event full messages.
1545 $checkEventFull = FALSE;
1550 if (!$eventId ||
!$checkEventFull) {
1551 return $eventfullMsg;
1554 //event is truly full.
1555 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1556 if (is_string($emptySeats) && $emptySeats !== NULL) {
1557 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1558 $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.", [
1559 1 => $maxParticipants,
1563 $hasWaiting = FALSE;
1564 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1565 if (is_numeric($waitListedCount)) {
1567 //only current processing participant is on waitlist.
1568 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1569 $hasWaiting = FALSE;
1574 $waitingStatusId = array_search('On waitlist',
1575 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1577 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1578 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1581 $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.",
1583 1 => $viewWaitListUrl,
1584 2 => $waitListedCount,
1589 return $eventfullMsg;
1593 * Check for whether participant is primary or not.
1595 * @param int $participantId
1598 * true if participant is primary
1600 public static function isPrimaryParticipant($participantId) {
1602 $participant = new CRM_Event_DAO_Participant();
1603 $participant->registered_by_id
= $participantId;
1605 if ($participant->find(TRUE)) {
1612 * Get additional participant Ids for cascading with primary participant status.
1614 * @param int $participantId
1616 * @param int $oldStatusId
1618 * @param int $newStatusId
1624 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1626 $additionalParticipantIds = [];
1628 static $participantStatuses = [];
1630 if (empty($participantStatuses)) {
1631 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1634 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1635 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1637 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1640 return $additionalParticipantIds;
1644 * Get participant record count for a Contact.
1646 * @param int $contactID
1649 * count of participant records
1651 public static function getContactParticipantCount($contactID) {
1652 $query = "SELECT count(*)
1653 FROM civicrm_participant
1654 WHERE civicrm_participant.contact_id = {$contactID} AND
1655 civicrm_participant.is_test = 0";
1656 return CRM_Core_DAO
::singleValueQuery($query);
1660 * Get participant ids by contribution id.
1662 * @param int $contributionId
1664 * @param bool $excludeCancelled
1665 * Exclude cancelled additional participant.
1669 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1672 if (!$contributionId) {
1676 // get primary participant id
1677 $query = "SELECT participant_id
1678 FROM civicrm_participant cp
1679 LEFT JOIN civicrm_participant_payment cpp ON cp.id = cpp.participant_id
1680 WHERE cpp.contribution_id = {$contributionId}
1681 AND cp.registered_by_id IS NULL";
1682 $participantPayment = CRM_Core_DAO
::executeQuery($query);
1684 // get additional participant ids (including cancelled)
1685 while ($participantPayment->fetch()) {
1686 $ids = array_merge($ids, array_merge([
1687 $participantPayment->participant_id
,
1688 ], self
::getAdditionalParticipantIds($participantPayment->participant_id
,
1697 * Get additional Participant edit & view url .
1699 * @param array $participantIds
1700 * An array of additional participant ids.
1705 public static function getAdditionalParticipantUrl($participantIds) {
1706 foreach ($participantIds as $value) {
1708 $details = self
::participantDetails($value);
1709 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1710 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1712 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1713 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1715 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1716 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1722 * create trxn entry if an event has discount.
1724 * @param int $eventID
1726 * @param array $contributionParams
1727 * Contribution params.
1729 * @param string $feeLevel (deprecated)
1730 * @param int $discountedPriceFieldOptionID
1731 * ID of the civicrm_price_field_value field for the discount id.
1733 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID = NULL) {
1734 $financialTypeID = $contributionParams['contribution']->financial_type_id
;
1735 $total_amount = $contributionParams['total_amount'];
1737 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID, 'civicrm_event');
1738 if (!empty($checkDiscount)) {
1739 $mainAmount = self
::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
1740 $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
1741 $financialTypeID, 'Discounts Account is');
1742 if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
1743 $transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
1744 $transactionParams['trxnParams']['payment_processor_id'] = NULL;
1745 $transactionParams['trxnParams']['payment_instrument_id'] = NULL;
1746 $transactionParams['trxnParams']['check_number'] = NULL;
1747 $transactionParams['trxnParams']['trxn_id'] = NULL;
1748 $transactionParams['trxnParams']['net_amount'] = NULL;
1749 $transactionParams['trxnParams']['fee_amount'] = NULL;
1750 CRM_Core_BAO_FinancialTrxn
::create($transactionParams);
1756 * Delete participants of contact.
1760 * @param int $contactId
1764 public static function deleteContactParticipant($contactId) {
1765 $participant = new CRM_Event_DAO_Participant();
1766 $participant->contact_id
= $contactId;
1767 $participant->find();
1768 while ($participant->fetch()) {
1769 self
::deleteParticipant($participant->id
);
1774 * @param int $participantId
1775 * @param $activityType
1777 * @throws CRM_Core_Exception
1779 public static function addActivityForSelection($participantId, $activityType) {
1780 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
1781 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
1783 $date = CRM_Utils_Date
::currentDBDate();
1784 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
1785 $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array
::value($eventId, $event));
1789 'source_contact_id' => $contactId,
1790 'source_record_id' => $participantId,
1791 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1792 'subject' => $subject,
1793 'activity_date_time' => $date,
1794 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1795 'skipRecentView' => TRUE,
1798 // create activity with target contacts
1799 $id = CRM_Core_Session
::singleton()->getLoggedInContactID();
1801 $activityParams['source_contact_id'] = $id;
1802 $activityParams['target_contact_id'][] = $contactId;
1804 // @todo use api & also look at duplication of similar methods.
1805 CRM_Activity_BAO_Activity
::create($activityParams);
1809 * Get options for a given field.
1810 * @see CRM_Core_DAO::buildOptions
1812 * @param string $fieldName
1813 * @param string $context
1814 * @see CRM_Core_DAO::buildOptionsContext
1815 * @param array $props
1816 * whatever is known about this dao object.
1818 * @return array|bool
1820 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1821 $params = ['condition' => []];
1823 if ($fieldName == 'status_id' && $context != 'validate') {
1824 // Get rid of cart-related option if disabled
1825 // FIXME: Why does this option even exist if cart is disabled?
1826 if (!Civi
::settings()->get('enable_cart')) {
1827 $params['condition'][] = "name <> 'Pending in cart'";
1831 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
1835 * CRM-17797 -- Format fields and setDefaults for primary and additional participants profile
1836 * @param int $contactId
1837 * @param CRM_Core_Form $form
1839 public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
1844 if (!empty($form->_fields
)) {
1845 $removeCustomFieldTypes = ['Participant'];
1847 foreach ($form->_fields
as $name => $dontCare) {
1848 if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
1849 && !CRM_Core_BAO_CustomGroup
::checkCustomField(substr($name, 7), $removeCustomFieldTypes))
1850 ||
substr($name, 0, 12) == 'participant_') {
1856 if (!empty($fields)) {
1857 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $fields, $form->_defaults
);