Merge pull request #21228 from colemanw/afformFixTitle
[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
EM
46
47 /**
0cf587a7 48 */
00be9182 49 public function __construct() {
6a488035
TO
50 parent::__construct();
51 }
52
53 /**
66f9e52b 54 * Takes an associative array and creates a participant object.
6a488035
TO
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 *
d4dd1e85
TO
60 * @param array $params
61 * (reference ) an assoc array of name/value pairs.
77035e4b 62 *
16b10e64 63 * @return CRM_Event_BAO_Participant
6a488035 64 */
00be9182 65 public static function &add(&$params) {
6a488035 66
a7488080 67 if (!empty($params['id'])) {
6a488035
TO
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
a7488080 75 if (!empty($params['register_date'])) {
6a488035
TO
76 $params['register_date'] = CRM_Utils_Date::isoToMysql($params['register_date']);
77 }
78
a7488080 79 if (!empty($params['participant_fee_amount'])) {
6a488035
TO
80 $params['participant_fee_amount'] = CRM_Utils_Rule::cleanMoney($params['participant_fee_amount']);
81 }
82
7577274a 83 // ensure that role ids are encoded as a string
3cef9954 84 if (isset($params['role_id']) && is_array($params['role_id'])) {
653cbe46 85 if (in_array(key($params['role_id']), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
e51b7372 86 $op = key($params['role_id']);
87 $params['role_id'] = $params['role_id'][$op];
88 }
774e09ad 89 else {
90 $params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
91 }
7577274a
KJ
92 }
93
2177d15c 94 $participantBAO = new CRM_Event_BAO_Participant();
a7488080 95 if (!empty($params['id'])) {
9c1bc317 96 $participantBAO->id = $params['id'] ?? NULL;
6a488035
TO
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
2b68a50c 119 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
6a488035 120
a7488080 121 if (!empty($params['id'])) {
6a488035
TO
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 *
d4dd1e85
TO
135 * @param array $params
136 * Input parameters to find object.
137 * @param array $values
138 * Output values of the object.
6a488035 139 *
77035e4b
EM
140 * @param $ids
141 *
6a488035 142 * @return CRM_Event_BAO_Participant|null the found object or null
6a488035 143 */
db62d3a5 144 public static function getValues(&$params, &$values = [], &$ids = []) {
6a488035
TO
145 if (empty($params)) {
146 return NULL;
147 }
148 $participant = new CRM_Event_BAO_Participant();
149 $participant->copyValues($params);
150 $participant->find();
be2fb01f 151 $participants = [];
6a488035
TO
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 /**
66f9e52b 161 * Takes an associative array and creates a participant object.
6a488035 162 *
d4dd1e85
TO
163 * @param array $params
164 * (reference ) an assoc array of name/value pairs.
77035e4b 165 *
16b10e64 166 * @return CRM_Event_BAO_Participant
6a488035 167 */
00be9182 168 public static function create(&$params) {
6a488035
TO
169
170 $transaction = new CRM_Core_Transaction();
171 $status = NULL;
172
a7488080 173 if (!empty($params['id'])) {
6a488035
TO
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
d41da727
CW
184 // Log activity when creating new participant or changing status
185 if (empty($params['id']) ||
9af2925b 186 (isset($params['status_id']) && $params['status_id'] != $status)
6a488035 187 ) {
d41da727
CW
188 // Default status if not specified
189 $participant->status_id = $participant->status_id ?: self::fields()['participant_status_id']['default'];
75ae745c 190 CRM_Activity_BAO_Activity::addActivity($participant, 'Event Registration');
6a488035
TO
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) {
9c1bc317 202 $id = $params['contact_id'] ?? NULL;
6a488035
TO
203 }
204
205 // add custom field values
a7488080 206 if (!empty($params['custom']) &&
6a488035
TO
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;
a7488080 214 if (!empty($params['id'])) {
6a488035
TO
215 $note = CRM_Core_BAO_Note::getNote($params['id'], 'civicrm_participant');
216 $noteId = key($note);
217 }
218 $noteValue = NULL;
219 $hasNoteField = FALSE;
be2fb01f 220 foreach ([
90b461f1
SL
221 'note',
222 'participant_note',
223 ] as $noteFld) {
6a488035
TO
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) {
be2fb01f 232 $noteParams = [
6a488035
TO
233 'entity_table' => 'civicrm_participant',
234 'note' => $noteValue,
235 'entity_id' => $participant->id,
236 'contact_id' => $id,
be2fb01f
CW
237 ];
238 $noteIDs = [];
6a488035
TO
239 if ($noteId) {
240 $noteIDs['id'] = $noteId;
241 }
242 CRM_Core_BAO_Note::add($noteParams, $noteIDs);
243 }
244 elseif ($noteId && $hasNoteField) {
6623e554 245 CRM_Core_BAO_Note::deleteRecord(['id' => $noteId]);
6a488035
TO
246 }
247 }
248
249 // Log the information on successful add/edit of Participant data.
be2fb01f 250 $logParams = [
6a488035
TO
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'),
be2fb01f 256 ];
6a488035
TO
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
a7488080 265 if (empty($params['skipRecentView'])) {
6a488035
TO
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
be2fb01f 271 $recentOther = [];
6a488035
TO
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 /**
66f9e52b 315 * Check whether the event is full for participation and return as.
6a488035
TO
316 * per requirements.
317 *
d4dd1e85
TO
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.
6a488035
TO
324 * calculation or not. (it is for cron job purpose)
325 *
77035e4b
EM
326 * @param bool $returnWaitingCount
327 * @param bool $considerTestParticipant
49f3a6ff
JG
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".
6a488035 334 *
72b3a70c
CW
335 * @return bool|int|null|string
336 * 1. false => If event having some empty spaces.
6a488035 337 */
2da40d21 338 public static function eventFull(
6a488035
TO
339 $eventId,
340 $returnEmptySeats = FALSE,
341 $includeWaitingList = TRUE,
342 $returnWaitingCount = FALSE,
49f3a6ff
JG
343 $considerTestParticipant = FALSE,
344 $onlyPositiveStatuses = FALSE
6a488035
TO
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
ddca8f33
TO
357 $participantRoles = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
358 $countedStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
49f3a6ff 359 $positiveStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Positive'");
ddca8f33 360 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
6a488035
TO
361 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
362
be2fb01f 363 $where = [' event.id = %1 '];
6a488035
TO
364 if (!$considerTestParticipant) {
365 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
366 }
49f3a6ff
JG
367
368 // Only count Participant Roles with the "Counted?" flag.
6a488035 369 if (!empty($participantRoles)) {
be2fb01f 370 $escapedRoles = [];
0906de17
MM
371 foreach (array_keys($participantRoles) as $participantRole) {
372 $escapedRoles[] = CRM_Utils_Type::escape($participantRole, 'String');
373 }
374
a7aa4454
CW
375 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', $escapedRoles) . "([[:cntrl:]]|$)";
376 $where[] = " participant.role_id REGEXP '{$regexp}'";
6a488035
TO
377 }
378
be2fb01f 379 $eventParams = [1 => [$eventId, 'Positive']];
6a488035
TO
380
381 //in case any waiting, straight forward event is full.
382 if ($includeWaitingList && $onWaitlistStatusId) {
383
384 //build the where clause.
ddca8f33
TO
385 $whereClause = ' WHERE ' . implode(' AND ', $where);
386 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
6a488035
TO
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
393INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
394 {$whereClause}";
395
92d6c5f5 396 $eventFullText = ts('This event is full.');
6a488035
TO
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
49f3a6ff
JG
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 }
ddca8f33 416 $whereClause = ' WHERE ' . implode(' AND ', $where);
6a488035
TO
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
424INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
425 {$whereClause}";
426
427 $eventMaxSeats = NULL;
92d6c5f5 428 $eventFullText = ts('This event is full.');
ddca8f33 429 $participants = CRM_Core_DAO::executeQuery($query, $eventParams);
6a488035
TO
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 = '
455SELECT 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
31312bdc 474 return $eventFullText;
6a488035
TO
475 }
476
477 /**
478 * Return the array of all price set field options,
479 * with total participant count that field going to carry.
480 *
d4dd1e85
TO
481 * @param int $eventId
482 * Event id.
483 * @param array $skipParticipantIds
484 * An array of participant ids those we should skip.
77035e4b
EM
485 * @param bool $considerCounted
486 * @param bool $considerWaiting
487 * @param bool $considerTestParticipants
488 *
a6c01b45
CW
489 * @return array
490 * an array of each option id and total count
6a488035 491 */
2da40d21 492 public static function priceSetOptionsCount(
6a488035 493 $eventId,
be2fb01f 494 $skipParticipantIds = [],
6a488035
TO
495 $considerCounted = TRUE,
496 $considerWaiting = TRUE,
497 $considerTestParticipants = FALSE
498 ) {
be2fb01f 499 $optionsCount = [];
6a488035
TO
500 if (!$eventId) {
501 return $optionsCount;
502 }
503
be2fb01f 504 $allStatusIds = [];
6a488035
TO
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
536INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
537 AND participant.id = line.entity_id )
538INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
539INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
540 WHERE participant.event_id = %1
0d9c7c6d 541 AND line.qty > 0
6a488035
TO
542 {$statusIdClause}
543 {$isTestClause}
544 {$skipParticipantClause}";
545
be2fb01f 546 $lineItem = CRM_Core_DAO::executeQuery($sql, [1 => [$eventId, 'Positive']]);
6a488035
TO
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 *
49f3a6ff
JG
565 * @deprecated
566 *
d4dd1e85
TO
567 * @param int $eventId
568 * Event id.
6a488035 569 *
a6c01b45
CW
570 * @return int
571 * $spaces Number of Empty Seats/null.
6a488035 572 */
00be9182 573 public static function pendingToConfirmSpaces($eventId) {
49f3a6ff
JG
574 CRM_Core_Error::deprecatedFunctionWarning('CRM_Event_BAO_Participant::eventFull');
575 return CRM_Event_BAO_Participant::eventFull($eventId, TRUE, FALSE, TRUE, FALSE, TRUE);
6a488035
TO
576 }
577
578 /**
66f9e52b 579 * Combine all the importable fields from the lower levels object.
6a488035 580 *
77035e4b
EM
581 * @param string $contactType
582 * @param bool $status
583 * @param bool $onlyParticipant
e9ff5391 584 * @param bool $checkPermission
585 * Is this a permissioned retrieval?
77035e4b 586 *
a6c01b45
CW
587 * @return array
588 * array of importable Fields
6a488035 589 */
e9ff5391 590 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE) {
6a488035
TO
591 if (!self::$_importableFields) {
592 if (!$onlyParticipant) {
593 if (!$status) {
be2fb01f 594 $fields = ['' => ['title' => ts('- do not import -')]];
6a488035
TO
595 }
596 else {
be2fb01f 597 $fields = ['' => ['title' => ts('- Participant Fields -')]];
6a488035
TO
598 }
599 }
600 else {
be2fb01f 601 $fields = [];
6a488035
TO
602 }
603
604 $tmpFields = CRM_Event_DAO_Participant::import();
605
be2fb01f
CW
606 $note = [
607 'participant_note' => [
3cb8f9b2 608 'title' => ts('Participant Note'),
6a488035
TO
609 'name' => 'participant_note',
610 'headerPattern' => '/(participant.)?note$/i',
672b875d 611 'data_type' => CRM_Utils_Type::T_TEXT,
be2fb01f
CW
612 ],
613 ];
6a488035 614
3cb8f9b2
CW
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
be2fb01f
CW
617 $participantStatus = [
618 'participant_status' => [
3cb8f9b2 619 'title' => ts('Participant Status'),
6a488035
TO
620 'name' => 'participant_status',
621 'data_type' => CRM_Utils_Type::T_STRING,
be2fb01f
CW
622 ],
623 ];
3cb8f9b2 624 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
6a488035 625
3cb8f9b2
CW
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
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
801 * @param string $lookup
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
be2fb01f 1177 $allParticipantIds = $primaryANDAdditonalIds = [];
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);
1190 $primaryANDAdditonalIds[$id] = $additionalIds;
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
CW
1199 static $eventDetails = [];
1200 static $domainValues = [];
1201 static $contactDetails = [];
6a488035 1202
be2fb01f 1203 $contactIds = $eventIds = $participantDetails = [];
6a488035 1204
ddca8f33 1205 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
6a488035 1206 $participantRoles = CRM_Event_PseudoConstant::participantRole();
ddca8f33 1207 $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL,
6a488035
TO
1208 "class = 'Pending'"
1209 );
1210
1211 //first thing is pull all necessory data from db.
1212 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1213
1214 //get all participants data.
1215 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1216 $dao = CRM_Core_DAO::executeQuery($query);
1217 while ($dao->fetch()) {
be2fb01f 1218 $participantDetails[$dao->id] = [
6a488035
TO
1219 'id' => $dao->id,
1220 'role' => $participantRoles[$dao->role_id],
1221 'is_test' => $dao->is_test,
1222 'event_id' => $dao->event_id,
1223 'status_id' => $dao->status_id,
1224 'fee_amount' => $dao->fee_amount,
1225 'contact_id' => $dao->contact_id,
1226 'register_date' => $dao->register_date,
1227 'registered_by_id' => $dao->registered_by_id,
be2fb01f 1228 ];
6a488035
TO
1229 if (!array_key_exists($dao->contact_id, $contactDetails)) {
1230 $contactIds[$dao->contact_id] = $dao->contact_id;
1231 }
1232
1233 if (!array_key_exists($dao->event_id, $eventDetails)) {
1234 $eventIds[$dao->event_id] = $dao->event_id;
1235 }
1236 }
1237
1238 //get the domain values.
1239 if (empty($domainValues)) {
1240 // making all tokens available to templates.
1241 $domain = CRM_Core_BAO_Domain::getDomain();
be2fb01f
CW
1242 $tokens = [
1243 'domain' => ['name', 'phone', 'address', 'email'],
6a488035 1244 'contact' => CRM_Core_SelectValues::contactTokens(),
be2fb01f 1245 ];
6a488035
TO
1246
1247 foreach ($tokens['domain'] as $token) {
1248 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
1249 }
1250 }
1251
1252 //get all required contacts detail.
1253 if (!empty($contactIds)) {
1254 // get the contact details.
1255 list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
1256 FALSE, FALSE, NULL,
be2fb01f 1257 [],
6a488035
TO
1258 'CRM_Event_BAO_Participant'
1259 );
1260 foreach ($currentContactDetails as $contactId => $contactValues) {
1261 $contactDetails[$contactId] = $contactValues;
1262 }
1263 }
1264
1265 //get all required events detail.
1266 if (!empty($eventIds)) {
1267 foreach ($eventIds as $eventId) {
1268 //retrieve event information
be2fb01f 1269 $eventParams = ['id' => $eventId];
6a488035
TO
1270 CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]);
1271
1272 //get default participant role.
9c1bc317 1273 $eventDetails[$eventId]['participant_role'] = $participantRoles[$eventDetails[$eventId]['default_role_id']] ?? NULL;
6a488035
TO
1274
1275 //get the location info
be2fb01f 1276 $locParams = ['entity_id' => $eventId, 'entity_table' => 'civicrm_event'];
6a488035
TO
1277 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
1278 }
1279 }
1280
1281 //now we are ready w/ all required data.
1282 //take a decision as per statuses.
1283
ddca8f33
TO
1284 $emailType = NULL;
1285 $toStatus = $statusTypes[$toStatusId];
9c1bc317 1286 $fromStatus = $statusTypes[$fromStatusId] ?? NULL;
6a488035
TO
1287
1288 switch ($toStatus) {
1289 case 'Pending from waitlist':
1290 case 'Pending from approval':
1291 switch ($fromStatus) {
1292 case 'On waitlist':
1293 case 'Awaiting approval':
1294 $emailType = 'Confirm';
1295 break;
1296 }
1297 break;
1298
1299 case 'Expired':
1300 //no matter from where u come send expired mail.
1301 $emailType = $toStatus;
1302 break;
1303
1304 case 'Cancelled':
1305 //no matter from where u come send cancel mail.
1306 $emailType = $toStatus;
1307 break;
1308 }
1309
1310 //as we process additional w/ primary, there might be case if user
1311 //select primary as well as additionals, so avoid double processing.
be2fb01f
CW
1312 $processedParticipantIds = [];
1313 $mailedParticipants = [];
6a488035
TO
1314
1315 //send mails and update status.
1316 foreach ($participantDetails as $participantId => $participantValues) {
be2fb01f 1317 $updateParticipantIds = [];
6a488035
TO
1318 if (in_array($participantId, $processedParticipantIds)) {
1319 continue;
1320 }
1321
1322 //check is it primary and has additional.
1323 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
a0d6db1e 1324 foreach ($primaryANDAdditonalIds[$participantId] as $additionalId) {
6a488035
TO
1325
1326 if ($emailType) {
a0d6db1e 1327 $mail = self::sendTransitionParticipantMail($additionalId,
1328 $participantDetails[$additionalId],
1329 $eventDetails[$participantDetails[$additionalId]['event_id']],
1330 $contactDetails[$participantDetails[$additionalId]['contact_id']],
6a488035
TO
1331 $domainValues,
1332 $emailType
1333 );
1334
1335 //get the mail participant ids
1336 if ($mail) {
a0d6db1e 1337 $mailedParticipants[$additionalId] = $contactDetails[$participantDetails[$additionalId]['contact_id']]['display_name'];
6a488035
TO
1338 }
1339 }
a0d6db1e 1340 $updateParticipantIds[] = $additionalId;
1341 $processedParticipantIds[] = $additionalId;
6a488035
TO
1342 }
1343 }
1344
1345 //now send email appropriate mail to primary.
1346 if ($emailType) {
1347 $mail = self::sendTransitionParticipantMail($participantId,
1348 $participantValues,
1349 $eventDetails[$participantValues['event_id']],
1350 $contactDetails[$participantValues['contact_id']],
1351 $domainValues,
1352 $emailType
1353 );
1354
1355 //get the mail participant ids
1356 if ($mail) {
1357 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1358 }
1359 }
1360
1361 //now update status of group/one at once.
1362 $updateParticipantIds[] = $participantId;
1363
1364 //update the register date only when we,
1365 //move participant to pending class, CRM-6496
1366 $updateRegisterDate = FALSE;
1367 if (array_key_exists($toStatusId, $pendingStatuses)) {
1368 $updateRegisterDate = TRUE;
1369 }
1370 self::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1371 $processedParticipantIds[] = $participantId;
1372 }
1373
1374 //return result for cron.
1375 if ($returnResult) {
be2fb01f 1376 $results = [
6a488035
TO
1377 'mailedParticipants' => $mailedParticipants,
1378 'updatedParticipantIds' => $processedParticipantIds,
be2fb01f 1379 ];
6a488035
TO
1380
1381 return $results;
1382 }
1383 }
1384
1385 /**
100fef9d 1386 * Send mail and create activity
6a488035
TO
1387 * when participant status changed.
1388 *
d4dd1e85
TO
1389 * @param int $participantId
1390 * Participant id.
1391 * @param array $participantValues
1392 * Participant detail values. status id for participants.
1393 * @param array $eventDetails
1394 * Required event details.
1395 * @param array $contactDetails
1396 * Required contact details.
1397 * @param array $domainValues
1398 * Required domain values.
1399 * @param string $mailType
1400 * (eg 'approval', 'confirm', 'expired' ).
6a488035 1401 *
654ca41c 1402 * @return bool
6a488035 1403 */
2da40d21 1404 public static function sendTransitionParticipantMail(
6a488035
TO
1405 $participantId,
1406 $participantValues,
1407 $eventDetails,
1408 $contactDetails,
1409 &$domainValues,
1410 $mailType
1411 ) {
1412 //send emails.
1413 $mailSent = FALSE;
1414
1415 //don't send confirmation mail to additional
1416 //since only primary able to confirm registration.
a7488080 1417 if (!empty($participantValues['registered_by_id']) &&
6a488035
TO
1418 $mailType == 'Confirm'
1419 ) {
1420 return $mailSent;
1421 }
9c1bc317 1422 $toEmail = $contactDetails['email'] ?? NULL;
0cca0bf4 1423 if ($toEmail) {
6a488035
TO
1424
1425 $contactId = $participantValues['contact_id'];
1426 $participantName = $contactDetails['display_name'];
1427
1428 //calculate the checksum value.
1429 $checksumValue = NULL;
1430 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1431 $checksumLife = 'inf';
9c1bc317 1432 $endDate = $eventDetails['end_date'] ?? NULL;
0cca0bf4 1433 if ($endDate) {
6a488035
TO
1434 $checksumLife = (CRM_Utils_Date::unixTime($endDate) - time()) / (60 * 60);
1435 }
1436 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId, NULL, $checksumLife);
1437 }
1438
1439 //take a receipt from as event else domain.
1440 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
8cc574cf 1441 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
6a488035
TO
1442 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1443 }
1444
c6327d7d 1445 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
be2fb01f 1446 [
6a488035
TO
1447 'groupName' => 'msg_tpl_workflow_event',
1448 'valueName' => 'participant_' . strtolower($mailType),
1449 'contactId' => $contactId,
be2fb01f 1450 'tplParams' => [
6a488035
TO
1451 'contact' => $contactDetails,
1452 'domain' => $domainValues,
1453 'participant' => $participantValues,
1454 'event' => $eventDetails,
6b409353
CW
1455 'paidEvent' => $eventDetails['is_monetary'] ?? NULL,
1456 'isShowLocation' => $eventDetails['is_show_location'] ?? NULL,
6a488035
TO
1457 'isAdditional' => $participantValues['registered_by_id'],
1458 'isExpired' => $mailType == 'Expired',
1459 'isConfirm' => $mailType == 'Confirm',
1460 'checksumValue' => $checksumValue,
be2fb01f 1461 ],
6a488035
TO
1462 'from' => $receiptFrom,
1463 'toName' => $participantName,
1464 'toEmail' => $toEmail,
6b409353
CW
1465 'cc' => $eventDetails['cc_confirm'] ?? NULL,
1466 'bcc' => $eventDetails['bcc_confirm'] ?? NULL,
be2fb01f 1467 ]
6a488035
TO
1468 );
1469
1470 // 3. create activity record.
1471 if ($mailSent) {
ddca8f33
TO
1472 $now = date('YmdHis');
1473 $activityType = 'Event Registration';
be2fb01f 1474 $activityParams = [
6a488035
TO
1475 'subject' => $subject,
1476 'source_contact_id' => $contactId,
1477 'source_record_id' => $participantId,
593dbb07 1478 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
6a488035
TO
1479 'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
1480 'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']),
1481 'is_test' => $participantValues['is_test'],
1482 'status_id' => 2,
be2fb01f 1483 ];
6a488035
TO
1484
1485 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
79e11805 1486 throw new CRM_Core_Exception('Failed creating Activity for expiration mail');
6a488035
TO
1487 }
1488 }
1489 }
1490
1491 return $mailSent;
1492 }
1493
1494 /**
100fef9d 1495 * Get participant status change message.
6a488035 1496 *
100fef9d 1497 * @param int $participantId
654ca41c 1498 * @param $statusChangeTo
100fef9d 1499 * @param int $fromStatusId
654ca41c 1500 *
6a488035 1501 * @return string
6a488035 1502 */
00be9182 1503 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
6a488035 1504 $statusMsg = NULL;
be2fb01f 1505 $results = self::transitionParticipants([$participantId],
6a488035
TO
1506 $statusChangeTo, $fromStatusId, TRUE
1507 );
1508
1509 $allStatuses = CRM_Event_PseudoConstant::participantStatus();
1510 //give user message only when mail has sent.
1511 if (is_array($results) && !empty($results)) {
1512 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1513 foreach ($results['updatedParticipantIds'] as $processedId) {
1514 if (is_array($results['mailedParticipants']) &&
1515 array_key_exists($processedId, $results['mailedParticipants'])
1516 ) {
1517 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
be2fb01f 1518 [
ddca8f33
TO
1519 1 => $allStatuses[$statusChangeTo],
1520 2 => $results['mailedParticipants'][$processedId],
be2fb01f 1521 ]
ddca8f33 1522 );
6a488035
TO
1523 }
1524 }
1525 }
1526 }
1527
1528 return $statusMsg;
1529 }
1530
1531 /**
100fef9d 1532 * Get event full and waiting list message.
6a488035 1533 *
100fef9d
CW
1534 * @param int $eventId
1535 * @param int $participantId
654ca41c 1536 *
6a488035 1537 * @return string
6a488035 1538 */
00be9182 1539 public static function eventFullMessage($eventId, $participantId = NULL) {
6a488035
TO
1540 $eventfullMsg = $dbStatusId = NULL;
1541 $checkEventFull = TRUE;
1542 if ($participantId) {
1543 $dbStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1544 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1'))) {
1545 //participant already in counted status no need to check for event full messages.
1546 $checkEventFull = FALSE;
1547 }
1548 }
1549
1550 //early return.
1551 if (!$eventId || !$checkEventFull) {
1552 return $eventfullMsg;
1553 }
1554
1555 //event is truly full.
1556 $emptySeats = self::eventFull($eventId, FALSE, FALSE);
1557 if (is_string($emptySeats) && $emptySeats !== NULL) {
1558 $maxParticipants = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
be2fb01f 1559 $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
1560 1 => $maxParticipants,
1561 ]) . '<br />';
6a488035
TO
1562 }
1563
1564 $hasWaiting = FALSE;
1565 $waitListedCount = self::eventFull($eventId, FALSE, TRUE, TRUE);
1566 if (is_numeric($waitListedCount)) {
1567 $hasWaiting = TRUE;
1568 //only current processing participant is on waitlist.
1569 if ($waitListedCount == 1 && CRM_Event_PseudoConstant::participantStatus($dbStatusId) == 'On waitlist') {
1570 $hasWaiting = FALSE;
1571 }
1572 }
1573
1574 if ($hasWaiting) {
1575 $waitingStatusId = array_search('On waitlist',
1576 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'")
1577 );
1578 $viewWaitListUrl = CRM_Utils_System::url('civicrm/event/search',
1579 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1580 );
1581
1582 $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 1583 [
6a488035
TO
1584 1 => $viewWaitListUrl,
1585 2 => $waitListedCount,
be2fb01f 1586 ]
6a488035
TO
1587 );
1588 }
1589
1590 return $eventfullMsg;
1591 }
1592
1593 /**
66f9e52b 1594 * Check for whether participant is primary or not.
6a488035 1595 *
100fef9d 1596 * @param int $participantId
6a488035 1597 *
72b3a70c
CW
1598 * @return bool
1599 * true if participant is primary
6a488035 1600 */
00be9182 1601 public static function isPrimaryParticipant($participantId) {
6a488035
TO
1602
1603 $participant = new CRM_Event_DAO_Participant();
1604 $participant->registered_by_id = $participantId;
1605
1606 if ($participant->find(TRUE)) {
1607 return TRUE;
1608 }
1609 return FALSE;
1610 }
1611
1612 /**
66f9e52b 1613 * Get additional participant Ids for cascading with primary participant status.
6a488035 1614 *
d4dd1e85
TO
1615 * @param int $participantId
1616 * Participant id.
1617 * @param int $oldStatusId
1618 * Previous status.
1619 * @param int $newStatusId
1620 * New status.
6a488035 1621 *
72b3a70c
CW
1622 * @return bool
1623 * true if allowed
6a488035 1624 */
00be9182 1625 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
6a488035 1626
be2fb01f 1627 $additionalParticipantIds = [];
6a488035 1628
be2fb01f 1629 static $participantStatuses = [];
6a488035
TO
1630
1631 if (empty($participantStatuses)) {
1632 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1633 }
1634
f3acfdd9 1635 if (!empty(self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]]) &&
6a488035
TO
1636 in_array($participantStatuses[$newStatusId], self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1637 ) {
1638 $additionalParticipantIds = self::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1639 }
1640
1641 return $additionalParticipantIds;
1642 }
1643
1644 /**
66f9e52b 1645 * Get participant record count for a Contact.
6a488035 1646 *
c490a46a 1647 * @param int $contactID
6a488035 1648 *
a6c01b45
CW
1649 * @return int
1650 * count of participant records
6a488035 1651 */
00be9182 1652 public static function getContactParticipantCount($contactID) {
6a488035
TO
1653 $query = "SELECT count(*)
1654FROM civicrm_participant
1655WHERE civicrm_participant.contact_id = {$contactID} AND
1656 civicrm_participant.is_test = 0";
1657 return CRM_Core_DAO::singleValueQuery($query);
1658 }
1659
1660 /**
66f9e52b 1661 * Get participant ids by contribution id.
6a488035 1662 *
d4dd1e85
TO
1663 * @param int $contributionId
1664 * Contribution Id.
1665 * @param bool $excludeCancelled
1666 * Exclude cancelled additional participant.
6a488035 1667 *
a6c01b45 1668 * @return array
6a488035 1669 */
00be9182 1670 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
6a488035 1671
be2fb01f 1672 $ids = [];
6a488035
TO
1673 if (!$contributionId) {
1674 return $ids;
1675 }
1676
1677 // get primary participant id
b677b23b
JP
1678 $query = "SELECT participant_id
1679 FROM civicrm_participant cp
1680 LEFT JOIN civicrm_participant_payment cpp ON cp.id = cpp.participant_id
1681 WHERE cpp.contribution_id = {$contributionId}
1682 AND cp.registered_by_id IS NULL";
1683 $participantPayment = CRM_Core_DAO::executeQuery($query);
6a488035
TO
1684
1685 // get additional participant ids (including cancelled)
b677b23b 1686 while ($participantPayment->fetch()) {
be2fb01f 1687 $ids = array_merge($ids, array_merge([
b677b23b 1688 $participantPayment->participant_id,
be2fb01f 1689 ], self::getAdditionalParticipantIds($participantPayment->participant_id,
ddca8f33 1690 $excludeCancelled
b677b23b 1691 )));
6a488035
TO
1692 }
1693
1694 return $ids;
1695 }
1696
1697 /**
100fef9d 1698 * Get additional Participant edit & view url .
6a488035 1699 *
d4dd1e85
TO
1700 * @param array $participantIds
1701 * An array of additional participant ids.
6a488035 1702 *
a6c01b45 1703 * @return array
16b10e64 1704 * Array of Urls.
6a488035 1705 */
00be9182 1706 public static function getAdditionalParticipantUrl($participantIds) {
6a488035 1707 foreach ($participantIds as $value) {
be2fb01f 1708 $links = [];
6a488035
TO
1709 $details = self::participantDetails($value);
1710 $viewUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1711 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1712 );
1713 $editUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1714 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1715 );
1716 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1717 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1718 return $links;
1719 }
1720 }
1721
1722 /**
dc195289 1723 * create trxn entry if an event has discount.
6a488035 1724 *
d4dd1e85
TO
1725 * @param int $eventID
1726 * Event id.
1727 * @param array $contributionParams
1728 * Contribution params.
654ca41c 1729 *
362bd1b7 1730 * @param string $feeLevel (deprecated)
1731 * @param int $discountedPriceFieldOptionID
1732 * ID of the civicrm_price_field_value field for the discount id.
6a488035 1733 */
9a05ea52 1734 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID = NULL) {
362bd1b7 1735 $financialTypeID = $contributionParams['contribution']->financial_type_id;
1736 $total_amount = $contributionParams['total_amount'];
1737
0479b4c8 1738 $checkDiscount = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
6a488035 1739 if (!empty($checkDiscount)) {
362bd1b7 1740 $mainAmount = self::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
876b8ab0
PN
1741 $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount(
1742 $financialTypeID, 'Discounts Account is');
362bd1b7 1743 if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
1744 $transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
1745 $transactionParams['trxnParams']['payment_processor_id'] = NULL;
1746 $transactionParams['trxnParams']['payment_instrument_id'] = NULL;
1747 $transactionParams['trxnParams']['check_number'] = NULL;
1748 $transactionParams['trxnParams']['trxn_id'] = NULL;
1749 $transactionParams['trxnParams']['net_amount'] = NULL;
1750 $transactionParams['trxnParams']['fee_amount'] = NULL;
1751 CRM_Core_BAO_FinancialTrxn::create($transactionParams);
6a488035
TO
1752 }
1753 }
6a488035 1754 }
c3d24ba7
PN
1755
1756 /**
66f9e52b 1757 * Delete participants of contact.
c3d24ba7 1758 *
0e480632 1759 * @see https://issues.civicrm.org/jira/browse/CRM-12155
c3d24ba7 1760 *
d4dd1e85
TO
1761 * @param int $contactId
1762 * Contact id.
c3d24ba7 1763 *
c3d24ba7 1764 */
00be9182 1765 public static function deleteContactParticipant($contactId) {
c3d24ba7
PN
1766 $participant = new CRM_Event_DAO_Participant();
1767 $participant->contact_id = $contactId;
1768 $participant->find();
1769 while ($participant->fetch()) {
1770 self::deleteParticipant($participant->id);
1771 }
1772 }
6a488035 1773
0cf587a7 1774 /**
100fef9d 1775 * @param int $participantId
0cf587a7
EM
1776 * @param $activityType
1777 *
1778 * @throws CRM_Core_Exception
1779 */
00be9182 1780 public static function addActivityForSelection($participantId, $activityType) {
0aaf8fe9
PJ
1781 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
1782 $contactId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
1783
1784 $date = CRM_Utils_Date::currentDBDate();
1785 $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
28c64535 1786 $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array::value($eventId, $event));
0aaf8fe9
PJ
1787
1788 // activity params
be2fb01f 1789 $activityParams = [
a0d6db1e 1790 'source_contact_id' => $contactId,
1791 'source_record_id' => $participantId,
d66c61b6 1792 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
0aaf8fe9
PJ
1793 'subject' => $subject,
1794 'activity_date_time' => $date,
d66c61b6 1795 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
0aaf8fe9 1796 'skipRecentView' => TRUE,
be2fb01f 1797 ];
0aaf8fe9
PJ
1798
1799 // create activity with target contacts
2dbdb9b9 1800 $id = CRM_Core_Session::getLoggedInContactID();
0aaf8fe9
PJ
1801 if ($id) {
1802 $activityParams['source_contact_id'] = $id;
a0d6db1e 1803 $activityParams['target_contact_id'][] = $contactId;
0aaf8fe9 1804 }
d66c61b6 1805 // @todo use api & also look at duplication of similar methods.
0aaf8fe9
PJ
1806 CRM_Activity_BAO_Activity::create($activityParams);
1807 }
f76b27fe
CW
1808
1809 /**
1810 * Get options for a given field.
1811 * @see CRM_Core_DAO::buildOptions
1812 *
d4dd1e85
TO
1813 * @param string $fieldName
1814 * @param string $context
a1a2a83d 1815 * @see CRM_Core_DAO::buildOptionsContext
d4dd1e85 1816 * @param array $props
16b10e64 1817 * whatever is known about this dao object.
f76b27fe 1818 *
5c766a0b 1819 * @return array|bool
f76b27fe 1820 */
be2fb01f
CW
1821 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1822 $params = ['condition' => []];
f76b27fe
CW
1823
1824 if ($fieldName == 'status_id' && $context != 'validate') {
1825 // Get rid of cart-related option if disabled
1826 // FIXME: Why does this option even exist if cart is disabled?
aaffa79f 1827 if (!Civi::settings()->get('enable_cart')) {
f76b27fe
CW
1828 $params['condition'][] = "name <> 'Pending in cart'";
1829 }
1830 }
1831
1832 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
1833 }
96025800 1834
c7d52684 1835 /**
c50429ca 1836 * CRM-17797 -- Format fields and setDefaults for primary and additional participants profile
1837 * @param int $contactId
1838 * @param CRM_Core_Form $form
c7d52684 1839 */
1840 public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
1841 if (!$contactId) {
1842 return;
1843 }
be2fb01f 1844 $fields = [];
c7d52684 1845 if (!empty($form->_fields)) {
be2fb01f 1846 $removeCustomFieldTypes = ['Participant'];
c7d52684 1847
a36f32b7 1848 foreach ($form->_fields as $name => $fieldInfo) {
c7d52684 1849 if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
1850 && !CRM_Core_BAO_CustomGroup::checkCustomField(substr($name, 7), $removeCustomFieldTypes))
1851 || substr($name, 0, 12) == 'participant_') {
1852 continue;
1853 }
a36f32b7 1854 $fields[$name] = $fieldInfo;
c7d52684 1855 }
1856
1857 if (!empty($fields)) {
1858 CRM_Core_BAO_UFGroup::setProfileDefaults($contactId, $fields, $form->_defaults);
1859 }
1860 }
1861 }
1862
4a3451de
JG
1863 /**
1864 * Evaluate whether a participant record is eligible for self-service transfer/cancellation. If so,
1865 * return additional participant/event details.
1866 *
4a3451de
JG
1867 * @param int $participantId
1868 * @param string $url
1869 * @param bool $isBackOffice
1870 */
c0fc0432 1871 public static function getSelfServiceEligibility(int $participantId, string $url, bool $isBackOffice) : array {
4a3451de
JG
1872 $optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'participant_role', 'id', 'name');
1873 $query = "
c0fc0432 1874 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
1875 FROM civicrm_participant cp
1876 LEFT JOIN civicrm_participant_status_type cpst ON cpst.id = cp.status_id
1877 LEFT JOIN civicrm_option_value cov ON cov.value = cp.role_id and cov.option_group_id = {$optionGroupId}
1878 LEFT JOIN civicrm_event ce ON ce.id = cp.event_id
1879 WHERE cp.id = {$participantId}";
1880 $dao = CRM_Core_DAO::executeQuery($query);
1881 while ($dao->fetch()) {
c0fc0432 1882 $details['eligible'] = TRUE;
4a3451de
JG
1883 $details['status'] = $dao->status;
1884 $details['role'] = $dao->role;
1885 $details['fee_level'] = trim($dao->fee_level, CRM_Core_DAO::VALUE_SEPARATOR);
1886 $details['fee_amount'] = $dao->fee_amount;
1887 $details['register_date'] = $dao->register_date;
1888 $details['event_start_date'] = $dao->start_date;
c0fc0432 1889 $details['allow_selfcancelxfer'] = $dao->allow_selfcancelxfer;
4a3451de
JG
1890 $eventTitle = $dao->title;
1891 $eventId = $dao->event_id;
1892 }
cd51716e 1893 if (!$details['allow_selfcancelxfer'] && !$isBackOffice) {
c0fc0432
JG
1894 $details['eligible'] = FALSE;
1895 $details['ineligible_message'] = ts('This event registration can not be transferred or cancelled. Contact the event organizer if you have questions.');
1896 return $details;
1897 }
4a3451de
JG
1898 //verify participant status is still Registered
1899 if ($details['status'] != 'Registered') {
c0fc0432
JG
1900 $details['eligible'] = FALSE;
1901 $details['ineligible_message'] = "You cannot transfer or cancel your registration for " . $eventTitle . ' as you are not currently registered for this event.';
1902 return $details;
4a3451de 1903 }
c0fc0432 1904 // Determine if it's too late to self-service cancel/transfer.
4a3451de
JG
1905 $query = "select start_date as start, selfcancelxfer_time as time from civicrm_event where id = " . $eventId;
1906 $dao = CRM_Core_DAO::executeQuery($query);
1907 while ($dao->fetch()) {
1908 $time_limit = $dao->time;
1909 $start_date = $dao->start;
1910 }
4a3451de 1911 $timenow = new Datetime();
c674ed12 1912 if (!$isBackOffice && isset($time_limit)) {
c0fc0432
JG
1913 $cancelHours = abs($time_limit);
1914 $cancelInterval = new DateInterval("PT${cancelHours}H");
1915 $cancelInterval->invert = $time_limit < 0 ? 1 : 0;
1916 $cancelDeadline = (new Datetime($start_date))->sub($cancelInterval);
1917 if ($timenow > $cancelDeadline) {
1918 $details['eligible'] = FALSE;
a54cf42b 1919 // Change the language of the status message based on whether the waitlist time limit is positive or negative.
c674ed12
JG
1920 $afterOrPrior = $time_limit <= 0 ? 'after' : 'prior to';
1921 $moreOrLess = $time_limit <= 0 ? 'more' : 'fewer';
1922 $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
1923 [1 => $moreOrLess, 2 => $cancelHours, 3 => $afterOrPrior]);
1924
4a3451de
JG
1925 }
1926 }
1927 return $details;
1928 }
1929
37d5fc55 1930}