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