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