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