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