3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Event_BAO_Participant
extends CRM_Event_DAO_Participant
{
36 * Static field for all the participant information that we can potentially import.
40 public static $_importableFields = NULL;
43 * Static field for all the participant information that we can potentially export.
47 public static $_exportableFields = NULL;
50 * Static array for valid status transitions rules.
54 public static $_statusTransitionsRules = [
55 'Pending from pay later' => ['Registered', 'Cancelled'],
56 'Pending from incomplete transaction' => ['Registered', 'Cancelled'],
57 'On waitlist' => ['Cancelled', 'Pending from waitlist'],
58 'Pending from waitlist' => ['Registered', 'Cancelled'],
59 'Awaiting approval' => ['Cancelled', 'Pending from approval'],
60 'Pending from approval' => ['Registered', 'Cancelled'],
65 public function __construct() {
66 parent
::__construct();
70 * Takes an associative array and creates a participant object.
72 * the function extract all the params it needs to initialize the create a
73 * participant object. the params array could contain additional unused name/value
76 * @param array $params
77 * (reference ) an assoc array of name/value pairs.
79 * @return CRM_Event_BAO_Participant
81 public static function &add(&$params) {
83 if (!empty($params['id'])) {
84 CRM_Utils_Hook
::pre('edit', 'Participant', $params['id'], $params);
87 CRM_Utils_Hook
::pre('create', 'Participant', NULL, $params);
90 // converting dates to mysql format
91 if (!empty($params['register_date'])) {
92 $params['register_date'] = CRM_Utils_Date
::isoToMysql($params['register_date']);
95 if (!empty($params['participant_fee_amount'])) {
96 $params['participant_fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['participant_fee_amount']);
99 if (!empty($params['fee_amount'])) {
100 $params['fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['fee_amount']);
103 // ensure that role ids are encoded as a string
104 if (isset($params['role_id']) && is_array($params['role_id'])) {
105 if (in_array(key($params['role_id']), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
106 $op = key($params['role_id']);
107 $params['role_id'] = $params['role_id'][$op];
110 $params['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['role_id']);
114 $participantBAO = new CRM_Event_BAO_Participant();
115 if (!empty($params['id'])) {
116 $participantBAO->id
= CRM_Utils_Array
::value('id', $params);
117 $participantBAO->find(TRUE);
118 $participantBAO->register_date
= CRM_Utils_Date
::isoToMysql($participantBAO->register_date
);
121 $participantBAO->copyValues($params);
124 //1. If currency present, it should be valid one.
125 //2. We should have currency when amount is not null.
126 $currency = $participantBAO->fee_currency
;
128 !CRM_Utils_System
::isNull($participantBAO->fee_amount
)
130 if (!CRM_Utils_Rule
::currencyCode($currency)) {
131 $config = CRM_Core_Config
::singleton();
132 $currency = $config->defaultCurrency
;
135 $participantBAO->fee_currency
= $currency;
137 $participantBAO->save();
139 // reset the group contact cache for this group
141 // CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
143 if (!empty($params['id'])) {
144 CRM_Utils_Hook
::post('edit', 'Participant', $participantBAO->id
, $participantBAO);
147 CRM_Utils_Hook
::post('create', 'Participant', $participantBAO->id
, $participantBAO);
150 return $participantBAO;
154 * Given the list of params in the params array, fetch the object
155 * and store the values in the values array
157 * @param array $params
158 * Input parameters to find object.
159 * @param array $values
160 * Output values of the object.
164 * @return CRM_Event_BAO_Participant|null the found object or null
166 public static function getValues(&$params, &$values, &$ids) {
167 if (empty($params)) {
170 $participant = new CRM_Event_BAO_Participant();
171 $participant->copyValues($params);
172 $participant->find();
174 while ($participant->fetch()) {
175 $ids['participant'] = $participant->id
;
176 CRM_Core_DAO
::storeValues($participant, $values[$participant->id
]);
177 $participants[$participant->id
] = $participant;
179 return $participants;
183 * Takes an associative array and creates a participant object.
185 * @param array $params
186 * (reference ) an assoc array of name/value pairs.
188 * @return CRM_Event_BAO_Participant
190 public static function create(&$params) {
192 $transaction = new CRM_Core_Transaction();
195 if (!empty($params['id'])) {
196 $status = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
199 $participant = self
::add($params);
201 if (is_a($participant, 'CRM_Core_Error')) {
202 $transaction->rollback();
206 // Log activity when creating new participant or changing status
207 if (empty($params['id']) ||
208 (isset($params['status_id']) && $params['status_id'] != $status)
210 // Default status if not specified
211 $participant->status_id
= $participant->status_id ?
: self
::fields()['participant_status_id']['default'];
212 CRM_Activity_BAO_Activity
::addActivity($participant);
217 if (self
::isPrimaryParticipant($participant->id
) && $status) {
218 self
::updateParticipantStatus($participant->id
, $status, $participant->status_id
);
221 $session = CRM_Core_Session
::singleton();
222 $id = $session->get('userID');
224 $id = CRM_Utils_Array
::value('contact_id', $params);
227 // add custom field values
228 if (!empty($params['custom']) &&
229 is_array($params['custom'])
231 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_participant', $participant->id
);
234 //process note, CRM-7634
236 if (!empty($params['id'])) {
237 $note = CRM_Core_BAO_Note
::getNote($params['id'], 'civicrm_participant');
238 $noteId = key($note);
241 $hasNoteField = FALSE;
246 if (array_key_exists($noteFld, $params)) {
247 $noteValue = $params[$noteFld];
248 $hasNoteField = TRUE;
252 if ($noteId ||
$noteValue) {
255 'entity_table' => 'civicrm_participant',
256 'note' => $noteValue,
257 'entity_id' => $participant->id
,
259 'modified_date' => date('Ymd'),
263 $noteIDs['id'] = $noteId;
265 CRM_Core_BAO_Note
::add($noteParams, $noteIDs);
267 elseif ($noteId && $hasNoteField) {
268 CRM_Core_BAO_Note
::del($noteId, FALSE);
272 // Log the information on successful add/edit of Participant data.
274 'entity_table' => 'civicrm_participant',
275 'entity_id' => $participant->id
,
276 'data' => CRM_Event_PseudoConstant
::participantStatus($participant->status_id
),
277 'modified_id' => $id,
278 'modified_date' => date('Ymd'),
281 CRM_Core_BAO_Log
::add($logParams);
283 $params['participant_id'] = $participant->id
;
285 $transaction->commit();
287 // do not add to recent items for import, CRM-4399
288 if (empty($params['skipRecentView'])) {
290 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
291 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
295 if (CRM_Core_Permission
::check('edit event participants')) {
296 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
297 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
300 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
301 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
302 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
306 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
308 if ($participant->role_id
) {
309 $role = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participant->role_id
);
311 foreach ($role as & $roleValue) {
312 if (isset($roleValue)) {
313 $roleValue = $participantRoles[$roleValue];
316 $roles = implode(', ', $role);
319 $roleString = empty($roles) ?
'' : $roles;
320 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $participant->event_id
, 'title');
321 $title = CRM_Contact_BAO_Contact
::displayName($participant->contact_id
) . ' (' . $roleString . ' - ' . $eventTitle . ')';
323 // add the recently created Participant
324 CRM_Utils_Recent
::add($title,
328 $participant->contact_id
,
338 * Check whether the event is full for participation and return as.
341 * @param int $eventId
343 * @param bool $returnEmptySeats
344 * Are we require number if empty seats.
345 * @param bool $includeWaitingList
346 * Consider waiting list in event full.
347 * calculation or not. (it is for cron job purpose)
349 * @param bool $returnWaitingCount
350 * @param bool $considerTestParticipant
352 * @return bool|int|null|string
353 * 1. false => If event having some empty spaces.
355 public static function eventFull(
357 $returnEmptySeats = FALSE,
358 $includeWaitingList = TRUE,
359 $returnWaitingCount = FALSE,
360 $considerTestParticipant = FALSE
367 // consider event is full when.
368 // 1. (count(is_counted) >= event_size) or
369 // 2. (count(participants-with-status-on-waitlist) > 0)
370 // It might be case there are some empty spaces and still event
371 // is full, as waitlist might represent group require spaces > empty.
373 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
374 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
375 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
376 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
378 //when we do require only waiting count don't consider counted.
379 if (!$returnWaitingCount && !empty($countedStatuses)) {
380 $allStatusIds = array_keys($countedStatuses);
383 $where = [' event.id = %1 '];
384 if (!$considerTestParticipant) {
385 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
387 if (!empty($participantRoles)) {
389 foreach (array_keys($participantRoles) as $participantRole) {
390 $escapedRoles[] = CRM_Utils_Type
::escape($participantRole, 'String');
393 $where[] = " participant.role_id IN ( '" . implode("', '", $escapedRoles) . "' ) ";
396 $eventParams = [1 => [$eventId, 'Positive']];
398 //in case any waiting, straight forward event is full.
399 if ($includeWaitingList && $onWaitlistStatusId) {
401 //build the where clause.
402 $whereClause = ' WHERE ' . implode(' AND ', $where);
403 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
404 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
407 SELECT participant.id id,
408 event.event_full_text as event_full_text
409 FROM civicrm_participant participant
410 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
413 $eventFullText = ts('This event is full.');
414 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
415 while ($participants->fetch()) {
416 //oops here event is full and we don't want waiting count.
417 if ($returnWaitingCount) {
418 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
421 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
426 //consider only counted participants.
427 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
428 $whereClause = ' WHERE ' . implode(' AND ', $where);
429 $eventSeatsWhere = implode(' AND ', $where);
432 SELECT participant.id id,
433 event.event_full_text as event_full_text,
434 event.max_participants as max_participants
435 FROM civicrm_participant participant
436 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
439 $eventMaxSeats = NULL;
440 $eventFullText = ts('This event is full.');
441 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
442 while ($participants->fetch()) {
443 if ($participants->event_full_text
) {
444 $eventFullText = $participants->event_full_text
;
446 $eventMaxSeats = $participants->max_participants
;
447 //don't have limit for event seats.
448 if ($participants->max_participants
== NULL) {
453 //get the total event seats occupied by these participants.
454 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
456 if ($eventRegisteredSeats) {
457 if ($eventRegisteredSeats >= $eventMaxSeats) {
458 $result = $eventFullText;
460 elseif ($returnEmptySeats) {
461 $result = $eventMaxSeats - $eventRegisteredSeats;
467 SELECT event.event_full_text,
468 event.max_participants
469 FROM civicrm_event event
470 WHERE event.id = %1';
471 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
472 while ($event->fetch()) {
473 $eventFullText = $event->event_full_text
;
474 $eventMaxSeats = $event->max_participants
;
478 // no limit for registration.
479 if ($eventMaxSeats == NULL) {
482 if ($eventMaxSeats) {
483 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
486 return $eventFullText;
490 * Return the array of all price set field options,
491 * with total participant count that field going to carry.
493 * @param int $eventId
495 * @param array $skipParticipantIds
496 * An array of participant ids those we should skip.
497 * @param bool $considerCounted
498 * @param bool $considerWaiting
499 * @param bool $considerTestParticipants
502 * an array of each option id and total count
504 public static function priceSetOptionsCount(
506 $skipParticipantIds = [],
507 $considerCounted = TRUE,
508 $considerWaiting = TRUE,
509 $considerTestParticipants = FALSE
513 return $optionsCount;
517 if ($considerCounted) {
518 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
519 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
521 if ($considerWaiting) {
522 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
523 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
525 $statusIdClause = NULL;
526 if (!empty($allStatusIds)) {
527 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
530 $isTestClause = NULL;
531 if (!$considerTestParticipants) {
532 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
535 $skipParticipantClause = NULL;
536 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
537 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
541 SELECT line.id as lineId,
542 line.entity_id as entity_id,
547 FROM civicrm_line_item line
548 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
549 AND participant.id = line.entity_id )
550 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
551 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
552 WHERE participant.event_id = %1
556 {$skipParticipantClause}";
558 $lineItem = CRM_Core_DAO
::executeQuery($sql, [1 => [$eventId, 'Positive']]);
559 while ($lineItem->fetch()) {
560 $count = $lineItem->count
;
564 if ($lineItem->html_type
== 'Text') {
565 $count *= $lineItem->qty
;
567 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
570 return $optionsCount;
574 * Get the empty spaces for event those we can allocate
575 * to pending participant to become confirm.
577 * @param int $eventId
581 * $spaces Number of Empty Seats/null.
583 public static function pendingToConfirmSpaces($eventId) {
589 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
590 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
593 SELECT count(participant.id) as registered,
594 civicrm_event.max_participants
595 FROM civicrm_participant participant, civicrm_event
596 WHERE participant.event_id = {$eventId}
597 AND civicrm_event.id = participant.event_id
598 AND participant.status_id IN {$statusIds}
599 GROUP BY participant.event_id
601 $dao = CRM_Core_DAO
::executeQuery($query);
605 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
610 if ($dao->registered
>= $dao->max_participants
) {
615 return $dao->max_participants
- $dao->registered
;
618 //space in case no registeration yet.
619 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
623 * Combine all the importable fields from the lower levels object.
625 * @param string $contactType
626 * @param bool $status
627 * @param bool $onlyParticipant
628 * @param bool $checkPermission
629 * Is this a permissioned retrieval?
632 * array of importable Fields
634 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE) {
635 if (!self
::$_importableFields) {
636 if (!$onlyParticipant) {
638 $fields = ['' => ['title' => ts('- do not import -')]];
641 $fields = ['' => ['title' => ts('- Participant Fields -')]];
648 $tmpFields = CRM_Event_DAO_Participant
::import();
651 'participant_note' => [
652 'title' => ts('Participant Note'),
653 'name' => 'participant_note',
654 'headerPattern' => '/(participant.)?note$/i',
655 'data_type' => CRM_Utils_Type
::T_TEXT
,
659 // Split status and status id into 2 fields
660 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
661 $participantStatus = [
662 'participant_status' => [
663 'title' => ts('Participant Status'),
664 'name' => 'participant_status',
665 'data_type' => CRM_Utils_Type
::T_STRING
,
668 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
670 // Split role and role id into 2 fields
671 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
673 'participant_role' => [
674 'title' => ts('Participant Role'),
675 'name' => 'participant_role',
676 'data_type' => CRM_Utils_Type
::T_STRING
,
679 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
683 'title' => ts('Event Type'),
684 'name' => 'event_type',
685 'data_type' => CRM_Utils_Type
::T_STRING
,
689 $tmpContactField = $contactFields = [];
691 if (!$onlyParticipant) {
692 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
694 // Using new Dedupe rule.
696 'contact_type' => $contactType,
697 'used' => 'Unsupervised',
699 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
701 if (is_array($fieldsArray)) {
702 foreach ($fieldsArray as $value) {
703 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
708 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
709 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
711 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
714 $title = $tmpContactField[trim($value)]['title'];
717 $tmpContactField[trim($value)]['title'] = $title;
721 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
722 if ($extIdentifier) {
723 $tmpContactField['external_identifier'] = $extIdentifier;
724 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
726 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
728 $fields = array_merge($fields, $tmpContactField);
729 $fields = array_merge($fields, $tmpFields);
730 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
731 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
733 self
::$_importableFields = $fields;
736 return self
::$_importableFields;
740 * Combine all the exportable fields from the lower level objects.
742 * @param bool $checkPermission
745 * array of exportable Fields
747 public static function &exportableFields($checkPermission = TRUE) {
748 if (!self
::$_exportableFields) {
749 if (!self
::$_exportableFields) {
750 self
::$_exportableFields = [];
753 $participantFields = CRM_Event_DAO_Participant
::export();
754 $eventFields = CRM_Event_DAO_Event
::export();
756 'participant_note' => [
757 'title' => ts('Participant Note'),
758 'name' => 'participant_note',
759 'type' => CRM_Utils_Type
::T_STRING
,
763 $participantStatus = [
764 'participant_status' => [
765 'title' => ts('Participant Status (label)'),
766 'name' => 'participant_status',
767 'type' => CRM_Utils_Type
::T_STRING
,
772 'participant_role' => [
773 'title' => ts('Participant Role (label)'),
774 'name' => 'participant_role',
775 'type' => CRM_Utils_Type
::T_STRING
,
779 $participantFields['participant_status_id']['title'] .= ' (ID)';
780 $participantFields['participant_role_id']['title'] .= ' (ID)';
782 $discountFields = CRM_Core_DAO_Discount
::export();
784 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
787 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
788 self
::$_exportableFields = $fields;
791 return self
::$_exportableFields;
795 * Get the event name/sort name for a particular participation / participant
797 * @param int $participantId
798 * Id of the participant.
801 * associated array with sort_name and event title
803 public static function participantDetails($participantId) {
805 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
806 FROM civicrm_participant
807 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
808 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
809 WHERE civicrm_participant.id = {$participantId}
811 $dao = CRM_Core_DAO
::executeQuery($query);
814 while ($dao->fetch()) {
815 $details['name'] = $dao->name
;
816 $details['title'] = $dao->title
;
817 $details['cid'] = $dao->cid
;
824 * Get the values for pseudoconstants for name->value and reverse.
826 * @param array $defaults
827 * (reference) the default values, some of which need to be resolved.
828 * @param bool $reverse
829 * True if we want to resolve the values in the reverse direction (value -> name).
831 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
832 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
833 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
834 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
838 * Convert associative array names to values and vice-versa.
840 * This function is used by both the web form layer and the api. Note that
841 * the api needs the name => value conversion, also the view layer typically
842 * requires value => name conversion
844 * @param array $defaults
845 * @param string $property
846 * @param string $lookup
847 * @param bool $reverse
851 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
852 $id = $property . '_id';
854 $src = $reverse ?
$property : $id;
855 $dst = $reverse ?
$id : $property;
857 if (!array_key_exists($src, $defaults)) {
861 $look = $reverse ?
array_flip($lookup) : $lookup;
863 if (is_array($look)) {
864 if (!array_key_exists($defaults[$src], $look)) {
868 $defaults[$dst] = $look[$defaults[$src]];
873 * Delete the records that are associated with this participation.
876 * Id of the participation to delete.
878 * @return \CRM_Event_DAO_Participant
880 public static function deleteParticipant($id) {
881 $participant = new CRM_Event_DAO_Participant();
882 $participant->id
= $id;
883 if (!$participant->find()) {
886 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
888 $transaction = new CRM_Core_Transaction();
890 //delete activity record
892 'source_record_id' => $id,
893 // activity type id for event registration
894 'activity_type_id' => 5,
897 CRM_Activity_BAO_Activity
::deleteActivity($params);
899 // delete the participant payment record
900 // we need to do this since the cascaded constraints
901 // dont work with join tables
902 $p = ['participant_id' => $id];
903 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
905 // cleanup line items.
906 $participantsId = [];
907 $participantsId = self
::getAdditionalParticipantIds($id);
908 $participantsId[] = $id;
909 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
911 //delete note when participant deleted.
912 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
913 $noteId = key($note);
915 CRM_Core_BAO_Note
::del($noteId, FALSE);
918 $participant->delete();
920 $transaction->commit();
922 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
924 // delete the recently created Participant
925 $participantRecent = [
927 'type' => 'Participant',
930 CRM_Utils_Recent
::del($participantRecent);
936 * Checks duplicate participants.
938 * @param array $input
939 * An assosiative array of name /value pairs.
940 * from other function
941 * @param array $duplicates
942 * (reference ) an assoc array of name/value pairs.
944 * @return CRM_Contribute_BAO_Contribution
946 public static function checkDuplicate($input, &$duplicates) {
947 $eventId = CRM_Utils_Array
::value('event_id', $input);
948 $contactId = CRM_Utils_Array
::value('contact_id', $input);
954 $clause[] = "event_id = %1";
955 $input[1] = [$eventId, 'Integer'];
959 $clause[] = "contact_id = %2";
960 $input[2] = [$contactId, 'Integer'];
963 if (empty($clause)) {
967 $clause = implode(' AND ', $clause);
969 $query = "SELECT id FROM civicrm_participant WHERE $clause";
970 $dao = CRM_Core_DAO
::executeQuery($query, $input);
972 while ($dao->fetch()) {
973 $duplicates[] = $dao->id
;
980 * Fix the event level.
982 * When price sets are used as event fee, fee_level is set as ^A
983 * separated string. We need to change that string to comma
984 * separated string before using fee_level in view mode.
986 * @param string $eventLevel
987 * Event_level string from db.
989 public static function fixEventLevel(&$eventLevel) {
990 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
991 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
993 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
994 $pos = strrpos($eventLevel, '(multiple participants)', 0);
996 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
999 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1000 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1001 substr($eventLevel, 0, 1)
1004 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1005 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1006 substr($eventLevel, 0, -1)
1012 * Get the additional participant ids.
1014 * @param int $primaryParticipantId
1015 * Primary partycipant Id.
1016 * @param bool $excludeCancel
1017 * Do not include participant those are cancelled.
1019 * @param int $oldStatusId
1023 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1024 $additionalParticipantIds = [];
1025 if (!$primaryParticipantId) {
1026 return $additionalParticipantIds;
1029 $where = "participant.registered_by_id={$primaryParticipantId}";
1030 if ($excludeCancel) {
1031 $cancelStatusId = 0;
1032 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1033 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1034 $where .= " AND participant.status_id != {$cancelStatusId}";
1038 $where .= " AND participant.status_id = {$oldStatusId}";
1042 SELECT participant.id
1043 FROM civicrm_participant participant
1046 $dao = CRM_Core_DAO
::executeQuery($query);
1047 while ($dao->fetch()) {
1048 $additionalParticipantIds[$dao->id
] = $dao->id
;
1050 return $additionalParticipantIds;
1054 * Get the amount for the undiscounted version of the field.
1056 * Note this function is part of the refactoring process rather than the best approach.
1058 * @param int $eventID
1059 * @param int $discountedPriceFieldOptionID
1060 * @param string $feeLevel (deprecated)
1062 * @return null|string
1064 public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
1065 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1067 1 => [$priceSetId, 'Integer'],
1069 if ($discountedPriceFieldOptionID) {
1070 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1071 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1072 WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
1073 $params[2] = [$discountedPriceFieldOptionID, 'Integer'];
1076 $feeLevel = current($feeLevel);
1077 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1078 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1079 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1080 $params[2] = [$feeLevel, 'String'];
1082 return CRM_Core_DAO
::singleValueQuery($query, $params);
1086 * Get the event fee info for given participant ids
1087 * either from line item table / participant table.
1089 * @param array $participantIds
1091 * @param bool $hasLineItems
1092 * Do fetch from line items.
1096 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1098 if (!is_array($participantIds) ||
empty($participantIds)) {
1103 SELECT participant.id as id,
1104 participant.fee_level as fee_level,
1105 participant.fee_amount as fee_amount';
1106 $from = 'FROM civicrm_participant participant';
1107 if ($hasLineItems) {
1109 lineItem.id as lineId,
1110 lineItem.label as label,
1111 lineItem.qty as qty,
1112 lineItem.unit_price as unit_price,
1113 lineItem.line_total as line_total,
1114 field.label as field_title,
1115 field.html_type as html_type,
1116 field.id as price_field_id,
1117 value.id as price_field_value_id,
1118 value.description as description,
1119 IF( value.count, value.count, 0 ) as participant_count';
1121 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1122 AND lineItem.entity_id = participant.id )
1123 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1124 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1127 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1128 $query = "$select $from $where";
1130 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1131 $feeProperties = ['fee_level', 'fee_amount'];
1141 'participant_count',
1142 'price_field_value_id',
1145 while ($feeInfo->fetch()) {
1146 if ($hasLineItems) {
1147 foreach ($lineProperties as $property) {
1148 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1152 foreach ($feeProperties as $property) {
1153 $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1162 * Retrieve additional participants display-names and URL to view their participant records.
1163 * (excludes cancelled participants automatically)
1165 * @param int $primaryParticipantID
1166 * Id of primary participant record.
1169 * $displayName => $viewUrl
1171 public static function getAdditionalParticipants($primaryParticipantID) {
1172 $additionalParticipantIDs = [];
1173 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1174 if (!empty($additionalParticipantIDs)) {
1175 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1176 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1177 $additionalParticipantID,
1180 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1181 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1182 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1185 $additionalParticipants[$additionalContactName] = $pViewURL;
1188 return $additionalParticipants;
1192 * Function for update primary and additional participant status.
1194 * @param int $participantID
1195 * Primary participant's id.
1196 * @param int $oldStatusID
1197 * @param int $newStatusID
1198 * @param bool $updatePrimaryStatus
1202 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1203 if (!$participantID ||
!$oldStatusID) {
1207 if (!$newStatusID) {
1208 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1210 elseif ($updatePrimaryStatus) {
1211 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1214 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1216 if (!empty($cascadeAdditionalIds)) {
1218 foreach ($cascadeAdditionalIds as $id) {
1219 $participantParams = [
1221 'status_id' => $newStatusID,
1223 civicrm_api3('Participant', 'create', $participantParams);
1227 catch (CiviCRM_API3_Exception
$e) {
1228 throw new CRM_Core_Exception('Failed to update additional participant status in database');
1235 * Function for update status for given participant ids.
1237 * @param int $participantIds
1238 * Array of participant ids.
1239 * @param int $statusId
1240 * Status id for participant.
1241 * @param bool $updateRegisterDate
1243 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1244 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1248 //lets update register date as we update status to keep track
1249 //when we did update status, useful for moving participant
1250 //from pending to expired.
1251 $setClause = "status_id = {$statusId}";
1252 if ($updateRegisterDate) {
1253 $setClause .= ", register_date = NOW()";
1256 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1259 UPDATE civicrm_participant
1261 WHERE id IN {$participantIdClause}";
1263 $dao = CRM_Core_DAO
::executeQuery($query);
1267 * Function takes participant ids and statuses
1268 * update status from $fromStatusId to $toStatusId
1269 * and send mail + create activities.
1271 * @param array $participantIds
1273 * @param int $toStatusId
1275 * @param int $fromStatusId
1277 * @param bool $returnResult
1278 * @param bool $skipCascadeRule
1280 * @return array|NULL
1282 public static function transitionParticipants(
1283 $participantIds, $toStatusId,
1284 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1286 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1290 //thumb rule is if we triggering primary participant need to triggered additional
1291 $allParticipantIds = $primaryANDAdditonalIds = [];
1292 foreach ($participantIds as $id) {
1293 $allParticipantIds[] = $id;
1294 if (self
::isPrimaryParticipant($id)) {
1295 //filter additional as per status transition rules, CRM-5403
1296 if ($skipCascadeRule) {
1297 $additionalIds = self
::getAdditionalParticipantIds($id);
1300 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1302 if (!empty($additionalIds)) {
1303 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1304 $primaryANDAdditonalIds[$id] = $additionalIds;
1309 //get the unique participant ids,
1310 $allParticipantIds = array_unique($allParticipantIds);
1312 //pull required participants, contacts, events data, if not in hand
1313 static $eventDetails = [];
1314 static $domainValues = [];
1315 static $contactDetails = [];
1317 $contactIds = $eventIds = $participantDetails = [];
1319 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1320 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1321 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1325 //first thing is pull all necessory data from db.
1326 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1328 //get all participants data.
1329 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1330 $dao = CRM_Core_DAO
::executeQuery($query);
1331 while ($dao->fetch()) {
1332 $participantDetails[$dao->id
] = [
1334 'role' => $participantRoles[$dao->role_id
],
1335 'is_test' => $dao->is_test
,
1336 'event_id' => $dao->event_id
,
1337 'status_id' => $dao->status_id
,
1338 'fee_amount' => $dao->fee_amount
,
1339 'contact_id' => $dao->contact_id
,
1340 'register_date' => $dao->register_date
,
1341 'registered_by_id' => $dao->registered_by_id
,
1343 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1344 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1347 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1348 $eventIds[$dao->event_id
] = $dao->event_id
;
1352 //get the domain values.
1353 if (empty($domainValues)) {
1354 // making all tokens available to templates.
1355 $domain = CRM_Core_BAO_Domain
::getDomain();
1357 'domain' => ['name', 'phone', 'address', 'email'],
1358 'contact' => CRM_Core_SelectValues
::contactTokens(),
1361 foreach ($tokens['domain'] as $token) {
1362 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1366 //get all required contacts detail.
1367 if (!empty($contactIds)) {
1368 // get the contact details.
1369 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1372 'CRM_Event_BAO_Participant'
1374 foreach ($currentContactDetails as $contactId => $contactValues) {
1375 $contactDetails[$contactId] = $contactValues;
1379 //get all required events detail.
1380 if (!empty($eventIds)) {
1381 foreach ($eventIds as $eventId) {
1382 //retrieve event information
1383 $eventParams = ['id' => $eventId];
1384 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1386 //get default participant role.
1387 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1389 //get the location info
1390 $locParams = ['entity_id' => $eventId, 'entity_table' => 'civicrm_event'];
1391 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1395 //now we are ready w/ all required data.
1396 //take a decision as per statuses.
1399 $toStatus = $statusTypes[$toStatusId];
1400 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1402 switch ($toStatus) {
1403 case 'Pending from waitlist':
1404 case 'Pending from approval':
1405 switch ($fromStatus) {
1407 case 'Awaiting approval':
1408 $emailType = 'Confirm';
1414 //no matter from where u come send expired mail.
1415 $emailType = $toStatus;
1419 //no matter from where u come send cancel mail.
1420 $emailType = $toStatus;
1424 //as we process additional w/ primary, there might be case if user
1425 //select primary as well as additionals, so avoid double processing.
1426 $processedParticipantIds = [];
1427 $mailedParticipants = [];
1429 //send mails and update status.
1430 foreach ($participantDetails as $participantId => $participantValues) {
1431 $updateParticipantIds = [];
1432 if (in_array($participantId, $processedParticipantIds)) {
1436 //check is it primary and has additional.
1437 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1438 foreach ($primaryANDAdditonalIds[$participantId] as $additionalId) {
1441 $mail = self
::sendTransitionParticipantMail($additionalId,
1442 $participantDetails[$additionalId],
1443 $eventDetails[$participantDetails[$additionalId]['event_id']],
1444 $contactDetails[$participantDetails[$additionalId]['contact_id']],
1449 //get the mail participant ids
1451 $mailedParticipants[$additionalId] = $contactDetails[$participantDetails[$additionalId]['contact_id']]['display_name'];
1454 $updateParticipantIds[] = $additionalId;
1455 $processedParticipantIds[] = $additionalId;
1459 //now send email appropriate mail to primary.
1461 $mail = self
::sendTransitionParticipantMail($participantId,
1463 $eventDetails[$participantValues['event_id']],
1464 $contactDetails[$participantValues['contact_id']],
1469 //get the mail participant ids
1471 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1475 //now update status of group/one at once.
1476 $updateParticipantIds[] = $participantId;
1478 //update the register date only when we,
1479 //move participant to pending class, CRM-6496
1480 $updateRegisterDate = FALSE;
1481 if (array_key_exists($toStatusId, $pendingStatuses)) {
1482 $updateRegisterDate = TRUE;
1484 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1485 $processedParticipantIds[] = $participantId;
1488 //return result for cron.
1489 if ($returnResult) {
1491 'mailedParticipants' => $mailedParticipants,
1492 'updatedParticipantIds' => $processedParticipantIds,
1500 * Send mail and create activity
1501 * when participant status changed.
1503 * @param int $participantId
1505 * @param array $participantValues
1506 * Participant detail values. status id for participants.
1507 * @param array $eventDetails
1508 * Required event details.
1509 * @param array $contactDetails
1510 * Required contact details.
1511 * @param array $domainValues
1512 * Required domain values.
1513 * @param string $mailType
1514 * (eg 'approval', 'confirm', 'expired' ).
1518 public static function sendTransitionParticipantMail(
1529 //don't send confirmation mail to additional
1530 //since only primary able to confirm registration.
1531 if (!empty($participantValues['registered_by_id']) &&
1532 $mailType == 'Confirm'
1536 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1539 $contactId = $participantValues['contact_id'];
1540 $participantName = $contactDetails['display_name'];
1542 //calculate the checksum value.
1543 $checksumValue = NULL;
1544 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1545 $checksumLife = 'inf';
1546 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1548 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1550 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1553 //take a receipt from as event else domain.
1554 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1555 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1556 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1559 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1561 'groupName' => 'msg_tpl_workflow_event',
1562 'valueName' => 'participant_' . strtolower($mailType),
1563 'contactId' => $contactId,
1565 'contact' => $contactDetails,
1566 'domain' => $domainValues,
1567 'participant' => $participantValues,
1568 'event' => $eventDetails,
1569 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1570 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1571 'isAdditional' => $participantValues['registered_by_id'],
1572 'isExpired' => $mailType == 'Expired',
1573 'isConfirm' => $mailType == 'Confirm',
1574 'checksumValue' => $checksumValue,
1576 'from' => $receiptFrom,
1577 'toName' => $participantName,
1578 'toEmail' => $toEmail,
1579 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1580 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1584 // 3. create activity record.
1586 $now = date('YmdHis');
1587 $activityType = 'Event Registration';
1589 'subject' => $subject,
1590 'source_contact_id' => $contactId,
1591 'source_record_id' => $participantId,
1592 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1593 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1594 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1595 'is_test' => $participantValues['is_test'],
1599 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1600 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1609 * Get participant status change message.
1611 * @param int $participantId
1612 * @param $statusChangeTo
1613 * @param int $fromStatusId
1617 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1619 $results = self
::transitionParticipants([$participantId],
1620 $statusChangeTo, $fromStatusId, TRUE
1623 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1624 //give user message only when mail has sent.
1625 if (is_array($results) && !empty($results)) {
1626 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1627 foreach ($results['updatedParticipantIds'] as $processedId) {
1628 if (is_array($results['mailedParticipants']) &&
1629 array_key_exists($processedId, $results['mailedParticipants'])
1631 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1633 1 => $allStatuses[$statusChangeTo],
1634 2 => $results['mailedParticipants'][$processedId],
1646 * Get event full and waiting list message.
1648 * @param int $eventId
1649 * @param int $participantId
1653 public static function eventFullMessage($eventId, $participantId = NULL) {
1654 $eventfullMsg = $dbStatusId = NULL;
1655 $checkEventFull = TRUE;
1656 if ($participantId) {
1657 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1658 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1659 //participant already in counted status no need to check for event full messages.
1660 $checkEventFull = FALSE;
1665 if (!$eventId ||
!$checkEventFull) {
1666 return $eventfullMsg;
1669 //event is truly full.
1670 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1671 if (is_string($emptySeats) && $emptySeats !== NULL) {
1672 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1673 $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.", [
1674 1 => $maxParticipants,
1678 $hasWaiting = FALSE;
1679 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1680 if (is_numeric($waitListedCount)) {
1682 //only current processing participant is on waitlist.
1683 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1684 $hasWaiting = FALSE;
1689 $waitingStatusId = array_search('On waitlist',
1690 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1692 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1693 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1696 $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.",
1698 1 => $viewWaitListUrl,
1699 2 => $waitListedCount,
1704 return $eventfullMsg;
1708 * Check for whether participant is primary or not.
1710 * @param int $participantId
1713 * true if participant is primary
1715 public static function isPrimaryParticipant($participantId) {
1717 $participant = new CRM_Event_DAO_Participant();
1718 $participant->registered_by_id
= $participantId;
1720 if ($participant->find(TRUE)) {
1727 * Get additional participant Ids for cascading with primary participant status.
1729 * @param int $participantId
1731 * @param int $oldStatusId
1733 * @param int $newStatusId
1739 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1741 $additionalParticipantIds = [];
1743 static $participantStatuses = [];
1745 if (empty($participantStatuses)) {
1746 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1749 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1750 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1752 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1755 return $additionalParticipantIds;
1759 * Get participant record count for a Contact.
1761 * @param int $contactID
1764 * count of participant records
1766 public static function getContactParticipantCount($contactID) {
1767 $query = "SELECT count(*)
1768 FROM civicrm_participant
1769 WHERE civicrm_participant.contact_id = {$contactID} AND
1770 civicrm_participant.is_test = 0";
1771 return CRM_Core_DAO
::singleValueQuery($query);
1775 * Get participant ids by contribution id.
1777 * @param int $contributionId
1779 * @param bool $excludeCancelled
1780 * Exclude cancelled additional participant.
1784 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1787 if (!$contributionId) {
1791 // get primary participant id
1792 $query = "SELECT participant_id
1793 FROM civicrm_participant cp
1794 LEFT JOIN civicrm_participant_payment cpp ON cp.id = cpp.participant_id
1795 WHERE cpp.contribution_id = {$contributionId}
1796 AND cp.registered_by_id IS NULL";
1797 $participantPayment = CRM_Core_DAO
::executeQuery($query);
1799 // get additional participant ids (including cancelled)
1800 while ($participantPayment->fetch()) {
1801 $ids = array_merge($ids, array_merge([
1802 $participantPayment->participant_id
,
1803 ], self
::getAdditionalParticipantIds($participantPayment->participant_id
,
1812 * Get additional Participant edit & view url .
1814 * @param array $participantIds
1815 * An array of additional participant ids.
1820 public static function getAdditionalParticipantUrl($participantIds) {
1821 foreach ($participantIds as $value) {
1823 $details = self
::participantDetails($value);
1824 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1825 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1827 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1828 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1830 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1831 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1837 * create trxn entry if an event has discount.
1839 * @param int $eventID
1841 * @param array $contributionParams
1842 * Contribution params.
1844 * @param string $feeLevel (deprecated)
1845 * @param int $discountedPriceFieldOptionID
1846 * ID of the civicrm_price_field_value field for the discount id.
1848 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID = NULL) {
1849 $financialTypeID = $contributionParams['contribution']->financial_type_id
;
1850 $total_amount = $contributionParams['total_amount'];
1852 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID, 'civicrm_event');
1853 if (!empty($checkDiscount)) {
1854 $mainAmount = self
::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
1855 $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
1856 $financialTypeID, 'Discounts Account is');
1857 if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
1858 $transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
1859 $transactionParams['trxnParams']['payment_processor_id'] = NULL;
1860 $transactionParams['trxnParams']['payment_instrument_id'] = NULL;
1861 $transactionParams['trxnParams']['check_number'] = NULL;
1862 $transactionParams['trxnParams']['trxn_id'] = NULL;
1863 $transactionParams['trxnParams']['net_amount'] = NULL;
1864 $transactionParams['trxnParams']['fee_amount'] = NULL;
1865 CRM_Core_BAO_FinancialTrxn
::create($transactionParams);
1871 * Delete participants of contact.
1875 * @param int $contactId
1879 public static function deleteContactParticipant($contactId) {
1880 $participant = new CRM_Event_DAO_Participant();
1881 $participant->contact_id
= $contactId;
1882 $participant->find();
1883 while ($participant->fetch()) {
1884 self
::deleteParticipant($participant->id
);
1889 * @param int $participantId
1890 * @param $activityType
1892 * @throws CRM_Core_Exception
1894 public static function addActivityForSelection($participantId, $activityType) {
1895 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
1896 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
1898 $date = CRM_Utils_Date
::currentDBDate();
1899 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
1900 $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array
::value($eventId, $event));
1904 'source_contact_id' => $contactId,
1905 'source_record_id' => $participantId,
1906 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1907 'subject' => $subject,
1908 'activity_date_time' => $date,
1909 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1910 'skipRecentView' => TRUE,
1913 // create activity with target contacts
1914 $id = CRM_Core_Session
::singleton()->getLoggedInContactID();;
1916 $activityParams['source_contact_id'] = $id;
1917 $activityParams['target_contact_id'][] = $contactId;
1919 // @todo use api & also look at duplication of similar methods.
1920 CRM_Activity_BAO_Activity
::create($activityParams);
1924 * Get options for a given field.
1925 * @see CRM_Core_DAO::buildOptions
1927 * @param string $fieldName
1928 * @param string $context
1929 * @see CRM_Core_DAO::buildOptionsContext
1930 * @param array $props
1931 * whatever is known about this dao object.
1933 * @return array|bool
1935 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1936 $params = ['condition' => []];
1938 if ($fieldName == 'status_id' && $context != 'validate') {
1939 // Get rid of cart-related option if disabled
1940 // FIXME: Why does this option even exist if cart is disabled?
1941 if (!Civi
::settings()->get('enable_cart')) {
1942 $params['condition'][] = "name <> 'Pending in cart'";
1946 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
1950 * CRM-17797 -- Format fields and setDefaults for primary and additional participants profile
1951 * @param int $contactId
1952 * @param CRM_Core_Form $form
1954 public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
1959 if (!empty($form->_fields
)) {
1960 $removeCustomFieldTypes = ['Participant'];
1962 foreach ($form->_fields
as $name => $dontCare) {
1963 if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
1964 && !CRM_Core_BAO_CustomGroup
::checkCustomField(substr($name, 7), $removeCustomFieldTypes))
1965 ||
substr($name, 0, 12) == 'participant_') {
1971 if (!empty($fields)) {
1972 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $fields, $form->_defaults
);