Merge pull request #23709 from eileenmcnaughton/buttons
[civicrm-core.git] / CRM / Event / BAO / Participant.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10
11 */
12
13 /**
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Event_BAO_Participant extends CRM_Event_DAO_Participant {
18
19 /**
20 * Static field for all the participant information that we can potentially import.
21 *
22 * @var array
23 */
24 public static $_importableFields = NULL;
25
26 /**
27 * Static field for all the participant information that we can potentially export.
28 *
29 * @var array
30 */
31 public static $_exportableFields = NULL;
32
33 /**
34 * Static array for valid status transitions rules.
35 *
36 * @var array
37 */
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'],
45 ];
46
47 /**
48 * Takes an associative array and creates a participant object.
49 *
50 * the function extract all the params it needs to initialize the create a
51 * participant object. the params array could contain additional unused name/value
52 * pairs
53 *
54 * @param array $params
55 * (reference ) an assoc array of name/value pairs.
56 *
57 * @return CRM_Event_BAO_Participant
58 */
59 public static function &add(&$params) {
60
61 if (!empty($params['id'])) {
62 CRM_Utils_Hook::pre('edit', 'Participant', $params['id'], $params);
63 }
64 else {
65 CRM_Utils_Hook::pre('create', 'Participant', NULL, $params);
66 }
67
68 // converting dates to mysql format
69 if (!empty($params['register_date'])) {
70 $params['register_date'] = CRM_Utils_Date::isoToMysql($params['register_date']);
71 }
72
73 if (!empty($params['participant_fee_amount'])) {
74 $params['participant_fee_amount'] = CRM_Utils_Rule::cleanMoney($params['participant_fee_amount']);
75 }
76
77 // ensure that role ids are encoded as a string
78 if (isset($params['role_id']) && is_array($params['role_id'])) {
79 if (in_array(key($params['role_id']), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
80 $op = key($params['role_id']);
81 $params['role_id'] = $params['role_id'][$op];
82 }
83 else {
84 $params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
85 }
86 }
87
88 $participantBAO = new CRM_Event_BAO_Participant();
89 if (!empty($params['id'])) {
90 $participantBAO->id = $params['id'] ?? NULL;
91 $participantBAO->find(TRUE);
92 $participantBAO->register_date = CRM_Utils_Date::isoToMysql($participantBAO->register_date);
93 }
94
95 $participantBAO->copyValues($params);
96
97 //CRM-6910
98 //1. If currency present, it should be valid one.
99 //2. We should have currency when amount is not null.
100 $currency = $participantBAO->fee_currency;
101 if ($currency ||
102 !CRM_Utils_System::isNull($participantBAO->fee_amount)
103 ) {
104 if (!CRM_Utils_Rule::currencyCode($currency)) {
105 $config = CRM_Core_Config::singleton();
106 $currency = $config->defaultCurrency;
107 }
108 }
109 $participantBAO->fee_currency = $currency;
110
111 $participantBAO->save();
112
113 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
114
115 if (!empty($params['id'])) {
116 CRM_Utils_Hook::post('edit', 'Participant', $participantBAO->id, $participantBAO);
117 }
118 else {
119 CRM_Utils_Hook::post('create', 'Participant', $participantBAO->id, $participantBAO);
120 }
121
122 return $participantBAO;
123 }
124
125 /**
126 * Given the list of params in the params array, fetch the object
127 * and store the values in the values array
128 *
129 * @param array $params
130 * Input parameters to find object.
131 * @param array $values
132 * Output values of the object.
133 *
134 * @param $ids
135 *
136 * @return CRM_Event_BAO_Participant|null the found object or null
137 */
138 public static function getValues(&$params, &$values = [], &$ids = []) {
139 if (empty($params)) {
140 return NULL;
141 }
142 $participant = new CRM_Event_BAO_Participant();
143 $participant->copyValues($params);
144 $participant->find();
145 $participants = [];
146 while ($participant->fetch()) {
147 $ids['participant'] = $participant->id;
148 CRM_Core_DAO::storeValues($participant, $values[$participant->id]);
149 $participants[$participant->id] = $participant;
150 }
151 return $participants;
152 }
153
154 /**
155 * Takes an associative array and creates a participant object.
156 *
157 * @param array $params
158 * (reference ) an assoc array of name/value pairs.
159 *
160 * @return CRM_Event_BAO_Participant
161 */
162 public static function create(&$params) {
163
164 $transaction = new CRM_Core_Transaction();
165 $status = NULL;
166
167 if (!empty($params['id'])) {
168 $status = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
169 }
170
171 $participant = self::add($params);
172
173 if (is_a($participant, 'CRM_Core_Error')) {
174 $transaction->rollback();
175 return $participant;
176 }
177
178 // Log activity when creating new participant or changing status
179 if (empty($params['id']) ||
180 (isset($params['status_id']) && $params['status_id'] != $status)
181 ) {
182 // Default status if not specified
183 $participant->status_id = $participant->status_id ?: self::fields()['participant_status_id']['default'];
184 CRM_Activity_BAO_Activity::addActivity($participant, 'Event Registration');
185 }
186
187 //CRM-5403
188 //for update mode
189 if (self::isPrimaryParticipant($participant->id) && $status) {
190 self::updateParticipantStatus($participant->id, $status, $participant->status_id);
191 }
192
193 $session = CRM_Core_Session::singleton();
194 $id = $session->get('userID');
195 if (!$id) {
196 $id = $params['contact_id'] ?? NULL;
197 }
198
199 // add custom field values
200 if (!empty($params['custom']) &&
201 is_array($params['custom'])
202 ) {
203 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_participant', $participant->id);
204 }
205
206 //process note, CRM-7634
207 $noteId = NULL;
208 if (!empty($params['id'])) {
209 $note = CRM_Core_BAO_Note::getNote($params['id'], 'civicrm_participant');
210 $noteId = key($note);
211 }
212 $noteValue = NULL;
213 $hasNoteField = FALSE;
214 foreach ([
215 'note',
216 'participant_note',
217 ] as $noteFld) {
218 if (array_key_exists($noteFld, $params)) {
219 $noteValue = $params[$noteFld];
220 $hasNoteField = TRUE;
221 break;
222 }
223 }
224 if ($noteId || $noteValue) {
225 if ($noteValue) {
226 $noteParams = [
227 'entity_table' => 'civicrm_participant',
228 'note' => $noteValue,
229 'entity_id' => $participant->id,
230 'contact_id' => $id,
231 ];
232 $noteIDs = [];
233 if ($noteId) {
234 $noteIDs['id'] = $noteId;
235 }
236 CRM_Core_BAO_Note::add($noteParams, $noteIDs);
237 }
238 elseif ($noteId && $hasNoteField) {
239 CRM_Core_BAO_Note::deleteRecord(['id' => $noteId]);
240 }
241 }
242
243 // Log the information on successful add/edit of Participant data.
244 $logParams = [
245 'entity_table' => 'civicrm_participant',
246 'entity_id' => $participant->id,
247 'data' => CRM_Event_PseudoConstant::participantStatus($participant->status_id),
248 'modified_id' => $id,
249 'modified_date' => date('Ymd'),
250 ];
251
252 CRM_Core_BAO_Log::add($logParams);
253
254 $params['participant_id'] = $participant->id;
255
256 $transaction->commit();
257
258 // do not add to recent items for import, CRM-4399
259 if (empty($params['skipRecentView'])) {
260
261 $url = CRM_Utils_System::url('civicrm/contact/view/participant',
262 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
263 );
264
265 $recentOther = [];
266 if (CRM_Core_Permission::check('edit event participants')) {
267 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
268 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
269 );
270 }
271 if (CRM_Core_Permission::check('delete in CiviEvent')) {
272 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
273 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
274 );
275 }
276
277 $participantRoles = CRM_Event_PseudoConstant::participantRole();
278
279 if ($participant->role_id) {
280 $role = explode(CRM_Core_DAO::VALUE_SEPARATOR, $participant->role_id);
281
282 foreach ($role as & $roleValue) {
283 if (isset($roleValue)) {
284 $roleValue = $participantRoles[$roleValue];
285 }
286 }
287 $roles = implode(', ', $role);
288 }
289
290 $roleString = empty($roles) ? '' : $roles;
291 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $participant->event_id, 'title');
292 $title = CRM_Contact_BAO_Contact::displayName($participant->contact_id) . ' (' . $roleString . ' - ' . $eventTitle . ')';
293
294 // add the recently created Participant
295 CRM_Utils_Recent::add($title,
296 $url,
297 $participant->id,
298 'Participant',
299 $participant->contact_id,
300 NULL,
301 $recentOther
302 );
303 }
304
305 return $participant;
306 }
307
308 /**
309 * Check whether the event is full for participation and return as.
310 * per requirements.
311 *
312 * @param int $eventId
313 * Event id.
314 * @param bool $returnEmptySeats
315 * Are we require number if empty seats.
316 * @param bool $includeWaitingList
317 * Consider waiting list in event full.
318 * calculation or not. (it is for cron job purpose)
319 *
320 * @param bool $returnWaitingCount
321 * @param bool $considerTestParticipant
322 * When TRUE, include participant records where is_test = 1.
323 * @param bool $onlyPositiveStatuses
324 * When FALSE, count all participant statuses where is_counted = 1. This includes
325 * both "Positive" participants (Registered, Attended, etc.) and waitlisted
326 * (and some pending) participants.
327 * When TRUE, count only participants with statuses of "Positive".
328 *
329 * @return bool|int|null|string
330 * 1. false => If event having some empty spaces.
331 */
332 public static function eventFull(
333 $eventId,
334 $returnEmptySeats = FALSE,
335 $includeWaitingList = TRUE,
336 $returnWaitingCount = FALSE,
337 $considerTestParticipant = FALSE,
338 $onlyPositiveStatuses = FALSE
339 ) {
340 $result = NULL;
341 if (!$eventId) {
342 return $result;
343 }
344
345 // consider event is full when.
346 // 1. (count(is_counted) >= event_size) or
347 // 2. (count(participants-with-status-on-waitlist) > 0)
348 // It might be case there are some empty spaces and still event
349 // is full, as waitlist might represent group require spaces > empty.
350
351 $participantRoles = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
352 $countedStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
353 $positiveStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Positive'");
354 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
355 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
356
357 $where = [' event.id = %1 '];
358 if (!$considerTestParticipant) {
359 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
360 }
361
362 // Only count Participant Roles with the "Counted?" flag.
363 if (!empty($participantRoles)) {
364 $escapedRoles = [];
365 foreach (array_keys($participantRoles) as $participantRole) {
366 $escapedRoles[] = CRM_Utils_Type::escape($participantRole, 'String');
367 }
368
369 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', $escapedRoles) . "([[:cntrl:]]|$)";
370 $where[] = " participant.role_id REGEXP '{$regexp}'";
371 }
372
373 $eventParams = [1 => [$eventId, 'Positive']];
374
375 //in case any waiting, straight forward event is full.
376 if ($includeWaitingList && $onWaitlistStatusId) {
377
378 //build the where clause.
379 $whereClause = ' WHERE ' . implode(' AND ', $where);
380 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
381 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
382
383 $query = "
384 SELECT participant.id id,
385 event.event_full_text as event_full_text
386 FROM civicrm_participant participant
387 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
388 {$whereClause}";
389
390 $eventFullText = ts('This event is full.');
391 $participants = CRM_Core_DAO::executeQuery($query, $eventParams);
392 while ($participants->fetch()) {
393 //oops here event is full and we don't want waiting count.
394 if ($returnWaitingCount) {
395 return CRM_Event_BAO_Event::eventTotalSeats($eventId, $eventSeatsWhere);
396 }
397 else {
398 return ($participants->event_full_text) ? $participants->event_full_text : $eventFullText;
399 }
400 }
401 }
402
403 //Consider only counted participants, or alternatively only registered (not on waitlist) participants.
404 if ($onlyPositiveStatuses) {
405 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($positiveStatuses)) . ' ) ';
406 }
407 else {
408 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
409 }
410 $whereClause = ' WHERE ' . implode(' AND ', $where);
411 $eventSeatsWhere = implode(' AND ', $where);
412
413 $query = "
414 SELECT participant.id id,
415 event.event_full_text as event_full_text,
416 event.max_participants as max_participants
417 FROM civicrm_participant participant
418 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
419 {$whereClause}";
420
421 $eventMaxSeats = NULL;
422 $eventFullText = ts('This event is full.');
423 $participants = CRM_Core_DAO::executeQuery($query, $eventParams);
424 while ($participants->fetch()) {
425 if ($participants->event_full_text) {
426 $eventFullText = $participants->event_full_text;
427 }
428 $eventMaxSeats = $participants->max_participants;
429 //don't have limit for event seats.
430 if ($participants->max_participants == NULL) {
431 return $result;
432 }
433 }
434
435 //get the total event seats occupied by these participants.
436 $eventRegisteredSeats = CRM_Event_BAO_Event::eventTotalSeats($eventId, $eventSeatsWhere);
437
438 if ($eventRegisteredSeats) {
439 if ($eventRegisteredSeats >= $eventMaxSeats) {
440 $result = $eventFullText;
441 }
442 elseif ($returnEmptySeats) {
443 $result = $eventMaxSeats - $eventRegisteredSeats;
444 }
445 return $result;
446 }
447 else {
448 $query = '
449 SELECT event.event_full_text,
450 event.max_participants
451 FROM civicrm_event event
452 WHERE event.id = %1';
453 $event = CRM_Core_DAO::executeQuery($query, $eventParams);
454 while ($event->fetch()) {
455 $eventFullText = $event->event_full_text;
456 $eventMaxSeats = $event->max_participants;
457 }
458 }
459
460 // no limit for registration.
461 if ($eventMaxSeats == NULL) {
462 return $result;
463 }
464 if ($eventMaxSeats) {
465 return ($returnEmptySeats) ? (int) $eventMaxSeats : FALSE;
466 }
467
468 return $eventFullText;
469 }
470
471 /**
472 * Return the array of all price set field options,
473 * with total participant count that field going to carry.
474 *
475 * @param int $eventId
476 * Event id.
477 * @param array $skipParticipantIds
478 * An array of participant ids those we should skip.
479 * @param bool $considerCounted
480 * @param bool $considerWaiting
481 * @param bool $considerTestParticipants
482 *
483 * @return array
484 * an array of each option id and total count
485 */
486 public static function priceSetOptionsCount(
487 $eventId,
488 $skipParticipantIds = [],
489 $considerCounted = TRUE,
490 $considerWaiting = TRUE,
491 $considerTestParticipants = FALSE
492 ) {
493 $optionsCount = [];
494 if (!$eventId) {
495 return $optionsCount;
496 }
497
498 $allStatusIds = [];
499 if ($considerCounted) {
500 $countedStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
501 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
502 }
503 if ($considerWaiting) {
504 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
505 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
506 }
507 $statusIdClause = NULL;
508 if (!empty($allStatusIds)) {
509 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
510 }
511
512 $isTestClause = NULL;
513 if (!$considerTestParticipants) {
514 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
515 }
516
517 $skipParticipantClause = NULL;
518 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
519 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
520 }
521
522 $sql = "
523 SELECT line.id as lineId,
524 line.entity_id as entity_id,
525 line.qty,
526 value.id as valueId,
527 value.count,
528 field.html_type
529 FROM civicrm_line_item line
530 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
531 AND participant.id = line.entity_id )
532 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
533 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
534 WHERE participant.event_id = %1
535 AND line.qty > 0
536 {$statusIdClause}
537 {$isTestClause}
538 {$skipParticipantClause}";
539
540 $lineItem = CRM_Core_DAO::executeQuery($sql, [1 => [$eventId, 'Positive']]);
541 while ($lineItem->fetch()) {
542 $count = $lineItem->count;
543 if (!$count) {
544 $count = 1;
545 }
546 if ($lineItem->html_type == 'Text') {
547 $count *= $lineItem->qty;
548 }
549 $optionsCount[$lineItem->valueId] = $count + CRM_Utils_Array::value($lineItem->valueId, $optionsCount, 0);
550 }
551
552 return $optionsCount;
553 }
554
555 /**
556 * Get the empty spaces for event those we can allocate
557 * to pending participant to become confirm.
558 *
559 * @deprecated
560 *
561 * @param int $eventId
562 * Event id.
563 *
564 * @return int
565 * $spaces Number of Empty Seats/null.
566 */
567 public static function pendingToConfirmSpaces($eventId) {
568 CRM_Core_Error::deprecatedFunctionWarning('CRM_Event_BAO_Participant::eventFull');
569 return CRM_Event_BAO_Participant::eventFull($eventId, TRUE, FALSE, TRUE, FALSE, TRUE);
570 }
571
572 /**
573 * Combine all the importable fields from the lower levels object.
574 *
575 * @param string $contactType
576 * @param bool $status
577 * @param bool $onlyParticipant
578 * @param bool $checkPermission
579 * Is this a permissioned retrieval?
580 *
581 * @return array
582 * array of importable Fields
583 */
584 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE) {
585 if (!self::$_importableFields) {
586 if (!$onlyParticipant) {
587 if (!$status) {
588 $fields = ['' => ['title' => ts('- do not import -')]];
589 }
590 else {
591 $fields = ['' => ['title' => ts('- Participant Fields -')]];
592 }
593 }
594 else {
595 $fields = [];
596 }
597
598 $tmpFields = CRM_Event_DAO_Participant::import();
599
600 $note = [
601 'participant_note' => [
602 'title' => ts('Participant Note'),
603 'name' => 'participant_note',
604 'headerPattern' => '/(participant.)?note$/i',
605 'data_type' => CRM_Utils_Type::T_TEXT,
606 ],
607 ];
608
609 // Split status and status id into 2 fields
610 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
611 // note import undoes this - it is still here in case the search usage uses it.
612 $participantStatus = [
613 'participant_status' => [
614 'title' => ts('Participant Status'),
615 'name' => 'participant_status',
616 'data_type' => CRM_Utils_Type::T_STRING,
617 ],
618 ];
619 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
620
621 // Split role and role id into 2 fields
622 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
623 // note import undoes this - it is still here in case the search usage uses it.
624 $participantRole = [
625 'participant_role' => [
626 'title' => ts('Participant Role'),
627 'name' => 'participant_role',
628 'data_type' => CRM_Utils_Type::T_STRING,
629 ],
630 ];
631 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
632
633 $eventType = [
634 'event_type' => [
635 'title' => ts('Event Type'),
636 'name' => 'event_type',
637 'data_type' => CRM_Utils_Type::T_STRING,
638 ],
639 ];
640
641 $tmpContactField = $contactFields = [];
642 $contactFields = [];
643 if (!$onlyParticipant) {
644 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
645
646 // Using new Dedupe rule.
647 $ruleParams = [
648 'contact_type' => $contactType,
649 'used' => 'Unsupervised',
650 ];
651 $fieldsArray = CRM_Dedupe_BAO_DedupeRule::dedupeRuleFields($ruleParams);
652
653 if (is_array($fieldsArray)) {
654 foreach ($fieldsArray as $value) {
655 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
656 $value,
657 'id',
658 'column_name'
659 );
660 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
661 $tmpContactField[trim($value)] = $contactFields[trim($value)] ?? NULL;
662 if (!$status) {
663 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
664 }
665 else {
666 $title = $tmpContactField[trim($value)]['title'];
667 }
668
669 $tmpContactField[trim($value)]['title'] = $title;
670 }
671 }
672 }
673 $extIdentifier = $contactFields['external_identifier'] ?? NULL;
674 if ($extIdentifier) {
675 $tmpContactField['external_identifier'] = $extIdentifier;
676 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array::value('title', $extIdentifier) . ' (match to contact)';
677 }
678 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
679
680 $fields = array_merge($fields, $tmpContactField);
681 $fields = array_merge($fields, $tmpFields);
682 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
683 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
684
685 self::$_importableFields = $fields;
686 }
687
688 return self::$_importableFields;
689 }
690
691 /**
692 * Combine all the exportable fields from the lower level objects.
693 *
694 * @param bool $checkPermission
695 *
696 * @return array
697 * array of exportable Fields
698 */
699 public static function &exportableFields($checkPermission = TRUE) {
700 if (!self::$_exportableFields) {
701 if (!self::$_exportableFields) {
702 self::$_exportableFields = [];
703 }
704
705 $participantFields = CRM_Event_DAO_Participant::export();
706 $eventFields = CRM_Event_DAO_Event::export();
707 $noteField = [
708 'participant_note' => [
709 'title' => ts('Participant Note'),
710 'name' => 'participant_note',
711 'type' => CRM_Utils_Type::T_STRING,
712 ],
713 ];
714
715 $participantStatus = [
716 'participant_status' => [
717 'title' => ts('Participant Status (label)'),
718 'name' => 'participant_status',
719 'type' => CRM_Utils_Type::T_STRING,
720 ],
721 ];
722
723 $participantRole = [
724 'participant_role' => [
725 'title' => ts('Participant Role (label)'),
726 'name' => 'participant_role',
727 'type' => CRM_Utils_Type::T_STRING,
728 ],
729 ];
730
731 $participantFields['participant_role_id']['title'] .= ' (ID)';
732
733 $discountFields = CRM_Core_DAO_Discount::export();
734
735 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
736
737 // add custom data
738 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
739 self::$_exportableFields = $fields;
740 }
741
742 return self::$_exportableFields;
743 }
744
745 /**
746 * Get the event name/sort name for a particular participation / participant
747 *
748 * @param int $participantId
749 * Id of the participant.
750 *
751 * @return array
752 * associated array with sort_name and event title
753 */
754 public static function participantDetails($participantId) {
755 $query = "
756 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
757 FROM civicrm_participant
758 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
759 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
760 WHERE civicrm_participant.id = {$participantId}
761 ";
762 $dao = CRM_Core_DAO::executeQuery($query);
763
764 $details = [];
765 while ($dao->fetch()) {
766 $details['name'] = $dao->name;
767 $details['title'] = $dao->title;
768 $details['cid'] = $dao->cid;
769 }
770
771 return $details;
772 }
773
774 /**
775 * Get the values for pseudoconstants for name->value and reverse.
776 *
777 * @param array $defaults
778 * (reference) the default values, some of which need to be resolved.
779 * @param bool $reverse
780 * True if we want to resolve the values in the reverse direction (value -> name).
781 */
782 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
783 self::lookupValue($defaults, 'event', CRM_Event_PseudoConstant::event(), $reverse);
784 self::lookupValue($defaults, 'status', CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'), $reverse);
785 self::lookupValue($defaults, 'role', CRM_Event_PseudoConstant::participantRole(), $reverse);
786 }
787
788 /**
789 * Convert associative array names to values and vice-versa.
790 *
791 * This function is used by both the web form layer and the api. Note that
792 * the api needs the name => value conversion, also the view layer typically
793 * requires value => name conversion
794 *
795 * @param array $defaults
796 * @param string $property
797 * @param string[] $lookup
798 * @param bool $reverse
799 *
800 * @return bool
801 */
802 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
803 $id = $property . '_id';
804
805 $src = $reverse ? $property : $id;
806 $dst = $reverse ? $id : $property;
807
808 if (!array_key_exists($src, $defaults)) {
809 return FALSE;
810 }
811
812 $look = $reverse ? array_flip($lookup) : $lookup;
813
814 if (is_array($look)) {
815 if (!array_key_exists($defaults[$src], $look)) {
816 return FALSE;
817 }
818 }
819 $defaults[$dst] = $look[$defaults[$src]];
820 return TRUE;
821 }
822
823 /**
824 * Delete the records that are associated with this participation.
825 *
826 * @param int $id
827 * Id of the participation to delete.
828 *
829 * @return \CRM_Event_DAO_Participant
830 */
831 public static function deleteParticipant($id) {
832 $participant = new CRM_Event_DAO_Participant();
833 $participant->id = $id;
834 if (!$participant->find()) {
835 return FALSE;
836 }
837 CRM_Utils_Hook::pre('delete', 'Participant', $id);
838
839 $transaction = new CRM_Core_Transaction();
840
841 //delete activity record
842 $params = [
843 'source_record_id' => $id,
844 // activity type id for event registration
845 'activity_type_id' => 5,
846 ];
847
848 CRM_Activity_BAO_Activity::deleteActivity($params);
849
850 // delete the participant payment record
851 // we need to do this since the cascaded constraints
852 // dont work with join tables
853 $p = ['participant_id' => $id];
854 CRM_Event_BAO_ParticipantPayment::deleteParticipantPayment($p);
855
856 // cleanup line items.
857 $participantsId = [];
858 $participantsId = self::getAdditionalParticipantIds($id);
859 $participantsId[] = $id;
860 CRM_Price_BAO_LineItem::deleteLineItems($participantsId, 'civicrm_participant');
861
862 //delete note when participant deleted.
863 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_participant');
864 $noteId = key($note);
865 if ($noteId) {
866 CRM_Core_BAO_Note::deleteRecord(['id' => $noteId]);
867 }
868
869 $participant->delete();
870
871 $transaction->commit();
872
873 CRM_Utils_Hook::post('delete', 'Participant', $participant->id, $participant);
874
875 return $participant;
876 }
877
878 /**
879 * Checks duplicate participants.
880 *
881 * @param array $input
882 * An assosiative array of name /value pairs.
883 * from other function
884 * @param array $duplicates
885 * (reference ) an assoc array of name/value pairs.
886 *
887 * @return CRM_Contribute_BAO_Contribution
888 */
889 public static function checkDuplicate($input, &$duplicates) {
890 $eventId = $input['event_id'] ?? NULL;
891 $contactId = $input['contact_id'] ?? NULL;
892
893 $clause = [];
894 $input = [];
895
896 if ($eventId) {
897 $clause[] = "event_id = %1";
898 $input[1] = [$eventId, 'Integer'];
899 }
900
901 if ($contactId) {
902 $clause[] = "contact_id = %2";
903 $input[2] = [$contactId, 'Integer'];
904 }
905
906 if (empty($clause)) {
907 return FALSE;
908 }
909
910 $clause = implode(' AND ', $clause);
911
912 $query = "SELECT id FROM civicrm_participant WHERE $clause";
913 $dao = CRM_Core_DAO::executeQuery($query, $input);
914 $result = FALSE;
915 while ($dao->fetch()) {
916 $duplicates[] = $dao->id;
917 $result = TRUE;
918 }
919 return $result;
920 }
921
922 /**
923 * Fix the event level.
924 *
925 * When price sets are used as event fee, fee_level is set as ^A
926 * separated string. We need to change that string to comma
927 * separated string before using fee_level in view mode.
928 *
929 * @param string $eventLevel
930 * Event_level string from db.
931 */
932 public static function fixEventLevel(&$eventLevel) {
933 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR) &&
934 (substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)
935 ) {
936 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($eventLevel, 1, -1)));
937 $pos = strrpos($eventLevel, '(multiple participants)', 0);
938 if ($pos) {
939 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
940 }
941 }
942 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
943 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
944 substr($eventLevel, 0, 1)
945 ));
946 }
947 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
948 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
949 substr($eventLevel, 0, -1)
950 ));
951 }
952 }
953
954 /**
955 * Get the ID of the default (first) participant role
956 *
957 * @return int
958 * @throws \CiviCRM_API3_Exception
959 */
960 public static function getDefaultRoleID() {
961 return (int) civicrm_api3('OptionValue', 'getvalue', [
962 'return' => 'value',
963 'option_group_id' => 'participant_role',
964 'is_active' => 1,
965 'options' => ['limit' => 1, 'sort' => 'is_default DESC'],
966 ]);
967 }
968
969 /**
970 * Get the additional participant ids.
971 *
972 * @param int $primaryParticipantId
973 * Primary partycipant Id.
974 * @param bool $excludeCancel
975 * Do not include participant those are cancelled.
976 *
977 * @param int $oldStatusId
978 *
979 * @return array
980 */
981 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
982 $additionalParticipantIds = [];
983 if (!$primaryParticipantId) {
984 return $additionalParticipantIds;
985 }
986
987 $where = "participant.registered_by_id={$primaryParticipantId}";
988 if ($excludeCancel) {
989 $cancelStatusId = 0;
990 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
991 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
992 $where .= " AND participant.status_id != {$cancelStatusId}";
993 }
994
995 if ($oldStatusId) {
996 $where .= " AND participant.status_id = {$oldStatusId}";
997 }
998
999 $query = "
1000 SELECT participant.id
1001 FROM civicrm_participant participant
1002 WHERE {$where}";
1003
1004 $dao = CRM_Core_DAO::executeQuery($query);
1005 while ($dao->fetch()) {
1006 $additionalParticipantIds[$dao->id] = $dao->id;
1007 }
1008 return $additionalParticipantIds;
1009 }
1010
1011 /**
1012 * Get the amount for the undiscounted version of the field.
1013 *
1014 * Note this function is part of the refactoring process rather than the best approach.
1015 *
1016 * @param int $eventID
1017 * @param int $discountedPriceFieldOptionID
1018 * @param string $feeLevel (deprecated)
1019 *
1020 * @return null|string
1021 */
1022 public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
1023 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID, NULL);
1024 $params = [
1025 1 => [$priceSetId, 'Integer'],
1026 ];
1027 if ($discountedPriceFieldOptionID) {
1028 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1029 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1030 WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
1031 $params[2] = [$discountedPriceFieldOptionID, 'Integer'];
1032 }
1033 else {
1034 $feeLevel = current($feeLevel);
1035 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1036 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1037 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1038 $params[2] = [$feeLevel, 'String'];
1039 }
1040 return CRM_Core_DAO::singleValueQuery($query, $params);
1041 }
1042
1043 /**
1044 * Retrieve additional participants display-names and URL to view their participant records.
1045 * (excludes cancelled participants automatically)
1046 *
1047 * @param int $primaryParticipantID
1048 * Id of primary participant record.
1049 *
1050 * @return array
1051 * $displayName => $viewUrl
1052 */
1053 public static function getAdditionalParticipants($primaryParticipantID) {
1054 $additionalParticipantIDs = [];
1055 $additionalParticipantIDs = self::getAdditionalParticipantIds($primaryParticipantID);
1056 if (!empty($additionalParticipantIDs)) {
1057 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1058 $additionalContactID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1059 $additionalParticipantID,
1060 'contact_id', 'id'
1061 );
1062 $additionalContactName = CRM_Contact_BAO_Contact::displayName($additionalContactID);
1063 $pViewURL = CRM_Utils_System::url('civicrm/contact/view/participant',
1064 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1065 );
1066
1067 $additionalParticipants[$additionalContactName] = $pViewURL;
1068 }
1069 }
1070 return $additionalParticipants;
1071 }
1072
1073 /**
1074 * Function for update primary and additional participant status.
1075 *
1076 * @param int $participantID
1077 * Primary participant's id.
1078 * @param int $oldStatusID
1079 * @param int $newStatusID
1080 * @param bool $updatePrimaryStatus
1081 *
1082 * @return bool|NULL
1083 */
1084 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1085 if (!$participantID || !$oldStatusID) {
1086 return NULL;
1087 }
1088
1089 if (!$newStatusID) {
1090 $newStatusID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1091 }
1092 elseif ($updatePrimaryStatus) {
1093 CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1094 }
1095
1096 $cascadeAdditionalIds = self::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1097
1098 if (!empty($cascadeAdditionalIds)) {
1099 try {
1100 foreach ($cascadeAdditionalIds as $id) {
1101 $participantParams = [
1102 'id' => $id,
1103 'status_id' => $newStatusID,
1104 ];
1105 civicrm_api3('Participant', 'create', $participantParams);
1106 }
1107 return TRUE;
1108 }
1109 catch (CiviCRM_API3_Exception $e) {
1110 throw new CRM_Core_Exception('Failed to update additional participant status in database');
1111 }
1112 }
1113 return FALSE;
1114 }
1115
1116 /**
1117 * Function for update status for given participant ids.
1118 *
1119 * @param int $participantIds
1120 * Array of participant ids.
1121 * @param int $statusId
1122 * Status id for participant.
1123 * @param bool $updateRegisterDate
1124 */
1125 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1126 if (!is_array($participantIds) || empty($participantIds) || !$statusId) {
1127 return;
1128 }
1129
1130 //lets update register date as we update status to keep track
1131 //when we did update status, useful for moving participant
1132 //from pending to expired.
1133 $setClause = "status_id = {$statusId}";
1134 if ($updateRegisterDate) {
1135 $setClause .= ", register_date = NOW()";
1136 }
1137
1138 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1139
1140 $query = "
1141 UPDATE civicrm_participant
1142 SET {$setClause}
1143 WHERE id IN {$participantIdClause}";
1144
1145 $dao = CRM_Core_DAO::executeQuery($query);
1146 }
1147
1148 /**
1149 * Function takes participant ids and statuses
1150 * update status from $fromStatusId to $toStatusId
1151 * and send mail + create activities.
1152 *
1153 * @param array $participantIds
1154 * Participant ids.
1155 * @param int $toStatusId
1156 * Update status id.
1157 * @param int $fromStatusId
1158 * From status id.
1159 * @param bool $returnResult
1160 * @param bool $skipCascadeRule
1161 *
1162 * @return array|NULL
1163 */
1164 public static function transitionParticipants(
1165 $participantIds, $toStatusId,
1166 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1167 ) {
1168 if (!is_array($participantIds) || empty($participantIds) || !$toStatusId) {
1169 return NULL;
1170 }
1171
1172 //thumb rule is if we triggering primary participant need to triggered additional
1173 $allParticipantIds = $primaryANDAdditionalIds = [];
1174 foreach ($participantIds as $id) {
1175 $allParticipantIds[] = $id;
1176 if (self::isPrimaryParticipant($id)) {
1177 //filter additional as per status transition rules, CRM-5403
1178 if ($skipCascadeRule) {
1179 $additionalIds = self::getAdditionalParticipantIds($id);
1180 }
1181 else {
1182 $additionalIds = self::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1183 }
1184 if (!empty($additionalIds)) {
1185 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1186 $primaryANDAdditionalIds[$id] = $additionalIds;
1187 }
1188 }
1189 }
1190
1191 //get the unique participant ids,
1192 $allParticipantIds = array_unique($allParticipantIds);
1193
1194 //pull required participants, contacts, events data, if not in hand
1195 static $eventDetails = [];
1196 static $contactDetails = [];
1197
1198 $contactIds = $eventIds = $participantDetails = [];
1199
1200 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
1201 $participantRoles = CRM_Event_PseudoConstant::participantRole();
1202 $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL,
1203 "class = 'Pending'"
1204 );
1205
1206 //first thing is pull all necessory data from db.
1207 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1208
1209 //get all participants data.
1210 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1211 $dao = CRM_Core_DAO::executeQuery($query);
1212 while ($dao->fetch()) {
1213 $participantDetails[$dao->id] = [
1214 'id' => $dao->id,
1215 'role' => $participantRoles[$dao->role_id],
1216 'is_test' => $dao->is_test,
1217 'event_id' => $dao->event_id,
1218 'status_id' => $dao->status_id,
1219 'fee_amount' => $dao->fee_amount,
1220 'contact_id' => $dao->contact_id,
1221 'register_date' => $dao->register_date,
1222 'registered_by_id' => $dao->registered_by_id,
1223 ];
1224 if (!array_key_exists($dao->contact_id, $contactDetails)) {
1225 $contactIds[$dao->contact_id] = $dao->contact_id;
1226 }
1227
1228 if (!array_key_exists($dao->event_id, $eventDetails)) {
1229 $eventIds[$dao->event_id] = $dao->event_id;
1230 }
1231 }
1232
1233 //get all required contacts detail.
1234 if (!empty($contactIds)) {
1235 $contactDetails += civicrm_api3('Contact', 'get', ['id' => ['IN' => $contactIds, 'return' => 'display_name']])['values'];
1236 }
1237
1238 //get all required events detail.
1239 if (!empty($eventIds)) {
1240 foreach ($eventIds as $eventId) {
1241 //retrieve event information
1242 $eventParams = ['id' => $eventId];
1243 CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]);
1244
1245 //get default participant role.
1246 $eventDetails[$eventId]['participant_role'] = $participantRoles[$eventDetails[$eventId]['default_role_id']] ?? NULL;
1247
1248 //get the location info
1249 $locParams = ['entity_id' => $eventId, 'entity_table' => 'civicrm_event'];
1250 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
1251 }
1252 }
1253
1254 //now we are ready w/ all required data.
1255 //take a decision as per statuses.
1256
1257 $emailType = NULL;
1258 $toStatus = $statusTypes[$toStatusId];
1259 $fromStatus = $statusTypes[$fromStatusId] ?? NULL;
1260
1261 switch ($toStatus) {
1262 case 'Pending from waitlist':
1263 case 'Pending from approval':
1264 switch ($fromStatus) {
1265 case 'On waitlist':
1266 case 'Awaiting approval':
1267 $emailType = 'Confirm';
1268 break;
1269 }
1270 break;
1271
1272 case 'Expired':
1273 //no matter from where u come send expired mail.
1274 $emailType = $toStatus;
1275 break;
1276
1277 case 'Cancelled':
1278 //no matter from where u come send cancel mail.
1279 $emailType = $toStatus;
1280 break;
1281 }
1282
1283 //as we process additional w/ primary, there might be case if user
1284 //select primary as well as additionals, so avoid double processing.
1285 $processedParticipantIds = [];
1286 $mailedParticipants = [];
1287
1288 //send mails and update status.
1289 foreach ($participantDetails as $participantId => $participantValues) {
1290 $updateParticipantIds = [];
1291 if (in_array($participantId, $processedParticipantIds)) {
1292 continue;
1293 }
1294
1295 //check is it primary and has additional.
1296 if (array_key_exists($participantId, $primaryANDAdditionalIds)) {
1297 foreach ($primaryANDAdditionalIds[$participantId] as $additionalId) {
1298
1299 if ($emailType) {
1300 $mail = self::sendTransitionParticipantMail($additionalId,
1301 $participantDetails[$additionalId],
1302 $eventDetails[$participantDetails[$additionalId]['event_id']],
1303 NULL,
1304 $emailType
1305 );
1306
1307 //get the mail participant ids
1308 if ($mail) {
1309 $mailedParticipants[$additionalId] = $contactDetails[$participantDetails[$additionalId]['contact_id']]['display_name'];
1310 }
1311 }
1312 $updateParticipantIds[] = $additionalId;
1313 $processedParticipantIds[] = $additionalId;
1314 }
1315 }
1316
1317 //now send email appropriate mail to primary.
1318 if ($emailType) {
1319 $mail = self::sendTransitionParticipantMail($participantId,
1320 $participantValues,
1321 $eventDetails[$participantValues['event_id']],
1322 NULL,
1323 $emailType
1324 );
1325
1326 //get the mail participant ids
1327 if ($mail) {
1328 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1329 }
1330 }
1331
1332 //now update status of group/one at once.
1333 $updateParticipantIds[] = $participantId;
1334
1335 //update the register date only when we,
1336 //move participant to pending class, CRM-6496
1337 $updateRegisterDate = FALSE;
1338 if (array_key_exists($toStatusId, $pendingStatuses)) {
1339 $updateRegisterDate = TRUE;
1340 }
1341 self::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1342 $processedParticipantIds[] = $participantId;
1343 }
1344
1345 //return result for cron.
1346 if ($returnResult) {
1347 $results = [
1348 'mailedParticipants' => $mailedParticipants,
1349 'updatedParticipantIds' => $processedParticipantIds,
1350 ];
1351
1352 return $results;
1353 }
1354 }
1355
1356 /**
1357 * Send mail and create activity
1358 * when participant status changed.
1359 *
1360 * @param int $participantId
1361 * Participant id.
1362 * @param array $participantValues
1363 * Participant detail values. status id for participants.
1364 * @param array $eventDetails
1365 * Required event details.
1366 * @param array $contactDetails
1367 * Required contact details.
1368 * @param string $mailType
1369 * (eg 'approval', 'confirm', 'expired' ).
1370 *
1371 * @return bool
1372 */
1373 public static function sendTransitionParticipantMail(
1374 $participantId,
1375 $participantValues,
1376 $eventDetails,
1377 $contactDetails,
1378 $mailType
1379 ) {
1380 //send emails.
1381 $mailSent = FALSE;
1382
1383 if (!$contactDetails) {
1384 $contactDetails = civicrm_api3('Contact', 'getsingle', [
1385 'id' => $participantValues['contact_id'],
1386 'return' => ['email', 'display_name'],
1387 ]);
1388 }
1389 //don't send confirmation mail to additional
1390 //since only primary able to confirm registration.
1391 if (!empty($participantValues['registered_by_id']) &&
1392 $mailType == 'Confirm'
1393 ) {
1394 return $mailSent;
1395 }
1396
1397 $toEmail = $contactDetails['email'] ?? NULL;
1398 if ($toEmail) {
1399
1400 $contactId = $participantValues['contact_id'];
1401 $participantName = $contactDetails['display_name'];
1402
1403 //calculate the checksum value.
1404 $checksumValue = NULL;
1405 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1406 $checksumLife = 'inf';
1407 $endDate = $eventDetails['end_date'] ?? NULL;
1408 if ($endDate) {
1409 $checksumLife = (CRM_Utils_Date::unixTime($endDate) - time()) / (60 * 60);
1410 }
1411 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId, NULL, $checksumLife);
1412 }
1413
1414 //take a receipt from as event else domain.
1415 $receiptFrom = CRM_Core_BAO_Domain::getFromEmail();
1416
1417 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1418 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1419 }
1420
1421 list($mailSent, $subject) = CRM_Core_BAO_MessageTemplate::sendTemplate(
1422 [
1423 'workflow' => 'participant_' . strtolower($mailType),
1424 'contactId' => $contactId,
1425 'tokenContext' => ['participantId' => $participantId],
1426 'tplParams' => [
1427 'participant' => $participantValues,
1428 'event' => $eventDetails,
1429 'paidEvent' => $eventDetails['is_monetary'] ?? NULL,
1430 'isShowLocation' => $eventDetails['is_show_location'] ?? NULL,
1431 'isAdditional' => $participantValues['registered_by_id'],
1432 'isExpired' => $mailType === 'Expired',
1433 'isConfirm' => $mailType === 'Confirm',
1434 'checksumValue' => $checksumValue,
1435 ],
1436 'from' => $receiptFrom,
1437 'toName' => $participantName,
1438 'toEmail' => $toEmail,
1439 'cc' => $eventDetails['cc_confirm'] ?? NULL,
1440 'bcc' => $eventDetails['bcc_confirm'] ?? NULL,
1441 ]
1442 );
1443
1444 // 3. create activity record.
1445 if ($mailSent) {
1446 $now = date('YmdHis');
1447 $activityType = 'Event Registration';
1448 $activityParams = [
1449 'subject' => $subject,
1450 'source_contact_id' => $contactId,
1451 'source_record_id' => $participantId,
1452 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1453 'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
1454 'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']),
1455 'is_test' => $participantValues['is_test'],
1456 'status_id' => 2,
1457 ];
1458
1459 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
1460 throw new CRM_Core_Exception('Failed creating Activity for expiration mail');
1461 }
1462 }
1463 }
1464
1465 return $mailSent;
1466 }
1467
1468 /**
1469 * Get participant status change message.
1470 *
1471 * @param int $participantId
1472 * @param $statusChangeTo
1473 * @param int $fromStatusId
1474 *
1475 * @return string
1476 */
1477 public static function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1478 $statusMsg = NULL;
1479 $results = self::transitionParticipants([$participantId],
1480 $statusChangeTo, $fromStatusId, TRUE
1481 );
1482
1483 $allStatuses = CRM_Event_PseudoConstant::participantStatus();
1484 //give user message only when mail has sent.
1485 if (is_array($results) && !empty($results)) {
1486 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1487 foreach ($results['updatedParticipantIds'] as $processedId) {
1488 if (is_array($results['mailedParticipants']) &&
1489 array_key_exists($processedId, $results['mailedParticipants'])
1490 ) {
1491 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1492 [
1493 1 => $allStatuses[$statusChangeTo],
1494 2 => $results['mailedParticipants'][$processedId],
1495 ]
1496 );
1497 }
1498 }
1499 }
1500 }
1501
1502 return $statusMsg;
1503 }
1504
1505 /**
1506 * Get event full and waiting list message.
1507 *
1508 * @param int $eventId
1509 * @param int $participantId
1510 *
1511 * @return string
1512 */
1513 public static function eventFullMessage($eventId, $participantId = NULL) {
1514 $eventfullMsg = $dbStatusId = NULL;
1515 $checkEventFull = TRUE;
1516 if ($participantId) {
1517 $dbStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1518 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1'))) {
1519 //participant already in counted status no need to check for event full messages.
1520 $checkEventFull = FALSE;
1521 }
1522 }
1523
1524 //early return.
1525 if (!$eventId || !$checkEventFull) {
1526 return $eventfullMsg;
1527 }
1528
1529 //event is truly full.
1530 $emptySeats = self::eventFull($eventId, FALSE, FALSE);
1531 if (is_string($emptySeats) && $emptySeats !== NULL) {
1532 $maxParticipants = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1533 $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.", [
1534 1 => $maxParticipants,
1535 ]) . '<br />';
1536 }
1537
1538 $hasWaiting = FALSE;
1539 $waitListedCount = self::eventFull($eventId, FALSE, TRUE, TRUE);
1540 if (is_numeric($waitListedCount)) {
1541 $hasWaiting = TRUE;
1542 //only current processing participant is on waitlist.
1543 if ($waitListedCount == 1 && CRM_Event_PseudoConstant::participantStatus($dbStatusId) == 'On waitlist') {
1544 $hasWaiting = FALSE;
1545 }
1546 }
1547
1548 if ($hasWaiting) {
1549 $waitingStatusId = array_search('On waitlist',
1550 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'")
1551 );
1552 $viewWaitListUrl = CRM_Utils_System::url('civicrm/event/search',
1553 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1554 );
1555
1556 $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.",
1557 [
1558 1 => $viewWaitListUrl,
1559 2 => $waitListedCount,
1560 ]
1561 );
1562 }
1563
1564 return $eventfullMsg;
1565 }
1566
1567 /**
1568 * Check for whether participant is primary or not.
1569 *
1570 * @param int $participantId
1571 *
1572 * @return bool
1573 * true if participant is primary
1574 */
1575 public static function isPrimaryParticipant($participantId) {
1576
1577 $participant = new CRM_Event_DAO_Participant();
1578 $participant->registered_by_id = $participantId;
1579
1580 if ($participant->find(TRUE)) {
1581 return TRUE;
1582 }
1583 return FALSE;
1584 }
1585
1586 /**
1587 * Get additional participant Ids for cascading with primary participant status.
1588 *
1589 * @param int $participantId
1590 * Participant id.
1591 * @param int $oldStatusId
1592 * Previous status.
1593 * @param int $newStatusId
1594 * New status.
1595 *
1596 * @return array
1597 */
1598 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1599
1600 $additionalParticipantIds = [];
1601
1602 static $participantStatuses = [];
1603
1604 if (empty($participantStatuses)) {
1605 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1606 }
1607
1608 if (!empty(self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]]) &&
1609 in_array($participantStatuses[$newStatusId], self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1610 ) {
1611 $additionalParticipantIds = self::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1612 }
1613
1614 return $additionalParticipantIds;
1615 }
1616
1617 /**
1618 * Get participant record count for a Contact.
1619 *
1620 * @param int $contactID
1621 *
1622 * @return int
1623 * count of participant records
1624 */
1625 public static function getContactParticipantCount($contactID) {
1626 $query = "SELECT count(*)
1627 FROM civicrm_participant
1628 WHERE civicrm_participant.contact_id = {$contactID} AND
1629 civicrm_participant.is_test = 0";
1630 return CRM_Core_DAO::singleValueQuery($query);
1631 }
1632
1633 /**
1634 * Get participant ids by contribution id.
1635 *
1636 * @param int $contributionId
1637 * Contribution Id.
1638 * @param bool $excludeCancelled
1639 * Exclude cancelled additional participant.
1640 *
1641 * @return array
1642 */
1643 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1644
1645 $ids = [];
1646 if (!$contributionId) {
1647 return $ids;
1648 }
1649
1650 // get primary participant id
1651 $query = "SELECT participant_id
1652 FROM civicrm_participant cp
1653 LEFT JOIN civicrm_participant_payment cpp ON cp.id = cpp.participant_id
1654 WHERE cpp.contribution_id = {$contributionId}
1655 AND cp.registered_by_id IS NULL";
1656 $participantPayment = CRM_Core_DAO::executeQuery($query);
1657
1658 // get additional participant ids (including cancelled)
1659 while ($participantPayment->fetch()) {
1660 $ids = array_merge($ids, array_merge([
1661 $participantPayment->participant_id,
1662 ], self::getAdditionalParticipantIds($participantPayment->participant_id,
1663 $excludeCancelled
1664 )));
1665 }
1666
1667 return $ids;
1668 }
1669
1670 /**
1671 * Get additional Participant edit & view url .
1672 *
1673 * @param array $participantIds
1674 * An array of additional participant ids.
1675 *
1676 * @return array
1677 * Array of Urls.
1678 */
1679 public static function getAdditionalParticipantUrl($participantIds) {
1680 foreach ($participantIds as $value) {
1681 $links = [];
1682 $details = self::participantDetails($value);
1683 $viewUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1684 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1685 );
1686 $editUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1687 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1688 );
1689 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1690 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1691 return $links;
1692 }
1693 }
1694
1695 /**
1696 * create trxn entry if an event has discount.
1697 *
1698 * @param int $eventID
1699 * Event id.
1700 * @param array $contributionParams
1701 * Contribution params.
1702 *
1703 * @param string $feeLevel (deprecated)
1704 * @param int $discountedPriceFieldOptionID
1705 * ID of the civicrm_price_field_value field for the discount id.
1706 */
1707 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID = NULL) {
1708 $financialTypeID = $contributionParams['contribution']->financial_type_id;
1709 $total_amount = $contributionParams['total_amount'];
1710
1711 $checkDiscount = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
1712 if (!empty($checkDiscount)) {
1713 $mainAmount = self::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
1714 $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount(
1715 $financialTypeID, 'Discounts Account is');
1716 if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
1717 $transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
1718 $transactionParams['trxnParams']['payment_processor_id'] = NULL;
1719 $transactionParams['trxnParams']['payment_instrument_id'] = NULL;
1720 $transactionParams['trxnParams']['check_number'] = NULL;
1721 $transactionParams['trxnParams']['trxn_id'] = NULL;
1722 $transactionParams['trxnParams']['net_amount'] = NULL;
1723 $transactionParams['trxnParams']['fee_amount'] = NULL;
1724 CRM_Core_BAO_FinancialTrxn::create($transactionParams);
1725 }
1726 }
1727 }
1728
1729 /**
1730 * Delete participants of contact.
1731 *
1732 * @see https://issues.civicrm.org/jira/browse/CRM-12155
1733 *
1734 * @param int $contactId
1735 * Contact id.
1736 *
1737 */
1738 public static function deleteContactParticipant($contactId) {
1739 $participant = new CRM_Event_DAO_Participant();
1740 $participant->contact_id = $contactId;
1741 $participant->find();
1742 while ($participant->fetch()) {
1743 self::deleteParticipant($participant->id);
1744 }
1745 }
1746
1747 /**
1748 * @param int $participantId
1749 * @param $activityType
1750 *
1751 * @throws CRM_Core_Exception
1752 */
1753 public static function addActivityForSelection($participantId, $activityType) {
1754 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
1755 $contactId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
1756
1757 $date = CRM_Utils_Date::currentDBDate();
1758 $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
1759 $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array::value($eventId, $event));
1760
1761 // activity params
1762 $activityParams = [
1763 'source_contact_id' => $contactId,
1764 'source_record_id' => $participantId,
1765 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1766 'subject' => $subject,
1767 'activity_date_time' => $date,
1768 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1769 'skipRecentView' => TRUE,
1770 ];
1771
1772 // create activity with target contacts
1773 $id = CRM_Core_Session::getLoggedInContactID();
1774 if ($id) {
1775 $activityParams['source_contact_id'] = $id;
1776 $activityParams['target_contact_id'][] = $contactId;
1777 }
1778 // @todo use api & also look at duplication of similar methods.
1779 CRM_Activity_BAO_Activity::create($activityParams);
1780 }
1781
1782 /**
1783 * Get options for a given field.
1784 * @see CRM_Core_DAO::buildOptions
1785 *
1786 * @param string $fieldName
1787 * @param string $context
1788 * @see CRM_Core_DAO::buildOptionsContext
1789 * @param array $props
1790 * whatever is known about this dao object.
1791 *
1792 * @return array|bool
1793 */
1794 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1795 $params = ['condition' => []];
1796
1797 if ($fieldName == 'status_id' && $context != 'validate') {
1798 // Get rid of cart-related option if disabled
1799 // FIXME: Why does this option even exist if cart is disabled?
1800 if (!Civi::settings()->get('enable_cart')) {
1801 $params['condition'][] = "name <> 'Pending in cart'";
1802 }
1803 }
1804
1805 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
1806 }
1807
1808 /**
1809 * CRM-17797 -- Format fields and setDefaults for primary and additional participants profile
1810 * @param int $contactId
1811 * @param CRM_Core_Form $form
1812 */
1813 public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
1814 if (!$contactId) {
1815 return;
1816 }
1817 $fields = [];
1818 if (!empty($form->_fields)) {
1819 $removeCustomFieldTypes = ['Participant'];
1820
1821 foreach ($form->_fields as $name => $fieldInfo) {
1822 if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
1823 && !CRM_Core_BAO_CustomGroup::checkCustomField(substr($name, 7), $removeCustomFieldTypes))
1824 || substr($name, 0, 12) == 'participant_') {
1825 continue;
1826 }
1827 $fields[$name] = $fieldInfo;
1828 }
1829
1830 if (!empty($fields)) {
1831 CRM_Core_BAO_UFGroup::setProfileDefaults($contactId, $fields, $form->_defaults);
1832 }
1833 }
1834 }
1835
1836 /**
1837 * Evaluate whether a participant record is eligible for self-service transfer/cancellation. If so,
1838 * return additional participant/event details.
1839 *
1840 * @param int $participantId
1841 * @param string $url
1842 * @param bool $isBackOffice
1843 */
1844 public static function getSelfServiceEligibility(int $participantId, string $url, bool $isBackOffice) : array {
1845 $optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'participant_role', 'id', 'name');
1846 $query = "
1847 SELECT cpst.name as status, cov.name as role, cp.fee_level, cp.fee_amount, cp.register_date, cp.status_id, ce.start_date, ce.title, cp.event_id, ce.allow_selfcancelxfer
1848 FROM civicrm_participant cp
1849 LEFT JOIN civicrm_participant_status_type cpst ON cpst.id = cp.status_id
1850 LEFT JOIN civicrm_option_value cov ON cov.value = cp.role_id and cov.option_group_id = {$optionGroupId}
1851 LEFT JOIN civicrm_event ce ON ce.id = cp.event_id
1852 WHERE cp.id = {$participantId}";
1853 $dao = CRM_Core_DAO::executeQuery($query);
1854 while ($dao->fetch()) {
1855 $details['eligible'] = TRUE;
1856 $details['status'] = $dao->status;
1857 $details['role'] = $dao->role;
1858 $details['fee_level'] = trim($dao->fee_level, CRM_Core_DAO::VALUE_SEPARATOR);
1859 $details['fee_amount'] = $dao->fee_amount;
1860 $details['register_date'] = $dao->register_date;
1861 $details['event_start_date'] = $dao->start_date;
1862 $details['allow_selfcancelxfer'] = $dao->allow_selfcancelxfer;
1863 $eventTitle = $dao->title;
1864 $eventId = $dao->event_id;
1865 }
1866 if (!$details['allow_selfcancelxfer'] && !$isBackOffice) {
1867 $details['eligible'] = FALSE;
1868 $details['ineligible_message'] = ts('This event registration can not be transferred or cancelled. Contact the event organizer if you have questions.');
1869 return $details;
1870 }
1871 // Verify participant status is one that can be self-cancelled
1872 if (!in_array($details['status'], ['Registered', 'Pending from pay later', 'On waitlist'])) {
1873 $details['eligible'] = FALSE;
1874 $details['ineligible_message'] = ts('You cannot transfer or cancel your registration for %1 as you are not currently registered for this event.', [1 => $eventTitle]);
1875 return $details;
1876 }
1877 // Determine if it's too late to self-service cancel/transfer.
1878 $query = "select start_date as start, selfcancelxfer_time as time from civicrm_event where id = " . $eventId;
1879 $dao = CRM_Core_DAO::executeQuery($query);
1880 while ($dao->fetch()) {
1881 $time_limit = $dao->time;
1882 $start_date = $dao->start;
1883 }
1884 $timenow = new Datetime();
1885 if (!$isBackOffice && isset($time_limit)) {
1886 $cancelHours = abs($time_limit);
1887 $cancelInterval = new DateInterval("PT${cancelHours}H");
1888 $cancelInterval->invert = $time_limit < 0 ? 1 : 0;
1889 $cancelDeadline = (new Datetime($start_date))->sub($cancelInterval);
1890 if ($timenow > $cancelDeadline) {
1891 $details['eligible'] = FALSE;
1892 // Change the language of the status message based on whether the waitlist time limit is positive or negative.
1893 $afterOrPrior = $time_limit <= 0 ? 'after' : 'prior to';
1894 $moreOrLess = $time_limit <= 0 ? 'more' : 'fewer';
1895 $details['ineligible_message'] = ts("Registration for this event cannot be cancelled or transferred %1 than %2 hours %3 the event's start time. Contact the event organizer if you have questions.",
1896 [1 => $moreOrLess, 2 => $cancelHours, 3 => $afterOrPrior]);
1897
1898 }
1899 }
1900 return $details;
1901 }
1902
1903 }