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 1. false => If event having some empty spaces.
357 static function eventFull(
359 $returnEmptySeats = FALSE,
360 $includeWaitingList = TRUE,
361 $returnWaitingCount = FALSE,
362 $considerTestParticipant = FALSE
369 // consider event is full when.
370 // 1. (count(is_counted) >= event_size) or
371 // 2. (count(participants-with-status-on-waitlist) > 0)
372 // It might be case there are some empty spaces and still event
373 // is full, as waitlist might represent group require spaces > empty.
375 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
376 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
377 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
378 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
380 //when we do require only waiting count don't consider counted.
381 if (!$returnWaitingCount && !empty($countedStatuses)) {
382 $allStatusIds = array_keys($countedStatuses);
385 $where = array(' event.id = %1 ');
386 if (!$considerTestParticipant) {
387 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
389 if (!empty($participantRoles)) {
390 $where[] = ' participant.role_id IN ( ' . implode(', ', array_keys($participantRoles)) . ' ) ';
393 $eventParams = array(1 => array($eventId, 'Positive'));
395 //in case any waiting, straight forward event is full.
396 if ($includeWaitingList && $onWaitlistStatusId) {
398 //build the where clause.
399 $whereClause = ' WHERE ' . implode(' AND ', $where);
400 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
401 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
404 SELECT participant.id id,
405 event.event_full_text as event_full_text
406 FROM civicrm_participant participant
407 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
410 $eventFullText = ts('This event is full.');
411 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
412 while ($participants->fetch()) {
413 //oops here event is full and we don't want waiting count.
414 if ($returnWaitingCount) {
415 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
418 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
423 //consider only counted participants.
424 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
425 $whereClause = ' WHERE ' . implode(' AND ', $where);
426 $eventSeatsWhere = implode(' AND ', $where);
429 SELECT participant.id id,
430 event.event_full_text as event_full_text,
431 event.max_participants as max_participants
432 FROM civicrm_participant participant
433 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
436 $eventMaxSeats = NULL;
437 $eventFullText = ts('This event is full.');
438 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
439 while ($participants->fetch()) {
440 if ($participants->event_full_text
) {
441 $eventFullText = $participants->event_full_text
;
443 $eventMaxSeats = $participants->max_participants
;
444 //don't have limit for event seats.
445 if ($participants->max_participants
== NULL) {
450 //get the total event seats occupied by these participants.
451 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
453 if ($eventRegisteredSeats) {
454 if ($eventRegisteredSeats >= $eventMaxSeats) {
455 $result = $eventFullText;
457 elseif ($returnEmptySeats) {
458 $result = $eventMaxSeats - $eventRegisteredSeats;
464 SELECT event.event_full_text,
465 event.max_participants
466 FROM civicrm_event event
467 WHERE event.id = %1';
468 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
469 while ($event->fetch()) {
470 $eventFullText = $event->event_full_text
;
471 $eventMaxSeats = $event->max_participants
;
475 // no limit for registration.
476 if ($eventMaxSeats == NULL) {
479 if ($eventMaxSeats) {
480 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
483 return $eventFullText;
487 * Return the array of all price set field options,
488 * with total participant count that field going to carry.
490 * @param int $eventId
492 * @param array $skipParticipantIds
493 * An array of participant ids those we should skip.
494 * @param bool $considerCounted
495 * @param bool $considerWaiting
496 * @param bool $considerTestParticipants
499 * an array of each option id and total count
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
578 * $spaces Number of Empty Seats/null.
581 public static function pendingToConfirmSpaces($eventId) {
587 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
588 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
591 SELECT count(participant.id) as registered,
592 civicrm_event.max_participants
593 FROM civicrm_participant participant, civicrm_event
594 WHERE participant.event_id = {$eventId}
595 AND civicrm_event.id = participant.event_id
596 AND participant.status_id IN {$statusIds}
597 GROUP BY participant.event_id
599 $dao = CRM_Core_DAO
::executeQuery($query);
603 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
608 if ($dao->registered
>= $dao->max_participants
) {
613 return $dao->max_participants
- $dao->registered
;
616 //space in case no registeration yet.
617 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
621 * Combine all the importable fields from the lower levels object
623 * @param string $contactType
624 * @param bool $status
625 * @param bool $onlyParticipant
628 * array of importable Fields
631 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE) {
632 if (!self
::$_importableFields) {
633 if (!$onlyParticipant) {
635 $fields = array('' => array('title' => ts('- do not import -')));
638 $fields = array('' => array('title' => ts('- Participant Fields -')));
645 $tmpFields = CRM_Event_DAO_Participant
::import();
648 'participant_note' => array(
649 'title' => ts('Participant Note'),
650 'name' => 'participant_note',
651 'headerPattern' => '/(participant.)?note$/i',
655 // Split status and status id into 2 fields
656 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
657 $participantStatus = array(
658 'participant_status' => array(
659 'title' => ts('Participant Status'),
660 'name' => 'participant_status',
661 'data_type' => CRM_Utils_Type
::T_STRING
,
664 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
666 // Split role and role id into 2 fields
667 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
668 $participantRole = array(
669 'participant_role' => array(
670 'title' => ts('Participant Role'),
671 'name' => 'participant_role',
672 'data_type' => CRM_Utils_Type
::T_STRING
,
675 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
678 'event_type' => array(
679 'title' => ts('Event Type'),
680 'name' => 'event_type',
681 'data_type' => CRM_Utils_Type
::T_STRING
,
685 $tmpContactField = $contactFields = array();
686 $contactFields = array();
687 if (!$onlyParticipant) {
688 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
690 // Using new Dedupe rule.
692 'contact_type' => $contactType,
693 'used' => 'Unsupervised',
695 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
697 if (is_array($fieldsArray)) {
698 foreach ($fieldsArray as $value) {
699 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
704 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
705 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
707 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
710 $title = $tmpContactField[trim($value)]['title'];
713 $tmpContactField[trim($value)]['title'] = $title;
717 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
718 if ($extIdentifier) {
719 $tmpContactField['external_identifier'] = $extIdentifier;
720 $tmpContactField['external_identifier']['title'] =
721 CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
723 $tmpFields['participant_contact_id']['title'] =
724 $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
726 $fields = array_merge($fields, $tmpContactField);
727 $fields = array_merge($fields, $tmpFields);
728 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
729 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
731 self
::$_importableFields = $fields;
734 return self
::$_importableFields;
738 * Combine all the exportable fields from the lower levels object
741 * array of exportable Fields
744 public static function &exportableFields() {
745 if (!self
::$_exportableFields) {
746 if (!self
::$_exportableFields) {
747 self
::$_exportableFields = array();
752 $participantFields = CRM_Event_DAO_Participant
::export();
754 'participant_note' => array(
755 'title' => 'Participant Note',
756 'name' => 'participant_note',
760 $participantStatus = array(
761 'participant_status' => array(
762 'title' => 'Participant Status',
763 'name' => 'participant_status',
767 $participantRole = array(
768 'participant_role' => array(
769 'title' => 'Participant Role',
770 'name' => 'participant_role',
774 //CRM-13595 add event id to participant export
777 'title' => 'Event ID',
778 'name' => 'event_id',
782 'event_title' => array(
783 'title' => 'Event Title',
784 'name' => 'event_title',
788 $discountFields = CRM_Core_DAO_Discount
::export();
790 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventid, $eventtitle, $noteField, $discountFields);
793 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
794 self
::$_exportableFields = $fields;
797 return self
::$_exportableFields;
801 * Get the event name/sort name for a particular participation / participant
803 * @param int $participantId
804 * Id of the participant.
807 * associated array with sort_name and event title
810 public static function participantDetails($participantId) {
812 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
813 FROM civicrm_participant
814 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
815 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
816 WHERE civicrm_participant.id = {$participantId}
818 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
821 while ($dao->fetch()) {
822 $details['name'] = $dao->name
;
823 $details['title'] = $dao->title
;
824 $details['cid'] = $dao->cid
;
831 * Get the values for pseudoconstants for name->value and reverse.
833 * @param array $defaults
834 * (reference) the default values, some of which need to be resolved.
835 * @param bool $reverse
836 * True if we want to resolve the values in the reverse direction (value -> name).
841 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
842 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
843 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
844 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
848 * convert associative array names to values
851 * This function is used by both the web form layer and the api. Note that
852 * the api needs the name => value conversion, also the view layer typically
853 * requires value => name conversion
855 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
856 $id = $property . '_id';
858 $src = $reverse ?
$property : $id;
859 $dst = $reverse ?
$id : $property;
861 if (!array_key_exists($src, $defaults)) {
865 $look = $reverse ?
array_flip($lookup) : $lookup;
867 if (is_array($look)) {
868 if (!array_key_exists($defaults[$src], $look)) {
872 $defaults[$dst] = $look[$defaults[$src]];
877 * Delete the record that are associated with this participation
880 * Id of the participation to delete.
885 public static function deleteParticipant($id) {
886 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
888 $transaction = new CRM_Core_Transaction();
890 //delete activity record
892 'source_record_id' => $id,
893 // activity type id for event registration
894 'activity_type_id' => 5,
897 CRM_Activity_BAO_Activity
::deleteActivity($params);
899 // delete the participant payment record
900 // we need to do this since the cascaded constraints
901 // dont work with join tables
902 $p = array('participant_id' => $id);
903 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
905 // cleanup line items.
906 $participantsId = array();
907 $participantsId = self
::getAdditionalParticipantIds($id);
908 $participantsId[] = $id;
909 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
911 //delete note when participant deleted.
912 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
913 $noteId = key($note);
915 CRM_Core_BAO_Note
::del($noteId, FALSE);
918 $participant = new CRM_Event_DAO_Participant();
919 $participant->id
= $id;
920 $participant->delete();
922 $transaction->commit();
924 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
926 // delete the recently created Participant
927 $participantRecent = array(
929 'type' => 'Participant',
932 CRM_Utils_Recent
::del($participantRecent);
938 * Checks duplicate participants
940 * @param array $duplicates
941 * (reference ) an assoc array of name/value pairs.
942 * @param array $input
943 * An assosiative array of name /value pairs.
944 * from other function
946 * @return CRM_Contribute_BAO_Contribution object
949 public static function checkDuplicate($input, &$duplicates) {
950 $eventId = CRM_Utils_Array
::value('event_id', $input);
951 $contactId = CRM_Utils_Array
::value('contact_id', $input);
957 $clause[] = "event_id = %1";
958 $input[1] = array($eventId, 'Integer');
962 $clause[] = "contact_id = %2";
963 $input[2] = array($contactId, 'Integer');
966 if (empty($clause)) {
970 $clause = implode(' AND ', $clause);
972 $query = "SELECT id FROM civicrm_participant WHERE $clause";
973 $dao = CRM_Core_DAO
::executeQuery($query, $input);
975 while ($dao->fetch()) {
976 $duplicates[] = $dao->id
;
983 * Fix the event level
985 * When price sets are used as event fee, fee_level is set as ^A
986 * separated string. We need to change that string to comma
987 * separated string before using fee_level in view mode.
989 * @param string $eventLevel
990 * Event_leval string from db.
996 public static function fixEventLevel(&$eventLevel) {
997 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
998 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
1000 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
1001 $pos = strrpos($eventLevel, '(multiple participants)', 0);
1003 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
1006 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1007 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1008 substr($eventLevel, 0, 1)
1011 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1012 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1013 substr($eventLevel, 0, -1)
1019 * Get the additional participant ids.
1021 * @param int $primaryParticipantId
1022 * Primary partycipant Id.
1023 * @param bool $excludeCancel
1024 * Do not include participant those are cancelled.
1026 * @param int $oldStatusId
1031 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1032 $additionalParticipantIds = array();
1033 if (!$primaryParticipantId) {
1034 return $additionalParticipantIds;
1037 $where = "participant.registered_by_id={$primaryParticipantId}";
1038 if ($excludeCancel) {
1039 $cancelStatusId = 0;
1040 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1041 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1042 $where .= " AND participant.status_id != {$cancelStatusId}";
1046 $where .= " AND participant.status_id = {$oldStatusId}";
1050 SELECT participant.id
1051 FROM civicrm_participant participant
1054 $dao = CRM_Core_DAO
::executeQuery($query);
1055 while ($dao->fetch()) {
1056 $additionalParticipantIds[$dao->id
] = $dao->id
;
1058 return $additionalParticipantIds;
1062 * Get the event fee info for given participant ids
1063 * either from line item table / participant table.
1065 * @param array $participantIds
1067 * @param bool $hasLineItems
1068 * Do fetch from line items.
1073 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1074 $feeDetails = array();
1075 if (!is_array($participantIds) ||
empty($participantIds)) {
1080 SELECT participant.id as id,
1081 participant.fee_level as fee_level,
1082 participant.fee_amount as fee_amount';
1083 $from = 'FROM civicrm_participant participant';
1084 if ($hasLineItems) {
1086 lineItem.id as lineId,
1087 lineItem.label as label,
1088 lineItem.qty as qty,
1089 lineItem.unit_price as unit_price,
1090 lineItem.line_total as line_total,
1091 field.label as field_title,
1092 field.html_type as html_type,
1093 field.id as price_field_id,
1094 value.id as price_field_value_id,
1095 value.description as description,
1096 IF( value.count, value.count, 0 ) as participant_count';
1098 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1099 AND lineItem.entity_id = participant.id )
1100 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1101 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1104 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1105 $query = "$select $from $where";
1107 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1108 $feeProperties = array('fee_level', 'fee_amount');
1109 $lineProperties = array(
1118 'participant_count',
1119 'price_field_value_id',
1122 while ($feeInfo->fetch()) {
1123 if ($hasLineItems) {
1124 foreach ($lineProperties as $property) {
1125 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1129 foreach ($feeProperties as $property) {
1130 $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1139 * Retrieve additional participants display-names and URL to view their participant records.
1140 * (excludes cancelled participants automatically)
1142 * @param int $primaryParticipantID
1143 * Id of primary participant record.
1146 * $displayName => $viewUrl
1149 public static function getAdditionalParticipants($primaryParticipantID) {
1150 $additionalParticipantIDs = array();
1151 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1152 if (!empty($additionalParticipantIDs)) {
1153 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1154 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1155 $additionalParticipantID,
1158 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1159 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1160 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1163 $additionalParticipants[$additionalContactName] = $pViewURL;
1166 return $additionalParticipants;
1170 * Function for update primary and additional participant status
1172 * @param int $participantID
1173 * Primary participant's id.
1174 * @param int $oldStatusID
1175 * @param int $newStatusID
1176 * @param bool $updatePrimaryStatus
1181 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1182 if (!$participantID ||
!$oldStatusID) {
1186 if (!$newStatusID) {
1187 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1189 elseif ($updatePrimaryStatus) {
1190 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1193 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1195 if (!empty($cascadeAdditionalIds)) {
1196 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1197 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1198 $params = array(1 => array($newStatusID, 'Integer'));
1199 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1206 * Function for update status for given participant ids
1208 * @param int $participantIds
1209 * Array of participant ids.
1210 * @param int $statusId
1211 * Status id for participant.
1212 * @param bool $updateRegisterDate
1218 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1219 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1223 //lets update register date as we update status to keep track
1224 //when we did update status, useful for moving participant
1225 //from pending to expired.
1226 $setClause = "status_id = {$statusId}";
1227 if ($updateRegisterDate) {
1228 $setClause .= ", register_date = NOW()";
1231 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1234 UPDATE civicrm_participant
1236 WHERE id IN {$participantIdClause}";
1238 $dao = CRM_Core_DAO
::executeQuery($query);
1242 * Function takes participant ids and statuses
1243 * update status from $fromStatusId to $toStatusId
1244 * and send mail + create activities.
1246 * @param array $participantIds
1248 * @param int $toStatusId
1250 * @param int $fromStatusId
1254 * @param bool $returnResult
1255 * @param bool $skipCascadeRule
1260 static function transitionParticipants(
1261 $participantIds, $toStatusId,
1262 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1264 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1268 //thumb rule is if we triggering primary participant need to triggered additional
1269 $allParticipantIds = $primaryANDAdditonalIds = array();
1270 foreach ($participantIds as $id) {
1271 $allParticipantIds[] = $id;
1272 if (self
::isPrimaryParticipant($id)) {
1273 //filter additional as per status transition rules, CRM-5403
1274 if ($skipCascadeRule) {
1275 $additionalIds = self
::getAdditionalParticipantIds($id);
1278 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1280 if (!empty($additionalIds)) {
1281 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1282 $primaryANDAdditonalIds[$id] = $additionalIds;
1287 //get the unique participant ids,
1288 $allParticipantIds = array_unique($allParticipantIds);
1290 //pull required participants, contacts, events data, if not in hand
1291 static $eventDetails = array();
1292 static $domainValues = array();
1293 static $contactDetails = array();
1295 $contactIds = $eventIds = $participantDetails = array();
1297 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1298 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1299 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1303 //first thing is pull all necessory data from db.
1304 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1306 //get all participants data.
1307 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1308 $dao = CRM_Core_DAO
::executeQuery($query);
1309 while ($dao->fetch()) {
1310 $participantDetails[$dao->id
] = array(
1312 'role' => $participantRoles[$dao->role_id
],
1313 'is_test' => $dao->is_test
,
1314 'event_id' => $dao->event_id
,
1315 'status_id' => $dao->status_id
,
1316 'fee_amount' => $dao->fee_amount
,
1317 'contact_id' => $dao->contact_id
,
1318 'register_date' => $dao->register_date
,
1319 'registered_by_id' => $dao->registered_by_id
,
1321 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1322 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1325 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1326 $eventIds[$dao->event_id
] = $dao->event_id
;
1330 //get the domain values.
1331 if (empty($domainValues)) {
1332 // making all tokens available to templates.
1333 $domain = CRM_Core_BAO_Domain
::getDomain();
1335 'domain' => array('name', 'phone', 'address', 'email'),
1336 'contact' => CRM_Core_SelectValues
::contactTokens(),
1339 foreach ($tokens['domain'] as $token) {
1340 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1344 //get all required contacts detail.
1345 if (!empty($contactIds)) {
1346 // get the contact details.
1347 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1350 'CRM_Event_BAO_Participant'
1352 foreach ($currentContactDetails as $contactId => $contactValues) {
1353 $contactDetails[$contactId] = $contactValues;
1357 //get all required events detail.
1358 if (!empty($eventIds)) {
1359 foreach ($eventIds as $eventId) {
1360 //retrieve event information
1361 $eventParams = array('id' => $eventId);
1362 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1364 //get default participant role.
1365 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1367 //get the location info
1368 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1369 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1373 //now we are ready w/ all required data.
1374 //take a decision as per statuses.
1377 $toStatus = $statusTypes[$toStatusId];
1378 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1380 switch ($toStatus) {
1381 case 'Pending from waitlist':
1382 case 'Pending from approval':
1383 switch ($fromStatus) {
1385 case 'Awaiting approval':
1386 $emailType = 'Confirm';
1392 //no matter from where u come send expired mail.
1393 $emailType = $toStatus;
1397 //no matter from where u come send cancel mail.
1398 $emailType = $toStatus;
1402 //as we process additional w/ primary, there might be case if user
1403 //select primary as well as additionals, so avoid double processing.
1404 $processedParticipantIds = array();
1405 $mailedParticipants = array();
1407 //send mails and update status.
1408 foreach ($participantDetails as $participantId => $participantValues) {
1409 $updateParticipantIds = array();
1410 if (in_array($participantId, $processedParticipantIds)) {
1414 //check is it primary and has additional.
1415 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1416 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1419 $mail = self
::sendTransitionParticipantMail($additonalId,
1420 $participantDetails[$additonalId],
1421 $eventDetails[$participantDetails[$additonalId]['event_id']],
1422 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1427 //get the mail participant ids
1429 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1432 $updateParticipantIds[] = $additonalId;
1433 $processedParticipantIds[] = $additonalId;
1437 //now send email appropriate mail to primary.
1439 $mail = self
::sendTransitionParticipantMail($participantId,
1441 $eventDetails[$participantValues['event_id']],
1442 $contactDetails[$participantValues['contact_id']],
1447 //get the mail participant ids
1449 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1453 //now update status of group/one at once.
1454 $updateParticipantIds[] = $participantId;
1456 //update the register date only when we,
1457 //move participant to pending class, CRM-6496
1458 $updateRegisterDate = FALSE;
1459 if (array_key_exists($toStatusId, $pendingStatuses)) {
1460 $updateRegisterDate = TRUE;
1462 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1463 $processedParticipantIds[] = $participantId;
1466 //return result for cron.
1467 if ($returnResult) {
1469 'mailedParticipants' => $mailedParticipants,
1470 'updatedParticipantIds' => $processedParticipantIds,
1478 * Send mail and create activity
1479 * when participant status changed.
1481 * @param int $participantId
1483 * @param array $participantValues
1484 * Participant detail values. status id for participants.
1485 * @param array $eventDetails
1486 * Required event details.
1487 * @param array $contactDetails
1488 * Required contact details.
1489 * @param array $domainValues
1490 * Required domain values.
1491 * @param string $mailType
1492 * (eg 'approval', 'confirm', 'expired' ).
1499 static function sendTransitionParticipantMail(
1510 //don't send confirmation mail to additional
1511 //since only primary able to confirm registration.
1512 if (!empty($participantValues['registered_by_id']) &&
1513 $mailType == 'Confirm'
1517 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1520 $contactId = $participantValues['contact_id'];
1521 $participantName = $contactDetails['display_name'];
1523 //calculate the checksum value.
1524 $checksumValue = NULL;
1525 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1526 $checksumLife = 'inf';
1527 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1529 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1531 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1534 //take a receipt from as event else domain.
1535 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1536 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1537 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1540 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1542 'groupName' => 'msg_tpl_workflow_event',
1543 'valueName' => 'participant_' . strtolower($mailType),
1544 'contactId' => $contactId,
1545 'tplParams' => array(
1546 'contact' => $contactDetails,
1547 'domain' => $domainValues,
1548 'participant' => $participantValues,
1549 'event' => $eventDetails,
1550 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1551 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1552 'isAdditional' => $participantValues['registered_by_id'],
1553 'isExpired' => $mailType == 'Expired',
1554 'isConfirm' => $mailType == 'Confirm',
1555 'checksumValue' => $checksumValue,
1557 'from' => $receiptFrom,
1558 'toName' => $participantName,
1559 'toEmail' => $toEmail,
1560 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1561 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1565 // 3. create activity record.
1567 $now = date('YmdHis');
1568 $activityType = 'Event Registration';
1569 $activityParams = array(
1570 'subject' => $subject,
1571 'source_contact_id' => $contactId,
1572 'source_record_id' => $participantId,
1573 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1577 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1578 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1579 'is_test' => $participantValues['is_test'],
1583 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1584 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1593 * Get participant status change message.
1595 * @param int $participantId
1596 * @param $statusChangeTo
1597 * @param int $fromStatusId
1601 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1603 $results = self
::transitionParticipants(array($participantId),
1604 $statusChangeTo, $fromStatusId, TRUE
1607 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1608 //give user message only when mail has sent.
1609 if (is_array($results) && !empty($results)) {
1610 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1611 foreach ($results['updatedParticipantIds'] as $processedId) {
1612 if (is_array($results['mailedParticipants']) &&
1613 array_key_exists($processedId, $results['mailedParticipants'])
1615 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1617 1 => $allStatuses[$statusChangeTo],
1618 2 => $results['mailedParticipants'][$processedId],
1630 * Get event full and waiting list message.
1632 * @param int $eventId
1633 * @param int $participantId
1637 public static function eventFullMessage($eventId, $participantId = NULL) {
1638 $eventfullMsg = $dbStatusId = NULL;
1639 $checkEventFull = TRUE;
1640 if ($participantId) {
1641 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1642 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1643 //participant already in counted status no need to check for event full messages.
1644 $checkEventFull = FALSE;
1649 if (!$eventId ||
!$checkEventFull) {
1650 return $eventfullMsg;
1653 //event is truly full.
1654 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1655 if (is_string($emptySeats) && $emptySeats !== NULL) {
1656 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1657 $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(
1658 1 => $maxParticipants,
1662 $hasWaiting = FALSE;
1663 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1664 if (is_numeric($waitListedCount)) {
1666 //only current processing participant is on waitlist.
1667 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1668 $hasWaiting = FALSE;
1673 $waitingStatusId = array_search('On waitlist',
1674 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1676 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1677 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1680 $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.",
1682 1 => $viewWaitListUrl,
1683 2 => $waitListedCount,
1688 return $eventfullMsg;
1692 * Check for whether participant is primary or not
1694 * @param int $participantId
1696 * @return true if participant is primary
1698 public static function isPrimaryParticipant($participantId) {
1700 $participant = new CRM_Event_DAO_Participant();
1701 $participant->registered_by_id
= $participantId;
1703 if ($participant->find(TRUE)) {
1710 * Get additional participant Ids for cascading with primary participant status
1712 * @param int $participantId
1714 * @param int $oldStatusId
1716 * @param int $newStatusId
1719 * @return true if allowed
1721 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1723 $additionalParticipantIds = array();
1725 static $participantStatuses = array();
1727 if (empty($participantStatuses)) {
1728 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1731 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1732 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1734 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1737 return $additionalParticipantIds;
1741 * Get participant record count for a Contact
1743 * @param int $contactID
1746 * count of participant records
1749 public static function getContactParticipantCount($contactID) {
1750 $query = "SELECT count(*)
1751 FROM civicrm_participant
1752 WHERE civicrm_participant.contact_id = {$contactID} AND
1753 civicrm_participant.is_test = 0";
1754 return CRM_Core_DAO
::singleValueQuery($query);
1758 * Get participant ids by contribution id
1760 * @param int $contributionId
1762 * @param bool $excludeCancelled
1763 * Exclude cancelled additional participant.
1768 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1771 if (!$contributionId) {
1775 // get primary participant id
1776 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1777 $participantId = CRM_Core_DAO
::singleValueQuery($query);
1779 // get additional participant ids (including cancelled)
1780 if ($participantId) {
1781 $ids = array_merge(array(
1783 ), self
::getAdditionalParticipantIds($participantId,
1792 * Get additional Participant edit & view url .
1794 * @param array $participantIds
1795 * An array of additional participant ids.
1801 public static function getAdditionalParticipantUrl($participantIds) {
1802 foreach ($participantIds as $value) {
1804 $details = self
::participantDetails($value);
1805 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1806 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1808 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1809 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1811 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1812 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1818 * create trxn entry if an event has discount.
1820 * @param int $eventID
1822 * @param array $contributionParams
1823 * Contribution params.
1829 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel) {
1831 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID, 'civicrm_event');
1832 if (!empty($checkDiscount)) {
1833 $feeLevel = current($feeLevel);
1834 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1835 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1836 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1837 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1839 1 => array($priceSetId, 'Integer'),
1840 2 => array($feeLevel, 'String'),
1842 $mainAmount = CRM_Core_DAO
::singleValueQuery($query, $params);
1843 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
1844 $contributionParams['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
1845 $contributionParams['contribution']->financial_type_id
, $relationTypeId);
1846 if (!empty($contributionParams['trxnParams']['from_financial_account_id'])) {
1847 $contributionParams['trxnParams']['total_amount'] = $mainAmount - $contributionParams['total_amount'];
1848 $contributionParams['trxnParams']['payment_processor_id'] = $contributionParams['trxnParams']['payment_instrument_id'] =
1849 $contributionParams['trxnParams']['check_number'] = $contributionParams['trxnParams']['trxn_id'] =
1850 $contributionParams['trxnParams']['net_amount'] = $contributionParams['trxnParams']['fee_amount'] = NULL;
1852 CRM_Core_BAO_FinancialTrxn
::create($contributionParams['trxnParams']);
1859 * Delete participants of contact
1863 * @param int $contactId
1868 public static function deleteContactParticipant($contactId) {
1869 $participant = new CRM_Event_DAO_Participant();
1870 $participant->contact_id
= $contactId;
1871 $participant->find();
1872 while ($participant->fetch()) {
1873 self
::deleteParticipant($participant->id
);
1878 * @param array $params
1879 * @param int $participantId
1880 * @param int $contributionId
1882 * @param array $lineItems
1883 * @param $paidAmount
1884 * @param int $priceSetId
1886 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) {
1887 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1888 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1889 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1890 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($participantId, 'participant');
1891 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
1895 // get the submitted
1896 foreach ($feeBlock as $id => $values) {
1897 CRM_Price_BAO_LineItem
::format($id, $params, $values, $submittedLineItems);
1898 $submittedFieldId[] = CRM_Utils_Array
::retrieveValueRecursive($submittedLineItems, 'price_field_id');
1900 if (!empty($submittedLineItems)) {
1901 $insertLines = $submittedLineItems;
1903 $submittedFieldValueIds = array_keys($submittedLineItems);
1904 $updateLines = array();
1905 foreach ($previousLineItems as $id => $previousLineItem) {
1906 // check through the submitted items if the previousItem exists,
1907 // if found in submitted items, do not use it for new item creations
1908 if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
1909 // if submitted line items are existing don't fire INSERT query
1910 unset($insertLines[$previousLineItem['price_field_value_id']]);
1911 // for updating the line items i.e. use-case - once deselect-option selecting again
1912 if (($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) ||
1913 ($submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1)
1915 $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
1916 $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
1921 $submittedFields = implode(', ', $submittedFieldId);
1922 $submittedFieldValues = implode(', ', $submittedFieldValueIds);
1924 if (!empty($submittedFields) && !empty($submittedFieldValues)) {
1925 $updateLineItem = "UPDATE civicrm_line_item li
1926 INNER JOIN civicrm_financial_item fi
1927 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1929 li.line_total = 0.00,
1930 li.tax_amount = NULL
1931 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
1932 (price_field_value_id NOT IN ({$submittedFieldValues}))
1934 CRM_Core_DAO
::executeQuery($updateLineItem);
1936 // gathering necessary info to record negative (deselected) financial_item
1937 $updateFinancialItem = "
1938 SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
1939 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1940 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
1941 GROUP BY li.entity_table, li.entity_id, price_field_value_id
1943 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1944 $trxn = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId, 'ASC', TRUE);
1945 $trxnId['id'] = $trxn['financialTrxnId'];
1946 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1947 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
1948 $updateFinancialItemInfoValues = array();
1950 while ($updateFinancialItemInfoDAO->fetch()) {
1951 $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
1952 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
1953 // the below params are not needed
1954 unset($updateFinancialItemInfoValues['id']);
1955 unset($updateFinancialItemInfoValues['created_date']);
1956 // if not submitted and difference is not 0 make it negative
1957 if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
1958 // INSERT negative financial_items
1959 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
1960 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1961 // INSERT negative financial_items for tax amount
1962 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
1963 $updateFinancialItemInfoValues['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
1964 $updateFinancialItemInfoValues['description'] = $taxTerm;
1965 if ($updateFinancialItemInfoValues['financial_type_id']) {
1966 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
1968 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1971 // if submitted and difference is 0 add a positive entry again
1972 elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
1973 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
1974 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1975 // INSERT financial_items for tax amount
1976 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
1977 isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
1979 $updateFinancialItemInfoValues['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
1980 $updateFinancialItemInfoValues['description'] = $taxTerm;
1981 if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
1982 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
1984 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1989 elseif (empty($submittedFields) && empty($submittedFieldValues)) {
1990 $updateLineItem = "UPDATE civicrm_line_item li
1991 INNER JOIN civicrm_financial_item fi
1992 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1994 li.line_total = 0.00,
1995 li.tax_amount = NULL
1996 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
1997 CRM_Core_DAO
::executeQuery($updateLineItem);
1999 if (!empty($updateLines)) {
2000 foreach ($updateLines as $valueId => $vals) {
2001 if (isset($vals['tax_amount'])) {
2002 $taxAmount = $vals['tax_amount'];
2005 $taxAmount = "NULL";
2008 UPDATE civicrm_line_item li
2009 SET li.qty = {$vals['qty']},
2010 li.line_total = {$vals['line_total']},
2011 li.tax_amount = {$taxAmount},
2012 li.unit_price = {$vals['unit_price']},
2013 li.label = '{$vals['label']}'
2014 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
2015 (price_field_value_id = {$valueId})
2017 CRM_Core_DAO
::executeQuery($updateLineItem);
2020 // insert new 'adjusted amount' transaction entry and update contribution entry.
2021 // ensure entity_financial_trxn table has a linking of it.
2022 // insert new line items
2023 if (!empty($insertLines)) {
2024 foreach ($insertLines as $valueId => $lineParams) {
2025 $lineParams['entity_table'] = 'civicrm_participant';
2026 $lineParams['entity_id'] = $participantId;
2027 $lineParams['contribution_id'] = $contributionId;
2028 $lineObj = CRM_Price_BAO_LineItem
::create($lineParams);
2032 // the recordAdjustedAmt code would execute over here
2033 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
2034 if (count($ids) > 1) {
2036 foreach ($ids as $val) {
2037 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, 'civicrm_participant');
2039 $updatedAmount = $total;
2042 $updatedAmount = $params['amount'];
2044 if (strlen($params['tax_amount']) != 0) {
2045 $taxAmount = $params['tax_amount'];
2048 $taxAmount = "NULL";
2050 self
::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount);
2052 $fetchCon = array('id' => $contributionId);
2053 $updatedContribution = CRM_Contribute_BAO_Contribution
::retrieve($fetchCon, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2054 // insert financial items
2055 if (!empty($insertLines)) {
2056 foreach ($insertLines as $valueId => $lineParams) {
2057 $lineParams['entity_table'] = 'civicrm_participant';
2058 $lineParams['entity_id'] = $participantId;
2059 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams, CRM_Core_DAO
::$_nullArray);
2060 // insert financial items
2061 // ensure entity_financial_trxn table has a linking of it.
2062 $prevItem = CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution);
2063 if (isset($lineObj->tax_amount
)) {
2064 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE);
2069 // update participant fee_amount column
2070 $partUpdateFeeAmt['id'] = $participantId;
2071 foreach ($lineItems as $lineValue) {
2072 if ($lineValue['price_field_value_id']) {
2073 $line[$lineValue['price_field_value_id']] = $lineValue['label'] . ' - ' . $lineValue['qty'];
2077 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
2078 $partUpdateFeeAmt['fee_amount'] = $params['amount'];
2079 self
::add($partUpdateFeeAmt);
2082 self
::addActivityForSelection($participantId, 'Change Registration');
2086 * @param $updatedAmount
2087 * @param $paidAmount
2088 * @param int $contributionId
2090 public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL) {
2091 $balanceAmt = $updatedAmount - $paidAmount;
2092 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2093 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
2094 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
2095 $completedStatusId = array_search('Completed', $contributionStatuses);
2097 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
2100 if ($balanceAmt > 0 && $paidAmount != 0) {
2101 $contributionStatusVal = $partiallyPaidStatusId;
2103 elseif ($balanceAmt < 0 && $paidAmount != 0) {
2104 $contributionStatusVal = $pendingRefundStatusId;
2106 elseif ($paidAmount == 0) {
2107 //skip updating the contribution status if no payment is made
2109 $updatedContributionDAO->cancel_date
= 'null';
2110 $updatedContributionDAO->cancel_reason
= NULL;
2112 // update contribution status and total amount without trigger financial code
2113 // as this is handled in current BAO function used for change selection
2114 $updatedContributionDAO->id
= $contributionId;
2116 $updatedContributionDAO->contribution_status_id
= $contributionStatusVal;
2118 $updatedContributionDAO->total_amount
= $updatedAmount;
2119 $updatedContributionDAO->tax_amount
= $taxAmount;
2120 $updatedContributionDAO->save();
2122 $ftDetail = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
2123 // adjusted amount financial_trxn creation
2124 if (empty($ftDetail['trxn_id'])) {
2125 $updatedContribution =
2126 CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contributionId), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2127 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2128 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($updatedContribution->financial_type_id
, $relationTypeId);
2130 $adjustedTrxnValues = array(
2131 'from_financial_account_id' => NULL,
2132 'to_financial_account_id' => $toFinancialAccount,
2133 'total_amount' => $balanceAmt,
2134 'status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
2135 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
2136 'contribution_id' => $updatedContribution->id
,
2137 'trxn_date' => date('YmdHis'),
2138 'currency' => $updatedContribution->currency
,
2140 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
2143 // update the financial trxn amount as well, as the fee selections has been updated
2144 if ($balanceAmt != $ftDetail['total_amount']) {
2145 CRM_Core_DAO
::setFieldValue('CRM_Core_BAO_FinancialTrxn', $ftDetail['trxn_id'], 'total_amount', $balanceAmt);
2152 * @param int $participantId
2153 * @param $activityType
2155 * @throws CRM_Core_Exception
2157 public static function addActivityForSelection($participantId, $activityType) {
2158 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
2159 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
2161 $date = CRM_Utils_Date
::currentDBDate();
2162 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
2163 $eventTitle = $event[$eventId];
2164 $subject = "Registration selections changed for $eventTitle";
2165 $targetCid = $contactId;
2166 $srcRecId = $participantId;
2169 $activityParams = array(
2170 'source_contact_id' => $targetCid,
2171 'source_record_id' => $srcRecId,
2172 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
2176 'subject' => $subject,
2177 'activity_date_time' => $date,
2178 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
2182 'skipRecentView' => TRUE,
2185 // create activity with target contacts
2186 $session = CRM_Core_Session
::singleton();
2187 $id = $session->get('userID');
2189 $activityParams['source_contact_id'] = $id;
2190 $activityParams['target_contact_id'][] = $targetCid;
2192 CRM_Activity_BAO_Activity
::create($activityParams);
2196 * Get options for a given field.
2197 * @see CRM_Core_DAO::buildOptions
2199 * @param string $fieldName
2200 * @param string $context
2201 * : @see CRM_Core_DAO::buildOptionsContext.
2202 * @param array $props
2203 * : whatever is known about this dao object.
2205 * @return Array|bool
2207 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2208 $params = array('condition' => array());
2210 if ($fieldName == 'status_id' && $context != 'validate') {
2211 // Get rid of cart-related option if disabled
2212 // FIXME: Why does this option even exist if cart is disabled?
2213 if (!CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
, 'enable_cart')) {
2214 $params['condition'][] = "name <> 'Pending in cart'";
2218 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);