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