Merge pull request #22971 from eileenmcnaughton/pay_later
[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 $participantStatus = [
612 'participant_status' => [
613 'title' => ts('Participant Status'),
614 'name' => 'participant_status',
615 'data_type' => CRM_Utils_Type::T_STRING,
616 ],
617 ];
618 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
619
620 // Split role and role id into 2 fields
621 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
622 $participantRole = [
623 'participant_role' => [
624 'title' => ts('Participant Role'),
625 'name' => 'participant_role',
626 'data_type' => CRM_Utils_Type::T_STRING,
627 ],
628 ];
629 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
630
631 $eventType = [
632 'event_type' => [
633 'title' => ts('Event Type'),
634 'name' => 'event_type',
635 'data_type' => CRM_Utils_Type::T_STRING,
636 ],
637 ];
638
639 $tmpContactField = $contactFields = [];
640 $contactFields = [];
641 if (!$onlyParticipant) {
642 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
643
644 // Using new Dedupe rule.
645 $ruleParams = [
646 'contact_type' => $contactType,
647 'used' => 'Unsupervised',
648 ];
649 $fieldsArray = CRM_Dedupe_BAO_DedupeRule::dedupeRuleFields($ruleParams);
650
651 if (is_array($fieldsArray)) {
652 foreach ($fieldsArray as $value) {
653 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
654 $value,
655 'id',
656 'column_name'
657 );
658 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
659 $tmpContactField[trim($value)] = $contactFields[trim($value)] ?? NULL;
660 if (!$status) {
661 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
662 }
663 else {
664 $title = $tmpContactField[trim($value)]['title'];
665 }
666
667 $tmpContactField[trim($value)]['title'] = $title;
668 }
669 }
670 }
671 $extIdentifier = $contactFields['external_identifier'] ?? NULL;
672 if ($extIdentifier) {
673 $tmpContactField['external_identifier'] = $extIdentifier;
674 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array::value('title', $extIdentifier) . ' (match to contact)';
675 }
676 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
677
678 $fields = array_merge($fields, $tmpContactField);
679 $fields = array_merge($fields, $tmpFields);
680 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
681 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
682
683 self::$_importableFields = $fields;
684 }
685
686 return self::$_importableFields;
687 }
688
689 /**
690 * Combine all the exportable fields from the lower level objects.
691 *
692 * @param bool $checkPermission
693 *
694 * @return array
695 * array of exportable Fields
696 */
697 public static function &exportableFields($checkPermission = TRUE) {
698 if (!self::$_exportableFields) {
699 if (!self::$_exportableFields) {
700 self::$_exportableFields = [];
701 }
702
703 $participantFields = CRM_Event_DAO_Participant::export();
704 $eventFields = CRM_Event_DAO_Event::export();
705 $noteField = [
706 'participant_note' => [
707 'title' => ts('Participant Note'),
708 'name' => 'participant_note',
709 'type' => CRM_Utils_Type::T_STRING,
710 ],
711 ];
712
713 $participantStatus = [
714 'participant_status' => [
715 'title' => ts('Participant Status (label)'),
716 'name' => 'participant_status',
717 'type' => CRM_Utils_Type::T_STRING,
718 ],
719 ];
720
721 $participantRole = [
722 'participant_role' => [
723 'title' => ts('Participant Role (label)'),
724 'name' => 'participant_role',
725 'type' => CRM_Utils_Type::T_STRING,
726 ],
727 ];
728
729 $participantFields['participant_role_id']['title'] .= ' (ID)';
730
731 $discountFields = CRM_Core_DAO_Discount::export();
732
733 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
734
735 // add custom data
736 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
737 self::$_exportableFields = $fields;
738 }
739
740 return self::$_exportableFields;
741 }
742
743 /**
744 * Get the event name/sort name for a particular participation / participant
745 *
746 * @param int $participantId
747 * Id of the participant.
748 *
749 * @return array
750 * associated array with sort_name and event title
751 */
752 public static function participantDetails($participantId) {
753 $query = "
754 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
755 FROM civicrm_participant
756 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
757 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
758 WHERE civicrm_participant.id = {$participantId}
759 ";
760 $dao = CRM_Core_DAO::executeQuery($query);
761
762 $details = [];
763 while ($dao->fetch()) {
764 $details['name'] = $dao->name;
765 $details['title'] = $dao->title;
766 $details['cid'] = $dao->cid;
767 }
768
769 return $details;
770 }
771
772 /**
773 * Get the values for pseudoconstants for name->value and reverse.
774 *
775 * @param array $defaults
776 * (reference) the default values, some of which need to be resolved.
777 * @param bool $reverse
778 * True if we want to resolve the values in the reverse direction (value -> name).
779 */
780 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
781 self::lookupValue($defaults, 'event', CRM_Event_PseudoConstant::event(), $reverse);
782 self::lookupValue($defaults, 'status', CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'), $reverse);
783 self::lookupValue($defaults, 'role', CRM_Event_PseudoConstant::participantRole(), $reverse);
784 }
785
786 /**
787 * Convert associative array names to values and vice-versa.
788 *
789 * This function is used by both the web form layer and the api. Note that
790 * the api needs the name => value conversion, also the view layer typically
791 * requires value => name conversion
792 *
793 * @param array $defaults
794 * @param string $property
795 * @param string[] $lookup
796 * @param bool $reverse
797 *
798 * @return bool
799 */
800 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
801 $id = $property . '_id';
802
803 $src = $reverse ? $property : $id;
804 $dst = $reverse ? $id : $property;
805
806 if (!array_key_exists($src, $defaults)) {
807 return FALSE;
808 }
809
810 $look = $reverse ? array_flip($lookup) : $lookup;
811
812 if (is_array($look)) {
813 if (!array_key_exists($defaults[$src], $look)) {
814 return FALSE;
815 }
816 }
817 $defaults[$dst] = $look[$defaults[$src]];
818 return TRUE;
819 }
820
821 /**
822 * Delete the records that are associated with this participation.
823 *
824 * @param int $id
825 * Id of the participation to delete.
826 *
827 * @return \CRM_Event_DAO_Participant
828 */
829 public static function deleteParticipant($id) {
830 $participant = new CRM_Event_DAO_Participant();
831 $participant->id = $id;
832 if (!$participant->find()) {
833 return FALSE;
834 }
835 CRM_Utils_Hook::pre('delete', 'Participant', $id);
836
837 $transaction = new CRM_Core_Transaction();
838
839 //delete activity record
840 $params = [
841 'source_record_id' => $id,
842 // activity type id for event registration
843 'activity_type_id' => 5,
844 ];
845
846 CRM_Activity_BAO_Activity::deleteActivity($params);
847
848 // delete the participant payment record
849 // we need to do this since the cascaded constraints
850 // dont work with join tables
851 $p = ['participant_id' => $id];
852 CRM_Event_BAO_ParticipantPayment::deleteParticipantPayment($p);
853
854 // cleanup line items.
855 $participantsId = [];
856 $participantsId = self::getAdditionalParticipantIds($id);
857 $participantsId[] = $id;
858 CRM_Price_BAO_LineItem::deleteLineItems($participantsId, 'civicrm_participant');
859
860 //delete note when participant deleted.
861 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_participant');
862 $noteId = key($note);
863 if ($noteId) {
864 CRM_Core_BAO_Note::deleteRecord(['id' => $noteId]);
865 }
866
867 $participant->delete();
868
869 $transaction->commit();
870
871 CRM_Utils_Hook::post('delete', 'Participant', $participant->id, $participant);
872
873 return $participant;
874 }
875
876 /**
877 * Checks duplicate participants.
878 *
879 * @param array $input
880 * An assosiative array of name /value pairs.
881 * from other function
882 * @param array $duplicates
883 * (reference ) an assoc array of name/value pairs.
884 *
885 * @return CRM_Contribute_BAO_Contribution
886 */
887 public static function checkDuplicate($input, &$duplicates) {
888 $eventId = $input['event_id'] ?? NULL;
889 $contactId = $input['contact_id'] ?? NULL;
890
891 $clause = [];
892 $input = [];
893
894 if ($eventId) {
895 $clause[] = "event_id = %1";
896 $input[1] = [$eventId, 'Integer'];
897 }
898
899 if ($contactId) {
900 $clause[] = "contact_id = %2";
901 $input[2] = [$contactId, 'Integer'];
902 }
903
904 if (empty($clause)) {
905 return FALSE;
906 }
907
908 $clause = implode(' AND ', $clause);
909
910 $query = "SELECT id FROM civicrm_participant WHERE $clause";
911 $dao = CRM_Core_DAO::executeQuery($query, $input);
912 $result = FALSE;
913 while ($dao->fetch()) {
914 $duplicates[] = $dao->id;
915 $result = TRUE;
916 }
917 return $result;
918 }
919
920 /**
921 * Fix the event level.
922 *
923 * When price sets are used as event fee, fee_level is set as ^A
924 * separated string. We need to change that string to comma
925 * separated string before using fee_level in view mode.
926 *
927 * @param string $eventLevel
928 * Event_level string from db.
929 */
930 public static function fixEventLevel(&$eventLevel) {
931 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR) &&
932 (substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)
933 ) {
934 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($eventLevel, 1, -1)));
935 $pos = strrpos($eventLevel, '(multiple participants)', 0);
936 if ($pos) {
937 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
938 }
939 }
940 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
941 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
942 substr($eventLevel, 0, 1)
943 ));
944 }
945 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
946 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
947 substr($eventLevel, 0, -1)
948 ));
949 }
950 }
951
952 /**
953 * Get the ID of the default (first) participant role
954 *
955 * @return int
956 * @throws \CiviCRM_API3_Exception
957 */
958 public static function getDefaultRoleID() {
959 return (int) civicrm_api3('OptionValue', 'getvalue', [
960 'return' => 'value',
961 'option_group_id' => 'participant_role',
962 'is_active' => 1,
963 'options' => ['limit' => 1, 'sort' => 'is_default DESC'],
964 ]);
965 }
966
967 /**
968 * Get the additional participant ids.
969 *
970 * @param int $primaryParticipantId
971 * Primary partycipant Id.
972 * @param bool $excludeCancel
973 * Do not include participant those are cancelled.
974 *
975 * @param int $oldStatusId
976 *
977 * @return array
978 */
979 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
980 $additionalParticipantIds = [];
981 if (!$primaryParticipantId) {
982 return $additionalParticipantIds;
983 }
984
985 $where = "participant.registered_by_id={$primaryParticipantId}";
986 if ($excludeCancel) {
987 $cancelStatusId = 0;
988 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
989 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
990 $where .= " AND participant.status_id != {$cancelStatusId}";
991 }
992
993 if ($oldStatusId) {
994 $where .= " AND participant.status_id = {$oldStatusId}";
995 }
996
997 $query = "
998 SELECT participant.id
999 FROM civicrm_participant participant
1000 WHERE {$where}";
1001
1002 $dao = CRM_Core_DAO::executeQuery($query);
1003 while ($dao->fetch()) {
1004 $additionalParticipantIds[$dao->id] = $dao->id;
1005 }
1006 return $additionalParticipantIds;
1007 }
1008
1009 /**
1010 * Get the amount for the undiscounted version of the field.
1011 *
1012 * Note this function is part of the refactoring process rather than the best approach.
1013 *
1014 * @param int $eventID
1015 * @param int $discountedPriceFieldOptionID
1016 * @param string $feeLevel (deprecated)
1017 *
1018 * @return null|string
1019 */
1020 public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
1021 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID, NULL);
1022 $params = [
1023 1 => [$priceSetId, 'Integer'],
1024 ];
1025 if ($discountedPriceFieldOptionID) {
1026 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1027 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1028 WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
1029 $params[2] = [$discountedPriceFieldOptionID, 'Integer'];
1030 }
1031 else {
1032 $feeLevel = current($feeLevel);
1033 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1034 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1035 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1036 $params[2] = [$feeLevel, 'String'];
1037 }
1038 return CRM_Core_DAO::singleValueQuery($query, $params);
1039 }
1040
1041 /**
1042 * Retrieve additional participants display-names and URL to view their participant records.
1043 * (excludes cancelled participants automatically)
1044 *
1045 * @param int $primaryParticipantID
1046 * Id of primary participant record.
1047 *
1048 * @return array
1049 * $displayName => $viewUrl
1050 */
1051 public static function getAdditionalParticipants($primaryParticipantID) {
1052 $additionalParticipantIDs = [];
1053 $additionalParticipantIDs = self::getAdditionalParticipantIds($primaryParticipantID);
1054 if (!empty($additionalParticipantIDs)) {
1055 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1056 $additionalContactID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1057 $additionalParticipantID,
1058 'contact_id', 'id'
1059 );
1060 $additionalContactName = CRM_Contact_BAO_Contact::displayName($additionalContactID);
1061 $pViewURL = CRM_Utils_System::url('civicrm/contact/view/participant',
1062 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1063 );
1064
1065 $additionalParticipants[$additionalContactName] = $pViewURL;
1066 }
1067 }
1068 return $additionalParticipants;
1069 }
1070
1071 /**
1072 * Function for update primary and additional participant status.
1073 *
1074 * @param int $participantID
1075 * Primary participant's id.
1076 * @param int $oldStatusID
1077 * @param int $newStatusID
1078 * @param bool $updatePrimaryStatus
1079 *
1080 * @return bool|NULL
1081 */
1082 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1083 if (!$participantID || !$oldStatusID) {
1084 return NULL;
1085 }
1086
1087 if (!$newStatusID) {
1088 $newStatusID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1089 }
1090 elseif ($updatePrimaryStatus) {
1091 CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1092 }
1093
1094 $cascadeAdditionalIds = self::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1095
1096 if (!empty($cascadeAdditionalIds)) {
1097 try {
1098 foreach ($cascadeAdditionalIds as $id) {
1099 $participantParams = [
1100 'id' => $id,
1101 'status_id' => $newStatusID,
1102 ];
1103 civicrm_api3('Participant', 'create', $participantParams);
1104 }
1105 return TRUE;
1106 }
1107 catch (CiviCRM_API3_Exception $e) {
1108 throw new CRM_Core_Exception('Failed to update additional participant status in database');
1109 }
1110 }
1111 return FALSE;
1112 }
1113
1114 /**
1115 * Function for update status for given participant ids.
1116 *
1117 * @param int $participantIds
1118 * Array of participant ids.
1119 * @param int $statusId
1120 * Status id for participant.
1121 * @param bool $updateRegisterDate
1122 */
1123 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1124 if (!is_array($participantIds) || empty($participantIds) || !$statusId) {
1125 return;
1126 }
1127
1128 //lets update register date as we update status to keep track
1129 //when we did update status, useful for moving participant
1130 //from pending to expired.
1131 $setClause = "status_id = {$statusId}";
1132 if ($updateRegisterDate) {
1133 $setClause .= ", register_date = NOW()";
1134 }
1135
1136 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1137
1138 $query = "
1139 UPDATE civicrm_participant
1140 SET {$setClause}
1141 WHERE id IN {$participantIdClause}";
1142
1143 $dao = CRM_Core_DAO::executeQuery($query);
1144 }
1145
1146 /**
1147 * Function takes participant ids and statuses
1148 * update status from $fromStatusId to $toStatusId
1149 * and send mail + create activities.
1150 *
1151 * @param array $participantIds
1152 * Participant ids.
1153 * @param int $toStatusId
1154 * Update status id.
1155 * @param int $fromStatusId
1156 * From status id.
1157 * @param bool $returnResult
1158 * @param bool $skipCascadeRule
1159 *
1160 * @return array|NULL
1161 */
1162 public static function transitionParticipants(
1163 $participantIds, $toStatusId,
1164 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1165 ) {
1166 if (!is_array($participantIds) || empty($participantIds) || !$toStatusId) {
1167 return NULL;
1168 }
1169
1170 //thumb rule is if we triggering primary participant need to triggered additional
1171 $allParticipantIds = $primaryANDAdditonalIds = [];
1172 foreach ($participantIds as $id) {
1173 $allParticipantIds[] = $id;
1174 if (self::isPrimaryParticipant($id)) {
1175 //filter additional as per status transition rules, CRM-5403
1176 if ($skipCascadeRule) {
1177 $additionalIds = self::getAdditionalParticipantIds($id);
1178 }
1179 else {
1180 $additionalIds = self::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1181 }
1182 if (!empty($additionalIds)) {
1183 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1184 $primaryANDAdditonalIds[$id] = $additionalIds;
1185 }
1186 }
1187 }
1188
1189 //get the unique participant ids,
1190 $allParticipantIds = array_unique($allParticipantIds);
1191
1192 //pull required participants, contacts, events data, if not in hand
1193 static $eventDetails = [];
1194 static $contactDetails = [];
1195
1196 $contactIds = $eventIds = $participantDetails = [];
1197
1198 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
1199 $participantRoles = CRM_Event_PseudoConstant::participantRole();
1200 $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL,
1201 "class = 'Pending'"
1202 );
1203
1204 //first thing is pull all necessory data from db.
1205 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1206
1207 //get all participants data.
1208 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1209 $dao = CRM_Core_DAO::executeQuery($query);
1210 while ($dao->fetch()) {
1211 $participantDetails[$dao->id] = [
1212 'id' => $dao->id,
1213 'role' => $participantRoles[$dao->role_id],
1214 'is_test' => $dao->is_test,
1215 'event_id' => $dao->event_id,
1216 'status_id' => $dao->status_id,
1217 'fee_amount' => $dao->fee_amount,
1218 'contact_id' => $dao->contact_id,
1219 'register_date' => $dao->register_date,
1220 'registered_by_id' => $dao->registered_by_id,
1221 ];
1222 if (!array_key_exists($dao->contact_id, $contactDetails)) {
1223 $contactIds[$dao->contact_id] = $dao->contact_id;
1224 }
1225
1226 if (!array_key_exists($dao->event_id, $eventDetails)) {
1227 $eventIds[$dao->event_id] = $dao->event_id;
1228 }
1229 }
1230
1231 //get all required contacts detail.
1232 if (!empty($contactIds)) {
1233 $contactDetails += civicrm_api3('Contact', 'get', ['id' => ['IN' => $contactIds, 'return' => 'display_name']])['values'];
1234 }
1235
1236 //get all required events detail.
1237 if (!empty($eventIds)) {
1238 foreach ($eventIds as $eventId) {
1239 //retrieve event information
1240 $eventParams = ['id' => $eventId];
1241 CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]);
1242
1243 //get default participant role.
1244 $eventDetails[$eventId]['participant_role'] = $participantRoles[$eventDetails[$eventId]['default_role_id']] ?? NULL;
1245
1246 //get the location info
1247 $locParams = ['entity_id' => $eventId, 'entity_table' => 'civicrm_event'];
1248 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
1249 }
1250 }
1251
1252 //now we are ready w/ all required data.
1253 //take a decision as per statuses.
1254
1255 $emailType = NULL;
1256 $toStatus = $statusTypes[$toStatusId];
1257 $fromStatus = $statusTypes[$fromStatusId] ?? NULL;
1258
1259 switch ($toStatus) {
1260 case 'Pending from waitlist':
1261 case 'Pending from approval':
1262 switch ($fromStatus) {
1263 case 'On waitlist':
1264 case 'Awaiting approval':
1265 $emailType = 'Confirm';
1266 break;
1267 }
1268 break;
1269
1270 case 'Expired':
1271 //no matter from where u come send expired mail.
1272 $emailType = $toStatus;
1273 break;
1274
1275 case 'Cancelled':
1276 //no matter from where u come send cancel mail.
1277 $emailType = $toStatus;
1278 break;
1279 }
1280
1281 //as we process additional w/ primary, there might be case if user
1282 //select primary as well as additionals, so avoid double processing.
1283 $processedParticipantIds = [];
1284 $mailedParticipants = [];
1285
1286 //send mails and update status.
1287 foreach ($participantDetails as $participantId => $participantValues) {
1288 $updateParticipantIds = [];
1289 if (in_array($participantId, $processedParticipantIds)) {
1290 continue;
1291 }
1292
1293 //check is it primary and has additional.
1294 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1295 foreach ($primaryANDAdditonalIds[$participantId] as $additionalId) {
1296
1297 if ($emailType) {
1298 $mail = self::sendTransitionParticipantMail($additionalId,
1299 $participantDetails[$additionalId],
1300 $eventDetails[$participantDetails[$additionalId]['event_id']],
1301 NULL,
1302 $emailType
1303 );
1304
1305 //get the mail participant ids
1306 if ($mail) {
1307 $mailedParticipants[$additionalId] = $contactDetails[$participantDetails[$additionalId]['contact_id']]['display_name'];
1308 }
1309 }
1310 $updateParticipantIds[] = $additionalId;
1311 $processedParticipantIds[] = $additionalId;
1312 }
1313 }
1314
1315 //now send email appropriate mail to primary.
1316 if ($emailType) {
1317 $mail = self::sendTransitionParticipantMail($participantId,
1318 $participantValues,
1319 $eventDetails[$participantValues['event_id']],
1320 NULL,
1321 $emailType
1322 );
1323
1324 //get the mail participant ids
1325 if ($mail) {
1326 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1327 }
1328 }
1329
1330 //now update status of group/one at once.
1331 $updateParticipantIds[] = $participantId;
1332
1333 //update the register date only when we,
1334 //move participant to pending class, CRM-6496
1335 $updateRegisterDate = FALSE;
1336 if (array_key_exists($toStatusId, $pendingStatuses)) {
1337 $updateRegisterDate = TRUE;
1338 }
1339 self::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1340 $processedParticipantIds[] = $participantId;
1341 }
1342
1343 //return result for cron.
1344 if ($returnResult) {
1345 $results = [
1346 'mailedParticipants' => $mailedParticipants,
1347 'updatedParticipantIds' => $processedParticipantIds,
1348 ];
1349
1350 return $results;
1351 }
1352 }
1353
1354 /**
1355 * Send mail and create activity
1356 * when participant status changed.
1357 *
1358 * @param int $participantId
1359 * Participant id.
1360 * @param array $participantValues
1361 * Participant detail values. status id for participants.
1362 * @param array $eventDetails
1363 * Required event details.
1364 * @param array $contactDetails
1365 * Required contact details.
1366 * @param string $mailType
1367 * (eg 'approval', 'confirm', 'expired' ).
1368 *
1369 * @return bool
1370 */
1371 public static function sendTransitionParticipantMail(
1372 $participantId,
1373 $participantValues,
1374 $eventDetails,
1375 $contactDetails,
1376 $mailType
1377 ) {
1378 //send emails.
1379 $mailSent = FALSE;
1380
1381 if (!$contactDetails) {
1382 $contactDetails = civicrm_api3('Contact', 'getsingle', [
1383 'id' => $participantValues['contact_id'],
1384 'return' => ['email', 'display_name'],
1385 ]);
1386 }
1387 //don't send confirmation mail to additional
1388 //since only primary able to confirm registration.
1389 if (!empty($participantValues['registered_by_id']) &&
1390 $mailType == 'Confirm'
1391 ) {
1392 return $mailSent;
1393 }
1394
1395 $toEmail = $contactDetails['email'] ?? NULL;
1396 if ($toEmail) {
1397
1398 $contactId = $participantValues['contact_id'];
1399 $participantName = $contactDetails['display_name'];
1400
1401 //calculate the checksum value.
1402 $checksumValue = NULL;
1403 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1404 $checksumLife = 'inf';
1405 $endDate = $eventDetails['end_date'] ?? NULL;
1406 if ($endDate) {
1407 $checksumLife = (CRM_Utils_Date::unixTime($endDate) - time()) / (60 * 60);
1408 }
1409 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId, NULL, $checksumLife);
1410 }
1411
1412 //take a receipt from as event else domain.
1413 $receiptFrom = CRM_Core_BAO_Domain::getFromEmail();
1414
1415 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1416 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1417 }
1418
1419 list($mailSent, $subject) = CRM_Core_BAO_MessageTemplate::sendTemplate(
1420 [
1421 'workflow' => 'participant_' . strtolower($mailType),
1422 'contactId' => $contactId,
1423 'tokenContext' => ['participantId' => $participantId],
1424 'tplParams' => [
1425 'participant' => $participantValues,
1426 'event' => $eventDetails,
1427 'paidEvent' => $eventDetails['is_monetary'] ?? NULL,
1428 'isShowLocation' => $eventDetails['is_show_location'] ?? NULL,
1429 'isAdditional' => $participantValues['registered_by_id'],
1430 'isExpired' => $mailType === 'Expired',
1431 'isConfirm' => $mailType === 'Confirm',
1432 'checksumValue' => $checksumValue,
1433 ],
1434 'from' => $receiptFrom,
1435 'toName' => $participantName,
1436 'toEmail' => $toEmail,
1437 'cc' => $eventDetails['cc_confirm'] ?? NULL,
1438 'bcc' => $eventDetails['bcc_confirm'] ?? NULL,
1439 ]
1440 );
1441
1442 // 3. create activity record.
1443 if ($mailSent) {
1444 $now = date('YmdHis');
1445 $activityType = 'Event Registration';
1446 $activityParams = [
1447 'subject' => $subject,
1448 'source_contact_id' => $contactId,
1449 'source_record_id' => $participantId,
1450 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1451 'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
1452 'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']),
1453 'is_test' => $participantValues['is_test'],
1454 'status_id' => 2,
1455 ];
1456
1457 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
1458 throw new CRM_Core_Exception('Failed creating Activity for expiration mail');
1459 }
1460 }
1461 }
1462
1463 return $mailSent;
1464 }
1465
1466 /**
1467 * Get participant status change message.
1468 *
1469 * @param int $participantId
1470 * @param $statusChangeTo
1471 * @param int $fromStatusId
1472 *
1473 * @return string
1474 */
1475 public static function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1476 $statusMsg = NULL;
1477 $results = self::transitionParticipants([$participantId],
1478 $statusChangeTo, $fromStatusId, TRUE
1479 );
1480
1481 $allStatuses = CRM_Event_PseudoConstant::participantStatus();
1482 //give user message only when mail has sent.
1483 if (is_array($results) && !empty($results)) {
1484 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1485 foreach ($results['updatedParticipantIds'] as $processedId) {
1486 if (is_array($results['mailedParticipants']) &&
1487 array_key_exists($processedId, $results['mailedParticipants'])
1488 ) {
1489 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1490 [
1491 1 => $allStatuses[$statusChangeTo],
1492 2 => $results['mailedParticipants'][$processedId],
1493 ]
1494 );
1495 }
1496 }
1497 }
1498 }
1499
1500 return $statusMsg;
1501 }
1502
1503 /**
1504 * Get event full and waiting list message.
1505 *
1506 * @param int $eventId
1507 * @param int $participantId
1508 *
1509 * @return string
1510 */
1511 public static function eventFullMessage($eventId, $participantId = NULL) {
1512 $eventfullMsg = $dbStatusId = NULL;
1513 $checkEventFull = TRUE;
1514 if ($participantId) {
1515 $dbStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1516 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1'))) {
1517 //participant already in counted status no need to check for event full messages.
1518 $checkEventFull = FALSE;
1519 }
1520 }
1521
1522 //early return.
1523 if (!$eventId || !$checkEventFull) {
1524 return $eventfullMsg;
1525 }
1526
1527 //event is truly full.
1528 $emptySeats = self::eventFull($eventId, FALSE, FALSE);
1529 if (is_string($emptySeats) && $emptySeats !== NULL) {
1530 $maxParticipants = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1531 $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.", [
1532 1 => $maxParticipants,
1533 ]) . '<br />';
1534 }
1535
1536 $hasWaiting = FALSE;
1537 $waitListedCount = self::eventFull($eventId, FALSE, TRUE, TRUE);
1538 if (is_numeric($waitListedCount)) {
1539 $hasWaiting = TRUE;
1540 //only current processing participant is on waitlist.
1541 if ($waitListedCount == 1 && CRM_Event_PseudoConstant::participantStatus($dbStatusId) == 'On waitlist') {
1542 $hasWaiting = FALSE;
1543 }
1544 }
1545
1546 if ($hasWaiting) {
1547 $waitingStatusId = array_search('On waitlist',
1548 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'")
1549 );
1550 $viewWaitListUrl = CRM_Utils_System::url('civicrm/event/search',
1551 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1552 );
1553
1554 $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.",
1555 [
1556 1 => $viewWaitListUrl,
1557 2 => $waitListedCount,
1558 ]
1559 );
1560 }
1561
1562 return $eventfullMsg;
1563 }
1564
1565 /**
1566 * Check for whether participant is primary or not.
1567 *
1568 * @param int $participantId
1569 *
1570 * @return bool
1571 * true if participant is primary
1572 */
1573 public static function isPrimaryParticipant($participantId) {
1574
1575 $participant = new CRM_Event_DAO_Participant();
1576 $participant->registered_by_id = $participantId;
1577
1578 if ($participant->find(TRUE)) {
1579 return TRUE;
1580 }
1581 return FALSE;
1582 }
1583
1584 /**
1585 * Get additional participant Ids for cascading with primary participant status.
1586 *
1587 * @param int $participantId
1588 * Participant id.
1589 * @param int $oldStatusId
1590 * Previous status.
1591 * @param int $newStatusId
1592 * New status.
1593 *
1594 * @return array
1595 */
1596 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1597
1598 $additionalParticipantIds = [];
1599
1600 static $participantStatuses = [];
1601
1602 if (empty($participantStatuses)) {
1603 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1604 }
1605
1606 if (!empty(self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]]) &&
1607 in_array($participantStatuses[$newStatusId], self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1608 ) {
1609 $additionalParticipantIds = self::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1610 }
1611
1612 return $additionalParticipantIds;
1613 }
1614
1615 /**
1616 * Get participant record count for a Contact.
1617 *
1618 * @param int $contactID
1619 *
1620 * @return int
1621 * count of participant records
1622 */
1623 public static function getContactParticipantCount($contactID) {
1624 $query = "SELECT count(*)
1625 FROM civicrm_participant
1626 WHERE civicrm_participant.contact_id = {$contactID} AND
1627 civicrm_participant.is_test = 0";
1628 return CRM_Core_DAO::singleValueQuery($query);
1629 }
1630
1631 /**
1632 * Get participant ids by contribution id.
1633 *
1634 * @param int $contributionId
1635 * Contribution Id.
1636 * @param bool $excludeCancelled
1637 * Exclude cancelled additional participant.
1638 *
1639 * @return array
1640 */
1641 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1642
1643 $ids = [];
1644 if (!$contributionId) {
1645 return $ids;
1646 }
1647
1648 // get primary participant id
1649 $query = "SELECT participant_id
1650 FROM civicrm_participant cp
1651 LEFT JOIN civicrm_participant_payment cpp ON cp.id = cpp.participant_id
1652 WHERE cpp.contribution_id = {$contributionId}
1653 AND cp.registered_by_id IS NULL";
1654 $participantPayment = CRM_Core_DAO::executeQuery($query);
1655
1656 // get additional participant ids (including cancelled)
1657 while ($participantPayment->fetch()) {
1658 $ids = array_merge($ids, array_merge([
1659 $participantPayment->participant_id,
1660 ], self::getAdditionalParticipantIds($participantPayment->participant_id,
1661 $excludeCancelled
1662 )));
1663 }
1664
1665 return $ids;
1666 }
1667
1668 /**
1669 * Get additional Participant edit & view url .
1670 *
1671 * @param array $participantIds
1672 * An array of additional participant ids.
1673 *
1674 * @return array
1675 * Array of Urls.
1676 */
1677 public static function getAdditionalParticipantUrl($participantIds) {
1678 foreach ($participantIds as $value) {
1679 $links = [];
1680 $details = self::participantDetails($value);
1681 $viewUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1682 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1683 );
1684 $editUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1685 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1686 );
1687 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1688 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1689 return $links;
1690 }
1691 }
1692
1693 /**
1694 * create trxn entry if an event has discount.
1695 *
1696 * @param int $eventID
1697 * Event id.
1698 * @param array $contributionParams
1699 * Contribution params.
1700 *
1701 * @param string $feeLevel (deprecated)
1702 * @param int $discountedPriceFieldOptionID
1703 * ID of the civicrm_price_field_value field for the discount id.
1704 */
1705 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID = NULL) {
1706 $financialTypeID = $contributionParams['contribution']->financial_type_id;
1707 $total_amount = $contributionParams['total_amount'];
1708
1709 $checkDiscount = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
1710 if (!empty($checkDiscount)) {
1711 $mainAmount = self::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
1712 $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount(
1713 $financialTypeID, 'Discounts Account is');
1714 if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
1715 $transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
1716 $transactionParams['trxnParams']['payment_processor_id'] = NULL;
1717 $transactionParams['trxnParams']['payment_instrument_id'] = NULL;
1718 $transactionParams['trxnParams']['check_number'] = NULL;
1719 $transactionParams['trxnParams']['trxn_id'] = NULL;
1720 $transactionParams['trxnParams']['net_amount'] = NULL;
1721 $transactionParams['trxnParams']['fee_amount'] = NULL;
1722 CRM_Core_BAO_FinancialTrxn::create($transactionParams);
1723 }
1724 }
1725 }
1726
1727 /**
1728 * Delete participants of contact.
1729 *
1730 * @see https://issues.civicrm.org/jira/browse/CRM-12155
1731 *
1732 * @param int $contactId
1733 * Contact id.
1734 *
1735 */
1736 public static function deleteContactParticipant($contactId) {
1737 $participant = new CRM_Event_DAO_Participant();
1738 $participant->contact_id = $contactId;
1739 $participant->find();
1740 while ($participant->fetch()) {
1741 self::deleteParticipant($participant->id);
1742 }
1743 }
1744
1745 /**
1746 * @param int $participantId
1747 * @param $activityType
1748 *
1749 * @throws CRM_Core_Exception
1750 */
1751 public static function addActivityForSelection($participantId, $activityType) {
1752 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
1753 $contactId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
1754
1755 $date = CRM_Utils_Date::currentDBDate();
1756 $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
1757 $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array::value($eventId, $event));
1758
1759 // activity params
1760 $activityParams = [
1761 'source_contact_id' => $contactId,
1762 'source_record_id' => $participantId,
1763 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1764 'subject' => $subject,
1765 'activity_date_time' => $date,
1766 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1767 'skipRecentView' => TRUE,
1768 ];
1769
1770 // create activity with target contacts
1771 $id = CRM_Core_Session::getLoggedInContactID();
1772 if ($id) {
1773 $activityParams['source_contact_id'] = $id;
1774 $activityParams['target_contact_id'][] = $contactId;
1775 }
1776 // @todo use api & also look at duplication of similar methods.
1777 CRM_Activity_BAO_Activity::create($activityParams);
1778 }
1779
1780 /**
1781 * Get options for a given field.
1782 * @see CRM_Core_DAO::buildOptions
1783 *
1784 * @param string $fieldName
1785 * @param string $context
1786 * @see CRM_Core_DAO::buildOptionsContext
1787 * @param array $props
1788 * whatever is known about this dao object.
1789 *
1790 * @return array|bool
1791 */
1792 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1793 $params = ['condition' => []];
1794
1795 if ($fieldName == 'status_id' && $context != 'validate') {
1796 // Get rid of cart-related option if disabled
1797 // FIXME: Why does this option even exist if cart is disabled?
1798 if (!Civi::settings()->get('enable_cart')) {
1799 $params['condition'][] = "name <> 'Pending in cart'";
1800 }
1801 }
1802
1803 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
1804 }
1805
1806 /**
1807 * CRM-17797 -- Format fields and setDefaults for primary and additional participants profile
1808 * @param int $contactId
1809 * @param CRM_Core_Form $form
1810 */
1811 public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
1812 if (!$contactId) {
1813 return;
1814 }
1815 $fields = [];
1816 if (!empty($form->_fields)) {
1817 $removeCustomFieldTypes = ['Participant'];
1818
1819 foreach ($form->_fields as $name => $fieldInfo) {
1820 if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
1821 && !CRM_Core_BAO_CustomGroup::checkCustomField(substr($name, 7), $removeCustomFieldTypes))
1822 || substr($name, 0, 12) == 'participant_') {
1823 continue;
1824 }
1825 $fields[$name] = $fieldInfo;
1826 }
1827
1828 if (!empty($fields)) {
1829 CRM_Core_BAO_UFGroup::setProfileDefaults($contactId, $fields, $form->_defaults);
1830 }
1831 }
1832 }
1833
1834 /**
1835 * Evaluate whether a participant record is eligible for self-service transfer/cancellation. If so,
1836 * return additional participant/event details.
1837 *
1838 * @param int $participantId
1839 * @param string $url
1840 * @param bool $isBackOffice
1841 */
1842 public static function getSelfServiceEligibility(int $participantId, string $url, bool $isBackOffice) : array {
1843 $optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'participant_role', 'id', 'name');
1844 $query = "
1845 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
1846 FROM civicrm_participant cp
1847 LEFT JOIN civicrm_participant_status_type cpst ON cpst.id = cp.status_id
1848 LEFT JOIN civicrm_option_value cov ON cov.value = cp.role_id and cov.option_group_id = {$optionGroupId}
1849 LEFT JOIN civicrm_event ce ON ce.id = cp.event_id
1850 WHERE cp.id = {$participantId}";
1851 $dao = CRM_Core_DAO::executeQuery($query);
1852 while ($dao->fetch()) {
1853 $details['eligible'] = TRUE;
1854 $details['status'] = $dao->status;
1855 $details['role'] = $dao->role;
1856 $details['fee_level'] = trim($dao->fee_level, CRM_Core_DAO::VALUE_SEPARATOR);
1857 $details['fee_amount'] = $dao->fee_amount;
1858 $details['register_date'] = $dao->register_date;
1859 $details['event_start_date'] = $dao->start_date;
1860 $details['allow_selfcancelxfer'] = $dao->allow_selfcancelxfer;
1861 $eventTitle = $dao->title;
1862 $eventId = $dao->event_id;
1863 }
1864 if (!$details['allow_selfcancelxfer'] && !$isBackOffice) {
1865 $details['eligible'] = FALSE;
1866 $details['ineligible_message'] = ts('This event registration can not be transferred or cancelled. Contact the event organizer if you have questions.');
1867 return $details;
1868 }
1869 //verify participant status is still Registered
1870 if ($details['status'] != 'Registered') {
1871 $details['eligible'] = FALSE;
1872 $details['ineligible_message'] = "You cannot transfer or cancel your registration for " . $eventTitle . ' as you are not currently registered for this event.';
1873 return $details;
1874 }
1875 // Determine if it's too late to self-service cancel/transfer.
1876 $query = "select start_date as start, selfcancelxfer_time as time from civicrm_event where id = " . $eventId;
1877 $dao = CRM_Core_DAO::executeQuery($query);
1878 while ($dao->fetch()) {
1879 $time_limit = $dao->time;
1880 $start_date = $dao->start;
1881 }
1882 $timenow = new Datetime();
1883 if (!$isBackOffice && isset($time_limit)) {
1884 $cancelHours = abs($time_limit);
1885 $cancelInterval = new DateInterval("PT${cancelHours}H");
1886 $cancelInterval->invert = $time_limit < 0 ? 1 : 0;
1887 $cancelDeadline = (new Datetime($start_date))->sub($cancelInterval);
1888 if ($timenow > $cancelDeadline) {
1889 $details['eligible'] = FALSE;
1890 // Change the language of the status message based on whether the waitlist time limit is positive or negative.
1891 $afterOrPrior = $time_limit <= 0 ? 'after' : 'prior to';
1892 $moreOrLess = $time_limit <= 0 ? 'more' : 'fewer';
1893 $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.",
1894 [1 => $moreOrLess, 2 => $cancelHours, 3 => $afterOrPrior]);
1895
1896 }
1897 }
1898 return $details;
1899 }
1900
1901 }