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