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