3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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
552 {$skipParticipantClause}";
554 $lineItem = CRM_Core_DAO
::executeQuery($sql, array(1 => array($eventId, 'Positive')));
555 while ($lineItem->fetch()) {
556 $count = $lineItem->count
;
560 if ($lineItem->html_type
== 'Text') {
561 $count *= $lineItem->qty
;
563 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
566 return $optionsCount;
570 * Get the empty spaces for event those we can allocate
571 * to pending participant to become confirm.
573 * @param int $eventId
577 * $spaces Number of Empty Seats/null.
579 public static function pendingToConfirmSpaces($eventId) {
585 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
586 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
589 SELECT count(participant.id) as registered,
590 civicrm_event.max_participants
591 FROM civicrm_participant participant, civicrm_event
592 WHERE participant.event_id = {$eventId}
593 AND civicrm_event.id = participant.event_id
594 AND participant.status_id IN {$statusIds}
595 GROUP BY participant.event_id
597 $dao = CRM_Core_DAO
::executeQuery($query);
601 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
606 if ($dao->registered
>= $dao->max_participants
) {
611 return $dao->max_participants
- $dao->registered
;
614 //space in case no registeration yet.
615 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
619 * Combine all the importable fields from the lower levels object.
621 * @param string $contactType
622 * @param bool $status
623 * @param bool $onlyParticipant
624 * @param bool $checkPermission
625 * Is this a permissioned retrieval?
628 * array of importable Fields
630 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE) {
631 if (!self
::$_importableFields) {
632 if (!$onlyParticipant) {
634 $fields = array('' => array('title' => ts('- do not import -')));
637 $fields = array('' => array('title' => ts('- Participant Fields -')));
644 $tmpFields = CRM_Event_DAO_Participant
::import();
647 'participant_note' => array(
648 'title' => ts('Participant Note'),
649 'name' => 'participant_note',
650 'headerPattern' => '/(participant.)?note$/i',
655 // Split status and status id into 2 fields
656 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
657 $participantStatus = array(
658 'participant_status' => array(
659 'title' => ts('Participant Status'),
660 'name' => 'participant_status',
661 'data_type' => CRM_Utils_Type
::T_STRING
,
664 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
666 // Split role and role id into 2 fields
667 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
668 $participantRole = array(
669 'participant_role' => array(
670 'title' => ts('Participant Role'),
671 'name' => 'participant_role',
672 'data_type' => CRM_Utils_Type
::T_STRING
,
675 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
678 'event_type' => array(
679 'title' => ts('Event Type'),
680 'name' => 'event_type',
681 'data_type' => CRM_Utils_Type
::T_STRING
,
685 $tmpContactField = $contactFields = array();
686 $contactFields = array();
687 if (!$onlyParticipant) {
688 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
690 // Using new Dedupe rule.
692 'contact_type' => $contactType,
693 'used' => 'Unsupervised',
695 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
697 if (is_array($fieldsArray)) {
698 foreach ($fieldsArray as $value) {
699 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
704 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
705 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
707 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
710 $title = $tmpContactField[trim($value)]['title'];
713 $tmpContactField[trim($value)]['title'] = $title;
717 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
718 if ($extIdentifier) {
719 $tmpContactField['external_identifier'] = $extIdentifier;
720 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
722 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
724 $fields = array_merge($fields, $tmpContactField);
725 $fields = array_merge($fields, $tmpFields);
726 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
727 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
729 self
::$_importableFields = $fields;
732 return self
::$_importableFields;
736 * Combine all the exportable fields from the lower level objects.
738 * @param bool $checkPermission
741 * array of exportable Fields
743 public static function &exportableFields($checkPermission = TRUE) {
744 if (!self
::$_exportableFields) {
745 if (!self
::$_exportableFields) {
746 self
::$_exportableFields = array();
749 $participantFields = CRM_Event_DAO_Participant
::export();
750 $eventFields = CRM_Event_DAO_Event
::export();
752 'participant_note' => array(
753 'title' => ts('Participant Note'),
754 'name' => 'participant_note',
755 'type' => CRM_Utils_Type
::T_STRING
,
759 $participantStatus = array(
760 'participant_status' => array(
761 'title' => ts('Participant Status (label)'),
762 'name' => 'participant_status',
763 'type' => CRM_Utils_Type
::T_STRING
,
767 $participantRole = array(
768 'participant_role' => array(
769 'title' => ts('Participant Role (label)'),
770 'name' => 'participant_role',
771 'type' => CRM_Utils_Type
::T_STRING
,
775 $participantFields['participant_status_id']['title'] .= ' (ID)';
776 $participantFields['participant_role_id']['title'] .= ' (ID)';
778 $discountFields = CRM_Core_DAO_Discount
::export();
780 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
783 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
784 self
::$_exportableFields = $fields;
787 return self
::$_exportableFields;
791 * Get the event name/sort name for a particular participation / participant
793 * @param int $participantId
794 * Id of the participant.
797 * associated array with sort_name and event title
799 public static function participantDetails($participantId) {
801 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
802 FROM civicrm_participant
803 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
804 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
805 WHERE civicrm_participant.id = {$participantId}
807 $dao = CRM_Core_DAO
::executeQuery($query);
810 while ($dao->fetch()) {
811 $details['name'] = $dao->name
;
812 $details['title'] = $dao->title
;
813 $details['cid'] = $dao->cid
;
820 * Get the values for pseudoconstants for name->value and reverse.
822 * @param array $defaults
823 * (reference) the default values, some of which need to be resolved.
824 * @param bool $reverse
825 * True if we want to resolve the values in the reverse direction (value -> name).
827 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
828 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
829 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
830 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
834 * Convert associative array names to values and vice-versa.
836 * This function is used by both the web form layer and the api. Note that
837 * the api needs the name => value conversion, also the view layer typically
838 * requires value => name conversion
840 * @param array $defaults
841 * @param string $property
842 * @param string $lookup
843 * @param bool $reverse
847 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
848 $id = $property . '_id';
850 $src = $reverse ?
$property : $id;
851 $dst = $reverse ?
$id : $property;
853 if (!array_key_exists($src, $defaults)) {
857 $look = $reverse ?
array_flip($lookup) : $lookup;
859 if (is_array($look)) {
860 if (!array_key_exists($defaults[$src], $look)) {
864 $defaults[$dst] = $look[$defaults[$src]];
869 * Delete the records that are associated with this participation.
872 * Id of the participation to delete.
874 * @return \CRM_Event_DAO_Participant
876 public static function deleteParticipant($id) {
877 $participant = new CRM_Event_DAO_Participant();
878 $participant->id
= $id;
879 if (!$participant->find()) {
882 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
884 $transaction = new CRM_Core_Transaction();
886 //delete activity record
888 'source_record_id' => $id,
889 // activity type id for event registration
890 'activity_type_id' => 5,
893 CRM_Activity_BAO_Activity
::deleteActivity($params);
895 // delete the participant payment record
896 // we need to do this since the cascaded constraints
897 // dont work with join tables
898 $p = array('participant_id' => $id);
899 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
901 // cleanup line items.
902 $participantsId = array();
903 $participantsId = self
::getAdditionalParticipantIds($id);
904 $participantsId[] = $id;
905 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
907 //delete note when participant deleted.
908 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
909 $noteId = key($note);
911 CRM_Core_BAO_Note
::del($noteId, FALSE);
914 $participant->delete();
916 $transaction->commit();
918 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
920 // delete the recently created Participant
921 $participantRecent = array(
923 'type' => 'Participant',
926 CRM_Utils_Recent
::del($participantRecent);
932 * Checks duplicate participants.
934 * @param array $input
935 * An assosiative array of name /value pairs.
936 * from other function
937 * @param array $duplicates
938 * (reference ) an assoc array of name/value pairs.
940 * @return CRM_Contribute_BAO_Contribution
942 public static function checkDuplicate($input, &$duplicates) {
943 $eventId = CRM_Utils_Array
::value('event_id', $input);
944 $contactId = CRM_Utils_Array
::value('contact_id', $input);
950 $clause[] = "event_id = %1";
951 $input[1] = array($eventId, 'Integer');
955 $clause[] = "contact_id = %2";
956 $input[2] = array($contactId, 'Integer');
959 if (empty($clause)) {
963 $clause = implode(' AND ', $clause);
965 $query = "SELECT id FROM civicrm_participant WHERE $clause";
966 $dao = CRM_Core_DAO
::executeQuery($query, $input);
968 while ($dao->fetch()) {
969 $duplicates[] = $dao->id
;
976 * Fix the event level.
978 * When price sets are used as event fee, fee_level is set as ^A
979 * separated string. We need to change that string to comma
980 * separated string before using fee_level in view mode.
982 * @param string $eventLevel
983 * Event_level string from db.
985 public static function fixEventLevel(&$eventLevel) {
986 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
987 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
989 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
990 $pos = strrpos($eventLevel, '(multiple participants)', 0);
992 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
995 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
996 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
997 substr($eventLevel, 0, 1)
1000 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1001 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1002 substr($eventLevel, 0, -1)
1008 * Get the additional participant ids.
1010 * @param int $primaryParticipantId
1011 * Primary partycipant Id.
1012 * @param bool $excludeCancel
1013 * Do not include participant those are cancelled.
1015 * @param int $oldStatusId
1019 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1020 $additionalParticipantIds = array();
1021 if (!$primaryParticipantId) {
1022 return $additionalParticipantIds;
1025 $where = "participant.registered_by_id={$primaryParticipantId}";
1026 if ($excludeCancel) {
1027 $cancelStatusId = 0;
1028 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1029 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1030 $where .= " AND participant.status_id != {$cancelStatusId}";
1034 $where .= " AND participant.status_id = {$oldStatusId}";
1038 SELECT participant.id
1039 FROM civicrm_participant participant
1042 $dao = CRM_Core_DAO
::executeQuery($query);
1043 while ($dao->fetch()) {
1044 $additionalParticipantIds[$dao->id
] = $dao->id
;
1046 return $additionalParticipantIds;
1050 * Get the amount for the undiscounted version of the field.
1052 * Note this function is part of the refactoring process rather than the best approach.
1054 * @param int $eventID
1055 * @param int $discountedPriceFieldOptionID
1056 * @param string $feeLevel (deprecated)
1058 * @return null|string
1060 public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
1061 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1063 1 => array($priceSetId, 'Integer'),
1065 if ($discountedPriceFieldOptionID) {
1066 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1067 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1068 WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
1069 $params[2] = array($discountedPriceFieldOptionID, 'Integer');
1072 $feeLevel = current($feeLevel);
1073 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1074 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1075 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1076 $params[2] = array($feeLevel, 'String');
1078 return CRM_Core_DAO
::singleValueQuery($query, $params);
1082 * Get the event fee info for given participant ids
1083 * either from line item table / participant table.
1085 * @param array $participantIds
1087 * @param bool $hasLineItems
1088 * Do fetch from line items.
1092 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1093 $feeDetails = array();
1094 if (!is_array($participantIds) ||
empty($participantIds)) {
1099 SELECT participant.id as id,
1100 participant.fee_level as fee_level,
1101 participant.fee_amount as fee_amount';
1102 $from = 'FROM civicrm_participant participant';
1103 if ($hasLineItems) {
1105 lineItem.id as lineId,
1106 lineItem.label as label,
1107 lineItem.qty as qty,
1108 lineItem.unit_price as unit_price,
1109 lineItem.line_total as line_total,
1110 field.label as field_title,
1111 field.html_type as html_type,
1112 field.id as price_field_id,
1113 value.id as price_field_value_id,
1114 value.description as description,
1115 IF( value.count, value.count, 0 ) as participant_count';
1117 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1118 AND lineItem.entity_id = participant.id )
1119 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1120 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1123 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1124 $query = "$select $from $where";
1126 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1127 $feeProperties = array('fee_level', 'fee_amount');
1128 $lineProperties = array(
1137 'participant_count',
1138 'price_field_value_id',
1141 while ($feeInfo->fetch()) {
1142 if ($hasLineItems) {
1143 foreach ($lineProperties as $property) {
1144 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1148 foreach ($feeProperties as $property) {
1149 $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1158 * Retrieve additional participants display-names and URL to view their participant records.
1159 * (excludes cancelled participants automatically)
1161 * @param int $primaryParticipantID
1162 * Id of primary participant record.
1165 * $displayName => $viewUrl
1167 public static function getAdditionalParticipants($primaryParticipantID) {
1168 $additionalParticipantIDs = array();
1169 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1170 if (!empty($additionalParticipantIDs)) {
1171 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1172 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1173 $additionalParticipantID,
1176 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1177 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1178 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1181 $additionalParticipants[$additionalContactName] = $pViewURL;
1184 return $additionalParticipants;
1188 * Function for update primary and additional participant status.
1190 * @param int $participantID
1191 * Primary participant's id.
1192 * @param int $oldStatusID
1193 * @param int $newStatusID
1194 * @param bool $updatePrimaryStatus
1198 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1199 if (!$participantID ||
!$oldStatusID) {
1203 if (!$newStatusID) {
1204 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1206 elseif ($updatePrimaryStatus) {
1207 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1210 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1212 if (!empty($cascadeAdditionalIds)) {
1214 foreach ($cascadeAdditionalIds as $id) {
1215 $participantParams = array(
1217 'status_id' => $newStatusID,
1219 civicrm_api3('Participant', 'create', $participantParams);
1223 catch (CiviCRM_API3_Exception
$e) {
1224 throw new CRM_Core_Exception('Failed to update additional participant status in database');
1231 * Function for update status for given participant ids.
1233 * @param int $participantIds
1234 * Array of participant ids.
1235 * @param int $statusId
1236 * Status id for participant.
1237 * @param bool $updateRegisterDate
1239 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1240 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1244 //lets update register date as we update status to keep track
1245 //when we did update status, useful for moving participant
1246 //from pending to expired.
1247 $setClause = "status_id = {$statusId}";
1248 if ($updateRegisterDate) {
1249 $setClause .= ", register_date = NOW()";
1252 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1255 UPDATE civicrm_participant
1257 WHERE id IN {$participantIdClause}";
1259 $dao = CRM_Core_DAO
::executeQuery($query);
1263 * Function takes participant ids and statuses
1264 * update status from $fromStatusId to $toStatusId
1265 * and send mail + create activities.
1267 * @param array $participantIds
1269 * @param int $toStatusId
1271 * @param int $fromStatusId
1273 * @param bool $returnResult
1274 * @param bool $skipCascadeRule
1276 * @return array|NULL
1278 public static function transitionParticipants(
1279 $participantIds, $toStatusId,
1280 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1282 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1286 //thumb rule is if we triggering primary participant need to triggered additional
1287 $allParticipantIds = $primaryANDAdditonalIds = array();
1288 foreach ($participantIds as $id) {
1289 $allParticipantIds[] = $id;
1290 if (self
::isPrimaryParticipant($id)) {
1291 //filter additional as per status transition rules, CRM-5403
1292 if ($skipCascadeRule) {
1293 $additionalIds = self
::getAdditionalParticipantIds($id);
1296 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1298 if (!empty($additionalIds)) {
1299 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1300 $primaryANDAdditonalIds[$id] = $additionalIds;
1305 //get the unique participant ids,
1306 $allParticipantIds = array_unique($allParticipantIds);
1308 //pull required participants, contacts, events data, if not in hand
1309 static $eventDetails = array();
1310 static $domainValues = array();
1311 static $contactDetails = array();
1313 $contactIds = $eventIds = $participantDetails = array();
1315 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1316 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1317 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1321 //first thing is pull all necessory data from db.
1322 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1324 //get all participants data.
1325 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1326 $dao = CRM_Core_DAO
::executeQuery($query);
1327 while ($dao->fetch()) {
1328 $participantDetails[$dao->id
] = array(
1330 'role' => $participantRoles[$dao->role_id
],
1331 'is_test' => $dao->is_test
,
1332 'event_id' => $dao->event_id
,
1333 'status_id' => $dao->status_id
,
1334 'fee_amount' => $dao->fee_amount
,
1335 'contact_id' => $dao->contact_id
,
1336 'register_date' => $dao->register_date
,
1337 'registered_by_id' => $dao->registered_by_id
,
1339 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1340 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1343 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1344 $eventIds[$dao->event_id
] = $dao->event_id
;
1348 //get the domain values.
1349 if (empty($domainValues)) {
1350 // making all tokens available to templates.
1351 $domain = CRM_Core_BAO_Domain
::getDomain();
1353 'domain' => array('name', 'phone', 'address', 'email'),
1354 'contact' => CRM_Core_SelectValues
::contactTokens(),
1357 foreach ($tokens['domain'] as $token) {
1358 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1362 //get all required contacts detail.
1363 if (!empty($contactIds)) {
1364 // get the contact details.
1365 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1368 'CRM_Event_BAO_Participant'
1370 foreach ($currentContactDetails as $contactId => $contactValues) {
1371 $contactDetails[$contactId] = $contactValues;
1375 //get all required events detail.
1376 if (!empty($eventIds)) {
1377 foreach ($eventIds as $eventId) {
1378 //retrieve event information
1379 $eventParams = array('id' => $eventId);
1380 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1382 //get default participant role.
1383 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1385 //get the location info
1386 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1387 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1391 //now we are ready w/ all required data.
1392 //take a decision as per statuses.
1395 $toStatus = $statusTypes[$toStatusId];
1396 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1398 switch ($toStatus) {
1399 case 'Pending from waitlist':
1400 case 'Pending from approval':
1401 switch ($fromStatus) {
1403 case 'Awaiting approval':
1404 $emailType = 'Confirm';
1410 //no matter from where u come send expired mail.
1411 $emailType = $toStatus;
1415 //no matter from where u come send cancel mail.
1416 $emailType = $toStatus;
1420 //as we process additional w/ primary, there might be case if user
1421 //select primary as well as additionals, so avoid double processing.
1422 $processedParticipantIds = array();
1423 $mailedParticipants = array();
1425 //send mails and update status.
1426 foreach ($participantDetails as $participantId => $participantValues) {
1427 $updateParticipantIds = array();
1428 if (in_array($participantId, $processedParticipantIds)) {
1432 //check is it primary and has additional.
1433 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1434 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1437 $mail = self
::sendTransitionParticipantMail($additonalId,
1438 $participantDetails[$additonalId],
1439 $eventDetails[$participantDetails[$additonalId]['event_id']],
1440 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1445 //get the mail participant ids
1447 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1450 $updateParticipantIds[] = $additonalId;
1451 $processedParticipantIds[] = $additonalId;
1455 //now send email appropriate mail to primary.
1457 $mail = self
::sendTransitionParticipantMail($participantId,
1459 $eventDetails[$participantValues['event_id']],
1460 $contactDetails[$participantValues['contact_id']],
1465 //get the mail participant ids
1467 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1471 //now update status of group/one at once.
1472 $updateParticipantIds[] = $participantId;
1474 //update the register date only when we,
1475 //move participant to pending class, CRM-6496
1476 $updateRegisterDate = FALSE;
1477 if (array_key_exists($toStatusId, $pendingStatuses)) {
1478 $updateRegisterDate = TRUE;
1480 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1481 $processedParticipantIds[] = $participantId;
1484 //return result for cron.
1485 if ($returnResult) {
1487 'mailedParticipants' => $mailedParticipants,
1488 'updatedParticipantIds' => $processedParticipantIds,
1496 * Send mail and create activity
1497 * when participant status changed.
1499 * @param int $participantId
1501 * @param array $participantValues
1502 * Participant detail values. status id for participants.
1503 * @param array $eventDetails
1504 * Required event details.
1505 * @param array $contactDetails
1506 * Required contact details.
1507 * @param array $domainValues
1508 * Required domain values.
1509 * @param string $mailType
1510 * (eg 'approval', 'confirm', 'expired' ).
1514 public static function sendTransitionParticipantMail(
1525 //don't send confirmation mail to additional
1526 //since only primary able to confirm registration.
1527 if (!empty($participantValues['registered_by_id']) &&
1528 $mailType == 'Confirm'
1532 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1535 $contactId = $participantValues['contact_id'];
1536 $participantName = $contactDetails['display_name'];
1538 //calculate the checksum value.
1539 $checksumValue = NULL;
1540 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1541 $checksumLife = 'inf';
1542 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1544 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1546 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1549 //take a receipt from as event else domain.
1550 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1551 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1552 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1555 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1557 'groupName' => 'msg_tpl_workflow_event',
1558 'valueName' => 'participant_' . strtolower($mailType),
1559 'contactId' => $contactId,
1560 'tplParams' => array(
1561 'contact' => $contactDetails,
1562 'domain' => $domainValues,
1563 'participant' => $participantValues,
1564 'event' => $eventDetails,
1565 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1566 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1567 'isAdditional' => $participantValues['registered_by_id'],
1568 'isExpired' => $mailType == 'Expired',
1569 'isConfirm' => $mailType == 'Confirm',
1570 'checksumValue' => $checksumValue,
1572 'from' => $receiptFrom,
1573 'toName' => $participantName,
1574 'toEmail' => $toEmail,
1575 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1576 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1580 // 3. create activity record.
1582 $now = date('YmdHis');
1583 $activityType = 'Event Registration';
1584 $activityParams = array(
1585 'subject' => $subject,
1586 'source_contact_id' => $contactId,
1587 'source_record_id' => $participantId,
1588 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1592 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1593 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1594 'is_test' => $participantValues['is_test'],
1598 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1599 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1608 * Get participant status change message.
1610 * @param int $participantId
1611 * @param $statusChangeTo
1612 * @param int $fromStatusId
1616 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1618 $results = self
::transitionParticipants(array($participantId),
1619 $statusChangeTo, $fromStatusId, TRUE
1622 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1623 //give user message only when mail has sent.
1624 if (is_array($results) && !empty($results)) {
1625 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1626 foreach ($results['updatedParticipantIds'] as $processedId) {
1627 if (is_array($results['mailedParticipants']) &&
1628 array_key_exists($processedId, $results['mailedParticipants'])
1630 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1632 1 => $allStatuses[$statusChangeTo],
1633 2 => $results['mailedParticipants'][$processedId],
1645 * Get event full and waiting list message.
1647 * @param int $eventId
1648 * @param int $participantId
1652 public static function eventFullMessage($eventId, $participantId = NULL) {
1653 $eventfullMsg = $dbStatusId = NULL;
1654 $checkEventFull = TRUE;
1655 if ($participantId) {
1656 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1657 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1658 //participant already in counted status no need to check for event full messages.
1659 $checkEventFull = FALSE;
1664 if (!$eventId ||
!$checkEventFull) {
1665 return $eventfullMsg;
1668 //event is truly full.
1669 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1670 if (is_string($emptySeats) && $emptySeats !== NULL) {
1671 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1672 $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(
1673 1 => $maxParticipants,
1677 $hasWaiting = FALSE;
1678 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1679 if (is_numeric($waitListedCount)) {
1681 //only current processing participant is on waitlist.
1682 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1683 $hasWaiting = FALSE;
1688 $waitingStatusId = array_search('On waitlist',
1689 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1691 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1692 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1695 $eventfullMsg .= ts("There are %2 people currently on the waiting list for this event. You can <a href='%1'>view waitlisted registrations here</a>, or you can continue and register additional participants using this form.",
1697 1 => $viewWaitListUrl,
1698 2 => $waitListedCount,
1703 return $eventfullMsg;
1707 * Check for whether participant is primary or not.
1709 * @param int $participantId
1712 * true if participant is primary
1714 public static function isPrimaryParticipant($participantId) {
1716 $participant = new CRM_Event_DAO_Participant();
1717 $participant->registered_by_id
= $participantId;
1719 if ($participant->find(TRUE)) {
1726 * Get additional participant Ids for cascading with primary participant status.
1728 * @param int $participantId
1730 * @param int $oldStatusId
1732 * @param int $newStatusId
1738 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1740 $additionalParticipantIds = array();
1742 static $participantStatuses = array();
1744 if (empty($participantStatuses)) {
1745 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1748 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1749 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1751 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1754 return $additionalParticipantIds;
1758 * Get participant record count for a Contact.
1760 * @param int $contactID
1763 * count of participant records
1765 public static function getContactParticipantCount($contactID) {
1766 $query = "SELECT count(*)
1767 FROM civicrm_participant
1768 WHERE civicrm_participant.contact_id = {$contactID} AND
1769 civicrm_participant.is_test = 0";
1770 return CRM_Core_DAO
::singleValueQuery($query);
1774 * Get participant ids by contribution id.
1776 * @param int $contributionId
1778 * @param bool $excludeCancelled
1779 * Exclude cancelled additional participant.
1783 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1786 if (!$contributionId) {
1790 // get primary participant id
1791 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1792 $participantId = CRM_Core_DAO
::singleValueQuery($query);
1794 // get additional participant ids (including cancelled)
1795 if ($participantId) {
1796 $ids = array_merge(array(
1798 ), self
::getAdditionalParticipantIds($participantId,
1807 * Get additional Participant edit & view url .
1809 * @param array $participantIds
1810 * An array of additional participant ids.
1815 public static function getAdditionalParticipantUrl($participantIds) {
1816 foreach ($participantIds as $value) {
1818 $details = self
::participantDetails($value);
1819 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1820 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1822 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1823 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1825 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1826 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1832 * create trxn entry if an event has discount.
1834 * @param int $eventID
1836 * @param array $contributionParams
1837 * Contribution params.
1839 * @param string $feeLevel (deprecated)
1840 * @param int $discountedPriceFieldOptionID
1841 * ID of the civicrm_price_field_value field for the discount id.
1843 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID) {
1844 $financialTypeID = $contributionParams['contribution']->financial_type_id
;
1845 $total_amount = $contributionParams['total_amount'];
1847 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID, 'civicrm_event');
1848 if (!empty($checkDiscount)) {
1849 $mainAmount = self
::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
1850 $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
1851 $financialTypeID, 'Discounts Account is');
1852 if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
1853 $transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
1854 $transactionParams['trxnParams']['payment_processor_id'] = NULL;
1855 $transactionParams['trxnParams']['payment_instrument_id'] = NULL;
1856 $transactionParams['trxnParams']['check_number'] = NULL;
1857 $transactionParams['trxnParams']['trxn_id'] = NULL;
1858 $transactionParams['trxnParams']['net_amount'] = NULL;
1859 $transactionParams['trxnParams']['fee_amount'] = NULL;
1860 CRM_Core_BAO_FinancialTrxn
::create($transactionParams);
1866 * Delete participants of contact.
1870 * @param int $contactId
1874 public static function deleteContactParticipant($contactId) {
1875 $participant = new CRM_Event_DAO_Participant();
1876 $participant->contact_id
= $contactId;
1877 $participant->find();
1878 while ($participant->fetch()) {
1879 self
::deleteParticipant($participant->id
);
1884 * @param int $participantId
1885 * @param $activityType
1887 * @throws CRM_Core_Exception
1889 public static function addActivityForSelection($participantId, $activityType) {
1890 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
1891 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
1893 $date = CRM_Utils_Date
::currentDBDate();
1894 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
1895 $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array
::value($eventId, $event));
1896 $targetCid = $contactId;
1897 $srcRecId = $participantId;
1900 $activityParams = array(
1901 'source_contact_id' => $targetCid,
1902 'source_record_id' => $srcRecId,
1903 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1904 'subject' => $subject,
1905 'activity_date_time' => $date,
1906 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1907 'skipRecentView' => TRUE,
1910 // create activity with target contacts
1911 $session = CRM_Core_Session
::singleton();
1912 $id = $session->get('userID');
1914 $activityParams['source_contact_id'] = $id;
1915 $activityParams['target_contact_id'][] = $targetCid;
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
);