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