3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
33 class CRM_Event_BAO_Participant
extends CRM_Event_DAO_Participant
{
36 * Static field for all the participant information that we can potentially import.
40 static $_importableFields = NULL;
43 * Static field for all the participant information that we can potentially export.
47 static $_exportableFields = NULL;
50 * Static array for valid status transitions rules.
54 static $_statusTransitionsRules = array(
55 'Pending from pay later' => array('Registered', 'Cancelled'),
56 'Pending from incomplete transaction' => array('Registered', 'Cancelled'),
57 'On waitlist' => array('Cancelled', 'Pending from waitlist'),
58 'Pending from waitlist' => array('Registered', 'Cancelled'),
59 'Awaiting approval' => array('Cancelled', 'Pending from approval'),
60 'Pending from approval' => array('Registered', 'Cancelled'),
65 public function __construct() {
66 parent
::__construct();
70 * Takes an associative array and creates a participant object.
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
76 * @param array $params
77 * (reference ) an assoc array of name/value pairs.
79 * @return CRM_Event_BAO_Participant
81 public static function &add(&$params) {
83 if (!empty($params['id'])) {
84 CRM_Utils_Hook
::pre('edit', 'Participant', $params['id'], $params);
87 CRM_Utils_Hook
::pre('create', 'Participant', NULL, $params);
90 // converting dates to mysql format
91 if (!empty($params['register_date'])) {
92 $params['register_date'] = CRM_Utils_Date
::isoToMysql($params['register_date']);
95 if (!empty($params['participant_fee_amount'])) {
96 $params['participant_fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['participant_fee_amount']);
99 if (!empty($params['fee_amount'])) {
100 $params['fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['fee_amount']);
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];
110 $params['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['role_id']);
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
);
121 $participantBAO->copyValues($params);
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
;
128 !CRM_Utils_System
::isNull($participantBAO->fee_amount
)
130 if (!CRM_Utils_Rule
::currencyCode($currency)) {
131 $config = CRM_Core_Config
::singleton();
132 $currency = $config->defaultCurrency
;
135 $participantBAO->fee_currency
= $currency;
137 $participantBAO->save();
139 $session = CRM_Core_Session
::singleton();
141 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
143 if (!empty($params['id'])) {
144 CRM_Utils_Hook
::post('edit', 'Participant', $participantBAO->id
, $participantBAO);
147 CRM_Utils_Hook
::post('create', 'Participant', $participantBAO->id
, $participantBAO);
150 return $participantBAO;
154 * Given the list of params in the params array, fetch the object
155 * and store the values in the values array
157 * @param array $params
158 * Input parameters to find object.
159 * @param array $values
160 * Output values of the object.
164 * @return CRM_Event_BAO_Participant|null the found object or null
166 public static function getValues(&$params, &$values, &$ids) {
167 if (empty($params)) {
170 $participant = new CRM_Event_BAO_Participant();
171 $participant->copyValues($params);
172 $participant->find();
173 $participants = array();
174 while ($participant->fetch()) {
175 $ids['participant'] = $participant->id
;
176 CRM_Core_DAO
::storeValues($participant, $values[$participant->id
]);
177 $participants[$participant->id
] = $participant;
179 return $participants;
183 * Takes an associative array and creates a participant object.
185 * @param array $params
186 * (reference ) an assoc array of name/value pairs.
188 * @return CRM_Event_BAO_Participant
190 public static function create(&$params) {
192 $transaction = new CRM_Core_Transaction();
195 if (!empty($params['id'])) {
196 $status = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
199 $participant = self
::add($params);
201 if (is_a($participant, 'CRM_Core_Error')) {
202 $transaction->rollback();
206 if ((!CRM_Utils_Array
::value('id', $params)) ||
207 (isset($params['status_id']) && $params['status_id'] != $status)
209 CRM_Activity_BAO_Activity
::addActivity($participant);
214 if (self
::isPrimaryParticipant($participant->id
) && $status) {
215 self
::updateParticipantStatus($participant->id
, $status, $participant->status_id
);
218 $session = CRM_Core_Session
::singleton();
219 $id = $session->get('userID');
221 $id = CRM_Utils_Array
::value('contact_id', $params);
224 // add custom field values
225 if (!empty($params['custom']) &&
226 is_array($params['custom'])
228 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_participant', $participant->id
);
231 //process note, CRM-7634
233 if (!empty($params['id'])) {
234 $note = CRM_Core_BAO_Note
::getNote($params['id'], 'civicrm_participant');
235 $noteId = key($note);
238 $hasNoteField = FALSE;
243 if (array_key_exists($noteFld, $params)) {
244 $noteValue = $params[$noteFld];
245 $hasNoteField = TRUE;
249 if ($noteId ||
$noteValue) {
252 'entity_table' => 'civicrm_participant',
253 'note' => $noteValue,
254 'entity_id' => $participant->id
,
256 'modified_date' => date('Ymd'),
260 $noteIDs['id'] = $noteId;
262 CRM_Core_BAO_Note
::add($noteParams, $noteIDs);
264 elseif ($noteId && $hasNoteField) {
265 CRM_Core_BAO_Note
::del($noteId, FALSE);
269 // Log the information on successful add/edit of Participant data.
271 'entity_table' => 'civicrm_participant',
272 'entity_id' => $participant->id
,
273 'data' => CRM_Event_PseudoConstant
::participantStatus($participant->status_id
),
274 'modified_id' => $id,
275 'modified_date' => date('Ymd'),
278 CRM_Core_BAO_Log
::add($logParams);
280 $params['participant_id'] = $participant->id
;
282 $transaction->commit();
284 // do not add to recent items for import, CRM-4399
285 if (empty($params['skipRecentView'])) {
287 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
288 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
291 $recentOther = array();
292 if (CRM_Core_Permission
::check('edit event participants')) {
293 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
294 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
297 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
298 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
299 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
303 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
305 if ($participant->role_id
) {
306 $role = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participant->role_id
);
308 foreach ($role as & $roleValue) {
309 if (isset($roleValue)) {
310 $roleValue = $participantRoles[$roleValue];
313 $roles = implode(', ', $role);
316 $roleString = empty($roles) ?
'' : $roles;
317 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $participant->event_id
, 'title');
318 $title = CRM_Contact_BAO_Contact
::displayName($participant->contact_id
) . ' (' . $roleString . ' - ' . $eventTitle . ')';
320 // add the recently created Participant
321 CRM_Utils_Recent
::add($title,
325 $participant->contact_id
,
335 * Check whether the event is full for participation and return as.
338 * @param int $eventId
340 * @param bool $returnEmptySeats
341 * Are we require number if empty seats.
342 * @param bool $includeWaitingList
343 * Consider waiting list in event full.
344 * calculation or not. (it is for cron job purpose)
346 * @param bool $returnWaitingCount
347 * @param bool $considerTestParticipant
349 * @return bool|int|null|string
350 * 1. false => If event having some empty spaces.
352 public static function eventFull(
354 $returnEmptySeats = FALSE,
355 $includeWaitingList = TRUE,
356 $returnWaitingCount = FALSE,
357 $considerTestParticipant = FALSE
364 // consider event is full when.
365 // 1. (count(is_counted) >= event_size) or
366 // 2. (count(participants-with-status-on-waitlist) > 0)
367 // It might be case there are some empty spaces and still event
368 // is full, as waitlist might represent group require spaces > empty.
370 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
371 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
372 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
373 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
375 //when we do require only waiting count don't consider counted.
376 if (!$returnWaitingCount && !empty($countedStatuses)) {
377 $allStatusIds = array_keys($countedStatuses);
380 $where = array(' event.id = %1 ');
381 if (!$considerTestParticipant) {
382 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
384 if (!empty($participantRoles)) {
385 $escapedRoles = array();
386 foreach (array_keys($participantRoles) as $participantRole) {
387 $escapedRoles[] = CRM_Utils_Type
::escape($participantRole, 'String');
390 $where[] = " participant.role_id IN ( '" . implode("', '", $escapedRoles) . "' ) ";
393 $eventParams = array(1 => array($eventId, 'Positive'));
395 //in case any waiting, straight forward event is full.
396 if ($includeWaitingList && $onWaitlistStatusId) {
398 //build the where clause.
399 $whereClause = ' WHERE ' . implode(' AND ', $where);
400 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
401 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
404 SELECT participant.id id,
405 event.event_full_text as event_full_text
406 FROM civicrm_participant participant
407 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
410 $eventFullText = ts('This event is full.');
411 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
412 while ($participants->fetch()) {
413 //oops here event is full and we don't want waiting count.
414 if ($returnWaitingCount) {
415 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
418 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
423 //consider only counted participants.
424 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
425 $whereClause = ' WHERE ' . implode(' AND ', $where);
426 $eventSeatsWhere = implode(' AND ', $where);
429 SELECT participant.id id,
430 event.event_full_text as event_full_text,
431 event.max_participants as max_participants
432 FROM civicrm_participant participant
433 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
436 $eventMaxSeats = NULL;
437 $eventFullText = ts('This event is full.');
438 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
439 while ($participants->fetch()) {
440 if ($participants->event_full_text
) {
441 $eventFullText = $participants->event_full_text
;
443 $eventMaxSeats = $participants->max_participants
;
444 //don't have limit for event seats.
445 if ($participants->max_participants
== NULL) {
450 //get the total event seats occupied by these participants.
451 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
453 if ($eventRegisteredSeats) {
454 if ($eventRegisteredSeats >= $eventMaxSeats) {
455 $result = $eventFullText;
457 elseif ($returnEmptySeats) {
458 $result = $eventMaxSeats - $eventRegisteredSeats;
464 SELECT event.event_full_text,
465 event.max_participants
466 FROM civicrm_event event
467 WHERE event.id = %1';
468 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
469 while ($event->fetch()) {
470 $eventFullText = $event->event_full_text
;
471 $eventMaxSeats = $event->max_participants
;
475 // no limit for registration.
476 if ($eventMaxSeats == NULL) {
479 if ($eventMaxSeats) {
480 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
483 return $eventFullText;
487 * Return the array of all price set field options,
488 * with total participant count that field going to carry.
490 * @param int $eventId
492 * @param array $skipParticipantIds
493 * An array of participant ids those we should skip.
494 * @param bool $considerCounted
495 * @param bool $considerWaiting
496 * @param bool $considerTestParticipants
499 * an array of each option id and total count
501 public static function priceSetOptionsCount(
503 $skipParticipantIds = array(),
504 $considerCounted = TRUE,
505 $considerWaiting = TRUE,
506 $considerTestParticipants = FALSE
508 $optionsCount = array();
510 return $optionsCount;
513 $allStatusIds = array();
514 if ($considerCounted) {
515 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
516 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
518 if ($considerWaiting) {
519 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
520 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
522 $statusIdClause = NULL;
523 if (!empty($allStatusIds)) {
524 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
527 $isTestClause = NULL;
528 if (!$considerTestParticipants) {
529 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
532 $skipParticipantClause = NULL;
533 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
534 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
538 SELECT line.id as lineId,
539 line.entity_id as entity_id,
544 FROM civicrm_line_item line
545 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
546 AND participant.id = line.entity_id )
547 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
548 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
549 WHERE participant.event_id = %1
553 {$skipParticipantClause}";
555 $lineItem = CRM_Core_DAO
::executeQuery($sql, array(1 => array($eventId, 'Positive')));
556 while ($lineItem->fetch()) {
557 $count = $lineItem->count
;
561 if ($lineItem->html_type
== 'Text') {
562 $count *= $lineItem->qty
;
564 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
567 return $optionsCount;
571 * Get the empty spaces for event those we can allocate
572 * to pending participant to become confirm.
574 * @param int $eventId
578 * $spaces Number of Empty Seats/null.
580 public static function pendingToConfirmSpaces($eventId) {
586 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
587 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
590 SELECT count(participant.id) as registered,
591 civicrm_event.max_participants
592 FROM civicrm_participant participant, civicrm_event
593 WHERE participant.event_id = {$eventId}
594 AND civicrm_event.id = participant.event_id
595 AND participant.status_id IN {$statusIds}
596 GROUP BY participant.event_id
598 $dao = CRM_Core_DAO
::executeQuery($query);
602 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
607 if ($dao->registered
>= $dao->max_participants
) {
612 return $dao->max_participants
- $dao->registered
;
615 //space in case no registeration yet.
616 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
620 * Combine all the importable fields from the lower levels object.
622 * @param string $contactType
623 * @param bool $status
624 * @param bool $onlyParticipant
625 * @param bool $checkPermission
626 * Is this a permissioned retrieval?
629 * array of importable Fields
631 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE) {
632 if (!self
::$_importableFields) {
633 if (!$onlyParticipant) {
635 $fields = array('' => array('title' => ts('- do not import -')));
638 $fields = array('' => array('title' => ts('- Participant Fields -')));
645 $tmpFields = CRM_Event_DAO_Participant
::import();
648 'participant_note' => array(
649 'title' => ts('Participant Note'),
650 'name' => 'participant_note',
651 'headerPattern' => '/(participant.)?note$/i',
652 'data_type' => CRM_Utils_Type
::T_TEXT
,
656 // Split status and status id into 2 fields
657 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
658 $participantStatus = array(
659 'participant_status' => array(
660 'title' => ts('Participant Status'),
661 'name' => 'participant_status',
662 'data_type' => CRM_Utils_Type
::T_STRING
,
665 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
667 // Split role and role id into 2 fields
668 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
669 $participantRole = array(
670 'participant_role' => array(
671 'title' => ts('Participant Role'),
672 'name' => 'participant_role',
673 'data_type' => CRM_Utils_Type
::T_STRING
,
676 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
679 'event_type' => array(
680 'title' => ts('Event Type'),
681 'name' => 'event_type',
682 'data_type' => CRM_Utils_Type
::T_STRING
,
686 $tmpContactField = $contactFields = array();
687 $contactFields = array();
688 if (!$onlyParticipant) {
689 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
691 // Using new Dedupe rule.
693 'contact_type' => $contactType,
694 'used' => 'Unsupervised',
696 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
698 if (is_array($fieldsArray)) {
699 foreach ($fieldsArray as $value) {
700 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
705 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
706 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
708 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
711 $title = $tmpContactField[trim($value)]['title'];
714 $tmpContactField[trim($value)]['title'] = $title;
718 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
719 if ($extIdentifier) {
720 $tmpContactField['external_identifier'] = $extIdentifier;
721 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
723 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
725 $fields = array_merge($fields, $tmpContactField);
726 $fields = array_merge($fields, $tmpFields);
727 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
728 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
730 self
::$_importableFields = $fields;
733 return self
::$_importableFields;
737 * Combine all the exportable fields from the lower level objects.
739 * @param bool $checkPermission
742 * array of exportable Fields
744 public static function &exportableFields($checkPermission = TRUE) {
745 if (!self
::$_exportableFields) {
746 if (!self
::$_exportableFields) {
747 self
::$_exportableFields = array();
750 $participantFields = CRM_Event_DAO_Participant
::export();
751 $eventFields = CRM_Event_DAO_Event
::export();
753 'participant_note' => array(
754 'title' => ts('Participant Note'),
755 'name' => 'participant_note',
756 'type' => CRM_Utils_Type
::T_STRING
,
760 $participantStatus = array(
761 'participant_status' => array(
762 'title' => ts('Participant Status (label)'),
763 'name' => 'participant_status',
764 'type' => CRM_Utils_Type
::T_STRING
,
768 $participantRole = array(
769 'participant_role' => array(
770 'title' => ts('Participant Role (label)'),
771 'name' => 'participant_role',
772 'type' => CRM_Utils_Type
::T_STRING
,
776 $participantFields['participant_status_id']['title'] .= ' (ID)';
777 $participantFields['participant_role_id']['title'] .= ' (ID)';
779 $discountFields = CRM_Core_DAO_Discount
::export();
781 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
784 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
785 self
::$_exportableFields = $fields;
788 return self
::$_exportableFields;
792 * Get the event name/sort name for a particular participation / participant
794 * @param int $participantId
795 * Id of the participant.
798 * associated array with sort_name and event title
800 public static function participantDetails($participantId) {
802 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
803 FROM civicrm_participant
804 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
805 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
806 WHERE civicrm_participant.id = {$participantId}
808 $dao = CRM_Core_DAO
::executeQuery($query);
811 while ($dao->fetch()) {
812 $details['name'] = $dao->name
;
813 $details['title'] = $dao->title
;
814 $details['cid'] = $dao->cid
;
821 * Get the values for pseudoconstants for name->value and reverse.
823 * @param array $defaults
824 * (reference) the default values, some of which need to be resolved.
825 * @param bool $reverse
826 * True if we want to resolve the values in the reverse direction (value -> name).
828 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
829 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
830 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
831 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
835 * Convert associative array names to values and vice-versa.
837 * This function is used by both the web form layer and the api. Note that
838 * the api needs the name => value conversion, also the view layer typically
839 * requires value => name conversion
841 * @param array $defaults
842 * @param string $property
843 * @param string $lookup
844 * @param bool $reverse
848 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
849 $id = $property . '_id';
851 $src = $reverse ?
$property : $id;
852 $dst = $reverse ?
$id : $property;
854 if (!array_key_exists($src, $defaults)) {
858 $look = $reverse ?
array_flip($lookup) : $lookup;
860 if (is_array($look)) {
861 if (!array_key_exists($defaults[$src], $look)) {
865 $defaults[$dst] = $look[$defaults[$src]];
870 * Delete the records that are associated with this participation.
873 * Id of the participation to delete.
875 * @return \CRM_Event_DAO_Participant
877 public static function deleteParticipant($id) {
878 $participant = new CRM_Event_DAO_Participant();
879 $participant->id
= $id;
880 if (!$participant->find()) {
883 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
885 $transaction = new CRM_Core_Transaction();
887 //delete activity record
889 'source_record_id' => $id,
890 // activity type id for event registration
891 'activity_type_id' => 5,
894 CRM_Activity_BAO_Activity
::deleteActivity($params);
896 // delete the participant payment record
897 // we need to do this since the cascaded constraints
898 // dont work with join tables
899 $p = array('participant_id' => $id);
900 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
902 // cleanup line items.
903 $participantsId = array();
904 $participantsId = self
::getAdditionalParticipantIds($id);
905 $participantsId[] = $id;
906 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
908 //delete note when participant deleted.
909 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
910 $noteId = key($note);
912 CRM_Core_BAO_Note
::del($noteId, FALSE);
915 $participant->delete();
917 $transaction->commit();
919 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
921 // delete the recently created Participant
922 $participantRecent = array(
924 'type' => 'Participant',
927 CRM_Utils_Recent
::del($participantRecent);
933 * Checks duplicate participants.
935 * @param array $input
936 * An assosiative array of name /value pairs.
937 * from other function
938 * @param array $duplicates
939 * (reference ) an assoc array of name/value pairs.
941 * @return CRM_Contribute_BAO_Contribution
943 public static function checkDuplicate($input, &$duplicates) {
944 $eventId = CRM_Utils_Array
::value('event_id', $input);
945 $contactId = CRM_Utils_Array
::value('contact_id', $input);
951 $clause[] = "event_id = %1";
952 $input[1] = array($eventId, 'Integer');
956 $clause[] = "contact_id = %2";
957 $input[2] = array($contactId, 'Integer');
960 if (empty($clause)) {
964 $clause = implode(' AND ', $clause);
966 $query = "SELECT id FROM civicrm_participant WHERE $clause";
967 $dao = CRM_Core_DAO
::executeQuery($query, $input);
969 while ($dao->fetch()) {
970 $duplicates[] = $dao->id
;
977 * Fix the event level.
979 * When price sets are used as event fee, fee_level is set as ^A
980 * separated string. We need to change that string to comma
981 * separated string before using fee_level in view mode.
983 * @param string $eventLevel
984 * Event_level string from db.
986 public static function fixEventLevel(&$eventLevel) {
987 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
988 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
990 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
991 $pos = strrpos($eventLevel, '(multiple participants)', 0);
993 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
996 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
997 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
998 substr($eventLevel, 0, 1)
1001 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1002 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1003 substr($eventLevel, 0, -1)
1009 * Get the additional participant ids.
1011 * @param int $primaryParticipantId
1012 * Primary partycipant Id.
1013 * @param bool $excludeCancel
1014 * Do not include participant those are cancelled.
1016 * @param int $oldStatusId
1020 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1021 $additionalParticipantIds = array();
1022 if (!$primaryParticipantId) {
1023 return $additionalParticipantIds;
1026 $where = "participant.registered_by_id={$primaryParticipantId}";
1027 if ($excludeCancel) {
1028 $cancelStatusId = 0;
1029 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1030 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1031 $where .= " AND participant.status_id != {$cancelStatusId}";
1035 $where .= " AND participant.status_id = {$oldStatusId}";
1039 SELECT participant.id
1040 FROM civicrm_participant participant
1043 $dao = CRM_Core_DAO
::executeQuery($query);
1044 while ($dao->fetch()) {
1045 $additionalParticipantIds[$dao->id
] = $dao->id
;
1047 return $additionalParticipantIds;
1051 * Get the amount for the undiscounted version of the field.
1053 * Note this function is part of the refactoring process rather than the best approach.
1055 * @param int $eventID
1056 * @param int $discountedPriceFieldOptionID
1057 * @param string $feeLevel (deprecated)
1059 * @return null|string
1061 public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
1062 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1064 1 => array($priceSetId, 'Integer'),
1066 if ($discountedPriceFieldOptionID) {
1067 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1068 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1069 WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
1070 $params[2] = array($discountedPriceFieldOptionID, 'Integer');
1073 $feeLevel = current($feeLevel);
1074 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1075 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1076 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1077 $params[2] = array($feeLevel, 'String');
1079 return CRM_Core_DAO
::singleValueQuery($query, $params);
1083 * Get the event fee info for given participant ids
1084 * either from line item table / participant table.
1086 * @param array $participantIds
1088 * @param bool $hasLineItems
1089 * Do fetch from line items.
1093 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1094 $feeDetails = array();
1095 if (!is_array($participantIds) ||
empty($participantIds)) {
1100 SELECT participant.id as id,
1101 participant.fee_level as fee_level,
1102 participant.fee_amount as fee_amount';
1103 $from = 'FROM civicrm_participant participant';
1104 if ($hasLineItems) {
1106 lineItem.id as lineId,
1107 lineItem.label as label,
1108 lineItem.qty as qty,
1109 lineItem.unit_price as unit_price,
1110 lineItem.line_total as line_total,
1111 field.label as field_title,
1112 field.html_type as html_type,
1113 field.id as price_field_id,
1114 value.id as price_field_value_id,
1115 value.description as description,
1116 IF( value.count, value.count, 0 ) as participant_count';
1118 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1119 AND lineItem.entity_id = participant.id )
1120 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1121 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1124 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1125 $query = "$select $from $where";
1127 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1128 $feeProperties = array('fee_level', 'fee_amount');
1129 $lineProperties = array(
1138 'participant_count',
1139 'price_field_value_id',
1142 while ($feeInfo->fetch()) {
1143 if ($hasLineItems) {
1144 foreach ($lineProperties as $property) {
1145 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1149 foreach ($feeProperties as $property) {
1150 $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1159 * Retrieve additional participants display-names and URL to view their participant records.
1160 * (excludes cancelled participants automatically)
1162 * @param int $primaryParticipantID
1163 * Id of primary participant record.
1166 * $displayName => $viewUrl
1168 public static function getAdditionalParticipants($primaryParticipantID) {
1169 $additionalParticipantIDs = array();
1170 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1171 if (!empty($additionalParticipantIDs)) {
1172 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1173 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1174 $additionalParticipantID,
1177 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1178 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1179 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1182 $additionalParticipants[$additionalContactName] = $pViewURL;
1185 return $additionalParticipants;
1189 * Function for update primary and additional participant status.
1191 * @param int $participantID
1192 * Primary participant's id.
1193 * @param int $oldStatusID
1194 * @param int $newStatusID
1195 * @param bool $updatePrimaryStatus
1199 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1200 if (!$participantID ||
!$oldStatusID) {
1204 if (!$newStatusID) {
1205 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1207 elseif ($updatePrimaryStatus) {
1208 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1211 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1213 if (!empty($cascadeAdditionalIds)) {
1215 foreach ($cascadeAdditionalIds as $id) {
1216 $participantParams = array(
1218 'status_id' => $newStatusID,
1220 civicrm_api3('Participant', 'create', $participantParams);
1224 catch (CiviCRM_API3_Exception
$e) {
1225 throw new CRM_Core_Exception('Failed to update additional participant status in database');
1232 * Function for update status for given participant ids.
1234 * @param int $participantIds
1235 * Array of participant ids.
1236 * @param int $statusId
1237 * Status id for participant.
1238 * @param bool $updateRegisterDate
1240 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1241 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1245 //lets update register date as we update status to keep track
1246 //when we did update status, useful for moving participant
1247 //from pending to expired.
1248 $setClause = "status_id = {$statusId}";
1249 if ($updateRegisterDate) {
1250 $setClause .= ", register_date = NOW()";
1253 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1256 UPDATE civicrm_participant
1258 WHERE id IN {$participantIdClause}";
1260 $dao = CRM_Core_DAO
::executeQuery($query);
1264 * Function takes participant ids and statuses
1265 * update status from $fromStatusId to $toStatusId
1266 * and send mail + create activities.
1268 * @param array $participantIds
1270 * @param int $toStatusId
1272 * @param int $fromStatusId
1274 * @param bool $returnResult
1275 * @param bool $skipCascadeRule
1277 * @return array|NULL
1279 public static function transitionParticipants(
1280 $participantIds, $toStatusId,
1281 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1283 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1287 //thumb rule is if we triggering primary participant need to triggered additional
1288 $allParticipantIds = $primaryANDAdditonalIds = array();
1289 foreach ($participantIds as $id) {
1290 $allParticipantIds[] = $id;
1291 if (self
::isPrimaryParticipant($id)) {
1292 //filter additional as per status transition rules, CRM-5403
1293 if ($skipCascadeRule) {
1294 $additionalIds = self
::getAdditionalParticipantIds($id);
1297 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1299 if (!empty($additionalIds)) {
1300 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1301 $primaryANDAdditonalIds[$id] = $additionalIds;
1306 //get the unique participant ids,
1307 $allParticipantIds = array_unique($allParticipantIds);
1309 //pull required participants, contacts, events data, if not in hand
1310 static $eventDetails = array();
1311 static $domainValues = array();
1312 static $contactDetails = array();
1314 $contactIds = $eventIds = $participantDetails = array();
1316 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1317 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1318 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1322 //first thing is pull all necessory data from db.
1323 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1325 //get all participants data.
1326 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1327 $dao = CRM_Core_DAO
::executeQuery($query);
1328 while ($dao->fetch()) {
1329 $participantDetails[$dao->id
] = array(
1331 'role' => $participantRoles[$dao->role_id
],
1332 'is_test' => $dao->is_test
,
1333 'event_id' => $dao->event_id
,
1334 'status_id' => $dao->status_id
,
1335 'fee_amount' => $dao->fee_amount
,
1336 'contact_id' => $dao->contact_id
,
1337 'register_date' => $dao->register_date
,
1338 'registered_by_id' => $dao->registered_by_id
,
1340 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1341 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1344 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1345 $eventIds[$dao->event_id
] = $dao->event_id
;
1349 //get the domain values.
1350 if (empty($domainValues)) {
1351 // making all tokens available to templates.
1352 $domain = CRM_Core_BAO_Domain
::getDomain();
1354 'domain' => array('name', 'phone', 'address', 'email'),
1355 'contact' => CRM_Core_SelectValues
::contactTokens(),
1358 foreach ($tokens['domain'] as $token) {
1359 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1363 //get all required contacts detail.
1364 if (!empty($contactIds)) {
1365 // get the contact details.
1366 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1369 'CRM_Event_BAO_Participant'
1371 foreach ($currentContactDetails as $contactId => $contactValues) {
1372 $contactDetails[$contactId] = $contactValues;
1376 //get all required events detail.
1377 if (!empty($eventIds)) {
1378 foreach ($eventIds as $eventId) {
1379 //retrieve event information
1380 $eventParams = array('id' => $eventId);
1381 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1383 //get default participant role.
1384 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1386 //get the location info
1387 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1388 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1392 //now we are ready w/ all required data.
1393 //take a decision as per statuses.
1396 $toStatus = $statusTypes[$toStatusId];
1397 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1399 switch ($toStatus) {
1400 case 'Pending from waitlist':
1401 case 'Pending from approval':
1402 switch ($fromStatus) {
1404 case 'Awaiting approval':
1405 $emailType = 'Confirm';
1411 //no matter from where u come send expired mail.
1412 $emailType = $toStatus;
1416 //no matter from where u come send cancel mail.
1417 $emailType = $toStatus;
1421 //as we process additional w/ primary, there might be case if user
1422 //select primary as well as additionals, so avoid double processing.
1423 $processedParticipantIds = array();
1424 $mailedParticipants = array();
1426 //send mails and update status.
1427 foreach ($participantDetails as $participantId => $participantValues) {
1428 $updateParticipantIds = array();
1429 if (in_array($participantId, $processedParticipantIds)) {
1433 //check is it primary and has additional.
1434 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1435 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1438 $mail = self
::sendTransitionParticipantMail($additonalId,
1439 $participantDetails[$additonalId],
1440 $eventDetails[$participantDetails[$additonalId]['event_id']],
1441 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1446 //get the mail participant ids
1448 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1451 $updateParticipantIds[] = $additonalId;
1452 $processedParticipantIds[] = $additonalId;
1456 //now send email appropriate mail to primary.
1458 $mail = self
::sendTransitionParticipantMail($participantId,
1460 $eventDetails[$participantValues['event_id']],
1461 $contactDetails[$participantValues['contact_id']],
1466 //get the mail participant ids
1468 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1472 //now update status of group/one at once.
1473 $updateParticipantIds[] = $participantId;
1475 //update the register date only when we,
1476 //move participant to pending class, CRM-6496
1477 $updateRegisterDate = FALSE;
1478 if (array_key_exists($toStatusId, $pendingStatuses)) {
1479 $updateRegisterDate = TRUE;
1481 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1482 $processedParticipantIds[] = $participantId;
1485 //return result for cron.
1486 if ($returnResult) {
1488 'mailedParticipants' => $mailedParticipants,
1489 'updatedParticipantIds' => $processedParticipantIds,
1497 * Send mail and create activity
1498 * when participant status changed.
1500 * @param int $participantId
1502 * @param array $participantValues
1503 * Participant detail values. status id for participants.
1504 * @param array $eventDetails
1505 * Required event details.
1506 * @param array $contactDetails
1507 * Required contact details.
1508 * @param array $domainValues
1509 * Required domain values.
1510 * @param string $mailType
1511 * (eg 'approval', 'confirm', 'expired' ).
1515 public static function sendTransitionParticipantMail(
1526 //don't send confirmation mail to additional
1527 //since only primary able to confirm registration.
1528 if (!empty($participantValues['registered_by_id']) &&
1529 $mailType == 'Confirm'
1533 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1536 $contactId = $participantValues['contact_id'];
1537 $participantName = $contactDetails['display_name'];
1539 //calculate the checksum value.
1540 $checksumValue = NULL;
1541 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1542 $checksumLife = 'inf';
1543 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1545 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1547 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1550 //take a receipt from as event else domain.
1551 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1552 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1553 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1556 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1558 'groupName' => 'msg_tpl_workflow_event',
1559 'valueName' => 'participant_' . strtolower($mailType),
1560 'contactId' => $contactId,
1561 'tplParams' => array(
1562 'contact' => $contactDetails,
1563 'domain' => $domainValues,
1564 'participant' => $participantValues,
1565 'event' => $eventDetails,
1566 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1567 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1568 'isAdditional' => $participantValues['registered_by_id'],
1569 'isExpired' => $mailType == 'Expired',
1570 'isConfirm' => $mailType == 'Confirm',
1571 'checksumValue' => $checksumValue,
1573 'from' => $receiptFrom,
1574 'toName' => $participantName,
1575 'toEmail' => $toEmail,
1576 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1577 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1581 // 3. create activity record.
1583 $now = date('YmdHis');
1584 $activityType = 'Event Registration';
1585 $activityParams = array(
1586 'subject' => $subject,
1587 'source_contact_id' => $contactId,
1588 'source_record_id' => $participantId,
1589 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
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'],
1599 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1600 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1609 * Get participant status change message.
1611 * @param int $participantId
1612 * @param $statusChangeTo
1613 * @param int $fromStatusId
1617 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1619 $results = self
::transitionParticipants(array($participantId),
1620 $statusChangeTo, $fromStatusId, TRUE
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'])
1631 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1633 1 => $allStatuses[$statusChangeTo],
1634 2 => $results['mailedParticipants'][$processedId],
1646 * Get event full and waiting list message.
1648 * @param int $eventId
1649 * @param int $participantId
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;
1665 if (!$eventId ||
!$checkEventFull) {
1666 return $eventfullMsg;
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.", array(
1674 1 => $maxParticipants,
1678 $hasWaiting = FALSE;
1679 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1680 if (is_numeric($waitListedCount)) {
1682 //only current processing participant is on waitlist.
1683 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1684 $hasWaiting = FALSE;
1689 $waitingStatusId = array_search('On waitlist',
1690 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1692 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1693 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
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.",
1698 1 => $viewWaitListUrl,
1699 2 => $waitListedCount,
1704 return $eventfullMsg;
1708 * Check for whether participant is primary or not.
1710 * @param int $participantId
1713 * true if participant is primary
1715 public static function isPrimaryParticipant($participantId) {
1717 $participant = new CRM_Event_DAO_Participant();
1718 $participant->registered_by_id
= $participantId;
1720 if ($participant->find(TRUE)) {
1727 * Get additional participant Ids for cascading with primary participant status.
1729 * @param int $participantId
1731 * @param int $oldStatusId
1733 * @param int $newStatusId
1739 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1741 $additionalParticipantIds = array();
1743 static $participantStatuses = array();
1745 if (empty($participantStatuses)) {
1746 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1749 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1750 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1752 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1755 return $additionalParticipantIds;
1759 * Get participant record count for a Contact.
1761 * @param int $contactID
1764 * count of participant records
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);
1775 * Get participant ids by contribution id.
1777 * @param int $contributionId
1779 * @param bool $excludeCancelled
1780 * Exclude cancelled additional participant.
1784 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1787 if (!$contributionId) {
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);
1799 // get additional participant ids (including cancelled)
1800 while ($participantPayment->fetch()) {
1801 $ids = array_merge($ids, array_merge(array(
1802 $participantPayment->participant_id
,
1803 ), self
::getAdditionalParticipantIds($participantPayment->participant_id
,
1812 * Get additional Participant edit & view url .
1814 * @param array $participantIds
1815 * An array of additional participant ids.
1820 public static function getAdditionalParticipantUrl($participantIds) {
1821 foreach ($participantIds as $value) {
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']}"
1827 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1828 "action=update&reset=1&id={$value}&cid={$details['cid']}"
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>";
1837 * create trxn entry if an event has discount.
1839 * @param int $eventID
1841 * @param array $contributionParams
1842 * Contribution params.
1844 * @param string $feeLevel (deprecated)
1845 * @param int $discountedPriceFieldOptionID
1846 * ID of the civicrm_price_field_value field for the discount id.
1848 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID) {
1849 $financialTypeID = $contributionParams['contribution']->financial_type_id
;
1850 $total_amount = $contributionParams['total_amount'];
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);
1871 * Delete participants of contact.
1875 * @param int $contactId
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
);
1889 * @param int $participantId
1890 * @param $activityType
1892 * @throws CRM_Core_Exception
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');
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 $targetCid = $contactId;
1902 $srcRecId = $participantId;
1905 $activityParams = array(
1906 'source_contact_id' => $targetCid,
1907 'source_record_id' => $srcRecId,
1908 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1909 'subject' => $subject,
1910 'activity_date_time' => $date,
1911 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1912 'skipRecentView' => TRUE,
1915 // create activity with target contacts
1916 $session = CRM_Core_Session
::singleton();
1917 $id = $session->get('userID');
1919 $activityParams['source_contact_id'] = $id;
1920 $activityParams['target_contact_id'][] = $targetCid;
1922 // @todo use api & also look at duplication of similar methods.
1923 CRM_Activity_BAO_Activity
::create($activityParams);
1927 * Get options for a given field.
1928 * @see CRM_Core_DAO::buildOptions
1930 * @param string $fieldName
1931 * @param string $context
1932 * @see CRM_Core_DAO::buildOptionsContext
1933 * @param array $props
1934 * whatever is known about this dao object.
1936 * @return array|bool
1938 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1939 $params = array('condition' => array());
1941 if ($fieldName == 'status_id' && $context != 'validate') {
1942 // Get rid of cart-related option if disabled
1943 // FIXME: Why does this option even exist if cart is disabled?
1944 if (!Civi
::settings()->get('enable_cart')) {
1945 $params['condition'][] = "name <> 'Pending in cart'";
1949 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
1953 * CRM-17797 -- Format fields and setDefaults for primary and additional participants profile
1954 * @param int $contactId
1955 * @param CRM_Core_Form $form
1957 public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
1962 if (!empty($form->_fields
)) {
1963 $removeCustomFieldTypes = array('Participant');
1965 foreach ($form->_fields
as $name => $dontCare) {
1966 if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
1967 && !CRM_Core_BAO_CustomGroup
::checkCustomField(substr($name, 7), $removeCustomFieldTypes))
1968 ||
substr($name, 0, 12) == 'participant_') {
1974 if (!empty($fields)) {
1975 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $fields, $form->_defaults
);