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