3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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'),
72 public function __construct() {
73 parent
::__construct();
77 * Takes an associative array and creates a participant object
79 * the function extract all the params it needs to initialize the create a
80 * participant object. the params array could contain additional unused name/value
83 * @param array $params
84 * (reference ) an assoc array of name/value pairs.
86 * @return CRM_Event_BAO_Participant object
89 public static function &add(&$params) {
91 if (!empty($params['id'])) {
92 CRM_Utils_Hook
::pre('edit', 'Participant', $params['id'], $params);
95 CRM_Utils_Hook
::pre('create', 'Participant', NULL, $params);
98 // converting dates to mysql format
99 if (!empty($params['register_date'])) {
100 $params['register_date'] = CRM_Utils_Date
::isoToMysql($params['register_date']);
103 if (!empty($params['participant_fee_amount'])) {
104 $params['participant_fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['participant_fee_amount']);
107 if (!empty($params['fee_amount'])) {
108 $params['fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['fee_amount']);
111 // ensure that role ids are encoded as a string
112 if (isset($params['role_id']) && is_array($params['role_id'])) {
113 $params['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['role_id']);
116 $participantBAO = new CRM_Event_BAO_Participant
;
117 if (!empty($params['id'])) {
118 $participantBAO->id
= CRM_Utils_Array
::value('id', $params);
119 $participantBAO->find(TRUE);
120 $participantBAO->register_date
= CRM_Utils_Date
::isoToMysql($participantBAO->register_date
);
123 $participantBAO->copyValues($params);
126 //1. If currency present, it should be valid one.
127 //2. We should have currency when amount is not null.
128 $currency = $participantBAO->fee_currency
;
130 !CRM_Utils_System
::isNull($participantBAO->fee_amount
)
132 if (!CRM_Utils_Rule
::currencyCode($currency)) {
133 $config = CRM_Core_Config
::singleton();
134 $currency = $config->defaultCurrency
;
137 $participantBAO->fee_currency
= $currency;
139 $participantBAO->save();
141 $session = CRM_Core_Session
::singleton();
143 // reset the group contact cache for this group
144 CRM_Contact_BAO_GroupContactCache
::remove();
146 if (!empty($params['id'])) {
147 CRM_Utils_Hook
::post('edit', 'Participant', $participantBAO->id
, $participantBAO);
150 CRM_Utils_Hook
::post('create', 'Participant', $participantBAO->id
, $participantBAO);
153 return $participantBAO;
157 * Given the list of params in the params array, fetch the object
158 * and store the values in the values array
160 * @param array $params
161 * Input parameters to find object.
162 * @param array $values
163 * Output values of the object.
167 * @return CRM_Event_BAO_Participant|null the found object or null
170 public static function getValues(&$params, &$values, &$ids) {
171 if (empty($params)) {
174 $participant = new CRM_Event_BAO_Participant();
175 $participant->copyValues($params);
176 $participant->find();
177 $participants = array();
178 while ($participant->fetch()) {
179 $ids['participant'] = $participant->id
;
180 CRM_Core_DAO
::storeValues($participant, $values[$participant->id
]);
181 $participants[$participant->id
] = $participant;
183 return $participants;
187 * Takes an associative array and creates a participant object
189 * @param array $params
190 * (reference ) an assoc array of name/value pairs.
192 * @return CRM_Event_BAO_Participant object
195 public static function create(&$params) {
197 $transaction = new CRM_Core_Transaction();
200 if (!empty($params['id'])) {
201 $status = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
204 $participant = self
::add($params);
206 if (is_a($participant, 'CRM_Core_Error')) {
207 $transaction->rollback();
211 if ((!CRM_Utils_Array
::value('id', $params)) ||
212 (isset($params['status_id']) && $params['status_id'] != $status)
214 CRM_Activity_BAO_Activity
::addActivity($participant);
219 if (self
::isPrimaryParticipant($participant->id
) && $status) {
220 self
::updateParticipantStatus($participant->id
, $status, $participant->status_id
);
223 $session = CRM_Core_Session
::singleton();
224 $id = $session->get('userID');
226 $id = CRM_Utils_Array
::value('contact_id', $params);
229 // add custom field values
230 if (!empty($params['custom']) &&
231 is_array($params['custom'])
233 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_participant', $participant->id
);
236 //process note, CRM-7634
238 if (!empty($params['id'])) {
239 $note = CRM_Core_BAO_Note
::getNote($params['id'], 'civicrm_participant');
240 $noteId = key($note);
243 $hasNoteField = FALSE;
248 if (array_key_exists($noteFld, $params)) {
249 $noteValue = $params[$noteFld];
250 $hasNoteField = TRUE;
254 if ($noteId ||
$noteValue) {
257 'entity_table' => 'civicrm_participant',
258 'note' => $noteValue,
259 'entity_id' => $participant->id
,
261 'modified_date' => date('Ymd'),
265 $noteIDs['id'] = $noteId;
267 CRM_Core_BAO_Note
::add($noteParams, $noteIDs);
269 elseif ($noteId && $hasNoteField) {
270 CRM_Core_BAO_Note
::del($noteId, FALSE);
274 // Log the information on successful add/edit of Participant data.
276 'entity_table' => 'civicrm_participant',
277 'entity_id' => $participant->id
,
278 'data' => CRM_Event_PseudoConstant
::participantStatus($participant->status_id
),
279 'modified_id' => $id,
280 'modified_date' => date('Ymd'),
283 CRM_Core_BAO_Log
::add($logParams);
285 $params['participant_id'] = $participant->id
;
287 $transaction->commit();
289 // do not add to recent items for import, CRM-4399
290 if (empty($params['skipRecentView'])) {
292 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
293 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
296 $recentOther = array();
297 if (CRM_Core_Permission
::check('edit event participants')) {
298 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
299 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
302 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
303 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
304 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
308 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
310 if ($participant->role_id
) {
311 $role = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participant->role_id
);
313 foreach ($role as & $roleValue) {
314 if (isset($roleValue)) {
315 $roleValue = $participantRoles[$roleValue];
318 $roles = implode(', ', $role);
321 $roleString = empty($roles) ?
'' : $roles;
322 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $participant->event_id
, 'title');
323 $title = CRM_Contact_BAO_Contact
::displayName($participant->contact_id
) . ' (' . $roleString . ' - ' . $eventTitle . ')';
325 // add the recently created Participant
326 CRM_Utils_Recent
::add($title,
330 $participant->contact_id
,
340 * Check whether the event is full for participation and return as
343 * @param int $eventId
345 * @param bool $returnEmptySeats
346 * Are we require number if empty seats.
347 * @param bool $includeWaitingList
348 * Consider waiting list in event full.
349 * calculation or not. (it is for cron job purpose)
351 * @param bool $returnWaitingCount
352 * @param bool $considerTestParticipant
354 * @return bool|int|null|string
355 * 1. false => If event having some empty spaces.
358 static function eventFull(
360 $returnEmptySeats = FALSE,
361 $includeWaitingList = TRUE,
362 $returnWaitingCount = FALSE,
363 $considerTestParticipant = FALSE
370 // consider event is full when.
371 // 1. (count(is_counted) >= event_size) or
372 // 2. (count(participants-with-status-on-waitlist) > 0)
373 // It might be case there are some empty spaces and still event
374 // is full, as waitlist might represent group require spaces > empty.
376 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
377 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
378 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
379 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
381 //when we do require only waiting count don't consider counted.
382 if (!$returnWaitingCount && !empty($countedStatuses)) {
383 $allStatusIds = array_keys($countedStatuses);
386 $where = array(' event.id = %1 ');
387 if (!$considerTestParticipant) {
388 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
390 if (!empty($participantRoles)) {
391 $where[] = ' participant.role_id IN ( ' . implode(', ', array_keys($participantRoles)) . ' ) ';
394 $eventParams = array(1 => array($eventId, 'Positive'));
396 //in case any waiting, straight forward event is full.
397 if ($includeWaitingList && $onWaitlistStatusId) {
399 //build the where clause.
400 $whereClause = ' WHERE ' . implode(' AND ', $where);
401 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
402 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
405 SELECT participant.id id,
406 event.event_full_text as event_full_text
407 FROM civicrm_participant participant
408 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
411 $eventFullText = ts('This event is full.');
412 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
413 while ($participants->fetch()) {
414 //oops here event is full and we don't want waiting count.
415 if ($returnWaitingCount) {
416 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
419 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
424 //consider only counted participants.
425 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
426 $whereClause = ' WHERE ' . implode(' AND ', $where);
427 $eventSeatsWhere = implode(' AND ', $where);
430 SELECT participant.id id,
431 event.event_full_text as event_full_text,
432 event.max_participants as max_participants
433 FROM civicrm_participant participant
434 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
437 $eventMaxSeats = NULL;
438 $eventFullText = ts('This event is full.');
439 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
440 while ($participants->fetch()) {
441 if ($participants->event_full_text
) {
442 $eventFullText = $participants->event_full_text
;
444 $eventMaxSeats = $participants->max_participants
;
445 //don't have limit for event seats.
446 if ($participants->max_participants
== NULL) {
451 //get the total event seats occupied by these participants.
452 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
454 if ($eventRegisteredSeats) {
455 if ($eventRegisteredSeats >= $eventMaxSeats) {
456 $result = $eventFullText;
458 elseif ($returnEmptySeats) {
459 $result = $eventMaxSeats - $eventRegisteredSeats;
465 SELECT event.event_full_text,
466 event.max_participants
467 FROM civicrm_event event
468 WHERE event.id = %1';
469 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
470 while ($event->fetch()) {
471 $eventFullText = $event->event_full_text
;
472 $eventMaxSeats = $event->max_participants
;
476 // no limit for registration.
477 if ($eventMaxSeats == NULL) {
480 if ($eventMaxSeats) {
481 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
484 return $eventFullText;
488 * Return the array of all price set field options,
489 * with total participant count that field going to carry.
491 * @param int $eventId
493 * @param array $skipParticipantIds
494 * An array of participant ids those we should skip.
495 * @param bool $considerCounted
496 * @param bool $considerWaiting
497 * @param bool $considerTestParticipants
500 * an array of each option id and total count
503 static function priceSetOptionsCount(
505 $skipParticipantIds = array(),
506 $considerCounted = TRUE,
507 $considerWaiting = TRUE,
508 $considerTestParticipants = FALSE
510 $optionsCount = array();
512 return $optionsCount;
515 $allStatusIds = array();
516 if ($considerCounted) {
517 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
518 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
520 if ($considerWaiting) {
521 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
522 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
524 $statusIdClause = NULL;
525 if (!empty($allStatusIds)) {
526 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
529 $isTestClause = NULL;
530 if (!$considerTestParticipants) {
531 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
534 $skipParticipantClause = NULL;
535 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
536 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
540 SELECT line.id as lineId,
541 line.entity_id as entity_id,
546 FROM civicrm_line_item line
547 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
548 AND participant.id = line.entity_id )
549 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
550 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
551 WHERE participant.event_id = %1
554 {$skipParticipantClause}";
556 $lineItem = CRM_Core_DAO
::executeQuery($sql, array(1 => array($eventId, 'Positive')));
557 while ($lineItem->fetch()) {
558 $count = $lineItem->count
;
562 if ($lineItem->html_type
== 'Text') {
563 $count *= $lineItem->qty
;
565 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
568 return $optionsCount;
572 * Get the empty spaces for event those we can allocate
573 * to pending participant to become confirm.
575 * @param int $eventId
579 * $spaces Number of Empty Seats/null.
582 public static function pendingToConfirmSpaces($eventId) {
588 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
589 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
592 SELECT count(participant.id) as registered,
593 civicrm_event.max_participants
594 FROM civicrm_participant participant, civicrm_event
595 WHERE participant.event_id = {$eventId}
596 AND civicrm_event.id = participant.event_id
597 AND participant.status_id IN {$statusIds}
598 GROUP BY participant.event_id
600 $dao = CRM_Core_DAO
::executeQuery($query);
604 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
609 if ($dao->registered
>= $dao->max_participants
) {
614 return $dao->max_participants
- $dao->registered
;
617 //space in case no registeration yet.
618 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
622 * Combine all the importable fields from the lower levels object
624 * @param string $contactType
625 * @param bool $status
626 * @param bool $onlyParticipant
629 * array of importable Fields
632 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE) {
633 if (!self
::$_importableFields) {
634 if (!$onlyParticipant) {
636 $fields = array('' => array('title' => ts('- do not import -')));
639 $fields = array('' => array('title' => ts('- Participant Fields -')));
646 $tmpFields = CRM_Event_DAO_Participant
::import();
649 'participant_note' => array(
650 'title' => ts('Participant Note'),
651 'name' => 'participant_note',
652 'headerPattern' => '/(participant.)?note$/i',
656 // Split status and status id into 2 fields
657 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
658 $participantStatus = array(
659 'participant_status' => array(
660 'title' => ts('Participant Status'),
661 'name' => 'participant_status',
662 'data_type' => CRM_Utils_Type
::T_STRING
,
665 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
667 // Split role and role id into 2 fields
668 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
669 $participantRole = array(
670 'participant_role' => array(
671 'title' => ts('Participant Role'),
672 'name' => 'participant_role',
673 'data_type' => CRM_Utils_Type
::T_STRING
,
676 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
679 'event_type' => array(
680 'title' => ts('Event Type'),
681 'name' => 'event_type',
682 'data_type' => CRM_Utils_Type
::T_STRING
,
686 $tmpContactField = $contactFields = array();
687 $contactFields = array();
688 if (!$onlyParticipant) {
689 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
691 // Using new Dedupe rule.
693 'contact_type' => $contactType,
694 'used' => 'Unsupervised',
696 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
698 if (is_array($fieldsArray)) {
699 foreach ($fieldsArray as $value) {
700 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
705 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
706 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
708 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
711 $title = $tmpContactField[trim($value)]['title'];
714 $tmpContactField[trim($value)]['title'] = $title;
718 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
719 if ($extIdentifier) {
720 $tmpContactField['external_identifier'] = $extIdentifier;
721 $tmpContactField['external_identifier']['title'] =
722 CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
724 $tmpFields['participant_contact_id']['title'] =
725 $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
727 $fields = array_merge($fields, $tmpContactField);
728 $fields = array_merge($fields, $tmpFields);
729 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
730 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
732 self
::$_importableFields = $fields;
735 return self
::$_importableFields;
739 * Combine all the exportable fields from the lower levels object
742 * array of exportable Fields
745 public static function &exportableFields() {
746 if (!self
::$_exportableFields) {
747 if (!self
::$_exportableFields) {
748 self
::$_exportableFields = array();
753 $participantFields = CRM_Event_DAO_Participant
::export();
755 'participant_note' => array(
756 'title' => 'Participant Note',
757 'name' => 'participant_note',
761 $participantStatus = array(
762 'participant_status' => array(
763 'title' => 'Participant Status',
764 'name' => 'participant_status',
768 $participantRole = array(
769 'participant_role' => array(
770 'title' => 'Participant Role',
771 'name' => 'participant_role',
775 //CRM-13595 add event id to participant export
778 'title' => 'Event ID',
779 'name' => 'event_id',
783 'event_title' => array(
784 'title' => 'Event Title',
785 'name' => 'event_title',
789 $discountFields = CRM_Core_DAO_Discount
::export();
791 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventid, $eventtitle, $noteField, $discountFields);
794 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
795 self
::$_exportableFields = $fields;
798 return self
::$_exportableFields;
802 * Get the event name/sort name for a particular participation / participant
804 * @param int $participantId
805 * Id of the participant.
808 * associated array with sort_name and event title
811 public static function participantDetails($participantId) {
813 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
814 FROM civicrm_participant
815 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
816 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
817 WHERE civicrm_participant.id = {$participantId}
819 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
822 while ($dao->fetch()) {
823 $details['name'] = $dao->name
;
824 $details['title'] = $dao->title
;
825 $details['cid'] = $dao->cid
;
832 * Get the values for pseudoconstants for name->value and reverse.
834 * @param array $defaults
835 * (reference) the default values, some of which need to be resolved.
836 * @param bool $reverse
837 * True if we want to resolve the values in the reverse direction (value -> name).
842 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
843 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
844 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
845 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
849 * convert associative array names to values
852 * This function is used by both the web form layer and the api. Note that
853 * the api needs the name => value conversion, also the view layer typically
854 * requires value => name conversion
856 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
857 $id = $property . '_id';
859 $src = $reverse ?
$property : $id;
860 $dst = $reverse ?
$id : $property;
862 if (!array_key_exists($src, $defaults)) {
866 $look = $reverse ?
array_flip($lookup) : $lookup;
868 if (is_array($look)) {
869 if (!array_key_exists($defaults[$src], $look)) {
873 $defaults[$dst] = $look[$defaults[$src]];
878 * Delete the record that are associated with this participation
881 * Id of the participation to delete.
886 public static function deleteParticipant($id) {
887 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
889 $transaction = new CRM_Core_Transaction();
891 //delete activity record
893 'source_record_id' => $id,
894 // activity type id for event registration
895 'activity_type_id' => 5,
898 CRM_Activity_BAO_Activity
::deleteActivity($params);
900 // delete the participant payment record
901 // we need to do this since the cascaded constraints
902 // dont work with join tables
903 $p = array('participant_id' => $id);
904 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
906 // cleanup line items.
907 $participantsId = array();
908 $participantsId = self
::getAdditionalParticipantIds($id);
909 $participantsId[] = $id;
910 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
912 //delete note when participant deleted.
913 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
914 $noteId = key($note);
916 CRM_Core_BAO_Note
::del($noteId, FALSE);
919 $participant = new CRM_Event_DAO_Participant();
920 $participant->id
= $id;
921 $participant->delete();
923 $transaction->commit();
925 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
927 // delete the recently created Participant
928 $participantRecent = array(
930 'type' => 'Participant',
933 CRM_Utils_Recent
::del($participantRecent);
939 * Checks duplicate participants
941 * @param array $duplicates
942 * (reference ) an assoc array of name/value pairs.
943 * @param array $input
944 * An assosiative array of name /value pairs.
945 * from other function
947 * @return CRM_Contribute_BAO_Contribution object
950 public static function checkDuplicate($input, &$duplicates) {
951 $eventId = CRM_Utils_Array
::value('event_id', $input);
952 $contactId = CRM_Utils_Array
::value('contact_id', $input);
958 $clause[] = "event_id = %1";
959 $input[1] = array($eventId, 'Integer');
963 $clause[] = "contact_id = %2";
964 $input[2] = array($contactId, 'Integer');
967 if (empty($clause)) {
971 $clause = implode(' AND ', $clause);
973 $query = "SELECT id FROM civicrm_participant WHERE $clause";
974 $dao = CRM_Core_DAO
::executeQuery($query, $input);
976 while ($dao->fetch()) {
977 $duplicates[] = $dao->id
;
984 * Fix the event level
986 * When price sets are used as event fee, fee_level is set as ^A
987 * separated string. We need to change that string to comma
988 * separated string before using fee_level in view mode.
990 * @param string $eventLevel
991 * Event_leval string from db.
997 public static function fixEventLevel(&$eventLevel) {
998 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
999 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
1001 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
1002 $pos = strrpos($eventLevel, '(multiple participants)', 0);
1004 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
1007 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1008 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1009 substr($eventLevel, 0, 1)
1012 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1013 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1014 substr($eventLevel, 0, -1)
1020 * Get the additional participant ids.
1022 * @param int $primaryParticipantId
1023 * Primary partycipant Id.
1024 * @param bool $excludeCancel
1025 * Do not include participant those are cancelled.
1027 * @param int $oldStatusId
1032 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1033 $additionalParticipantIds = array();
1034 if (!$primaryParticipantId) {
1035 return $additionalParticipantIds;
1038 $where = "participant.registered_by_id={$primaryParticipantId}";
1039 if ($excludeCancel) {
1040 $cancelStatusId = 0;
1041 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1042 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1043 $where .= " AND participant.status_id != {$cancelStatusId}";
1047 $where .= " AND participant.status_id = {$oldStatusId}";
1051 SELECT participant.id
1052 FROM civicrm_participant participant
1055 $dao = CRM_Core_DAO
::executeQuery($query);
1056 while ($dao->fetch()) {
1057 $additionalParticipantIds[$dao->id
] = $dao->id
;
1059 return $additionalParticipantIds;
1063 * Get the event fee info for given participant ids
1064 * either from line item table / participant table.
1066 * @param array $participantIds
1068 * @param bool $hasLineItems
1069 * Do fetch from line items.
1074 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1075 $feeDetails = array();
1076 if (!is_array($participantIds) ||
empty($participantIds)) {
1081 SELECT participant.id as id,
1082 participant.fee_level as fee_level,
1083 participant.fee_amount as fee_amount';
1084 $from = 'FROM civicrm_participant participant';
1085 if ($hasLineItems) {
1087 lineItem.id as lineId,
1088 lineItem.label as label,
1089 lineItem.qty as qty,
1090 lineItem.unit_price as unit_price,
1091 lineItem.line_total as line_total,
1092 field.label as field_title,
1093 field.html_type as html_type,
1094 field.id as price_field_id,
1095 value.id as price_field_value_id,
1096 value.description as description,
1097 IF( value.count, value.count, 0 ) as participant_count';
1099 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1100 AND lineItem.entity_id = participant.id )
1101 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1102 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1105 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1106 $query = "$select $from $where";
1108 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1109 $feeProperties = array('fee_level', 'fee_amount');
1110 $lineProperties = array(
1119 'participant_count',
1120 'price_field_value_id',
1123 while ($feeInfo->fetch()) {
1124 if ($hasLineItems) {
1125 foreach ($lineProperties as $property) {
1126 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1130 foreach ($feeProperties as $property) {
1131 $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1140 * Retrieve additional participants display-names and URL to view their participant records.
1141 * (excludes cancelled participants automatically)
1143 * @param int $primaryParticipantID
1144 * Id of primary participant record.
1147 * $displayName => $viewUrl
1150 public static function getAdditionalParticipants($primaryParticipantID) {
1151 $additionalParticipantIDs = array();
1152 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1153 if (!empty($additionalParticipantIDs)) {
1154 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1155 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1156 $additionalParticipantID,
1159 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1160 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1161 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1164 $additionalParticipants[$additionalContactName] = $pViewURL;
1167 return $additionalParticipants;
1171 * Function for update primary and additional participant status
1173 * @param int $participantID
1174 * Primary participant's id.
1175 * @param int $oldStatusID
1176 * @param int $newStatusID
1177 * @param bool $updatePrimaryStatus
1182 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1183 if (!$participantID ||
!$oldStatusID) {
1187 if (!$newStatusID) {
1188 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1190 elseif ($updatePrimaryStatus) {
1191 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1194 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1196 if (!empty($cascadeAdditionalIds)) {
1197 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1198 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1199 $params = array(1 => array($newStatusID, 'Integer'));
1200 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1207 * Function for update status for given participant ids
1209 * @param int $participantIds
1210 * Array of participant ids.
1211 * @param int $statusId
1212 * Status id for participant.
1213 * @param bool $updateRegisterDate
1219 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1220 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1224 //lets update register date as we update status to keep track
1225 //when we did update status, useful for moving participant
1226 //from pending to expired.
1227 $setClause = "status_id = {$statusId}";
1228 if ($updateRegisterDate) {
1229 $setClause .= ", register_date = NOW()";
1232 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1235 UPDATE civicrm_participant
1237 WHERE id IN {$participantIdClause}";
1239 $dao = CRM_Core_DAO
::executeQuery($query);
1243 * Function takes participant ids and statuses
1244 * update status from $fromStatusId to $toStatusId
1245 * and send mail + create activities.
1247 * @param array $participantIds
1249 * @param int $toStatusId
1251 * @param int $fromStatusId
1255 * @param bool $returnResult
1256 * @param bool $skipCascadeRule
1261 static function transitionParticipants(
1262 $participantIds, $toStatusId,
1263 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1265 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1269 //thumb rule is if we triggering primary participant need to triggered additional
1270 $allParticipantIds = $primaryANDAdditonalIds = array();
1271 foreach ($participantIds as $id) {
1272 $allParticipantIds[] = $id;
1273 if (self
::isPrimaryParticipant($id)) {
1274 //filter additional as per status transition rules, CRM-5403
1275 if ($skipCascadeRule) {
1276 $additionalIds = self
::getAdditionalParticipantIds($id);
1279 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1281 if (!empty($additionalIds)) {
1282 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1283 $primaryANDAdditonalIds[$id] = $additionalIds;
1288 //get the unique participant ids,
1289 $allParticipantIds = array_unique($allParticipantIds);
1291 //pull required participants, contacts, events data, if not in hand
1292 static $eventDetails = array();
1293 static $domainValues = array();
1294 static $contactDetails = array();
1296 $contactIds = $eventIds = $participantDetails = array();
1298 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1299 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1300 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1304 //first thing is pull all necessory data from db.
1305 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1307 //get all participants data.
1308 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1309 $dao = CRM_Core_DAO
::executeQuery($query);
1310 while ($dao->fetch()) {
1311 $participantDetails[$dao->id
] = array(
1313 'role' => $participantRoles[$dao->role_id
],
1314 'is_test' => $dao->is_test
,
1315 'event_id' => $dao->event_id
,
1316 'status_id' => $dao->status_id
,
1317 'fee_amount' => $dao->fee_amount
,
1318 'contact_id' => $dao->contact_id
,
1319 'register_date' => $dao->register_date
,
1320 'registered_by_id' => $dao->registered_by_id
,
1322 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1323 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1326 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1327 $eventIds[$dao->event_id
] = $dao->event_id
;
1331 //get the domain values.
1332 if (empty($domainValues)) {
1333 // making all tokens available to templates.
1334 $domain = CRM_Core_BAO_Domain
::getDomain();
1336 'domain' => array('name', 'phone', 'address', 'email'),
1337 'contact' => CRM_Core_SelectValues
::contactTokens(),
1340 foreach ($tokens['domain'] as $token) {
1341 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1345 //get all required contacts detail.
1346 if (!empty($contactIds)) {
1347 // get the contact details.
1348 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1351 'CRM_Event_BAO_Participant'
1353 foreach ($currentContactDetails as $contactId => $contactValues) {
1354 $contactDetails[$contactId] = $contactValues;
1358 //get all required events detail.
1359 if (!empty($eventIds)) {
1360 foreach ($eventIds as $eventId) {
1361 //retrieve event information
1362 $eventParams = array('id' => $eventId);
1363 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1365 //get default participant role.
1366 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1368 //get the location info
1369 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1370 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1374 //now we are ready w/ all required data.
1375 //take a decision as per statuses.
1378 $toStatus = $statusTypes[$toStatusId];
1379 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1381 switch ($toStatus) {
1382 case 'Pending from waitlist':
1383 case 'Pending from approval':
1384 switch ($fromStatus) {
1386 case 'Awaiting approval':
1387 $emailType = 'Confirm';
1393 //no matter from where u come send expired mail.
1394 $emailType = $toStatus;
1398 //no matter from where u come send cancel mail.
1399 $emailType = $toStatus;
1403 //as we process additional w/ primary, there might be case if user
1404 //select primary as well as additionals, so avoid double processing.
1405 $processedParticipantIds = array();
1406 $mailedParticipants = array();
1408 //send mails and update status.
1409 foreach ($participantDetails as $participantId => $participantValues) {
1410 $updateParticipantIds = array();
1411 if (in_array($participantId, $processedParticipantIds)) {
1415 //check is it primary and has additional.
1416 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1417 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1420 $mail = self
::sendTransitionParticipantMail($additonalId,
1421 $participantDetails[$additonalId],
1422 $eventDetails[$participantDetails[$additonalId]['event_id']],
1423 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1428 //get the mail participant ids
1430 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1433 $updateParticipantIds[] = $additonalId;
1434 $processedParticipantIds[] = $additonalId;
1438 //now send email appropriate mail to primary.
1440 $mail = self
::sendTransitionParticipantMail($participantId,
1442 $eventDetails[$participantValues['event_id']],
1443 $contactDetails[$participantValues['contact_id']],
1448 //get the mail participant ids
1450 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1454 //now update status of group/one at once.
1455 $updateParticipantIds[] = $participantId;
1457 //update the register date only when we,
1458 //move participant to pending class, CRM-6496
1459 $updateRegisterDate = FALSE;
1460 if (array_key_exists($toStatusId, $pendingStatuses)) {
1461 $updateRegisterDate = TRUE;
1463 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1464 $processedParticipantIds[] = $participantId;
1467 //return result for cron.
1468 if ($returnResult) {
1470 'mailedParticipants' => $mailedParticipants,
1471 'updatedParticipantIds' => $processedParticipantIds,
1479 * Send mail and create activity
1480 * when participant status changed.
1482 * @param int $participantId
1484 * @param array $participantValues
1485 * Participant detail values. status id for participants.
1486 * @param array $eventDetails
1487 * Required event details.
1488 * @param array $contactDetails
1489 * Required contact details.
1490 * @param array $domainValues
1491 * Required domain values.
1492 * @param string $mailType
1493 * (eg 'approval', 'confirm', 'expired' ).
1500 static function sendTransitionParticipantMail(
1511 //don't send confirmation mail to additional
1512 //since only primary able to confirm registration.
1513 if (!empty($participantValues['registered_by_id']) &&
1514 $mailType == 'Confirm'
1518 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1521 $contactId = $participantValues['contact_id'];
1522 $participantName = $contactDetails['display_name'];
1524 //calculate the checksum value.
1525 $checksumValue = NULL;
1526 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1527 $checksumLife = 'inf';
1528 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1530 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1532 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1535 //take a receipt from as event else domain.
1536 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1537 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1538 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1541 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1543 'groupName' => 'msg_tpl_workflow_event',
1544 'valueName' => 'participant_' . strtolower($mailType),
1545 'contactId' => $contactId,
1546 'tplParams' => array(
1547 'contact' => $contactDetails,
1548 'domain' => $domainValues,
1549 'participant' => $participantValues,
1550 'event' => $eventDetails,
1551 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1552 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1553 'isAdditional' => $participantValues['registered_by_id'],
1554 'isExpired' => $mailType == 'Expired',
1555 'isConfirm' => $mailType == 'Confirm',
1556 'checksumValue' => $checksumValue,
1558 'from' => $receiptFrom,
1559 'toName' => $participantName,
1560 'toEmail' => $toEmail,
1561 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1562 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1566 // 3. create activity record.
1568 $now = date('YmdHis');
1569 $activityType = 'Event Registration';
1570 $activityParams = array(
1571 'subject' => $subject,
1572 'source_contact_id' => $contactId,
1573 'source_record_id' => $participantId,
1574 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1578 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1579 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1580 'is_test' => $participantValues['is_test'],
1584 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1585 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1594 * Get participant status change message.
1596 * @param int $participantId
1597 * @param $statusChangeTo
1598 * @param int $fromStatusId
1602 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1604 $results = self
::transitionParticipants(array($participantId),
1605 $statusChangeTo, $fromStatusId, TRUE
1608 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1609 //give user message only when mail has sent.
1610 if (is_array($results) && !empty($results)) {
1611 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1612 foreach ($results['updatedParticipantIds'] as $processedId) {
1613 if (is_array($results['mailedParticipants']) &&
1614 array_key_exists($processedId, $results['mailedParticipants'])
1616 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1618 1 => $allStatuses[$statusChangeTo],
1619 2 => $results['mailedParticipants'][$processedId],
1631 * Get event full and waiting list message.
1633 * @param int $eventId
1634 * @param int $participantId
1638 public static function eventFullMessage($eventId, $participantId = NULL) {
1639 $eventfullMsg = $dbStatusId = NULL;
1640 $checkEventFull = TRUE;
1641 if ($participantId) {
1642 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1643 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1644 //participant already in counted status no need to check for event full messages.
1645 $checkEventFull = FALSE;
1650 if (!$eventId ||
!$checkEventFull) {
1651 return $eventfullMsg;
1654 //event is truly full.
1655 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1656 if (is_string($emptySeats) && $emptySeats !== NULL) {
1657 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1658 $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(
1659 1 => $maxParticipants,
1663 $hasWaiting = FALSE;
1664 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1665 if (is_numeric($waitListedCount)) {
1667 //only current processing participant is on waitlist.
1668 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1669 $hasWaiting = FALSE;
1674 $waitingStatusId = array_search('On waitlist',
1675 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1677 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1678 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1681 $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.",
1683 1 => $viewWaitListUrl,
1684 2 => $waitListedCount,
1689 return $eventfullMsg;
1693 * Check for whether participant is primary or not
1695 * @param int $participantId
1698 * true if participant is primary
1700 public static function isPrimaryParticipant($participantId) {
1702 $participant = new CRM_Event_DAO_Participant();
1703 $participant->registered_by_id
= $participantId;
1705 if ($participant->find(TRUE)) {
1712 * Get additional participant Ids for cascading with primary participant status
1714 * @param int $participantId
1716 * @param int $oldStatusId
1718 * @param int $newStatusId
1724 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1726 $additionalParticipantIds = array();
1728 static $participantStatuses = array();
1730 if (empty($participantStatuses)) {
1731 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1734 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1735 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1737 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1740 return $additionalParticipantIds;
1744 * Get participant record count for a Contact
1746 * @param int $contactID
1749 * count of participant records
1752 public static function getContactParticipantCount($contactID) {
1753 $query = "SELECT count(*)
1754 FROM civicrm_participant
1755 WHERE civicrm_participant.contact_id = {$contactID} AND
1756 civicrm_participant.is_test = 0";
1757 return CRM_Core_DAO
::singleValueQuery($query);
1761 * Get participant ids by contribution id
1763 * @param int $contributionId
1765 * @param bool $excludeCancelled
1766 * Exclude cancelled additional participant.
1771 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1774 if (!$contributionId) {
1778 // get primary participant id
1779 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1780 $participantId = CRM_Core_DAO
::singleValueQuery($query);
1782 // get additional participant ids (including cancelled)
1783 if ($participantId) {
1784 $ids = array_merge(array(
1786 ), self
::getAdditionalParticipantIds($participantId,
1795 * Get additional Participant edit & view url .
1797 * @param array $participantIds
1798 * An array of additional participant ids.
1804 public static function getAdditionalParticipantUrl($participantIds) {
1805 foreach ($participantIds as $value) {
1807 $details = self
::participantDetails($value);
1808 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1809 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1811 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1812 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1814 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1815 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1821 * create trxn entry if an event has discount.
1823 * @param int $eventID
1825 * @param array $contributionParams
1826 * Contribution params.
1832 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel) {
1834 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID, 'civicrm_event');
1835 if (!empty($checkDiscount)) {
1836 $feeLevel = current($feeLevel);
1837 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1838 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1839 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1840 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1842 1 => array($priceSetId, 'Integer'),
1843 2 => array($feeLevel, 'String'),
1845 $mainAmount = CRM_Core_DAO
::singleValueQuery($query, $params);
1846 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
1847 $contributionParams['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
1848 $contributionParams['contribution']->financial_type_id
, $relationTypeId);
1849 if (!empty($contributionParams['trxnParams']['from_financial_account_id'])) {
1850 $contributionParams['trxnParams']['total_amount'] = $mainAmount - $contributionParams['total_amount'];
1851 $contributionParams['trxnParams']['payment_processor_id'] = $contributionParams['trxnParams']['payment_instrument_id'] =
1852 $contributionParams['trxnParams']['check_number'] = $contributionParams['trxnParams']['trxn_id'] =
1853 $contributionParams['trxnParams']['net_amount'] = $contributionParams['trxnParams']['fee_amount'] = NULL;
1855 CRM_Core_BAO_FinancialTrxn
::create($contributionParams['trxnParams']);
1862 * Delete participants of contact
1866 * @param int $contactId
1871 public static function deleteContactParticipant($contactId) {
1872 $participant = new CRM_Event_DAO_Participant();
1873 $participant->contact_id
= $contactId;
1874 $participant->find();
1875 while ($participant->fetch()) {
1876 self
::deleteParticipant($participant->id
);
1881 * @param array $params
1882 * @param int $participantId
1883 * @param int $contributionId
1885 * @param array $lineItems
1886 * @param $paidAmount
1887 * @param int $priceSetId
1889 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) {
1890 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1891 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1892 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1893 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($participantId, 'participant');
1894 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
1898 // get the submitted
1899 foreach ($feeBlock as $id => $values) {
1900 CRM_Price_BAO_LineItem
::format($id, $params, $values, $submittedLineItems);
1901 $submittedFieldId[] = CRM_Utils_Array
::retrieveValueRecursive($submittedLineItems, 'price_field_id');
1903 if (!empty($submittedLineItems)) {
1904 $insertLines = $submittedLineItems;
1906 $submittedFieldValueIds = array_keys($submittedLineItems);
1907 $updateLines = array();
1908 foreach ($previousLineItems as $id => $previousLineItem) {
1909 // check through the submitted items if the previousItem exists,
1910 // if found in submitted items, do not use it for new item creations
1911 if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
1912 // if submitted line items are existing don't fire INSERT query
1913 unset($insertLines[$previousLineItem['price_field_value_id']]);
1914 // for updating the line items i.e. use-case - once deselect-option selecting again
1915 if (($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) ||
1916 ($submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1)
1918 $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
1919 $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
1924 $submittedFields = implode(', ', $submittedFieldId);
1925 $submittedFieldValues = implode(', ', $submittedFieldValueIds);
1927 if (!empty($submittedFields) && !empty($submittedFieldValues)) {
1928 $updateLineItem = "UPDATE civicrm_line_item li
1929 INNER JOIN civicrm_financial_item fi
1930 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1932 li.line_total = 0.00,
1933 li.tax_amount = NULL
1934 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
1935 (price_field_value_id NOT IN ({$submittedFieldValues}))
1937 CRM_Core_DAO
::executeQuery($updateLineItem);
1939 // gathering necessary info to record negative (deselected) financial_item
1940 $updateFinancialItem = "
1941 SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
1942 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1943 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
1944 GROUP BY li.entity_table, li.entity_id, price_field_value_id
1946 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1947 $trxn = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId, 'ASC', TRUE);
1948 $trxnId['id'] = $trxn['financialTrxnId'];
1949 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1950 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
1951 $updateFinancialItemInfoValues = array();
1953 while ($updateFinancialItemInfoDAO->fetch()) {
1954 $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
1955 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
1956 // the below params are not needed
1957 unset($updateFinancialItemInfoValues['id']);
1958 unset($updateFinancialItemInfoValues['created_date']);
1959 // if not submitted and difference is not 0 make it negative
1960 if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
1961 // INSERT negative financial_items
1962 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
1963 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1964 // INSERT negative financial_items for tax amount
1965 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
1966 $updateFinancialItemInfoValues['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
1967 $updateFinancialItemInfoValues['description'] = $taxTerm;
1968 if ($updateFinancialItemInfoValues['financial_type_id']) {
1969 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
1971 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1974 // if submitted and difference is 0 add a positive entry again
1975 elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
1976 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
1977 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1978 // INSERT financial_items for tax amount
1979 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
1980 isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
1982 $updateFinancialItemInfoValues['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
1983 $updateFinancialItemInfoValues['description'] = $taxTerm;
1984 if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
1985 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
1987 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1992 elseif (empty($submittedFields) && empty($submittedFieldValues)) {
1993 $updateLineItem = "UPDATE civicrm_line_item li
1994 INNER JOIN civicrm_financial_item fi
1995 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1997 li.line_total = 0.00,
1998 li.tax_amount = NULL
1999 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
2000 CRM_Core_DAO
::executeQuery($updateLineItem);
2002 if (!empty($updateLines)) {
2003 foreach ($updateLines as $valueId => $vals) {
2004 if (isset($vals['tax_amount'])) {
2005 $taxAmount = $vals['tax_amount'];
2008 $taxAmount = "NULL";
2011 UPDATE civicrm_line_item li
2012 SET li.qty = {$vals['qty']},
2013 li.line_total = {$vals['line_total']},
2014 li.tax_amount = {$taxAmount},
2015 li.unit_price = {$vals['unit_price']},
2016 li.label = '{$vals['label']}'
2017 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
2018 (price_field_value_id = {$valueId})
2020 CRM_Core_DAO
::executeQuery($updateLineItem);
2023 // insert new 'adjusted amount' transaction entry and update contribution entry.
2024 // ensure entity_financial_trxn table has a linking of it.
2025 // insert new line items
2026 if (!empty($insertLines)) {
2027 foreach ($insertLines as $valueId => $lineParams) {
2028 $lineParams['entity_table'] = 'civicrm_participant';
2029 $lineParams['entity_id'] = $participantId;
2030 $lineParams['contribution_id'] = $contributionId;
2031 $lineObj = CRM_Price_BAO_LineItem
::create($lineParams);
2035 // the recordAdjustedAmt code would execute over here
2036 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
2037 if (count($ids) > 1) {
2039 foreach ($ids as $val) {
2040 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, 'civicrm_participant');
2042 $updatedAmount = $total;
2045 $updatedAmount = $params['amount'];
2047 if (strlen($params['tax_amount']) != 0) {
2048 $taxAmount = $params['tax_amount'];
2051 $taxAmount = "NULL";
2053 self
::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount);
2055 $fetchCon = array('id' => $contributionId);
2056 $updatedContribution = CRM_Contribute_BAO_Contribution
::retrieve($fetchCon, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2057 // insert financial items
2058 if (!empty($insertLines)) {
2059 foreach ($insertLines as $valueId => $lineParams) {
2060 $lineParams['entity_table'] = 'civicrm_participant';
2061 $lineParams['entity_id'] = $participantId;
2062 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams, CRM_Core_DAO
::$_nullArray);
2063 // insert financial items
2064 // ensure entity_financial_trxn table has a linking of it.
2065 $prevItem = CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution);
2066 if (isset($lineObj->tax_amount
)) {
2067 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE);
2072 // update participant fee_amount column
2073 $partUpdateFeeAmt['id'] = $participantId;
2074 foreach ($lineItems as $lineValue) {
2075 if ($lineValue['price_field_value_id']) {
2076 $line[$lineValue['price_field_value_id']] = $lineValue['label'] . ' - ' . $lineValue['qty'];
2080 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
2081 $partUpdateFeeAmt['fee_amount'] = $params['amount'];
2082 self
::add($partUpdateFeeAmt);
2085 self
::addActivityForSelection($participantId, 'Change Registration');
2089 * @param $updatedAmount
2090 * @param $paidAmount
2091 * @param int $contributionId
2093 public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL) {
2094 $balanceAmt = $updatedAmount - $paidAmount;
2095 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2096 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
2097 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
2098 $completedStatusId = array_search('Completed', $contributionStatuses);
2100 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
2103 if ($balanceAmt > 0 && $paidAmount != 0) {
2104 $contributionStatusVal = $partiallyPaidStatusId;
2106 elseif ($balanceAmt < 0 && $paidAmount != 0) {
2107 $contributionStatusVal = $pendingRefundStatusId;
2109 elseif ($paidAmount == 0) {
2110 //skip updating the contribution status if no payment is made
2112 $updatedContributionDAO->cancel_date
= 'null';
2113 $updatedContributionDAO->cancel_reason
= NULL;
2115 // update contribution status and total amount without trigger financial code
2116 // as this is handled in current BAO function used for change selection
2117 $updatedContributionDAO->id
= $contributionId;
2119 $updatedContributionDAO->contribution_status_id
= $contributionStatusVal;
2121 $updatedContributionDAO->total_amount
= $updatedAmount;
2122 $updatedContributionDAO->tax_amount
= $taxAmount;
2123 $updatedContributionDAO->save();
2125 $ftDetail = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
2126 // adjusted amount financial_trxn creation
2127 if (empty($ftDetail['trxn_id'])) {
2128 $updatedContribution =
2129 CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contributionId), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2130 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2131 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($updatedContribution->financial_type_id
, $relationTypeId);
2133 $adjustedTrxnValues = array(
2134 'from_financial_account_id' => NULL,
2135 'to_financial_account_id' => $toFinancialAccount,
2136 'total_amount' => $balanceAmt,
2137 'status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
2138 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
2139 'contribution_id' => $updatedContribution->id
,
2140 'trxn_date' => date('YmdHis'),
2141 'currency' => $updatedContribution->currency
,
2143 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
2146 // update the financial trxn amount as well, as the fee selections has been updated
2147 if ($balanceAmt != $ftDetail['total_amount']) {
2148 CRM_Core_DAO
::setFieldValue('CRM_Core_BAO_FinancialTrxn', $ftDetail['trxn_id'], 'total_amount', $balanceAmt);
2155 * @param int $participantId
2156 * @param $activityType
2158 * @throws CRM_Core_Exception
2160 public static function addActivityForSelection($participantId, $activityType) {
2161 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
2162 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
2164 $date = CRM_Utils_Date
::currentDBDate();
2165 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
2166 $eventTitle = $event[$eventId];
2167 $subject = "Registration selections changed for $eventTitle";
2168 $targetCid = $contactId;
2169 $srcRecId = $participantId;
2172 $activityParams = array(
2173 'source_contact_id' => $targetCid,
2174 'source_record_id' => $srcRecId,
2175 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
2179 'subject' => $subject,
2180 'activity_date_time' => $date,
2181 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
2185 'skipRecentView' => TRUE,
2188 // create activity with target contacts
2189 $session = CRM_Core_Session
::singleton();
2190 $id = $session->get('userID');
2192 $activityParams['source_contact_id'] = $id;
2193 $activityParams['target_contact_id'][] = $targetCid;
2195 CRM_Activity_BAO_Activity
::create($activityParams);
2199 * Get options for a given field.
2200 * @see CRM_Core_DAO::buildOptions
2202 * @param string $fieldName
2203 * @param string $context
2204 * : @see CRM_Core_DAO::buildOptionsContext.
2205 * @param array $props
2206 * : whatever is known about this dao object.
2208 * @return Array|bool
2210 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2211 $params = array('condition' => array());
2213 if ($fieldName == 'status_id' && $context != 'validate') {
2214 // Get rid of cart-related option if disabled
2215 // FIXME: Why does this option even exist if cart is disabled?
2216 if (!CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
, 'enable_cart')) {
2217 $params['condition'][] = "name <> 'Pending in cart'";
2221 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);