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
334 * @return bool|int|null|string
335 * 1. false => If event having some empty spaces.
337 public static function eventFull(
339 $returnEmptySeats = FALSE,
340 $includeWaitingList = TRUE,
341 $returnWaitingCount = FALSE,
342 $considerTestParticipant = FALSE
349 // consider event is full when.
350 // 1. (count(is_counted) >= event_size) or
351 // 2. (count(participants-with-status-on-waitlist) > 0)
352 // It might be case there are some empty spaces and still event
353 // is full, as waitlist might represent group require spaces > empty.
355 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
356 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
357 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
358 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
360 //when we do require only waiting count don't consider counted.
361 if (!$returnWaitingCount && !empty($countedStatuses)) {
362 $allStatusIds = array_keys($countedStatuses);
365 $where = [' event.id = %1 '];
366 if (!$considerTestParticipant) {
367 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
369 if (!empty($participantRoles)) {
371 foreach (array_keys($participantRoles) as $participantRole) {
372 $escapedRoles[] = CRM_Utils_Type
::escape($participantRole, 'String');
375 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', $escapedRoles) . "([[:cntrl:]]|$)";
376 $where[] = " participant.role_id REGEXP '{$regexp}'";
379 $eventParams = [1 => [$eventId, 'Positive']];
381 //in case any waiting, straight forward event is full.
382 if ($includeWaitingList && $onWaitlistStatusId) {
384 //build the where clause.
385 $whereClause = ' WHERE ' . implode(' AND ', $where);
386 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
387 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
390 SELECT participant.id id,
391 event.event_full_text as event_full_text
392 FROM civicrm_participant participant
393 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
396 $eventFullText = ts('This event is full.');
397 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
398 while ($participants->fetch()) {
399 //oops here event is full and we don't want waiting count.
400 if ($returnWaitingCount) {
401 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
404 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
409 //consider only counted participants.
410 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
411 $whereClause = ' WHERE ' . implode(' AND ', $where);
412 $eventSeatsWhere = implode(' AND ', $where);
415 SELECT participant.id id,
416 event.event_full_text as event_full_text,
417 event.max_participants as max_participants
418 FROM civicrm_participant participant
419 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
422 $eventMaxSeats = NULL;
423 $eventFullText = ts('This event is full.');
424 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
425 while ($participants->fetch()) {
426 if ($participants->event_full_text
) {
427 $eventFullText = $participants->event_full_text
;
429 $eventMaxSeats = $participants->max_participants
;
430 //don't have limit for event seats.
431 if ($participants->max_participants
== NULL) {
436 //get the total event seats occupied by these participants.
437 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
439 if ($eventRegisteredSeats) {
440 if ($eventRegisteredSeats >= $eventMaxSeats) {
441 $result = $eventFullText;
443 elseif ($returnEmptySeats) {
444 $result = $eventMaxSeats - $eventRegisteredSeats;
450 SELECT event.event_full_text,
451 event.max_participants
452 FROM civicrm_event event
453 WHERE event.id = %1';
454 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
455 while ($event->fetch()) {
456 $eventFullText = $event->event_full_text
;
457 $eventMaxSeats = $event->max_participants
;
461 // no limit for registration.
462 if ($eventMaxSeats == NULL) {
465 if ($eventMaxSeats) {
466 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
469 return $eventFullText;
473 * Return the array of all price set field options,
474 * with total participant count that field going to carry.
476 * @param int $eventId
478 * @param array $skipParticipantIds
479 * An array of participant ids those we should skip.
480 * @param bool $considerCounted
481 * @param bool $considerWaiting
482 * @param bool $considerTestParticipants
485 * an array of each option id and total count
487 public static function priceSetOptionsCount(
489 $skipParticipantIds = [],
490 $considerCounted = TRUE,
491 $considerWaiting = TRUE,
492 $considerTestParticipants = FALSE
496 return $optionsCount;
500 if ($considerCounted) {
501 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
502 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
504 if ($considerWaiting) {
505 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
506 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
508 $statusIdClause = NULL;
509 if (!empty($allStatusIds)) {
510 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
513 $isTestClause = NULL;
514 if (!$considerTestParticipants) {
515 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
518 $skipParticipantClause = NULL;
519 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
520 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
524 SELECT line.id as lineId,
525 line.entity_id as entity_id,
530 FROM civicrm_line_item line
531 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
532 AND participant.id = line.entity_id )
533 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
534 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
535 WHERE participant.event_id = %1
539 {$skipParticipantClause}";
541 $lineItem = CRM_Core_DAO
::executeQuery($sql, [1 => [$eventId, 'Positive']]);
542 while ($lineItem->fetch()) {
543 $count = $lineItem->count
;
547 if ($lineItem->html_type
== 'Text') {
548 $count *= $lineItem->qty
;
550 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
553 return $optionsCount;
557 * Get the empty spaces for event those we can allocate
558 * to pending participant to become confirm.
560 * @param int $eventId
564 * $spaces Number of Empty Seats/null.
566 public static function pendingToConfirmSpaces($eventId) {
572 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
573 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
576 SELECT count(participant.id) as registered,
577 civicrm_event.max_participants
578 FROM civicrm_participant participant, civicrm_event
579 WHERE participant.event_id = {$eventId}
580 AND civicrm_event.id = participant.event_id
581 AND participant.status_id IN {$statusIds}
582 GROUP BY participant.event_id
584 $dao = CRM_Core_DAO
::executeQuery($query);
588 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
593 if ($dao->registered
>= $dao->max_participants
) {
598 return $dao->max_participants
- $dao->registered
;
601 //space in case no registeration yet.
602 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
606 * Combine all the importable fields from the lower levels object.
608 * @param string $contactType
609 * @param bool $status
610 * @param bool $onlyParticipant
611 * @param bool $checkPermission
612 * Is this a permissioned retrieval?
615 * array of importable Fields
617 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE) {
618 if (!self
::$_importableFields) {
619 if (!$onlyParticipant) {
621 $fields = ['' => ['title' => ts('- do not import -')]];
624 $fields = ['' => ['title' => ts('- Participant Fields -')]];
631 $tmpFields = CRM_Event_DAO_Participant
::import();
634 'participant_note' => [
635 'title' => ts('Participant Note'),
636 'name' => 'participant_note',
637 'headerPattern' => '/(participant.)?note$/i',
638 'data_type' => CRM_Utils_Type
::T_TEXT
,
642 // Split status and status id into 2 fields
643 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
644 $participantStatus = [
645 'participant_status' => [
646 'title' => ts('Participant Status'),
647 'name' => 'participant_status',
648 'data_type' => CRM_Utils_Type
::T_STRING
,
651 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
653 // Split role and role id into 2 fields
654 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
656 'participant_role' => [
657 'title' => ts('Participant Role'),
658 'name' => 'participant_role',
659 'data_type' => CRM_Utils_Type
::T_STRING
,
662 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
666 'title' => ts('Event Type'),
667 'name' => 'event_type',
668 'data_type' => CRM_Utils_Type
::T_STRING
,
672 $tmpContactField = $contactFields = [];
674 if (!$onlyParticipant) {
675 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
677 // Using new Dedupe rule.
679 'contact_type' => $contactType,
680 'used' => 'Unsupervised',
682 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
684 if (is_array($fieldsArray)) {
685 foreach ($fieldsArray as $value) {
686 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
691 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
692 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
694 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
697 $title = $tmpContactField[trim($value)]['title'];
700 $tmpContactField[trim($value)]['title'] = $title;
704 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
705 if ($extIdentifier) {
706 $tmpContactField['external_identifier'] = $extIdentifier;
707 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
709 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
711 $fields = array_merge($fields, $tmpContactField);
712 $fields = array_merge($fields, $tmpFields);
713 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
714 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
716 self
::$_importableFields = $fields;
719 return self
::$_importableFields;
723 * Combine all the exportable fields from the lower level objects.
725 * @param bool $checkPermission
728 * array of exportable Fields
730 public static function &exportableFields($checkPermission = TRUE) {
731 if (!self
::$_exportableFields) {
732 if (!self
::$_exportableFields) {
733 self
::$_exportableFields = [];
736 $participantFields = CRM_Event_DAO_Participant
::export();
737 $eventFields = CRM_Event_DAO_Event
::export();
739 'participant_note' => [
740 'title' => ts('Participant Note'),
741 'name' => 'participant_note',
742 'type' => CRM_Utils_Type
::T_STRING
,
746 $participantStatus = [
747 'participant_status' => [
748 'title' => ts('Participant Status (label)'),
749 'name' => 'participant_status',
750 'type' => CRM_Utils_Type
::T_STRING
,
755 'participant_role' => [
756 'title' => ts('Participant Role (label)'),
757 'name' => 'participant_role',
758 'type' => CRM_Utils_Type
::T_STRING
,
762 $participantFields['participant_status_id']['title'] .= ' (ID)';
763 $participantFields['participant_role_id']['title'] .= ' (ID)';
765 $discountFields = CRM_Core_DAO_Discount
::export();
767 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
770 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
771 self
::$_exportableFields = $fields;
774 return self
::$_exportableFields;
778 * Get the event name/sort name for a particular participation / participant
780 * @param int $participantId
781 * Id of the participant.
784 * associated array with sort_name and event title
786 public static function participantDetails($participantId) {
788 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
789 FROM civicrm_participant
790 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
791 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
792 WHERE civicrm_participant.id = {$participantId}
794 $dao = CRM_Core_DAO
::executeQuery($query);
797 while ($dao->fetch()) {
798 $details['name'] = $dao->name
;
799 $details['title'] = $dao->title
;
800 $details['cid'] = $dao->cid
;
807 * Get the values for pseudoconstants for name->value and reverse.
809 * @param array $defaults
810 * (reference) the default values, some of which need to be resolved.
811 * @param bool $reverse
812 * True if we want to resolve the values in the reverse direction (value -> name).
814 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
815 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
816 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
817 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
821 * Convert associative array names to values and vice-versa.
823 * This function is used by both the web form layer and the api. Note that
824 * the api needs the name => value conversion, also the view layer typically
825 * requires value => name conversion
827 * @param array $defaults
828 * @param string $property
829 * @param string $lookup
830 * @param bool $reverse
834 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
835 $id = $property . '_id';
837 $src = $reverse ?
$property : $id;
838 $dst = $reverse ?
$id : $property;
840 if (!array_key_exists($src, $defaults)) {
844 $look = $reverse ?
array_flip($lookup) : $lookup;
846 if (is_array($look)) {
847 if (!array_key_exists($defaults[$src], $look)) {
851 $defaults[$dst] = $look[$defaults[$src]];
856 * Delete the records that are associated with this participation.
859 * Id of the participation to delete.
861 * @return \CRM_Event_DAO_Participant
863 public static function deleteParticipant($id) {
864 $participant = new CRM_Event_DAO_Participant();
865 $participant->id
= $id;
866 if (!$participant->find()) {
869 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
871 $transaction = new CRM_Core_Transaction();
873 //delete activity record
875 'source_record_id' => $id,
876 // activity type id for event registration
877 'activity_type_id' => 5,
880 CRM_Activity_BAO_Activity
::deleteActivity($params);
882 // delete the participant payment record
883 // we need to do this since the cascaded constraints
884 // dont work with join tables
885 $p = ['participant_id' => $id];
886 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
888 // cleanup line items.
889 $participantsId = [];
890 $participantsId = self
::getAdditionalParticipantIds($id);
891 $participantsId[] = $id;
892 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
894 //delete note when participant deleted.
895 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
896 $noteId = key($note);
898 CRM_Core_BAO_Note
::del($noteId, FALSE);
901 $participant->delete();
903 $transaction->commit();
905 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
907 // delete the recently created Participant
908 $participantRecent = [
910 'type' => 'Participant',
913 CRM_Utils_Recent
::del($participantRecent);
919 * Checks duplicate participants.
921 * @param array $input
922 * An assosiative array of name /value pairs.
923 * from other function
924 * @param array $duplicates
925 * (reference ) an assoc array of name/value pairs.
927 * @return CRM_Contribute_BAO_Contribution
929 public static function checkDuplicate($input, &$duplicates) {
930 $eventId = CRM_Utils_Array
::value('event_id', $input);
931 $contactId = CRM_Utils_Array
::value('contact_id', $input);
937 $clause[] = "event_id = %1";
938 $input[1] = [$eventId, 'Integer'];
942 $clause[] = "contact_id = %2";
943 $input[2] = [$contactId, 'Integer'];
946 if (empty($clause)) {
950 $clause = implode(' AND ', $clause);
952 $query = "SELECT id FROM civicrm_participant WHERE $clause";
953 $dao = CRM_Core_DAO
::executeQuery($query, $input);
955 while ($dao->fetch()) {
956 $duplicates[] = $dao->id
;
963 * Fix the event level.
965 * When price sets are used as event fee, fee_level is set as ^A
966 * separated string. We need to change that string to comma
967 * separated string before using fee_level in view mode.
969 * @param string $eventLevel
970 * Event_level string from db.
972 public static function fixEventLevel(&$eventLevel) {
973 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
974 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
976 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
977 $pos = strrpos($eventLevel, '(multiple participants)', 0);
979 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
982 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
983 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
984 substr($eventLevel, 0, 1)
987 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
988 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
989 substr($eventLevel, 0, -1)
995 * Get the additional participant ids.
997 * @param int $primaryParticipantId
998 * Primary partycipant Id.
999 * @param bool $excludeCancel
1000 * Do not include participant those are cancelled.
1002 * @param int $oldStatusId
1006 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1007 $additionalParticipantIds = [];
1008 if (!$primaryParticipantId) {
1009 return $additionalParticipantIds;
1012 $where = "participant.registered_by_id={$primaryParticipantId}";
1013 if ($excludeCancel) {
1014 $cancelStatusId = 0;
1015 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1016 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1017 $where .= " AND participant.status_id != {$cancelStatusId}";
1021 $where .= " AND participant.status_id = {$oldStatusId}";
1025 SELECT participant.id
1026 FROM civicrm_participant participant
1029 $dao = CRM_Core_DAO
::executeQuery($query);
1030 while ($dao->fetch()) {
1031 $additionalParticipantIds[$dao->id
] = $dao->id
;
1033 return $additionalParticipantIds;
1037 * Get the amount for the undiscounted version of the field.
1039 * Note this function is part of the refactoring process rather than the best approach.
1041 * @param int $eventID
1042 * @param int $discountedPriceFieldOptionID
1043 * @param string $feeLevel (deprecated)
1045 * @return null|string
1047 public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
1048 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1050 1 => [$priceSetId, 'Integer'],
1052 if ($discountedPriceFieldOptionID) {
1053 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1054 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1055 WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
1056 $params[2] = [$discountedPriceFieldOptionID, 'Integer'];
1059 $feeLevel = current($feeLevel);
1060 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1061 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1062 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1063 $params[2] = [$feeLevel, 'String'];
1065 return CRM_Core_DAO
::singleValueQuery($query, $params);
1069 * Get the event fee info for given participant ids
1070 * either from line item table / participant table.
1072 * @param array $participantIds
1074 * @param bool $hasLineItems
1075 * Do fetch from line items.
1079 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1081 if (!is_array($participantIds) ||
empty($participantIds)) {
1086 SELECT participant.id as id,
1087 participant.fee_level as fee_level,
1088 participant.fee_amount as fee_amount';
1089 $from = 'FROM civicrm_participant participant';
1090 if ($hasLineItems) {
1092 lineItem.id as lineId,
1093 lineItem.label as label,
1094 lineItem.qty as qty,
1095 lineItem.unit_price as unit_price,
1096 lineItem.line_total as line_total,
1097 field.label as field_title,
1098 field.html_type as html_type,
1099 field.id as price_field_id,
1100 value.id as price_field_value_id,
1101 value.description as description,
1102 IF( value.count, value.count, 0 ) as participant_count';
1104 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1105 AND lineItem.entity_id = participant.id )
1106 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1107 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1110 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1111 $query = "$select $from $where";
1113 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1114 $feeProperties = ['fee_level', 'fee_amount'];
1124 'participant_count',
1125 'price_field_value_id',
1128 while ($feeInfo->fetch()) {
1129 if ($hasLineItems) {
1130 foreach ($lineProperties as $property) {
1131 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1135 foreach ($feeProperties as $property) {
1136 $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1145 * Retrieve additional participants display-names and URL to view their participant records.
1146 * (excludes cancelled participants automatically)
1148 * @param int $primaryParticipantID
1149 * Id of primary participant record.
1152 * $displayName => $viewUrl
1154 public static function getAdditionalParticipants($primaryParticipantID) {
1155 $additionalParticipantIDs = [];
1156 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1157 if (!empty($additionalParticipantIDs)) {
1158 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1159 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1160 $additionalParticipantID,
1163 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1164 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1165 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1168 $additionalParticipants[$additionalContactName] = $pViewURL;
1171 return $additionalParticipants;
1175 * Function for update primary and additional participant status.
1177 * @param int $participantID
1178 * Primary participant's id.
1179 * @param int $oldStatusID
1180 * @param int $newStatusID
1181 * @param bool $updatePrimaryStatus
1185 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1186 if (!$participantID ||
!$oldStatusID) {
1190 if (!$newStatusID) {
1191 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1193 elseif ($updatePrimaryStatus) {
1194 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1197 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1199 if (!empty($cascadeAdditionalIds)) {
1201 foreach ($cascadeAdditionalIds as $id) {
1202 $participantParams = [
1204 'status_id' => $newStatusID,
1206 civicrm_api3('Participant', 'create', $participantParams);
1210 catch (CiviCRM_API3_Exception
$e) {
1211 throw new CRM_Core_Exception('Failed to update additional participant status in database');
1218 * Function for update status for given participant ids.
1220 * @param int $participantIds
1221 * Array of participant ids.
1222 * @param int $statusId
1223 * Status id for participant.
1224 * @param bool $updateRegisterDate
1226 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1227 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1231 //lets update register date as we update status to keep track
1232 //when we did update status, useful for moving participant
1233 //from pending to expired.
1234 $setClause = "status_id = {$statusId}";
1235 if ($updateRegisterDate) {
1236 $setClause .= ", register_date = NOW()";
1239 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1242 UPDATE civicrm_participant
1244 WHERE id IN {$participantIdClause}";
1246 $dao = CRM_Core_DAO
::executeQuery($query);
1250 * Function takes participant ids and statuses
1251 * update status from $fromStatusId to $toStatusId
1252 * and send mail + create activities.
1254 * @param array $participantIds
1256 * @param int $toStatusId
1258 * @param int $fromStatusId
1260 * @param bool $returnResult
1261 * @param bool $skipCascadeRule
1263 * @return array|NULL
1265 public static function transitionParticipants(
1266 $participantIds, $toStatusId,
1267 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1269 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1273 //thumb rule is if we triggering primary participant need to triggered additional
1274 $allParticipantIds = $primaryANDAdditonalIds = [];
1275 foreach ($participantIds as $id) {
1276 $allParticipantIds[] = $id;
1277 if (self
::isPrimaryParticipant($id)) {
1278 //filter additional as per status transition rules, CRM-5403
1279 if ($skipCascadeRule) {
1280 $additionalIds = self
::getAdditionalParticipantIds($id);
1283 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1285 if (!empty($additionalIds)) {
1286 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1287 $primaryANDAdditonalIds[$id] = $additionalIds;
1292 //get the unique participant ids,
1293 $allParticipantIds = array_unique($allParticipantIds);
1295 //pull required participants, contacts, events data, if not in hand
1296 static $eventDetails = [];
1297 static $domainValues = [];
1298 static $contactDetails = [];
1300 $contactIds = $eventIds = $participantDetails = [];
1302 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1303 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1304 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1308 //first thing is pull all necessory data from db.
1309 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1311 //get all participants data.
1312 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1313 $dao = CRM_Core_DAO
::executeQuery($query);
1314 while ($dao->fetch()) {
1315 $participantDetails[$dao->id
] = [
1317 'role' => $participantRoles[$dao->role_id
],
1318 'is_test' => $dao->is_test
,
1319 'event_id' => $dao->event_id
,
1320 'status_id' => $dao->status_id
,
1321 'fee_amount' => $dao->fee_amount
,
1322 'contact_id' => $dao->contact_id
,
1323 'register_date' => $dao->register_date
,
1324 'registered_by_id' => $dao->registered_by_id
,
1326 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1327 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1330 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1331 $eventIds[$dao->event_id
] = $dao->event_id
;
1335 //get the domain values.
1336 if (empty($domainValues)) {
1337 // making all tokens available to templates.
1338 $domain = CRM_Core_BAO_Domain
::getDomain();
1340 'domain' => ['name', 'phone', 'address', 'email'],
1341 'contact' => CRM_Core_SelectValues
::contactTokens(),
1344 foreach ($tokens['domain'] as $token) {
1345 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1349 //get all required contacts detail.
1350 if (!empty($contactIds)) {
1351 // get the contact details.
1352 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1355 'CRM_Event_BAO_Participant'
1357 foreach ($currentContactDetails as $contactId => $contactValues) {
1358 $contactDetails[$contactId] = $contactValues;
1362 //get all required events detail.
1363 if (!empty($eventIds)) {
1364 foreach ($eventIds as $eventId) {
1365 //retrieve event information
1366 $eventParams = ['id' => $eventId];
1367 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1369 //get default participant role.
1370 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1372 //get the location info
1373 $locParams = ['entity_id' => $eventId, 'entity_table' => 'civicrm_event'];
1374 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1378 //now we are ready w/ all required data.
1379 //take a decision as per statuses.
1382 $toStatus = $statusTypes[$toStatusId];
1383 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1385 switch ($toStatus) {
1386 case 'Pending from waitlist':
1387 case 'Pending from approval':
1388 switch ($fromStatus) {
1390 case 'Awaiting approval':
1391 $emailType = 'Confirm';
1397 //no matter from where u come send expired mail.
1398 $emailType = $toStatus;
1402 //no matter from where u come send cancel mail.
1403 $emailType = $toStatus;
1407 //as we process additional w/ primary, there might be case if user
1408 //select primary as well as additionals, so avoid double processing.
1409 $processedParticipantIds = [];
1410 $mailedParticipants = [];
1412 //send mails and update status.
1413 foreach ($participantDetails as $participantId => $participantValues) {
1414 $updateParticipantIds = [];
1415 if (in_array($participantId, $processedParticipantIds)) {
1419 //check is it primary and has additional.
1420 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1421 foreach ($primaryANDAdditonalIds[$participantId] as $additionalId) {
1424 $mail = self
::sendTransitionParticipantMail($additionalId,
1425 $participantDetails[$additionalId],
1426 $eventDetails[$participantDetails[$additionalId]['event_id']],
1427 $contactDetails[$participantDetails[$additionalId]['contact_id']],
1432 //get the mail participant ids
1434 $mailedParticipants[$additionalId] = $contactDetails[$participantDetails[$additionalId]['contact_id']]['display_name'];
1437 $updateParticipantIds[] = $additionalId;
1438 $processedParticipantIds[] = $additionalId;
1442 //now send email appropriate mail to primary.
1444 $mail = self
::sendTransitionParticipantMail($participantId,
1446 $eventDetails[$participantValues['event_id']],
1447 $contactDetails[$participantValues['contact_id']],
1452 //get the mail participant ids
1454 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1458 //now update status of group/one at once.
1459 $updateParticipantIds[] = $participantId;
1461 //update the register date only when we,
1462 //move participant to pending class, CRM-6496
1463 $updateRegisterDate = FALSE;
1464 if (array_key_exists($toStatusId, $pendingStatuses)) {
1465 $updateRegisterDate = TRUE;
1467 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1468 $processedParticipantIds[] = $participantId;
1471 //return result for cron.
1472 if ($returnResult) {
1474 'mailedParticipants' => $mailedParticipants,
1475 'updatedParticipantIds' => $processedParticipantIds,
1483 * Send mail and create activity
1484 * when participant status changed.
1486 * @param int $participantId
1488 * @param array $participantValues
1489 * Participant detail values. status id for participants.
1490 * @param array $eventDetails
1491 * Required event details.
1492 * @param array $contactDetails
1493 * Required contact details.
1494 * @param array $domainValues
1495 * Required domain values.
1496 * @param string $mailType
1497 * (eg 'approval', 'confirm', 'expired' ).
1501 public static function sendTransitionParticipantMail(
1512 //don't send confirmation mail to additional
1513 //since only primary able to confirm registration.
1514 if (!empty($participantValues['registered_by_id']) &&
1515 $mailType == 'Confirm'
1519 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1522 $contactId = $participantValues['contact_id'];
1523 $participantName = $contactDetails['display_name'];
1525 //calculate the checksum value.
1526 $checksumValue = NULL;
1527 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1528 $checksumLife = 'inf';
1529 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1531 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1533 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1536 //take a receipt from as event else domain.
1537 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1538 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1539 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1542 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1544 'groupName' => 'msg_tpl_workflow_event',
1545 'valueName' => 'participant_' . strtolower($mailType),
1546 'contactId' => $contactId,
1548 'contact' => $contactDetails,
1549 'domain' => $domainValues,
1550 'participant' => $participantValues,
1551 'event' => $eventDetails,
1552 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1553 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1554 'isAdditional' => $participantValues['registered_by_id'],
1555 'isExpired' => $mailType == 'Expired',
1556 'isConfirm' => $mailType == 'Confirm',
1557 'checksumValue' => $checksumValue,
1559 'from' => $receiptFrom,
1560 'toName' => $participantName,
1561 'toEmail' => $toEmail,
1562 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1563 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1567 // 3. create activity record.
1569 $now = date('YmdHis');
1570 $activityType = 'Event Registration';
1572 'subject' => $subject,
1573 'source_contact_id' => $contactId,
1574 'source_record_id' => $participantId,
1575 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1576 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1577 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1578 'is_test' => $participantValues['is_test'],
1582 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1583 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1592 * Get participant status change message.
1594 * @param int $participantId
1595 * @param $statusChangeTo
1596 * @param int $fromStatusId
1600 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1602 $results = self
::transitionParticipants([$participantId],
1603 $statusChangeTo, $fromStatusId, TRUE
1606 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1607 //give user message only when mail has sent.
1608 if (is_array($results) && !empty($results)) {
1609 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1610 foreach ($results['updatedParticipantIds'] as $processedId) {
1611 if (is_array($results['mailedParticipants']) &&
1612 array_key_exists($processedId, $results['mailedParticipants'])
1614 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1616 1 => $allStatuses[$statusChangeTo],
1617 2 => $results['mailedParticipants'][$processedId],
1629 * Get event full and waiting list message.
1631 * @param int $eventId
1632 * @param int $participantId
1636 public static function eventFullMessage($eventId, $participantId = NULL) {
1637 $eventfullMsg = $dbStatusId = NULL;
1638 $checkEventFull = TRUE;
1639 if ($participantId) {
1640 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1641 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1642 //participant already in counted status no need to check for event full messages.
1643 $checkEventFull = FALSE;
1648 if (!$eventId ||
!$checkEventFull) {
1649 return $eventfullMsg;
1652 //event is truly full.
1653 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1654 if (is_string($emptySeats) && $emptySeats !== NULL) {
1655 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1656 $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.", [
1657 1 => $maxParticipants,
1661 $hasWaiting = FALSE;
1662 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1663 if (is_numeric($waitListedCount)) {
1665 //only current processing participant is on waitlist.
1666 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1667 $hasWaiting = FALSE;
1672 $waitingStatusId = array_search('On waitlist',
1673 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1675 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1676 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1679 $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.",
1681 1 => $viewWaitListUrl,
1682 2 => $waitListedCount,
1687 return $eventfullMsg;
1691 * Check for whether participant is primary or not.
1693 * @param int $participantId
1696 * true if participant is primary
1698 public static function isPrimaryParticipant($participantId) {
1700 $participant = new CRM_Event_DAO_Participant();
1701 $participant->registered_by_id
= $participantId;
1703 if ($participant->find(TRUE)) {
1710 * Get additional participant Ids for cascading with primary participant status.
1712 * @param int $participantId
1714 * @param int $oldStatusId
1716 * @param int $newStatusId
1722 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1724 $additionalParticipantIds = [];
1726 static $participantStatuses = [];
1728 if (empty($participantStatuses)) {
1729 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1732 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1733 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1735 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1738 return $additionalParticipantIds;
1742 * Get participant record count for a Contact.
1744 * @param int $contactID
1747 * count of participant records
1749 public static function getContactParticipantCount($contactID) {
1750 $query = "SELECT count(*)
1751 FROM civicrm_participant
1752 WHERE civicrm_participant.contact_id = {$contactID} AND
1753 civicrm_participant.is_test = 0";
1754 return CRM_Core_DAO
::singleValueQuery($query);
1758 * Get participant ids by contribution id.
1760 * @param int $contributionId
1762 * @param bool $excludeCancelled
1763 * Exclude cancelled additional participant.
1767 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1770 if (!$contributionId) {
1774 // get primary participant id
1775 $query = "SELECT participant_id
1776 FROM civicrm_participant cp
1777 LEFT JOIN civicrm_participant_payment cpp ON cp.id = cpp.participant_id
1778 WHERE cpp.contribution_id = {$contributionId}
1779 AND cp.registered_by_id IS NULL";
1780 $participantPayment = CRM_Core_DAO
::executeQuery($query);
1782 // get additional participant ids (including cancelled)
1783 while ($participantPayment->fetch()) {
1784 $ids = array_merge($ids, array_merge([
1785 $participantPayment->participant_id
,
1786 ], self
::getAdditionalParticipantIds($participantPayment->participant_id
,
1795 * Get additional Participant edit & view url .
1797 * @param array $participantIds
1798 * An array of additional participant ids.
1803 public static function getAdditionalParticipantUrl($participantIds) {
1804 foreach ($participantIds as $value) {
1806 $details = self
::participantDetails($value);
1807 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1808 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1810 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1811 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1813 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1814 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1820 * create trxn entry if an event has discount.
1822 * @param int $eventID
1824 * @param array $contributionParams
1825 * Contribution params.
1827 * @param string $feeLevel (deprecated)
1828 * @param int $discountedPriceFieldOptionID
1829 * ID of the civicrm_price_field_value field for the discount id.
1831 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID = NULL) {
1832 $financialTypeID = $contributionParams['contribution']->financial_type_id
;
1833 $total_amount = $contributionParams['total_amount'];
1835 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID, 'civicrm_event');
1836 if (!empty($checkDiscount)) {
1837 $mainAmount = self
::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
1838 $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
1839 $financialTypeID, 'Discounts Account is');
1840 if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
1841 $transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
1842 $transactionParams['trxnParams']['payment_processor_id'] = NULL;
1843 $transactionParams['trxnParams']['payment_instrument_id'] = NULL;
1844 $transactionParams['trxnParams']['check_number'] = NULL;
1845 $transactionParams['trxnParams']['trxn_id'] = NULL;
1846 $transactionParams['trxnParams']['net_amount'] = NULL;
1847 $transactionParams['trxnParams']['fee_amount'] = NULL;
1848 CRM_Core_BAO_FinancialTrxn
::create($transactionParams);
1854 * Delete participants of contact.
1858 * @param int $contactId
1862 public static function deleteContactParticipant($contactId) {
1863 $participant = new CRM_Event_DAO_Participant();
1864 $participant->contact_id
= $contactId;
1865 $participant->find();
1866 while ($participant->fetch()) {
1867 self
::deleteParticipant($participant->id
);
1872 * @param int $participantId
1873 * @param $activityType
1875 * @throws CRM_Core_Exception
1877 public static function addActivityForSelection($participantId, $activityType) {
1878 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
1879 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
1881 $date = CRM_Utils_Date
::currentDBDate();
1882 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
1883 $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array
::value($eventId, $event));
1887 'source_contact_id' => $contactId,
1888 'source_record_id' => $participantId,
1889 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1890 'subject' => $subject,
1891 'activity_date_time' => $date,
1892 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1893 'skipRecentView' => TRUE,
1896 // create activity with target contacts
1897 $id = CRM_Core_Session
::singleton()->getLoggedInContactID();
1899 $activityParams['source_contact_id'] = $id;
1900 $activityParams['target_contact_id'][] = $contactId;
1902 // @todo use api & also look at duplication of similar methods.
1903 CRM_Activity_BAO_Activity
::create($activityParams);
1907 * Get options for a given field.
1908 * @see CRM_Core_DAO::buildOptions
1910 * @param string $fieldName
1911 * @param string $context
1912 * @see CRM_Core_DAO::buildOptionsContext
1913 * @param array $props
1914 * whatever is known about this dao object.
1916 * @return array|bool
1918 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1919 $params = ['condition' => []];
1921 if ($fieldName == 'status_id' && $context != 'validate') {
1922 // Get rid of cart-related option if disabled
1923 // FIXME: Why does this option even exist if cart is disabled?
1924 if (!Civi
::settings()->get('enable_cart')) {
1925 $params['condition'][] = "name <> 'Pending in cart'";
1929 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
1933 * CRM-17797 -- Format fields and setDefaults for primary and additional participants profile
1934 * @param int $contactId
1935 * @param CRM_Core_Form $form
1937 public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
1942 if (!empty($form->_fields
)) {
1943 $removeCustomFieldTypes = ['Participant'];
1945 foreach ($form->_fields
as $name => $dontCare) {
1946 if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
1947 && !CRM_Core_BAO_CustomGroup
::checkCustomField(substr($name, 7), $removeCustomFieldTypes))
1948 ||
substr($name, 0, 12) == 'participant_') {
1954 if (!empty($fields)) {
1955 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $fields, $form->_defaults
);