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