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