3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
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 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
141 if (!empty($params['id'])) {
142 CRM_Utils_Hook
::post('edit', 'Participant', $participantBAO->id
, $participantBAO);
145 CRM_Utils_Hook
::post('create', 'Participant', $participantBAO->id
, $participantBAO);
148 return $participantBAO;
152 * Given the list of params in the params array, fetch the object
153 * and store the values in the values array
155 * @param array $params
156 * Input parameters to find object.
157 * @param array $values
158 * Output values of the object.
162 * @return CRM_Event_BAO_Participant|null the found object or null
164 public static function getValues(&$params, &$values, &$ids) {
165 if (empty($params)) {
168 $participant = new CRM_Event_BAO_Participant();
169 $participant->copyValues($params);
170 $participant->find();
171 $participants = array();
172 while ($participant->fetch()) {
173 $ids['participant'] = $participant->id
;
174 CRM_Core_DAO
::storeValues($participant, $values[$participant->id
]);
175 $participants[$participant->id
] = $participant;
177 return $participants;
181 * Takes an associative array and creates a participant object.
183 * @param array $params
184 * (reference ) an assoc array of name/value pairs.
186 * @return CRM_Event_BAO_Participant
188 public static function create(&$params) {
190 $transaction = new CRM_Core_Transaction();
193 if (!empty($params['id'])) {
194 $status = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
197 $participant = self
::add($params);
199 if (is_a($participant, 'CRM_Core_Error')) {
200 $transaction->rollback();
204 // Log activity when creating new participant or changing status
205 if (empty($params['id']) ||
206 (isset($params['status_id']) && $params['status_id'] != $status)
208 // Default status if not specified
209 $participant->status_id
= $participant->status_id ?
: self
::fields()['participant_status_id']['default'];
210 CRM_Activity_BAO_Activity
::addActivity($participant);
215 if (self
::isPrimaryParticipant($participant->id
) && $status) {
216 self
::updateParticipantStatus($participant->id
, $status, $participant->status_id
);
219 $session = CRM_Core_Session
::singleton();
220 $id = $session->get('userID');
222 $id = CRM_Utils_Array
::value('contact_id', $params);
225 // add custom field values
226 if (!empty($params['custom']) &&
227 is_array($params['custom'])
229 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_participant', $participant->id
);
232 //process note, CRM-7634
234 if (!empty($params['id'])) {
235 $note = CRM_Core_BAO_Note
::getNote($params['id'], 'civicrm_participant');
236 $noteId = key($note);
239 $hasNoteField = FALSE;
244 if (array_key_exists($noteFld, $params)) {
245 $noteValue = $params[$noteFld];
246 $hasNoteField = TRUE;
250 if ($noteId ||
$noteValue) {
253 'entity_table' => 'civicrm_participant',
254 'note' => $noteValue,
255 'entity_id' => $participant->id
,
257 'modified_date' => date('Ymd'),
261 $noteIDs['id'] = $noteId;
263 CRM_Core_BAO_Note
::add($noteParams, $noteIDs);
265 elseif ($noteId && $hasNoteField) {
266 CRM_Core_BAO_Note
::del($noteId, FALSE);
270 // Log the information on successful add/edit of Participant data.
272 'entity_table' => 'civicrm_participant',
273 'entity_id' => $participant->id
,
274 'data' => CRM_Event_PseudoConstant
::participantStatus($participant->status_id
),
275 'modified_id' => $id,
276 'modified_date' => date('Ymd'),
279 CRM_Core_BAO_Log
::add($logParams);
281 $params['participant_id'] = $participant->id
;
283 $transaction->commit();
285 // do not add to recent items for import, CRM-4399
286 if (empty($params['skipRecentView'])) {
288 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
289 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
292 $recentOther = array();
293 if (CRM_Core_Permission
::check('edit event participants')) {
294 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
295 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
298 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
299 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
300 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
304 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
306 if ($participant->role_id
) {
307 $role = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participant->role_id
);
309 foreach ($role as & $roleValue) {
310 if (isset($roleValue)) {
311 $roleValue = $participantRoles[$roleValue];
314 $roles = implode(', ', $role);
317 $roleString = empty($roles) ?
'' : $roles;
318 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $participant->event_id
, 'title');
319 $title = CRM_Contact_BAO_Contact
::displayName($participant->contact_id
) . ' (' . $roleString . ' - ' . $eventTitle . ')';
321 // add the recently created Participant
322 CRM_Utils_Recent
::add($title,
326 $participant->contact_id
,
336 * Check whether the event is full for participation and return as.
339 * @param int $eventId
341 * @param bool $returnEmptySeats
342 * Are we require number if empty seats.
343 * @param bool $includeWaitingList
344 * Consider waiting list in event full.
345 * calculation or not. (it is for cron job purpose)
347 * @param bool $returnWaitingCount
348 * @param bool $considerTestParticipant
350 * @return bool|int|null|string
351 * 1. false => If event having some empty spaces.
353 public static function eventFull(
355 $returnEmptySeats = FALSE,
356 $includeWaitingList = TRUE,
357 $returnWaitingCount = FALSE,
358 $considerTestParticipant = FALSE
365 // consider event is full when.
366 // 1. (count(is_counted) >= event_size) or
367 // 2. (count(participants-with-status-on-waitlist) > 0)
368 // It might be case there are some empty spaces and still event
369 // is full, as waitlist might represent group require spaces > empty.
371 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
372 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
373 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
374 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
376 //when we do require only waiting count don't consider counted.
377 if (!$returnWaitingCount && !empty($countedStatuses)) {
378 $allStatusIds = array_keys($countedStatuses);
381 $where = array(' event.id = %1 ');
382 if (!$considerTestParticipant) {
383 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
385 if (!empty($participantRoles)) {
386 $escapedRoles = array();
387 foreach (array_keys($participantRoles) as $participantRole) {
388 $escapedRoles[] = CRM_Utils_Type
::escape($participantRole, 'String');
391 $where[] = " participant.role_id IN ( '" . implode("', '", $escapedRoles) . "' ) ";
394 $eventParams = array(1 => array($eventId, 'Positive'));
396 //in case any waiting, straight forward event is full.
397 if ($includeWaitingList && $onWaitlistStatusId) {
399 //build the where clause.
400 $whereClause = ' WHERE ' . implode(' AND ', $where);
401 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
402 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
405 SELECT participant.id id,
406 event.event_full_text as event_full_text
407 FROM civicrm_participant participant
408 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
411 $eventFullText = ts('This event is full.');
412 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
413 while ($participants->fetch()) {
414 //oops here event is full and we don't want waiting count.
415 if ($returnWaitingCount) {
416 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
419 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
424 //consider only counted participants.
425 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
426 $whereClause = ' WHERE ' . implode(' AND ', $where);
427 $eventSeatsWhere = implode(' AND ', $where);
430 SELECT participant.id id,
431 event.event_full_text as event_full_text,
432 event.max_participants as max_participants
433 FROM civicrm_participant participant
434 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
437 $eventMaxSeats = NULL;
438 $eventFullText = ts('This event is full.');
439 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
440 while ($participants->fetch()) {
441 if ($participants->event_full_text
) {
442 $eventFullText = $participants->event_full_text
;
444 $eventMaxSeats = $participants->max_participants
;
445 //don't have limit for event seats.
446 if ($participants->max_participants
== NULL) {
451 //get the total event seats occupied by these participants.
452 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
454 if ($eventRegisteredSeats) {
455 if ($eventRegisteredSeats >= $eventMaxSeats) {
456 $result = $eventFullText;
458 elseif ($returnEmptySeats) {
459 $result = $eventMaxSeats - $eventRegisteredSeats;
465 SELECT event.event_full_text,
466 event.max_participants
467 FROM civicrm_event event
468 WHERE event.id = %1';
469 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
470 while ($event->fetch()) {
471 $eventFullText = $event->event_full_text
;
472 $eventMaxSeats = $event->max_participants
;
476 // no limit for registration.
477 if ($eventMaxSeats == NULL) {
480 if ($eventMaxSeats) {
481 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
484 return $eventFullText;
488 * Return the array of all price set field options,
489 * with total participant count that field going to carry.
491 * @param int $eventId
493 * @param array $skipParticipantIds
494 * An array of participant ids those we should skip.
495 * @param bool $considerCounted
496 * @param bool $considerWaiting
497 * @param bool $considerTestParticipants
500 * an array of each option id and total count
502 public static function priceSetOptionsCount(
504 $skipParticipantIds = array(),
505 $considerCounted = TRUE,
506 $considerWaiting = TRUE,
507 $considerTestParticipants = FALSE
509 $optionsCount = array();
511 return $optionsCount;
514 $allStatusIds = array();
515 if ($considerCounted) {
516 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
517 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
519 if ($considerWaiting) {
520 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
521 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
523 $statusIdClause = NULL;
524 if (!empty($allStatusIds)) {
525 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
528 $isTestClause = NULL;
529 if (!$considerTestParticipants) {
530 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
533 $skipParticipantClause = NULL;
534 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
535 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
539 SELECT line.id as lineId,
540 line.entity_id as entity_id,
545 FROM civicrm_line_item line
546 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
547 AND participant.id = line.entity_id )
548 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
549 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
550 WHERE participant.event_id = %1
554 {$skipParticipantClause}";
556 $lineItem = CRM_Core_DAO
::executeQuery($sql, array(1 => array($eventId, 'Positive')));
557 while ($lineItem->fetch()) {
558 $count = $lineItem->count
;
562 if ($lineItem->html_type
== 'Text') {
563 $count *= $lineItem->qty
;
565 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
568 return $optionsCount;
572 * Get the empty spaces for event those we can allocate
573 * to pending participant to become confirm.
575 * @param int $eventId
579 * $spaces Number of Empty Seats/null.
581 public static function pendingToConfirmSpaces($eventId) {
587 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
588 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
591 SELECT count(participant.id) as registered,
592 civicrm_event.max_participants
593 FROM civicrm_participant participant, civicrm_event
594 WHERE participant.event_id = {$eventId}
595 AND civicrm_event.id = participant.event_id
596 AND participant.status_id IN {$statusIds}
597 GROUP BY participant.event_id
599 $dao = CRM_Core_DAO
::executeQuery($query);
603 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
608 if ($dao->registered
>= $dao->max_participants
) {
613 return $dao->max_participants
- $dao->registered
;
616 //space in case no registeration yet.
617 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
621 * Combine all the importable fields from the lower levels object.
623 * @param string $contactType
624 * @param bool $status
625 * @param bool $onlyParticipant
626 * @param bool $checkPermission
627 * Is this a permissioned retrieval?
630 * array of importable Fields
632 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE) {
633 if (!self
::$_importableFields) {
634 if (!$onlyParticipant) {
636 $fields = array('' => array('title' => ts('- do not import -')));
639 $fields = array('' => array('title' => ts('- Participant Fields -')));
646 $tmpFields = CRM_Event_DAO_Participant
::import();
649 'participant_note' => array(
650 'title' => ts('Participant Note'),
651 'name' => 'participant_note',
652 'headerPattern' => '/(participant.)?note$/i',
653 'data_type' => CRM_Utils_Type
::T_TEXT
,
657 // Split status and status id into 2 fields
658 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
659 $participantStatus = array(
660 'participant_status' => array(
661 'title' => ts('Participant Status'),
662 'name' => 'participant_status',
663 'data_type' => CRM_Utils_Type
::T_STRING
,
666 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
668 // Split role and role id into 2 fields
669 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
670 $participantRole = array(
671 'participant_role' => array(
672 'title' => ts('Participant Role'),
673 'name' => 'participant_role',
674 'data_type' => CRM_Utils_Type
::T_STRING
,
677 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
680 'event_type' => array(
681 'title' => ts('Event Type'),
682 'name' => 'event_type',
683 'data_type' => CRM_Utils_Type
::T_STRING
,
687 $tmpContactField = $contactFields = array();
688 $contactFields = array();
689 if (!$onlyParticipant) {
690 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
692 // Using new Dedupe rule.
694 'contact_type' => $contactType,
695 'used' => 'Unsupervised',
697 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
699 if (is_array($fieldsArray)) {
700 foreach ($fieldsArray as $value) {
701 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
706 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
707 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
709 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
712 $title = $tmpContactField[trim($value)]['title'];
715 $tmpContactField[trim($value)]['title'] = $title;
719 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
720 if ($extIdentifier) {
721 $tmpContactField['external_identifier'] = $extIdentifier;
722 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
724 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
726 $fields = array_merge($fields, $tmpContactField);
727 $fields = array_merge($fields, $tmpFields);
728 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
729 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
731 self
::$_importableFields = $fields;
734 return self
::$_importableFields;
738 * Combine all the exportable fields from the lower level objects.
740 * @param bool $checkPermission
743 * array of exportable Fields
745 public static function &exportableFields($checkPermission = TRUE) {
746 if (!self
::$_exportableFields) {
747 if (!self
::$_exportableFields) {
748 self
::$_exportableFields = array();
751 $participantFields = CRM_Event_DAO_Participant
::export();
752 $eventFields = CRM_Event_DAO_Event
::export();
754 'participant_note' => array(
755 'title' => ts('Participant Note'),
756 'name' => 'participant_note',
757 'type' => CRM_Utils_Type
::T_STRING
,
761 $participantStatus = array(
762 'participant_status' => array(
763 'title' => ts('Participant Status (label)'),
764 'name' => 'participant_status',
765 'type' => CRM_Utils_Type
::T_STRING
,
769 $participantRole = array(
770 'participant_role' => array(
771 'title' => ts('Participant Role (label)'),
772 'name' => 'participant_role',
773 'type' => CRM_Utils_Type
::T_STRING
,
777 $participantFields['participant_status_id']['title'] .= ' (ID)';
778 $participantFields['participant_role_id']['title'] .= ' (ID)';
780 $discountFields = CRM_Core_DAO_Discount
::export();
782 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
785 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
786 self
::$_exportableFields = $fields;
789 return self
::$_exportableFields;
793 * Get the event name/sort name for a particular participation / participant
795 * @param int $participantId
796 * Id of the participant.
799 * associated array with sort_name and event title
801 public static function participantDetails($participantId) {
803 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
804 FROM civicrm_participant
805 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
806 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
807 WHERE civicrm_participant.id = {$participantId}
809 $dao = CRM_Core_DAO
::executeQuery($query);
812 while ($dao->fetch()) {
813 $details['name'] = $dao->name
;
814 $details['title'] = $dao->title
;
815 $details['cid'] = $dao->cid
;
822 * Get the values for pseudoconstants for name->value and reverse.
824 * @param array $defaults
825 * (reference) the default values, some of which need to be resolved.
826 * @param bool $reverse
827 * True if we want to resolve the values in the reverse direction (value -> name).
829 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
830 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
831 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
832 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
836 * Convert associative array names to values and vice-versa.
838 * This function is used by both the web form layer and the api. Note that
839 * the api needs the name => value conversion, also the view layer typically
840 * requires value => name conversion
842 * @param array $defaults
843 * @param string $property
844 * @param string $lookup
845 * @param bool $reverse
849 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
850 $id = $property . '_id';
852 $src = $reverse ?
$property : $id;
853 $dst = $reverse ?
$id : $property;
855 if (!array_key_exists($src, $defaults)) {
859 $look = $reverse ?
array_flip($lookup) : $lookup;
861 if (is_array($look)) {
862 if (!array_key_exists($defaults[$src], $look)) {
866 $defaults[$dst] = $look[$defaults[$src]];
871 * Delete the records that are associated with this participation.
874 * Id of the participation to delete.
876 * @return \CRM_Event_DAO_Participant
878 public static function deleteParticipant($id) {
879 $participant = new CRM_Event_DAO_Participant();
880 $participant->id
= $id;
881 if (!$participant->find()) {
884 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
886 $transaction = new CRM_Core_Transaction();
888 //delete activity record
890 'source_record_id' => $id,
891 // activity type id for event registration
892 'activity_type_id' => 5,
895 CRM_Activity_BAO_Activity
::deleteActivity($params);
897 // delete the participant payment record
898 // we need to do this since the cascaded constraints
899 // dont work with join tables
900 $p = array('participant_id' => $id);
901 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
903 // cleanup line items.
904 $participantsId = array();
905 $participantsId = self
::getAdditionalParticipantIds($id);
906 $participantsId[] = $id;
907 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
909 //delete note when participant deleted.
910 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
911 $noteId = key($note);
913 CRM_Core_BAO_Note
::del($noteId, FALSE);
916 $participant->delete();
918 $transaction->commit();
920 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
922 // delete the recently created Participant
923 $participantRecent = array(
925 'type' => 'Participant',
928 CRM_Utils_Recent
::del($participantRecent);
934 * Checks duplicate participants.
936 * @param array $input
937 * An assosiative array of name /value pairs.
938 * from other function
939 * @param array $duplicates
940 * (reference ) an assoc array of name/value pairs.
942 * @return CRM_Contribute_BAO_Contribution
944 public static function checkDuplicate($input, &$duplicates) {
945 $eventId = CRM_Utils_Array
::value('event_id', $input);
946 $contactId = CRM_Utils_Array
::value('contact_id', $input);
952 $clause[] = "event_id = %1";
953 $input[1] = array($eventId, 'Integer');
957 $clause[] = "contact_id = %2";
958 $input[2] = array($contactId, 'Integer');
961 if (empty($clause)) {
965 $clause = implode(' AND ', $clause);
967 $query = "SELECT id FROM civicrm_participant WHERE $clause";
968 $dao = CRM_Core_DAO
::executeQuery($query, $input);
970 while ($dao->fetch()) {
971 $duplicates[] = $dao->id
;
978 * Fix the event level.
980 * When price sets are used as event fee, fee_level is set as ^A
981 * separated string. We need to change that string to comma
982 * separated string before using fee_level in view mode.
984 * @param string $eventLevel
985 * Event_level string from db.
987 public static function fixEventLevel(&$eventLevel) {
988 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
989 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
991 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
992 $pos = strrpos($eventLevel, '(multiple participants)', 0);
994 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
997 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
998 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
999 substr($eventLevel, 0, 1)
1002 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1003 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1004 substr($eventLevel, 0, -1)
1010 * Get the additional participant ids.
1012 * @param int $primaryParticipantId
1013 * Primary partycipant Id.
1014 * @param bool $excludeCancel
1015 * Do not include participant those are cancelled.
1017 * @param int $oldStatusId
1021 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1022 $additionalParticipantIds = array();
1023 if (!$primaryParticipantId) {
1024 return $additionalParticipantIds;
1027 $where = "participant.registered_by_id={$primaryParticipantId}";
1028 if ($excludeCancel) {
1029 $cancelStatusId = 0;
1030 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1031 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1032 $where .= " AND participant.status_id != {$cancelStatusId}";
1036 $where .= " AND participant.status_id = {$oldStatusId}";
1040 SELECT participant.id
1041 FROM civicrm_participant participant
1044 $dao = CRM_Core_DAO
::executeQuery($query);
1045 while ($dao->fetch()) {
1046 $additionalParticipantIds[$dao->id
] = $dao->id
;
1048 return $additionalParticipantIds;
1052 * Get the amount for the undiscounted version of the field.
1054 * Note this function is part of the refactoring process rather than the best approach.
1056 * @param int $eventID
1057 * @param int $discountedPriceFieldOptionID
1058 * @param string $feeLevel (deprecated)
1060 * @return null|string
1062 public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
1063 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1065 1 => array($priceSetId, 'Integer'),
1067 if ($discountedPriceFieldOptionID) {
1068 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1069 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1070 WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
1071 $params[2] = array($discountedPriceFieldOptionID, 'Integer');
1074 $feeLevel = current($feeLevel);
1075 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1076 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1077 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1078 $params[2] = array($feeLevel, 'String');
1080 return CRM_Core_DAO
::singleValueQuery($query, $params);
1084 * Get the event fee info for given participant ids
1085 * either from line item table / participant table.
1087 * @param array $participantIds
1089 * @param bool $hasLineItems
1090 * Do fetch from line items.
1094 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1095 $feeDetails = array();
1096 if (!is_array($participantIds) ||
empty($participantIds)) {
1101 SELECT participant.id as id,
1102 participant.fee_level as fee_level,
1103 participant.fee_amount as fee_amount';
1104 $from = 'FROM civicrm_participant participant';
1105 if ($hasLineItems) {
1107 lineItem.id as lineId,
1108 lineItem.label as label,
1109 lineItem.qty as qty,
1110 lineItem.unit_price as unit_price,
1111 lineItem.line_total as line_total,
1112 field.label as field_title,
1113 field.html_type as html_type,
1114 field.id as price_field_id,
1115 value.id as price_field_value_id,
1116 value.description as description,
1117 IF( value.count, value.count, 0 ) as participant_count';
1119 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1120 AND lineItem.entity_id = participant.id )
1121 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1122 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1125 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1126 $query = "$select $from $where";
1128 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1129 $feeProperties = array('fee_level', 'fee_amount');
1130 $lineProperties = array(
1139 'participant_count',
1140 'price_field_value_id',
1143 while ($feeInfo->fetch()) {
1144 if ($hasLineItems) {
1145 foreach ($lineProperties as $property) {
1146 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1150 foreach ($feeProperties as $property) {
1151 $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1160 * Retrieve additional participants display-names and URL to view their participant records.
1161 * (excludes cancelled participants automatically)
1163 * @param int $primaryParticipantID
1164 * Id of primary participant record.
1167 * $displayName => $viewUrl
1169 public static function getAdditionalParticipants($primaryParticipantID) {
1170 $additionalParticipantIDs = array();
1171 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1172 if (!empty($additionalParticipantIDs)) {
1173 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1174 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1175 $additionalParticipantID,
1178 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1179 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1180 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1183 $additionalParticipants[$additionalContactName] = $pViewURL;
1186 return $additionalParticipants;
1190 * Function for update primary and additional participant status.
1192 * @param int $participantID
1193 * Primary participant's id.
1194 * @param int $oldStatusID
1195 * @param int $newStatusID
1196 * @param bool $updatePrimaryStatus
1200 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1201 if (!$participantID ||
!$oldStatusID) {
1205 if (!$newStatusID) {
1206 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1208 elseif ($updatePrimaryStatus) {
1209 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1212 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1214 if (!empty($cascadeAdditionalIds)) {
1216 foreach ($cascadeAdditionalIds as $id) {
1217 $participantParams = array(
1219 'status_id' => $newStatusID,
1221 civicrm_api3('Participant', 'create', $participantParams);
1225 catch (CiviCRM_API3_Exception
$e) {
1226 throw new CRM_Core_Exception('Failed to update additional participant status in database');
1233 * Function for update status for given participant ids.
1235 * @param int $participantIds
1236 * Array of participant ids.
1237 * @param int $statusId
1238 * Status id for participant.
1239 * @param bool $updateRegisterDate
1241 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1242 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1246 //lets update register date as we update status to keep track
1247 //when we did update status, useful for moving participant
1248 //from pending to expired.
1249 $setClause = "status_id = {$statusId}";
1250 if ($updateRegisterDate) {
1251 $setClause .= ", register_date = NOW()";
1254 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1257 UPDATE civicrm_participant
1259 WHERE id IN {$participantIdClause}";
1261 $dao = CRM_Core_DAO
::executeQuery($query);
1265 * Function takes participant ids and statuses
1266 * update status from $fromStatusId to $toStatusId
1267 * and send mail + create activities.
1269 * @param array $participantIds
1271 * @param int $toStatusId
1273 * @param int $fromStatusId
1275 * @param bool $returnResult
1276 * @param bool $skipCascadeRule
1278 * @return array|NULL
1280 public static function transitionParticipants(
1281 $participantIds, $toStatusId,
1282 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1284 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1288 //thumb rule is if we triggering primary participant need to triggered additional
1289 $allParticipantIds = $primaryANDAdditonalIds = array();
1290 foreach ($participantIds as $id) {
1291 $allParticipantIds[] = $id;
1292 if (self
::isPrimaryParticipant($id)) {
1293 //filter additional as per status transition rules, CRM-5403
1294 if ($skipCascadeRule) {
1295 $additionalIds = self
::getAdditionalParticipantIds($id);
1298 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1300 if (!empty($additionalIds)) {
1301 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1302 $primaryANDAdditonalIds[$id] = $additionalIds;
1307 //get the unique participant ids,
1308 $allParticipantIds = array_unique($allParticipantIds);
1310 //pull required participants, contacts, events data, if not in hand
1311 static $eventDetails = array();
1312 static $domainValues = array();
1313 static $contactDetails = array();
1315 $contactIds = $eventIds = $participantDetails = array();
1317 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1318 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1319 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1323 //first thing is pull all necessory data from db.
1324 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1326 //get all participants data.
1327 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1328 $dao = CRM_Core_DAO
::executeQuery($query);
1329 while ($dao->fetch()) {
1330 $participantDetails[$dao->id
] = array(
1332 'role' => $participantRoles[$dao->role_id
],
1333 'is_test' => $dao->is_test
,
1334 'event_id' => $dao->event_id
,
1335 'status_id' => $dao->status_id
,
1336 'fee_amount' => $dao->fee_amount
,
1337 'contact_id' => $dao->contact_id
,
1338 'register_date' => $dao->register_date
,
1339 'registered_by_id' => $dao->registered_by_id
,
1341 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1342 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1345 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1346 $eventIds[$dao->event_id
] = $dao->event_id
;
1350 //get the domain values.
1351 if (empty($domainValues)) {
1352 // making all tokens available to templates.
1353 $domain = CRM_Core_BAO_Domain
::getDomain();
1355 'domain' => array('name', 'phone', 'address', 'email'),
1356 'contact' => CRM_Core_SelectValues
::contactTokens(),
1359 foreach ($tokens['domain'] as $token) {
1360 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1364 //get all required contacts detail.
1365 if (!empty($contactIds)) {
1366 // get the contact details.
1367 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1370 'CRM_Event_BAO_Participant'
1372 foreach ($currentContactDetails as $contactId => $contactValues) {
1373 $contactDetails[$contactId] = $contactValues;
1377 //get all required events detail.
1378 if (!empty($eventIds)) {
1379 foreach ($eventIds as $eventId) {
1380 //retrieve event information
1381 $eventParams = array('id' => $eventId);
1382 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1384 //get default participant role.
1385 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1387 //get the location info
1388 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1389 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1393 //now we are ready w/ all required data.
1394 //take a decision as per statuses.
1397 $toStatus = $statusTypes[$toStatusId];
1398 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1400 switch ($toStatus) {
1401 case 'Pending from waitlist':
1402 case 'Pending from approval':
1403 switch ($fromStatus) {
1405 case 'Awaiting approval':
1406 $emailType = 'Confirm';
1412 //no matter from where u come send expired mail.
1413 $emailType = $toStatus;
1417 //no matter from where u come send cancel mail.
1418 $emailType = $toStatus;
1422 //as we process additional w/ primary, there might be case if user
1423 //select primary as well as additionals, so avoid double processing.
1424 $processedParticipantIds = array();
1425 $mailedParticipants = array();
1427 //send mails and update status.
1428 foreach ($participantDetails as $participantId => $participantValues) {
1429 $updateParticipantIds = array();
1430 if (in_array($participantId, $processedParticipantIds)) {
1434 //check is it primary and has additional.
1435 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1436 foreach ($primaryANDAdditonalIds[$participantId] as $additionalId) {
1439 $mail = self
::sendTransitionParticipantMail($additionalId,
1440 $participantDetails[$additionalId],
1441 $eventDetails[$participantDetails[$additionalId]['event_id']],
1442 $contactDetails[$participantDetails[$additionalId]['contact_id']],
1447 //get the mail participant ids
1449 $mailedParticipants[$additionalId] = $contactDetails[$participantDetails[$additionalId]['contact_id']]['display_name'];
1452 $updateParticipantIds[] = $additionalId;
1453 $processedParticipantIds[] = $additionalId;
1457 //now send email appropriate mail to primary.
1459 $mail = self
::sendTransitionParticipantMail($participantId,
1461 $eventDetails[$participantValues['event_id']],
1462 $contactDetails[$participantValues['contact_id']],
1467 //get the mail participant ids
1469 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1473 //now update status of group/one at once.
1474 $updateParticipantIds[] = $participantId;
1476 //update the register date only when we,
1477 //move participant to pending class, CRM-6496
1478 $updateRegisterDate = FALSE;
1479 if (array_key_exists($toStatusId, $pendingStatuses)) {
1480 $updateRegisterDate = TRUE;
1482 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1483 $processedParticipantIds[] = $participantId;
1486 //return result for cron.
1487 if ($returnResult) {
1489 'mailedParticipants' => $mailedParticipants,
1490 'updatedParticipantIds' => $processedParticipantIds,
1498 * Send mail and create activity
1499 * when participant status changed.
1501 * @param int $participantId
1503 * @param array $participantValues
1504 * Participant detail values. status id for participants.
1505 * @param array $eventDetails
1506 * Required event details.
1507 * @param array $contactDetails
1508 * Required contact details.
1509 * @param array $domainValues
1510 * Required domain values.
1511 * @param string $mailType
1512 * (eg 'approval', 'confirm', 'expired' ).
1516 public static function sendTransitionParticipantMail(
1527 //don't send confirmation mail to additional
1528 //since only primary able to confirm registration.
1529 if (!empty($participantValues['registered_by_id']) &&
1530 $mailType == 'Confirm'
1534 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1537 $contactId = $participantValues['contact_id'];
1538 $participantName = $contactDetails['display_name'];
1540 //calculate the checksum value.
1541 $checksumValue = NULL;
1542 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1543 $checksumLife = 'inf';
1544 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1546 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1548 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1551 //take a receipt from as event else domain.
1552 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1553 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1554 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1557 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1559 'groupName' => 'msg_tpl_workflow_event',
1560 'valueName' => 'participant_' . strtolower($mailType),
1561 'contactId' => $contactId,
1562 'tplParams' => array(
1563 'contact' => $contactDetails,
1564 'domain' => $domainValues,
1565 'participant' => $participantValues,
1566 'event' => $eventDetails,
1567 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1568 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1569 'isAdditional' => $participantValues['registered_by_id'],
1570 'isExpired' => $mailType == 'Expired',
1571 'isConfirm' => $mailType == 'Confirm',
1572 'checksumValue' => $checksumValue,
1574 'from' => $receiptFrom,
1575 'toName' => $participantName,
1576 'toEmail' => $toEmail,
1577 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1578 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1582 // 3. create activity record.
1584 $now = date('YmdHis');
1585 $activityType = 'Event Registration';
1586 $activityParams = array(
1587 'subject' => $subject,
1588 'source_contact_id' => $contactId,
1589 'source_record_id' => $participantId,
1590 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1591 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1592 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1593 'is_test' => $participantValues['is_test'],
1597 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1598 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1607 * Get participant status change message.
1609 * @param int $participantId
1610 * @param $statusChangeTo
1611 * @param int $fromStatusId
1615 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1617 $results = self
::transitionParticipants(array($participantId),
1618 $statusChangeTo, $fromStatusId, TRUE
1621 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1622 //give user message only when mail has sent.
1623 if (is_array($results) && !empty($results)) {
1624 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1625 foreach ($results['updatedParticipantIds'] as $processedId) {
1626 if (is_array($results['mailedParticipants']) &&
1627 array_key_exists($processedId, $results['mailedParticipants'])
1629 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1631 1 => $allStatuses[$statusChangeTo],
1632 2 => $results['mailedParticipants'][$processedId],
1644 * Get event full and waiting list message.
1646 * @param int $eventId
1647 * @param int $participantId
1651 public static function eventFullMessage($eventId, $participantId = NULL) {
1652 $eventfullMsg = $dbStatusId = NULL;
1653 $checkEventFull = TRUE;
1654 if ($participantId) {
1655 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1656 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1657 //participant already in counted status no need to check for event full messages.
1658 $checkEventFull = FALSE;
1663 if (!$eventId ||
!$checkEventFull) {
1664 return $eventfullMsg;
1667 //event is truly full.
1668 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1669 if (is_string($emptySeats) && $emptySeats !== NULL) {
1670 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1671 $eventfullMsg = ts("This event currently has the maximum number of participants registered (%1). However, you can still override this limit and register additional participants using this form.", array(
1672 1 => $maxParticipants,
1676 $hasWaiting = FALSE;
1677 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1678 if (is_numeric($waitListedCount)) {
1680 //only current processing participant is on waitlist.
1681 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1682 $hasWaiting = FALSE;
1687 $waitingStatusId = array_search('On waitlist',
1688 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1690 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1691 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1694 $eventfullMsg .= ts("There are %2 people currently on the waiting list for this event. You can <a href='%1'>view waitlisted registrations here</a>, or you can continue and register additional participants using this form.",
1696 1 => $viewWaitListUrl,
1697 2 => $waitListedCount,
1702 return $eventfullMsg;
1706 * Check for whether participant is primary or not.
1708 * @param int $participantId
1711 * true if participant is primary
1713 public static function isPrimaryParticipant($participantId) {
1715 $participant = new CRM_Event_DAO_Participant();
1716 $participant->registered_by_id
= $participantId;
1718 if ($participant->find(TRUE)) {
1725 * Get additional participant Ids for cascading with primary participant status.
1727 * @param int $participantId
1729 * @param int $oldStatusId
1731 * @param int $newStatusId
1737 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1739 $additionalParticipantIds = array();
1741 static $participantStatuses = array();
1743 if (empty($participantStatuses)) {
1744 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1747 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1748 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1750 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1753 return $additionalParticipantIds;
1757 * Get participant record count for a Contact.
1759 * @param int $contactID
1762 * count of participant records
1764 public static function getContactParticipantCount($contactID) {
1765 $query = "SELECT count(*)
1766 FROM civicrm_participant
1767 WHERE civicrm_participant.contact_id = {$contactID} AND
1768 civicrm_participant.is_test = 0";
1769 return CRM_Core_DAO
::singleValueQuery($query);
1773 * Get participant ids by contribution id.
1775 * @param int $contributionId
1777 * @param bool $excludeCancelled
1778 * Exclude cancelled additional participant.
1782 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1785 if (!$contributionId) {
1789 // get primary participant id
1790 $query = "SELECT participant_id
1791 FROM civicrm_participant cp
1792 LEFT JOIN civicrm_participant_payment cpp ON cp.id = cpp.participant_id
1793 WHERE cpp.contribution_id = {$contributionId}
1794 AND cp.registered_by_id IS NULL";
1795 $participantPayment = CRM_Core_DAO
::executeQuery($query);
1797 // get additional participant ids (including cancelled)
1798 while ($participantPayment->fetch()) {
1799 $ids = array_merge($ids, array_merge(array(
1800 $participantPayment->participant_id
,
1801 ), self
::getAdditionalParticipantIds($participantPayment->participant_id
,
1810 * Get additional Participant edit & view url .
1812 * @param array $participantIds
1813 * An array of additional participant ids.
1818 public static function getAdditionalParticipantUrl($participantIds) {
1819 foreach ($participantIds as $value) {
1821 $details = self
::participantDetails($value);
1822 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1823 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1825 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1826 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1828 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1829 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1835 * create trxn entry if an event has discount.
1837 * @param int $eventID
1839 * @param array $contributionParams
1840 * Contribution params.
1842 * @param string $feeLevel (deprecated)
1843 * @param int $discountedPriceFieldOptionID
1844 * ID of the civicrm_price_field_value field for the discount id.
1846 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID = NULL) {
1847 $financialTypeID = $contributionParams['contribution']->financial_type_id
;
1848 $total_amount = $contributionParams['total_amount'];
1850 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID, 'civicrm_event');
1851 if (!empty($checkDiscount)) {
1852 $mainAmount = self
::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
1853 $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
1854 $financialTypeID, 'Discounts Account is');
1855 if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
1856 $transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
1857 $transactionParams['trxnParams']['payment_processor_id'] = NULL;
1858 $transactionParams['trxnParams']['payment_instrument_id'] = NULL;
1859 $transactionParams['trxnParams']['check_number'] = NULL;
1860 $transactionParams['trxnParams']['trxn_id'] = NULL;
1861 $transactionParams['trxnParams']['net_amount'] = NULL;
1862 $transactionParams['trxnParams']['fee_amount'] = NULL;
1863 CRM_Core_BAO_FinancialTrxn
::create($transactionParams);
1869 * Delete participants of contact.
1873 * @param int $contactId
1877 public static function deleteContactParticipant($contactId) {
1878 $participant = new CRM_Event_DAO_Participant();
1879 $participant->contact_id
= $contactId;
1880 $participant->find();
1881 while ($participant->fetch()) {
1882 self
::deleteParticipant($participant->id
);
1887 * @param int $participantId
1888 * @param $activityType
1890 * @throws CRM_Core_Exception
1892 public static function addActivityForSelection($participantId, $activityType) {
1893 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
1894 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
1896 $date = CRM_Utils_Date
::currentDBDate();
1897 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
1898 $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array
::value($eventId, $event));
1901 $activityParams = array(
1902 'source_contact_id' => $contactId,
1903 'source_record_id' => $participantId,
1904 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1905 'subject' => $subject,
1906 'activity_date_time' => $date,
1907 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1908 'skipRecentView' => TRUE,
1911 // create activity with target contacts
1912 $id = CRM_Core_Session
::singleton()->getLoggedInContactID();;
1914 $activityParams['source_contact_id'] = $id;
1915 $activityParams['target_contact_id'][] = $contactId;
1917 // @todo use api & also look at duplication of similar methods.
1918 CRM_Activity_BAO_Activity
::create($activityParams);
1922 * Get options for a given field.
1923 * @see CRM_Core_DAO::buildOptions
1925 * @param string $fieldName
1926 * @param string $context
1927 * @see CRM_Core_DAO::buildOptionsContext
1928 * @param array $props
1929 * whatever is known about this dao object.
1931 * @return array|bool
1933 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1934 $params = array('condition' => array());
1936 if ($fieldName == 'status_id' && $context != 'validate') {
1937 // Get rid of cart-related option if disabled
1938 // FIXME: Why does this option even exist if cart is disabled?
1939 if (!Civi
::settings()->get('enable_cart')) {
1940 $params['condition'][] = "name <> 'Pending in cart'";
1944 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
1948 * CRM-17797 -- Format fields and setDefaults for primary and additional participants profile
1949 * @param int $contactId
1950 * @param CRM_Core_Form $form
1952 public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
1957 if (!empty($form->_fields
)) {
1958 $removeCustomFieldTypes = array('Participant');
1960 foreach ($form->_fields
as $name => $dontCare) {
1961 if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
1962 && !CRM_Core_BAO_CustomGroup
::checkCustomField(substr($name, 7), $removeCustomFieldTypes))
1963 ||
substr($name, 0, 12) == 'participant_') {
1969 if (!empty($fields)) {
1970 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $fields, $form->_defaults
);