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