3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
33 * @copyright CiviCRM LLC (c) 2004-2014
37 class CRM_Event_BAO_Participant
extends CRM_Event_DAO_Participant
{
40 * static field for all the participant information that we can potentially import
45 static $_importableFields = NULL;
48 * static field for all the participant information that we can potentially export
53 static $_exportableFields = NULL;
56 * static array for valid status transitions rules
61 static $_statusTransitionsRules = array(
62 'Pending from pay later' => array('Registered', 'Cancelled'),
63 'Pending from incomplete transaction' => array('Registered', 'Cancelled'),
64 'On waitlist' => array('Cancelled', 'Pending from waitlist'),
65 'Pending from waitlist' => array('Registered', 'Cancelled'),
66 'Awaiting approval' => array('Cancelled', 'Pending from approval'),
67 'Pending from approval' => array('Registered', 'Cancelled'),
73 function __construct() {
74 parent
::__construct();
78 * takes an associative array and creates a participant object
80 * the function extract all the params it needs to initialize the create a
81 * participant object. the params array could contain additional unused name/value
84 * @param array $params (reference ) an assoc array of name/value pairs
86 * @internal param array $ids the array that holds all the db ids
88 * @return object CRM_Event_BAO_Participant object
92 static function &add(&$params) {
94 if (!empty($params['id'])) {
95 CRM_Utils_Hook
::pre('edit', 'Participant', $params['id'], $params);
98 CRM_Utils_Hook
::pre('create', 'Participant', NULL, $params);
101 // converting dates to mysql format
102 if (!empty($params['register_date'])) {
103 $params['register_date'] = CRM_Utils_Date
::isoToMysql($params['register_date']);
106 if (!empty($params['participant_fee_amount'])) {
107 $params['participant_fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['participant_fee_amount']);
110 if (!empty($params['fee_amount'])) {
111 $params['fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['fee_amount']);
114 // ensure that role ids are encoded as a string
115 if (isset($params['role_id']) && is_array($params['role_id'])) {
116 $params['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['role_id']);
119 $participantBAO = new CRM_Event_BAO_Participant
;
120 if (!empty($params['id'])) {
121 $participantBAO->id
= CRM_Utils_Array
::value('id', $params);
122 $participantBAO->find(TRUE);
123 $participantBAO->register_date
= CRM_Utils_Date
::isoToMysql($participantBAO->register_date
);
126 $participantBAO->copyValues($params);
129 //1. If currency present, it should be valid one.
130 //2. We should have currency when amount is not null.
131 $currency = $participantBAO->fee_currency
;
133 !CRM_Utils_System
::isNull($participantBAO->fee_amount
)
135 if (!CRM_Utils_Rule
::currencyCode($currency)) {
136 $config = CRM_Core_Config
::singleton();
137 $currency = $config->defaultCurrency
;
140 $participantBAO->fee_currency
= $currency;
142 $participantBAO->save();
144 $session = CRM_Core_Session
::singleton();
146 // reset the group contact cache for this group
147 CRM_Contact_BAO_GroupContactCache
::remove();
149 if (!empty($params['id'])) {
150 CRM_Utils_Hook
::post('edit', 'Participant', $participantBAO->id
, $participantBAO);
153 CRM_Utils_Hook
::post('create', 'Participant', $participantBAO->id
, $participantBAO);
156 return $participantBAO;
160 * Given the list of params in the params array, fetch the object
161 * and store the values in the values array
163 * @param array $params input parameters to find object
164 * @param array $values output values of the object
168 * @return CRM_Event_BAO_Participant|null the found object or null
172 static function getValues(&$params, &$values, &$ids) {
173 if (empty($params)) {
176 $participant = new CRM_Event_BAO_Participant();
177 $participant->copyValues($params);
178 $participant->find();
179 $participants = array();
180 while ($participant->fetch()) {
181 $ids['participant'] = $participant->id
;
182 CRM_Core_DAO
::storeValues($participant, $values[$participant->id
]);
183 $participants[$participant->id
] = $participant;
185 return $participants;
189 * takes an associative array and creates a participant object
191 * @param array $params (reference ) an assoc array of name/value pairs
193 * @internal param array $ids the array that holds all the db ids
195 * @return object CRM_Event_BAO_Participant object
199 static function create(&$params) {
201 $transaction = new CRM_Core_Transaction();
204 if (!empty($params['id'])) {
205 $status = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
208 $participant = self
::add($params);
210 if (is_a($participant, 'CRM_Core_Error')) {
211 $transaction->rollback();
215 if ((!CRM_Utils_Array
::value('id', $params)) ||
216 (isset($params['status_id']) && $params['status_id'] != $status)
218 CRM_Activity_BAO_Activity
::addActivity($participant);
223 if (self
::isPrimaryParticipant($participant->id
) && $status) {
224 self
::updateParticipantStatus($participant->id
, $status, $participant->status_id
);
227 $session = CRM_Core_Session
::singleton();
228 $id = $session->get('userID');
230 $id = CRM_Utils_Array
::value('contact_id', $params);
233 // add custom field values
234 if (!empty($params['custom']) &&
235 is_array($params['custom'])
237 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_participant', $participant->id
);
240 //process note, CRM-7634
242 if (!empty($params['id'])) {
243 $note = CRM_Core_BAO_Note
::getNote($params['id'], 'civicrm_participant');
244 $noteId = key($note);
247 $hasNoteField = FALSE;
249 'note', 'participant_note') as $noteFld) {
250 if (array_key_exists($noteFld, $params)) {
251 $noteValue = $params[$noteFld];
252 $hasNoteField = TRUE;
256 if ($noteId ||
$noteValue) {
259 'entity_table' => 'civicrm_participant',
260 'note' => $noteValue,
261 'entity_id' => $participant->id
,
263 'modified_date' => date('Ymd'),
267 $noteIDs['id'] = $noteId;
269 CRM_Core_BAO_Note
::add($noteParams, $noteIDs);
271 elseif ($noteId && $hasNoteField) {
272 CRM_Core_BAO_Note
::del($noteId, FALSE);
276 // Log the information on successful add/edit of Participant data.
278 'entity_table' => 'civicrm_participant',
279 'entity_id' => $participant->id
,
280 'data' => CRM_Event_PseudoConstant
::participantStatus($participant->status_id
),
281 'modified_id' => $id,
282 'modified_date' => date('Ymd'),
285 CRM_Core_BAO_Log
::add($logParams);
287 $params['participant_id'] = $participant->id
;
289 $transaction->commit();
291 // do not add to recent items for import, CRM-4399
292 if (empty($params['skipRecentView'])) {
294 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
295 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
298 $recentOther = array();
299 if (CRM_Core_Permission
::check('edit event participants')) {
300 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
301 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
304 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
305 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
306 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
310 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
312 if ($participant->role_id
) {
313 $role = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participant->role_id
);
315 foreach ($role as & $roleValue) {
316 if (isset($roleValue)) {
317 $roleValue = $participantRoles[$roleValue];
320 $roles = implode(', ', $role);
323 $roleString = empty($roles) ?
'' : $roles;
324 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $participant->event_id
, 'title');
325 $title = CRM_Contact_BAO_Contact
::displayName($participant->contact_id
) . ' (' . $roleString . ' - ' . $eventTitle . ')';
327 // add the recently created Participant
328 CRM_Utils_Recent
::add($title,
332 $participant->contact_id
,
342 * Check whether the event is full for participation and return as
345 * @param int $eventId event id.
346 * @param boolean $returnEmptySeats are we require number if empty seats.
347 * @param boolean $includeWaitingList consider waiting list in event full
348 * calculation or not. (it is for cron job purpose)
350 * @param bool $returnWaitingCount
351 * @param bool $considerTestParticipant
353 * @return bool|int|null|string 1. false => If event having some empty spaces.@static
356 static function eventFull(
358 $returnEmptySeats = FALSE,
359 $includeWaitingList = TRUE,
360 $returnWaitingCount = FALSE,
361 $considerTestParticipant = FALSE
368 // consider event is full when.
369 // 1. (count(is_counted) >= event_size) or
370 // 2. (count(participants-with-status-on-waitlist) > 0)
371 // It might be case there are some empty spaces and still event
372 // is full, as waitlist might represent group require spaces > empty.
374 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
375 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
376 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
377 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
379 //when we do require only waiting count don't consider counted.
380 if (!$returnWaitingCount && !empty($countedStatuses)) {
381 $allStatusIds = array_keys($countedStatuses);
384 $where = array(' event.id = %1 ');
385 if (!$considerTestParticipant) {
386 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
388 if (!empty($participantRoles)) {
389 $where[] = ' participant.role_id IN ( ' . implode(', ', array_keys($participantRoles)) . ' ) ';
392 $eventParams = array(1 => array($eventId, 'Positive'));
394 //in case any waiting, straight forward event is full.
395 if ($includeWaitingList && $onWaitlistStatusId) {
397 //build the where clause.
398 $whereClause = ' WHERE ' . implode(' AND ', $where);
399 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
400 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
403 SELECT participant.id id,
404 event.event_full_text as event_full_text
405 FROM civicrm_participant participant
406 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
409 $eventFullText = ts('This event is full.');
410 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
411 while ($participants->fetch()) {
412 //oops here event is full and we don't want waiting count.
413 if ($returnWaitingCount) {
414 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
417 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
422 //consider only counted participants.
423 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
424 $whereClause = ' WHERE ' . implode(' AND ', $where);
425 $eventSeatsWhere = implode(' AND ', $where);
428 SELECT participant.id id,
429 event.event_full_text as event_full_text,
430 event.max_participants as max_participants
431 FROM civicrm_participant participant
432 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
435 $eventMaxSeats = NULL;
436 $eventFullText = ts('This event is full.');
437 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
438 while ($participants->fetch()) {
439 if ($participants->event_full_text
) {
440 $eventFullText = $participants->event_full_text
;
442 $eventMaxSeats = $participants->max_participants
;
443 //don't have limit for event seats.
444 if ($participants->max_participants
== NULL) {
449 //get the total event seats occupied by these participants.
450 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
452 if ($eventRegisteredSeats) {
453 if ($eventRegisteredSeats >= $eventMaxSeats) {
454 $result = $eventFullText;
456 elseif ($returnEmptySeats) {
457 $result = $eventMaxSeats - $eventRegisteredSeats;
463 SELECT event.event_full_text,
464 event.max_participants
465 FROM civicrm_event event
466 WHERE event.id = %1';
467 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
468 while ($event->fetch()) {
469 $eventFullText = $event->event_full_text
;
470 $eventMaxSeats = $event->max_participants
;
474 // no limit for registration.
475 if ($eventMaxSeats == NULL) {
478 if ($eventMaxSeats) {
479 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
482 return $eventFullText;
486 * Return the array of all price set field options,
487 * with total participant count that field going to carry.
489 * @param int $eventId event id.
490 * @param array $skipParticipantIds
491 * @param bool $considerCounted
492 * @param bool $considerWaiting
493 * @param bool $considerTestParticipants
495 * @internal param array $skipParticipants an array of participant ids those we should skip.
496 * @internal param int $isTest would you like to consider test participants.
498 * @return array $optionsCount an array of each option id and total count
502 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
553 {$skipParticipantClause}";
555 $lineItem = CRM_Core_DAO
::executeQuery($sql, array(1 => array($eventId, 'Positive')));
556 while ($lineItem->fetch()) {
557 $count = $lineItem->count
;
561 if ($lineItem->html_type
== 'Text') {
562 $count *= $lineItem->qty
;
564 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
567 return $optionsCount;
571 * Get the empty spaces for event those we can allocate
572 * to pending participant to become confirm.
574 * @param int $eventId event id.
576 * @return int $spaces Number of Empty Seats/null.
580 static function pendingToConfirmSpaces($eventId) {
586 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
587 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
590 SELECT count(participant.id) as registered,
591 civicrm_event.max_participants
592 FROM civicrm_participant participant, civicrm_event
593 WHERE participant.event_id = {$eventId}
594 AND civicrm_event.id = participant.event_id
595 AND participant.status_id IN {$statusIds}
596 GROUP BY participant.event_id
598 $dao = CRM_Core_DAO
::executeQuery($query);
602 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
607 if ($dao->registered
>= $dao->max_participants
) {
612 return $dao->max_participants
- $dao->registered
;
615 //space in case no registeration yet.
616 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
620 * combine all the importable fields from the lower levels object
622 * @param string $contactType
623 * @param bool $status
624 * @param bool $onlyParticipant
626 * @return array array of importable Fields
630 static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE) {
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',
653 // Split status and status id into 2 fields
654 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
655 $participantStatus = array(
656 'participant_status' => array(
657 'title' => ts('Participant Status'),
658 'name' => 'participant_status',
659 'data_type' => CRM_Utils_Type
::T_STRING
,
661 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
663 // Split role and role id into 2 fields
664 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
665 $participantRole = array(
666 'participant_role' => array(
667 'title' => ts('Participant Role'),
668 'name' => 'participant_role',
669 'data_type' => CRM_Utils_Type
::T_STRING
,
671 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
674 'event_type' => array(
675 'title' => ts('Event Type'),
676 'name' => 'event_type',
677 'data_type' => CRM_Utils_Type
::T_STRING
,
680 $tmpContactField = $contactFields = array();
681 $contactFields = array( );
682 if (!$onlyParticipant) {
683 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
685 // Using new Dedupe rule.
687 'contact_type' => $contactType,
688 'used' => 'Unsupervised',
690 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
692 if (is_array($fieldsArray)) {
693 foreach ($fieldsArray as $value) {
694 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
699 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
700 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
702 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
705 $title = $tmpContactField[trim($value)]['title'];
708 $tmpContactField[trim($value)]['title'] = $title;
712 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
713 if ($extIdentifier) {
714 $tmpContactField['external_identifier'] = $extIdentifier;
715 $tmpContactField['external_identifier']['title'] =
716 CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
718 $tmpFields['participant_contact_id']['title'] =
719 $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
721 $fields = array_merge($fields, $tmpContactField);
722 $fields = array_merge($fields, $tmpFields);
723 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
724 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
726 self
::$_importableFields = $fields;
729 return self
::$_importableFields;
733 * combine all the exportable fields from the lower levels object
735 * @return array array of exportable Fields
739 static function &exportableFields() {
740 if (!self
::$_exportableFields) {
741 if (!self
::$_exportableFields) {
742 self
::$_exportableFields = array();
747 $participantFields = CRM_Event_DAO_Participant
::export();
749 'participant_note' => array('title' => 'Participant Note',
750 'name' => 'participant_note',
753 $participantStatus = array(
754 'participant_status' => array('title' => 'Participant Status',
755 'name' => 'participant_status',
758 $participantRole = array(
759 'participant_role' => array('title' => 'Participant Role',
760 'name' => 'participant_role',
763 //CRM-13595 add event id to participant export
765 'event_id' => array('title' => 'Event ID',
766 'name' => 'event_id',
769 'event_title' => array('title' => 'Event Title',
770 'name' => 'event_title',
773 $discountFields = CRM_Core_DAO_Discount
::export();
775 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventid, $eventtitle, $noteField, $discountFields);
778 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
779 self
::$_exportableFields = $fields;
782 return self
::$_exportableFields;
786 * function to get the event name/sort name for a particular participation / participant
788 * @param int $participantId id of the participant
791 * @return array $name associated array with sort_name and event title
795 static function participantDetails($participantId) {
797 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
798 FROM civicrm_participant
799 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
800 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
801 WHERE civicrm_participant.id = {$participantId}
803 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
806 while ($dao->fetch()) {
807 $details['name'] = $dao->name
;
808 $details['title'] = $dao->title
;
809 $details['cid'] = $dao->cid
;
816 * Get the values for pseudoconstants for name->value and reverse.
818 * @param array $defaults (reference) the default values, some of which need to be resolved.
819 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
825 static function resolveDefaults(&$defaults, $reverse = FALSE) {
826 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
827 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
828 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
832 * This function is used to convert associative array names to values
835 * This function is used by both the web form layer and the api. Note that
836 * the api needs the name => value conversion, also the view layer typically
837 * requires value => name conversion
839 static function lookupValue(&$defaults, $property, $lookup, $reverse) {
840 $id = $property . '_id';
842 $src = $reverse ?
$property : $id;
843 $dst = $reverse ?
$id : $property;
845 if (!array_key_exists($src, $defaults)) {
849 $look = $reverse ?
array_flip($lookup) : $lookup;
851 if (is_array($look)) {
852 if (!array_key_exists($defaults[$src], $look)) {
856 $defaults[$dst] = $look[$defaults[$src]];
861 * Delete the record that are associated with this participation
863 * @param int $id id of the participation to delete
869 static function deleteParticipant($id) {
870 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
872 $transaction = new CRM_Core_Transaction();
874 //delete activity record
876 'source_record_id' => $id,
877 // activity type id for event registration
878 'activity_type_id' => 5,
881 CRM_Activity_BAO_Activity
::deleteActivity($params);
883 // delete the participant payment record
884 // we need to do this since the cascaded constraints
885 // dont work with join tables
886 $p = array('participant_id' => $id);
887 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
889 // cleanup line items.
890 $participantsId = array();
891 $participantsId = self
::getAdditionalParticipantIds($id);
892 $participantsId[] = $id;
893 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
895 //delete note when participant deleted.
896 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
897 $noteId = key($note);
899 CRM_Core_BAO_Note
::del($noteId, FALSE);
902 $participant = new CRM_Event_DAO_Participant();
903 $participant->id
= $id;
904 $participant->delete();
906 $transaction->commit();
908 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
910 // delete the recently created Participant
911 $participantRecent = array(
913 'type' => 'Participant',
916 CRM_Utils_Recent
::del($participantRecent);
922 * Checks duplicate participants
924 * @param array $duplicates (reference ) an assoc array of name/value pairs
925 * @param array $input an assosiative array of name /value pairs
926 * from other function
928 * @return object CRM_Contribute_BAO_Contribution object
932 static function checkDuplicate($input, &$duplicates) {
933 $eventId = CRM_Utils_Array
::value('event_id', $input);
934 $contactId = CRM_Utils_Array
::value('contact_id', $input);
940 $clause[] = "event_id = %1";
941 $input[1] = array($eventId, 'Integer');
945 $clause[] = "contact_id = %2";
946 $input[2] = array($contactId, 'Integer');
949 if (empty($clause)) {
953 $clause = implode(' AND ', $clause);
955 $query = "SELECT id FROM civicrm_participant WHERE $clause";
956 $dao = CRM_Core_DAO
::executeQuery($query, $input);
958 while ($dao->fetch()) {
959 $duplicates[] = $dao->id
;
966 * fix the event level
968 * When price sets are used as event fee, fee_level is set as ^A
969 * separated string. We need to change that string to comma
970 * separated string before using fee_level in view mode.
972 * @param string $eventLevel event_leval string from db
978 static function fixEventLevel(&$eventLevel) {
979 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
980 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
982 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
983 $pos = strrpos($eventLevel, '(multiple participants)', 0);
985 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
988 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
989 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
990 substr($eventLevel, 0, 1)
993 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
994 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
995 substr($eventLevel, 0, -1)
1001 * get the additional participant ids.
1003 * @param int $primaryParticipantId primary partycipant Id
1004 * @param boolean $excludeCancel do not include participant those are cancelled.
1006 * @param null $oldStatusId
1008 * @return array $additionalParticipantIds
1011 static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1012 $additionalParticipantIds = array();
1013 if (!$primaryParticipantId) {
1014 return $additionalParticipantIds;
1017 $where = "participant.registered_by_id={$primaryParticipantId}";
1018 if ($excludeCancel) {
1019 $cancelStatusId = 0;
1020 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1021 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1022 $where .= " AND participant.status_id != {$cancelStatusId}";
1026 $where .= " AND participant.status_id = {$oldStatusId}";
1030 SELECT participant.id
1031 FROM civicrm_participant participant
1034 $dao = CRM_Core_DAO
::executeQuery($query);
1035 while ($dao->fetch()) {
1036 $additionalParticipantIds[$dao->id
] = $dao->id
;
1038 return $additionalParticipantIds;
1042 * Get the event fee info for given participant ids
1043 * either from line item table / participant table.
1045 * @param array $participantIds participant ids.
1046 * @param boolean $hasLineItems do fetch from line items.
1048 * @return array $feeDetails
1051 function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1052 $feeDetails = array();
1053 if (!is_array($participantIds) ||
empty($participantIds)) {
1058 SELECT participant.id as id,
1059 participant.fee_level as fee_level,
1060 participant.fee_amount as fee_amount';
1061 $from = 'FROM civicrm_participant participant';
1062 if ($hasLineItems) {
1064 lineItem.id as lineId,
1065 lineItem.label as label,
1066 lineItem.qty as qty,
1067 lineItem.unit_price as unit_price,
1068 lineItem.line_total as line_total,
1069 field.label as field_title,
1070 field.html_type as html_type,
1071 field.id as price_field_id,
1072 value.id as price_field_value_id,
1073 value.description as description,
1074 IF( value.count, value.count, 0 ) as participant_count';
1076 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1077 AND lineItem.entity_id = participant.id )
1078 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1079 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1082 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1083 $query = "$select $from $where";
1085 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1086 $feeProperties = array('fee_level', 'fee_amount');
1087 $lineProperties = array(
1088 'lineId', 'label', 'qty', 'unit_price',
1089 'line_total', 'field_title', 'html_type',
1090 'price_field_id', 'participant_count', 'price_field_value_id', 'description',
1092 while ($feeInfo->fetch()) {
1093 if ($hasLineItems) {
1094 foreach ($lineProperties as $property) {
1095 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1099 foreach ($feeProperties as $property) $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1107 * Retrieve additional participants display-names and URL to view their participant records.
1108 * (excludes cancelled participants automatically)
1110 * @param int $primaryParticipantID id of primary participant record
1112 * @return array $additionalParticipants $displayName => $viewUrl
1115 static function getAdditionalParticipants($primaryParticipantID) {
1116 $additionalParticipantIDs = array();
1117 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1118 if (!empty($additionalParticipantIDs)) {
1119 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1120 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1121 $additionalParticipantID,
1124 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1125 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1126 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1129 $additionalParticipants[$additionalContactName] = $pViewURL;
1132 return $additionalParticipants;
1136 * Function for update primary and additional participant status
1138 * @param int $participantID primary participant's id
1139 * @param $oldStatusID
1140 * @param null $newStatusID
1141 * @param bool $updatePrimaryStatus
1143 * @internal param int $statusId status id for participant
1150 static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1151 if (!$participantID ||
!$oldStatusID) {
1155 if (!$newStatusID) {
1156 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1158 elseif ($updatePrimaryStatus) {
1159 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1162 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1164 if (!empty($cascadeAdditionalIds)) {
1165 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1166 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1167 $params = array(1 => array($newStatusID, 'Integer'));
1168 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1175 * Function for update status for given participant ids
1177 * @param int $participantIds array of participant ids
1178 * @param int $statusId status id for participant
1179 * @param bool $updateRegisterDate
1180 * @params boolean $updateRegisterDate way to track when status changed.
1187 static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1188 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1192 //lets update register date as we update status to keep track
1193 //when we did update status, useful for moving participant
1194 //from pending to expired.
1195 $setClause = "status_id = {$statusId}";
1196 if ($updateRegisterDate) {
1197 $setClause .= ", register_date = NOW()";
1200 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1203 UPDATE civicrm_participant
1205 WHERE id IN {$participantIdClause}";
1207 $dao = CRM_Core_DAO
::executeQuery($query);
1211 * Function takes participant ids and statuses
1212 * update status from $fromStatusId to $toStatusId
1213 * and send mail + create activities.
1215 * @param array $participantIds participant ids.
1216 * @param int $toStatusId update status id.
1217 * @param int $fromStatusId from status id
1220 * @param bool $returnResult
1221 * @param bool $skipCascadeRule
1227 static function transitionParticipants($participantIds, $toStatusId,
1228 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1230 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1234 //thumb rule is if we triggering primary participant need to triggered additional
1235 $allParticipantIds = $primaryANDAdditonalIds = array();
1236 foreach ($participantIds as $id) {
1237 $allParticipantIds[] = $id;
1238 if (self
::isPrimaryParticipant($id)) {
1239 //filter additional as per status transition rules, CRM-5403
1240 if ($skipCascadeRule) {
1241 $additionalIds = self
::getAdditionalParticipantIds($id);
1244 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1246 if (!empty($additionalIds)) {
1247 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1248 $primaryANDAdditonalIds[$id] = $additionalIds;
1253 //get the unique participant ids,
1254 $allParticipantIds = array_unique($allParticipantIds);
1256 //pull required participants, contacts, events data, if not in hand
1257 static $eventDetails = array();
1258 static $domainValues = array();
1259 static $contactDetails = array();
1261 $contactIds = $eventIds = $participantDetails = array();
1263 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1264 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1265 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1269 //first thing is pull all necessory data from db.
1270 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1272 //get all participants data.
1273 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1274 $dao = CRM_Core_DAO
::executeQuery($query);
1275 while ($dao->fetch()) {
1276 $participantDetails[$dao->id
] = array(
1278 'role' => $participantRoles[$dao->role_id
],
1279 'is_test' => $dao->is_test
,
1280 'event_id' => $dao->event_id
,
1281 'status_id' => $dao->status_id
,
1282 'fee_amount' => $dao->fee_amount
,
1283 'contact_id' => $dao->contact_id
,
1284 'register_date' => $dao->register_date
,
1285 'registered_by_id' => $dao->registered_by_id
,
1287 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1288 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1291 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1292 $eventIds[$dao->event_id
] = $dao->event_id
;
1296 //get the domain values.
1297 if (empty($domainValues)) {
1298 // making all tokens available to templates.
1299 $domain = CRM_Core_BAO_Domain
::getDomain();
1300 $tokens = array('domain' => array('name', 'phone', 'address', 'email'),
1301 'contact' => CRM_Core_SelectValues
::contactTokens(),
1304 foreach ($tokens['domain'] as $token) {
1305 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1309 //get all required contacts detail.
1310 if (!empty($contactIds)) {
1311 // get the contact details.
1312 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1315 'CRM_Event_BAO_Participant'
1317 foreach ($currentContactDetails as $contactId => $contactValues) {
1318 $contactDetails[$contactId] = $contactValues;
1322 //get all required events detail.
1323 if (!empty($eventIds)) {
1324 foreach ($eventIds as $eventId) {
1325 //retrieve event information
1326 $eventParams = array('id' => $eventId);
1327 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1329 //get default participant role.
1330 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1332 //get the location info
1333 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1334 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1338 //now we are ready w/ all required data.
1339 //take a decision as per statuses.
1342 $toStatus = $statusTypes[$toStatusId];
1343 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1345 switch ($toStatus) {
1346 case 'Pending from waitlist':
1347 case 'Pending from approval':
1348 switch ($fromStatus) {
1350 case 'Awaiting approval':
1351 $emailType = 'Confirm';
1357 //no matter from where u come send expired mail.
1358 $emailType = $toStatus;
1362 //no matter from where u come send cancel mail.
1363 $emailType = $toStatus;
1367 //as we process additional w/ primary, there might be case if user
1368 //select primary as well as additionals, so avoid double processing.
1369 $processedParticipantIds = array();
1370 $mailedParticipants = array();
1372 //send mails and update status.
1373 foreach ($participantDetails as $participantId => $participantValues) {
1374 $updateParticipantIds = array();
1375 if (in_array($participantId, $processedParticipantIds)) {
1379 //check is it primary and has additional.
1380 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1381 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1384 $mail = self
::sendTransitionParticipantMail($additonalId,
1385 $participantDetails[$additonalId],
1386 $eventDetails[$participantDetails[$additonalId]['event_id']],
1387 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1392 //get the mail participant ids
1394 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1397 $updateParticipantIds[] = $additonalId;
1398 $processedParticipantIds[] = $additonalId;
1402 //now send email appropriate mail to primary.
1404 $mail = self
::sendTransitionParticipantMail($participantId,
1406 $eventDetails[$participantValues['event_id']],
1407 $contactDetails[$participantValues['contact_id']],
1412 //get the mail participant ids
1414 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1418 //now update status of group/one at once.
1419 $updateParticipantIds[] = $participantId;
1421 //update the register date only when we,
1422 //move participant to pending class, CRM-6496
1423 $updateRegisterDate = FALSE;
1424 if (array_key_exists($toStatusId, $pendingStatuses)) {
1425 $updateRegisterDate = TRUE;
1427 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1428 $processedParticipantIds[] = $participantId;
1431 //return result for cron.
1432 if ($returnResult) {
1434 'mailedParticipants' => $mailedParticipants,
1435 'updatedParticipantIds' => $processedParticipantIds,
1443 * Function to send mail and create activity
1444 * when participant status changed.
1446 * @param int $participantId participant id.
1447 * @param array $participantValues participant detail values. status id for participants
1448 * @param array $eventDetails required event details
1449 * @param array $contactDetails required contact details
1450 * @param array $domainValues required domain values.
1451 * @param string $mailType (eg 'approval', 'confirm', 'expired' )
1459 static function sendTransitionParticipantMail(
1470 //don't send confirmation mail to additional
1471 //since only primary able to confirm registration.
1472 if (!empty($participantValues['registered_by_id']) &&
1473 $mailType == 'Confirm'
1477 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1480 $contactId = $participantValues['contact_id'];
1481 $participantName = $contactDetails['display_name'];
1483 //calculate the checksum value.
1484 $checksumValue = NULL;
1485 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1486 $checksumLife = 'inf';
1487 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1489 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1491 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1494 //take a receipt from as event else domain.
1495 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1496 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1497 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1500 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1502 'groupName' => 'msg_tpl_workflow_event',
1503 'valueName' => 'participant_' . strtolower($mailType),
1504 'contactId' => $contactId,
1505 'tplParams' => array(
1506 'contact' => $contactDetails,
1507 'domain' => $domainValues,
1508 'participant' => $participantValues,
1509 'event' => $eventDetails,
1510 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1511 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1512 'isAdditional' => $participantValues['registered_by_id'],
1513 'isExpired' => $mailType == 'Expired',
1514 'isConfirm' => $mailType == 'Confirm',
1515 'checksumValue' => $checksumValue,
1517 'from' => $receiptFrom,
1518 'toName' => $participantName,
1519 'toEmail' => $toEmail,
1520 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1521 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1525 // 3. create activity record.
1527 $now = date('YmdHis');
1528 $activityType = 'Event Registration';
1529 $activityParams = array(
1530 'subject' => $subject,
1531 'source_contact_id' => $contactId,
1532 'source_record_id' => $participantId,
1533 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1537 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1538 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1539 'is_test' => $participantValues['is_test'],
1543 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1544 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1553 * get participant status change message.
1555 * @param $participantId
1556 * @param $statusChangeTo
1557 * @param $fromStatusId
1562 function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1564 $results = self
::transitionParticipants(array($participantId),
1565 $statusChangeTo, $fromStatusId, TRUE
1568 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1569 //give user message only when mail has sent.
1570 if (is_array($results) && !empty($results)) {
1571 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1572 foreach ($results['updatedParticipantIds'] as $processedId) {
1573 if (is_array($results['mailedParticipants']) &&
1574 array_key_exists($processedId, $results['mailedParticipants'])
1576 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1578 1 => $allStatuses[$statusChangeTo],
1579 2 => $results['mailedParticipants'][$processedId],
1591 * get event full and waiting list message.
1594 * @param null $participantId
1599 static function eventFullMessage($eventId, $participantId = NULL) {
1600 $eventfullMsg = $dbStatusId = NULL;
1601 $checkEventFull = TRUE;
1602 if ($participantId) {
1603 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1604 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1605 //participant already in counted status no need to check for event full messages.
1606 $checkEventFull = FALSE;
1611 if (!$eventId ||
!$checkEventFull) {
1612 return $eventfullMsg;
1615 //event is truly full.
1616 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1617 if (is_string($emptySeats) && $emptySeats !== NULL) {
1618 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1619 $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(
1620 1 => $maxParticipants)) . '<br />';
1623 $hasWaiting = FALSE;
1624 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1625 if (is_numeric($waitListedCount)) {
1627 //only current processing participant is on waitlist.
1628 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1629 $hasWaiting = FALSE;
1634 $waitingStatusId = array_search('On waitlist',
1635 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1637 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1638 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1641 $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.",
1643 1 => $viewWaitListUrl,
1644 2 => $waitListedCount,
1649 return $eventfullMsg;
1653 * check for whether participant is primary or not
1655 * @param $participantId
1657 * @return true if participant is primary
1660 static function isPrimaryParticipant($participantId) {
1662 $participant = new CRM_Event_DAO_Participant();
1663 $participant->registered_by_id
= $participantId;
1665 if ($participant->find(TRUE)) {
1672 * get additional participant Ids for cascading with primary participant status
1674 * @param int $participantId participant id.
1675 * @param int $oldStatusId previous status
1676 * @param int $newStatusId new status
1678 * @return true if allowed
1681 static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1683 $additionalParticipantIds = array();
1685 static $participantStatuses = array();
1687 if (empty($participantStatuses)) {
1688 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1691 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1692 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1694 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1697 return $additionalParticipantIds;
1701 * Function to get participant record count for a Contact
1705 * @internal param int $contactId Contact ID
1707 * @return int count of participant records
1711 static function getContactParticipantCount($contactID) {
1712 $query = "SELECT count(*)
1713 FROM civicrm_participant
1714 WHERE civicrm_participant.contact_id = {$contactID} AND
1715 civicrm_participant.is_test = 0";
1716 return CRM_Core_DAO
::singleValueQuery($query);
1720 * Function to get participant ids by contribution id
1722 * @param int $contributionId Contribution Id
1723 * @param bool $excludeCancelled Exclude cancelled additional participant
1725 * @return array $participantsId
1729 static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1732 if (!$contributionId) {
1736 // get primary participant id
1737 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1738 $participantId = CRM_Core_DAO
::singleValueQuery($query);
1740 // get additional participant ids (including cancelled)
1741 if ($participantId) {
1742 $ids = array_merge(array(
1743 $participantId), self
::getAdditionalParticipantIds($participantId,
1752 * Function to get additional Participant edit & view url .
1754 * @param $participantIds
1756 * @internal param array $paticipantIds an array of additional participant ids.
1758 * @return array of Urls.
1762 static function getAdditionalParticipantUrl($participantIds) {
1763 foreach ($participantIds as $value) {
1765 $details = self
::participantDetails($value);
1766 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1767 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1769 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1770 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1772 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1773 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1779 * to create trxn entry if an event has discount.
1781 * @param int $eventID event id
1782 * @param array $contributionParams contribution params.
1788 static function createDiscountTrxn($eventID, $contributionParams, $feeLevel) {
1790 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID,'civicrm_event');
1791 if (!empty($checkDiscount)) {
1792 $feeLevel = current($feeLevel);
1793 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1794 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1795 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1796 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1797 $params = array(1 => array($priceSetId, 'Integer'),
1798 2 => array($feeLevel, 'String'));
1799 $mainAmount = CRM_Core_DAO
::singleValueQuery($query, $params);
1800 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
1801 $contributionParams['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
1802 $contributionParams['contribution']->financial_type_id
, $relationTypeId);
1803 if (!empty($contributionParams['trxnParams']['from_financial_account_id'])) {
1804 $contributionParams['trxnParams']['total_amount'] = $mainAmount - $contributionParams['total_amount'];
1805 $contributionParams['trxnParams']['payment_processor_id'] = $contributionParams['trxnParams']['payment_instrument_id'] =
1806 $contributionParams['trxnParams']['check_number'] = $contributionParams['trxnParams']['trxn_id'] =
1807 $contributionParams['trxnParams']['net_amount'] = $contributionParams['trxnParams']['fee_amount'] = NULL;
1809 CRM_Core_BAO_FinancialTrxn
::create($contributionParams['trxnParams']);
1816 * Function to delete participants of contact
1820 * @param integer $contactId contact id
1825 static function deleteContactParticipant($contactId) {
1826 $participant = new CRM_Event_DAO_Participant();
1827 $participant->contact_id
= $contactId;
1828 $participant->find();
1829 while ($participant->fetch()) {
1830 self
::deleteParticipant($participant->id
);
1836 * @param $participantId
1837 * @param $contributionId
1840 * @param $paidAmount
1841 * @param $priceSetId
1843 static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) {
1844 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1845 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1846 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1847 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($participantId, 'participant');
1848 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
1852 // get the submitted
1853 foreach ($feeBlock as $id => $values) {
1854 CRM_Price_BAO_LineItem
::format($id, $params, $values, $submittedLineItems);
1855 $submittedFieldId[] = CRM_Utils_Array
::retrieveValueRecursive($submittedLineItems, 'price_field_id');
1857 $insertLines = $submittedLineItems;
1859 $submittedFieldValueIds = array_keys($submittedLineItems);
1860 $updateLines = array();
1861 foreach ($previousLineItems as $id => $previousLineItem) {
1862 // check through the submitted items if the previousItem exists,
1863 // if found in submitted items, do not use it for new item creations
1864 if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
1865 // if submitted line items are existing don't fire INSERT query
1866 unset($insertLines[$previousLineItem['price_field_value_id']]);
1867 // for updating the line items i.e. use-case - once deselect-option selecting again
1868 if ($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) {
1869 $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
1870 $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
1875 $submittedFields = implode(', ', $submittedFieldId);
1876 $submittedFieldValues = implode(', ', $submittedFieldValueIds);
1878 if (!empty($submittedFields) && !empty($submittedFieldValues)) {
1879 $updateLineItem = "UPDATE civicrm_line_item li
1880 INNER JOIN civicrm_financial_item fi
1881 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1883 li.line_total = 0.00,
1884 li.tax_amount = NULL
1885 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
1886 (price_field_value_id NOT IN ({$submittedFieldValues}))
1888 CRM_Core_DAO
::executeQuery($updateLineItem);
1890 // gathering necessary info to record negative (deselected) financial_item
1891 $updateFinancialItem = "
1892 SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
1893 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1894 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
1895 GROUP BY li.entity_table, li.entity_id, price_field_value_id
1897 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1898 $trxn = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId, 'ASC', TRUE);
1899 $trxnId['id'] = $trxn['financialTrxnId'];
1900 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1901 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
1902 $updateFinancialItemInfoValues = array();
1904 while ($updateFinancialItemInfoDAO->fetch()) {
1905 $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
1906 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
1907 // the below params are not needed
1908 unset($updateFinancialItemInfoValues['id']);
1909 unset($updateFinancialItemInfoValues['created_date']);
1910 // if not submitted and difference is not 0 make it negative
1911 if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
1912 // INSERT negative financial_items
1913 $updateFinancialItemInfoValues['amount'] = - $updateFinancialItemInfoValues['amount'];
1914 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1915 // INSERT negative financial_items for tax amount
1916 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
1917 $updateFinancialItemInfoValues['amount'] = - ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
1918 $updateFinancialItemInfoValues['description'] = $taxTerm;
1919 if ($updateFinancialItemInfoValues['financial_type_id']) {
1920 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
1922 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1925 // if submitted and difference is 0 add a positive entry again
1926 elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
1927 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
1928 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1929 // INSERT financial_items for tax amount
1930 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
1931 isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
1933 $updateFinancialItemInfoValues['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
1934 $updateFinancialItemInfoValues['description'] = $taxTerm;
1935 if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
1936 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
1938 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1944 if (!empty($updateLines)) {
1945 foreach ($updateLines as $valueId => $vals) {
1946 if (isset($vals['tax_amount'])) {
1947 $taxAmount = $vals['tax_amount'];
1950 $taxAmount = "NULL";
1953 UPDATE civicrm_line_item li
1954 SET li.qty = {$vals['qty']},
1955 li.line_total = {$vals['line_total']},
1956 li.tax_amount = {$taxAmount},
1957 li.unit_price = {$vals['unit_price']},
1958 li.label = '{$vals['label']}'
1959 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
1960 (price_field_value_id = {$valueId})
1962 CRM_Core_DAO
::executeQuery($updateLineItem);
1965 // insert new 'adjusted amount' transaction entry and update contribution entry.
1966 // ensure entity_financial_trxn table has a linking of it.
1967 // insert new line items
1968 foreach ($insertLines as $valueId => $lineParams) {
1969 $lineParams['entity_table'] = 'civicrm_participant';
1970 $lineParams['entity_id'] = $participantId;
1971 $lineParams['contribution_id'] = $contributionId;
1972 $lineObj = CRM_Price_BAO_LineItem
::create($lineParams);
1975 // the recordAdjustedAmt code would execute over here
1976 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
1977 if (count($ids) > 1) {
1979 foreach ($ids as $val) {
1980 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, 'civicrm_participant');
1982 $updatedAmount = $total;
1985 $updatedAmount = $params['amount'];
1987 if (strlen($params['tax_amount']) != 0) {
1988 $taxAmount = $params['tax_amount'];
1991 $taxAmount = "NULL";
1993 self
::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount);
1995 $fetchCon = array('id' => $contributionId);
1996 $updatedContribution = CRM_Contribute_BAO_Contribution
::retrieve($fetchCon, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
1997 // insert financial items
1998 foreach ($insertLines as $valueId => $lineParams) {
1999 $lineParams['entity_table'] = 'civicrm_participant';
2000 $lineParams['entity_id'] = $participantId;
2001 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams, CRM_Core_DAO
::$_nullArray);
2002 // insert financial items
2003 // ensure entity_financial_trxn table has a linking of it.
2004 $prevItem = CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution);
2005 if (isset($lineObj->tax_amount
)) {
2006 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE);
2010 // update participant fee_amount column
2011 $partUpdateFeeAmt['id'] = $participantId;
2012 $partUpdateFeeAmt['fee_amount'] = $params['amount'];
2013 self
::add($partUpdateFeeAmt);
2016 self
::addActivityForSelection($participantId, 'Change Registration');
2020 * @param $updatedAmount
2021 * @param $paidAmount
2022 * @param $contributionId
2024 static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL) {
2025 $balanceAmt = $updatedAmount - $paidAmount;
2026 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2027 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
2028 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
2029 $completedStatusId = array_search('Completed', $contributionStatuses);
2031 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
2034 if ($balanceAmt > 0 && $paidAmount != 0) {
2035 $contributionStatusVal = $partiallyPaidStatusId;
2037 elseif ($balanceAmt < 0 && $paidAmount != 0) {
2038 $contributionStatusVal = $pendingRefundStatusId;
2040 elseif ($paidAmount == 0) {
2041 //skip updating the contribution status if no payment is made
2043 $updatedContributionDAO->cancel_date
= 'null';
2044 $updatedContributionDAO->cancel_reason
= NULL;
2046 // update contribution status and total amount without trigger financial code
2047 // as this is handled in current BAO function used for change selection
2048 $updatedContributionDAO->id
= $contributionId;
2050 $updatedContributionDAO->contribution_status_id
= $contributionStatusVal;
2052 $updatedContributionDAO->total_amount
= $updatedAmount;
2053 $updatedContributionDAO->tax_amount
= $taxAmount;
2054 $updatedContributionDAO->save();
2056 $ftDetail = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
2057 // adjusted amount financial_trxn creation
2058 if (empty($ftDetail['trxn_id'])) {
2059 $updatedContribution =
2060 CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contributionId), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2061 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2062 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($updatedContribution->financial_type_id
, $relationTypeId);
2064 $adjustedTrxnValues = array(
2065 'from_financial_account_id' => NULL,
2066 'to_financial_account_id' => $toFinancialAccount,
2067 'total_amount' => $balanceAmt,
2068 'status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
2069 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
2070 'contribution_id' => $updatedContribution->id
,
2071 'trxn_date' => date('YmdHis'),
2072 'currency' => $updatedContribution->currency
2074 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
2077 // update the financial trxn amount as well, as the fee selections has been updated
2078 if ($balanceAmt != $ftDetail['total_amount']) {
2079 CRM_Core_DAO
::setFieldValue('CRM_Core_BAO_FinancialTrxn', $ftDetail['trxn_id'], 'total_amount', $balanceAmt);
2086 * @param $participantId
2087 * @param $activityType
2089 * @throws CRM_Core_Exception
2091 static function addActivityForSelection($participantId, $activityType) {
2092 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
2093 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
2095 $date = CRM_Utils_Date
::currentDBDate();
2096 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
2097 $eventTitle = $event[$eventId];
2098 $subject = "Registration selections changed for $eventTitle";
2099 $targetCid = $contactId;
2100 $srcRecId = $participantId;
2103 $activityParams = array(
2104 'source_contact_id' => $targetCid,
2105 'source_record_id' => $srcRecId,
2106 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
2110 'subject' => $subject,
2111 'activity_date_time' => $date,
2112 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
2116 'skipRecentView' => TRUE,
2119 // create activity with target contacts
2120 $session = CRM_Core_Session
::singleton();
2121 $id = $session->get('userID');
2123 $activityParams['source_contact_id'] = $id;
2124 $activityParams['target_contact_id'][] = $targetCid;
2126 CRM_Activity_BAO_Activity
::create($activityParams);