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'),
73 public function __construct() {
74 parent
::__construct();
78 * Takes an associative array and creates a participant object
80 * the function extract all the params it needs to initialize the create a
81 * participant object. the params array could contain additional unused name/value
84 * @param array $params
85 * (reference ) an assoc array of name/value pairs.
87 * @return CRM_Event_BAO_Participant object
90 public static function &add(&$params) {
92 if (!empty($params['id'])) {
93 CRM_Utils_Hook
::pre('edit', 'Participant', $params['id'], $params);
96 CRM_Utils_Hook
::pre('create', 'Participant', NULL, $params);
99 // converting dates to mysql format
100 if (!empty($params['register_date'])) {
101 $params['register_date'] = CRM_Utils_Date
::isoToMysql($params['register_date']);
104 if (!empty($params['participant_fee_amount'])) {
105 $params['participant_fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['participant_fee_amount']);
108 if (!empty($params['fee_amount'])) {
109 $params['fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['fee_amount']);
112 // ensure that role ids are encoded as a string
113 if (isset($params['role_id']) && is_array($params['role_id'])) {
114 $params['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['role_id']);
117 $participantBAO = new CRM_Event_BAO_Participant
;
118 if (!empty($params['id'])) {
119 $participantBAO->id
= CRM_Utils_Array
::value('id', $params);
120 $participantBAO->find(TRUE);
121 $participantBAO->register_date
= CRM_Utils_Date
::isoToMysql($participantBAO->register_date
);
124 $participantBAO->copyValues($params);
127 //1. If currency present, it should be valid one.
128 //2. We should have currency when amount is not null.
129 $currency = $participantBAO->fee_currency
;
131 !CRM_Utils_System
::isNull($participantBAO->fee_amount
)
133 if (!CRM_Utils_Rule
::currencyCode($currency)) {
134 $config = CRM_Core_Config
::singleton();
135 $currency = $config->defaultCurrency
;
138 $participantBAO->fee_currency
= $currency;
140 $participantBAO->save();
142 $session = CRM_Core_Session
::singleton();
144 // reset the group contact cache for this group
145 CRM_Contact_BAO_GroupContactCache
::remove();
147 if (!empty($params['id'])) {
148 CRM_Utils_Hook
::post('edit', 'Participant', $participantBAO->id
, $participantBAO);
151 CRM_Utils_Hook
::post('create', 'Participant', $participantBAO->id
, $participantBAO);
154 return $participantBAO;
158 * Given the list of params in the params array, fetch the object
159 * and store the values in the values array
161 * @param array $params
162 * Input parameters to find object.
163 * @param array $values
164 * Output values of the object.
168 * @return CRM_Event_BAO_Participant|null the found object or null
171 public static function getValues(&$params, &$values, &$ids) {
172 if (empty($params)) {
175 $participant = new CRM_Event_BAO_Participant();
176 $participant->copyValues($params);
177 $participant->find();
178 $participants = array();
179 while ($participant->fetch()) {
180 $ids['participant'] = $participant->id
;
181 CRM_Core_DAO
::storeValues($participant, $values[$participant->id
]);
182 $participants[$participant->id
] = $participant;
184 return $participants;
188 * Takes an associative array and creates a participant object
190 * @param array $params
191 * (reference ) an assoc array of name/value pairs.
193 * @return CRM_Event_BAO_Participant object
196 public static function create(&$params) {
198 $transaction = new CRM_Core_Transaction();
201 if (!empty($params['id'])) {
202 $status = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
205 $participant = self
::add($params);
207 if (is_a($participant, 'CRM_Core_Error')) {
208 $transaction->rollback();
212 if ((!CRM_Utils_Array
::value('id', $params)) ||
213 (isset($params['status_id']) && $params['status_id'] != $status)
215 CRM_Activity_BAO_Activity
::addActivity($participant);
220 if (self
::isPrimaryParticipant($participant->id
) && $status) {
221 self
::updateParticipantStatus($participant->id
, $status, $participant->status_id
);
224 $session = CRM_Core_Session
::singleton();
225 $id = $session->get('userID');
227 $id = CRM_Utils_Array
::value('contact_id', $params);
230 // add custom field values
231 if (!empty($params['custom']) &&
232 is_array($params['custom'])
234 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_participant', $participant->id
);
237 //process note, CRM-7634
239 if (!empty($params['id'])) {
240 $note = CRM_Core_BAO_Note
::getNote($params['id'], 'civicrm_participant');
241 $noteId = key($note);
244 $hasNoteField = FALSE;
249 if (array_key_exists($noteFld, $params)) {
250 $noteValue = $params[$noteFld];
251 $hasNoteField = TRUE;
255 if ($noteId ||
$noteValue) {
258 'entity_table' => 'civicrm_participant',
259 'note' => $noteValue,
260 'entity_id' => $participant->id
,
262 'modified_date' => date('Ymd'),
266 $noteIDs['id'] = $noteId;
268 CRM_Core_BAO_Note
::add($noteParams, $noteIDs);
270 elseif ($noteId && $hasNoteField) {
271 CRM_Core_BAO_Note
::del($noteId, FALSE);
275 // Log the information on successful add/edit of Participant data.
277 'entity_table' => 'civicrm_participant',
278 'entity_id' => $participant->id
,
279 'data' => CRM_Event_PseudoConstant
::participantStatus($participant->status_id
),
280 'modified_id' => $id,
281 'modified_date' => date('Ymd'),
284 CRM_Core_BAO_Log
::add($logParams);
286 $params['participant_id'] = $participant->id
;
288 $transaction->commit();
290 // do not add to recent items for import, CRM-4399
291 if (empty($params['skipRecentView'])) {
293 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
294 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
297 $recentOther = array();
298 if (CRM_Core_Permission
::check('edit event participants')) {
299 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
300 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
303 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
304 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
305 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
309 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
311 if ($participant->role_id
) {
312 $role = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participant->role_id
);
314 foreach ($role as & $roleValue) {
315 if (isset($roleValue)) {
316 $roleValue = $participantRoles[$roleValue];
319 $roles = implode(', ', $role);
322 $roleString = empty($roles) ?
'' : $roles;
323 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $participant->event_id
, 'title');
324 $title = CRM_Contact_BAO_Contact
::displayName($participant->contact_id
) . ' (' . $roleString . ' - ' . $eventTitle . ')';
326 // add the recently created Participant
327 CRM_Utils_Recent
::add($title,
331 $participant->contact_id
,
341 * Check whether the event is full for participation and return as
344 * @param int $eventId
346 * @param bool $returnEmptySeats
347 * Are we require number if empty seats.
348 * @param bool $includeWaitingList
349 * Consider waiting list in event full.
350 * calculation or not. (it is for cron job purpose)
352 * @param bool $returnWaitingCount
353 * @param bool $considerTestParticipant
355 * @return bool|int|null|string 1. false => If event having some empty spaces.@static
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
498 * @return array $optionsCount an array of each option id and total count
501 static function priceSetOptionsCount(
503 $skipParticipantIds = array(),
504 $considerCounted = TRUE,
505 $considerWaiting = TRUE,
506 $considerTestParticipants = FALSE
508 $optionsCount = array();
510 return $optionsCount;
513 $allStatusIds = array();
514 if ($considerCounted) {
515 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
516 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
518 if ($considerWaiting) {
519 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
520 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
522 $statusIdClause = NULL;
523 if (!empty($allStatusIds)) {
524 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
527 $isTestClause = NULL;
528 if (!$considerTestParticipants) {
529 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
532 $skipParticipantClause = NULL;
533 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
534 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
538 SELECT line.id as lineId,
539 line.entity_id as entity_id,
544 FROM civicrm_line_item line
545 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
546 AND participant.id = line.entity_id )
547 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
548 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
549 WHERE participant.event_id = %1
552 {$skipParticipantClause}";
554 $lineItem = CRM_Core_DAO
::executeQuery($sql, array(1 => array($eventId, 'Positive')));
555 while ($lineItem->fetch()) {
556 $count = $lineItem->count
;
560 if ($lineItem->html_type
== 'Text') {
561 $count *= $lineItem->qty
;
563 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
566 return $optionsCount;
570 * Get the empty spaces for event those we can allocate
571 * to pending participant to become confirm.
573 * @param int $eventId
576 * @return int $spaces Number of Empty Seats/null.
579 public static function pendingToConfirmSpaces($eventId) {
585 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
586 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
589 SELECT count(participant.id) as registered,
590 civicrm_event.max_participants
591 FROM civicrm_participant participant, civicrm_event
592 WHERE participant.event_id = {$eventId}
593 AND civicrm_event.id = participant.event_id
594 AND participant.status_id IN {$statusIds}
595 GROUP BY participant.event_id
597 $dao = CRM_Core_DAO
::executeQuery($query);
601 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
606 if ($dao->registered
>= $dao->max_participants
) {
611 return $dao->max_participants
- $dao->registered
;
614 //space in case no registeration yet.
615 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
619 * Combine all the importable fields from the lower levels object
621 * @param string $contactType
622 * @param bool $status
623 * @param bool $onlyParticipant
625 * @return array array of importable Fields
628 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE) {
629 if (!self
::$_importableFields) {
630 if (!$onlyParticipant) {
632 $fields = array('' => array('title' => ts('- do not import -')));
635 $fields = array('' => array('title' => ts('- Participant Fields -')));
642 $tmpFields = CRM_Event_DAO_Participant
::import();
645 'participant_note' => array(
646 'title' => ts('Participant Note'),
647 'name' => 'participant_note',
648 'headerPattern' => '/(participant.)?note$/i',
652 // Split status and status id into 2 fields
653 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
654 $participantStatus = array(
655 'participant_status' => array(
656 'title' => ts('Participant Status'),
657 'name' => 'participant_status',
658 'data_type' => CRM_Utils_Type
::T_STRING
,
661 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
663 // Split role and role id into 2 fields
664 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
665 $participantRole = array(
666 'participant_role' => array(
667 'title' => ts('Participant Role'),
668 'name' => 'participant_role',
669 'data_type' => CRM_Utils_Type
::T_STRING
,
672 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
675 'event_type' => array(
676 'title' => ts('Event Type'),
677 'name' => 'event_type',
678 'data_type' => CRM_Utils_Type
::T_STRING
,
682 $tmpContactField = $contactFields = array();
683 $contactFields = array();
684 if (!$onlyParticipant) {
685 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
687 // Using new Dedupe rule.
689 'contact_type' => $contactType,
690 'used' => 'Unsupervised',
692 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
694 if (is_array($fieldsArray)) {
695 foreach ($fieldsArray as $value) {
696 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
701 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
702 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
704 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
707 $title = $tmpContactField[trim($value)]['title'];
710 $tmpContactField[trim($value)]['title'] = $title;
714 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
715 if ($extIdentifier) {
716 $tmpContactField['external_identifier'] = $extIdentifier;
717 $tmpContactField['external_identifier']['title'] =
718 CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
720 $tmpFields['participant_contact_id']['title'] =
721 $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
723 $fields = array_merge($fields, $tmpContactField);
724 $fields = array_merge($fields, $tmpFields);
725 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
726 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
728 self
::$_importableFields = $fields;
731 return self
::$_importableFields;
735 * Combine all the exportable fields from the lower levels object
737 * @return array array of exportable Fields
740 public static function &exportableFields() {
741 if (!self
::$_exportableFields) {
742 if (!self
::$_exportableFields) {
743 self
::$_exportableFields = array();
748 $participantFields = CRM_Event_DAO_Participant
::export();
750 'participant_note' => array(
751 'title' => 'Participant Note',
752 'name' => 'participant_note',
756 $participantStatus = array(
757 'participant_status' => array(
758 'title' => 'Participant Status',
759 'name' => 'participant_status',
763 $participantRole = array(
764 'participant_role' => array(
765 'title' => 'Participant Role',
766 'name' => 'participant_role',
770 //CRM-13595 add event id to participant export
773 'title' => 'Event ID',
774 'name' => 'event_id',
778 'event_title' => array(
779 'title' => 'Event Title',
780 'name' => 'event_title',
784 $discountFields = CRM_Core_DAO_Discount
::export();
786 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventid, $eventtitle, $noteField, $discountFields);
789 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
790 self
::$_exportableFields = $fields;
793 return self
::$_exportableFields;
797 * Get the event name/sort name for a particular participation / participant
799 * @param int $participantId
800 * Id of the participant.
802 * @return array $name associated array with sort_name and event title
805 public static function participantDetails($participantId) {
807 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
808 FROM civicrm_participant
809 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
810 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
811 WHERE civicrm_participant.id = {$participantId}
813 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
816 while ($dao->fetch()) {
817 $details['name'] = $dao->name
;
818 $details['title'] = $dao->title
;
819 $details['cid'] = $dao->cid
;
826 * Get the values for pseudoconstants for name->value and reverse.
828 * @param array $defaults
829 * (reference) the default values, some of which need to be resolved.
830 * @param bool $reverse
831 * True if we want to resolve the values in the reverse direction (value -> name).
836 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
837 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
838 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
839 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
843 * This function is used to convert associative array names to values
846 * This function is used by both the web form layer and the api. Note that
847 * the api needs the name => value conversion, also the view layer typically
848 * requires value => name conversion
850 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
851 $id = $property . '_id';
853 $src = $reverse ?
$property : $id;
854 $dst = $reverse ?
$id : $property;
856 if (!array_key_exists($src, $defaults)) {
860 $look = $reverse ?
array_flip($lookup) : $lookup;
862 if (is_array($look)) {
863 if (!array_key_exists($defaults[$src], $look)) {
867 $defaults[$dst] = $look[$defaults[$src]];
872 * Delete the record that are associated with this participation
875 * Id of the participation to delete.
880 public static function deleteParticipant($id) {
881 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
883 $transaction = new CRM_Core_Transaction();
885 //delete activity record
887 'source_record_id' => $id,
888 // activity type id for event registration
889 'activity_type_id' => 5,
892 CRM_Activity_BAO_Activity
::deleteActivity($params);
894 // delete the participant payment record
895 // we need to do this since the cascaded constraints
896 // dont work with join tables
897 $p = array('participant_id' => $id);
898 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
900 // cleanup line items.
901 $participantsId = array();
902 $participantsId = self
::getAdditionalParticipantIds($id);
903 $participantsId[] = $id;
904 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
906 //delete note when participant deleted.
907 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
908 $noteId = key($note);
910 CRM_Core_BAO_Note
::del($noteId, FALSE);
913 $participant = new CRM_Event_DAO_Participant();
914 $participant->id
= $id;
915 $participant->delete();
917 $transaction->commit();
919 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
921 // delete the recently created Participant
922 $participantRecent = array(
924 'type' => 'Participant',
927 CRM_Utils_Recent
::del($participantRecent);
933 * Checks duplicate participants
935 * @param array $duplicates
936 * (reference ) an assoc array of name/value pairs.
937 * @param array $input
938 * An assosiative array of name /value pairs.
939 * from other function
941 * @return CRM_Contribute_BAO_Contribution object
944 public static function checkDuplicate($input, &$duplicates) {
945 $eventId = CRM_Utils_Array
::value('event_id', $input);
946 $contactId = CRM_Utils_Array
::value('contact_id', $input);
952 $clause[] = "event_id = %1";
953 $input[1] = array($eventId, 'Integer');
957 $clause[] = "contact_id = %2";
958 $input[2] = array($contactId, 'Integer');
961 if (empty($clause)) {
965 $clause = implode(' AND ', $clause);
967 $query = "SELECT id FROM civicrm_participant WHERE $clause";
968 $dao = CRM_Core_DAO
::executeQuery($query, $input);
970 while ($dao->fetch()) {
971 $duplicates[] = $dao->id
;
978 * Fix the event level
980 * When price sets are used as event fee, fee_level is set as ^A
981 * separated string. We need to change that string to comma
982 * separated string before using fee_level in view mode.
984 * @param string $eventLevel
985 * Event_leval string from db.
991 public static function fixEventLevel(&$eventLevel) {
992 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
993 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
995 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
996 $pos = strrpos($eventLevel, '(multiple participants)', 0);
998 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
1001 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1002 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1003 substr($eventLevel, 0, 1)
1006 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1007 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1008 substr($eventLevel, 0, -1)
1014 * Get the additional participant ids.
1016 * @param int $primaryParticipantId
1017 * Primary partycipant Id.
1018 * @param bool $excludeCancel
1019 * Do not include participant those are cancelled.
1021 * @param int $oldStatusId
1023 * @return array $additionalParticipantIds
1026 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1027 $additionalParticipantIds = array();
1028 if (!$primaryParticipantId) {
1029 return $additionalParticipantIds;
1032 $where = "participant.registered_by_id={$primaryParticipantId}";
1033 if ($excludeCancel) {
1034 $cancelStatusId = 0;
1035 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1036 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1037 $where .= " AND participant.status_id != {$cancelStatusId}";
1041 $where .= " AND participant.status_id = {$oldStatusId}";
1045 SELECT participant.id
1046 FROM civicrm_participant participant
1049 $dao = CRM_Core_DAO
::executeQuery($query);
1050 while ($dao->fetch()) {
1051 $additionalParticipantIds[$dao->id
] = $dao->id
;
1053 return $additionalParticipantIds;
1057 * Get the event fee info for given participant ids
1058 * either from line item table / participant table.
1060 * @param array $participantIds
1062 * @param bool $hasLineItems
1063 * Do fetch from line items.
1065 * @return array $feeDetails
1068 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1069 $feeDetails = array();
1070 if (!is_array($participantIds) ||
empty($participantIds)) {
1075 SELECT participant.id as id,
1076 participant.fee_level as fee_level,
1077 participant.fee_amount as fee_amount';
1078 $from = 'FROM civicrm_participant participant';
1079 if ($hasLineItems) {
1081 lineItem.id as lineId,
1082 lineItem.label as label,
1083 lineItem.qty as qty,
1084 lineItem.unit_price as unit_price,
1085 lineItem.line_total as line_total,
1086 field.label as field_title,
1087 field.html_type as html_type,
1088 field.id as price_field_id,
1089 value.id as price_field_value_id,
1090 value.description as description,
1091 IF( value.count, value.count, 0 ) as participant_count';
1093 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1094 AND lineItem.entity_id = participant.id )
1095 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1096 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1099 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1100 $query = "$select $from $where";
1102 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1103 $feeProperties = array('fee_level', 'fee_amount');
1104 $lineProperties = array(
1113 'participant_count',
1114 'price_field_value_id',
1117 while ($feeInfo->fetch()) {
1118 if ($hasLineItems) {
1119 foreach ($lineProperties as $property) {
1120 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1124 foreach ($feeProperties as $property) {
1125 $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1134 * Retrieve additional participants display-names and URL to view their participant records.
1135 * (excludes cancelled participants automatically)
1137 * @param int $primaryParticipantID
1138 * Id of primary participant record.
1140 * @return array $additionalParticipants $displayName => $viewUrl
1143 public static function getAdditionalParticipants($primaryParticipantID) {
1144 $additionalParticipantIDs = array();
1145 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1146 if (!empty($additionalParticipantIDs)) {
1147 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1148 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1149 $additionalParticipantID,
1152 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1153 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1154 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1157 $additionalParticipants[$additionalContactName] = $pViewURL;
1160 return $additionalParticipants;
1164 * Function for update primary and additional participant status
1166 * @param int $participantID
1167 * Primary participant's id.
1168 * @param int $oldStatusID
1169 * @param int $newStatusID
1170 * @param bool $updatePrimaryStatus
1175 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1176 if (!$participantID ||
!$oldStatusID) {
1180 if (!$newStatusID) {
1181 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1183 elseif ($updatePrimaryStatus) {
1184 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1187 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1189 if (!empty($cascadeAdditionalIds)) {
1190 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1191 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1192 $params = array(1 => array($newStatusID, 'Integer'));
1193 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1200 * Function for update status for given participant ids
1202 * @param int $participantIds
1203 * Array of participant ids.
1204 * @param int $statusId
1205 * Status id for participant.
1206 * @param bool $updateRegisterDate
1212 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1213 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1217 //lets update register date as we update status to keep track
1218 //when we did update status, useful for moving participant
1219 //from pending to expired.
1220 $setClause = "status_id = {$statusId}";
1221 if ($updateRegisterDate) {
1222 $setClause .= ", register_date = NOW()";
1225 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1228 UPDATE civicrm_participant
1230 WHERE id IN {$participantIdClause}";
1232 $dao = CRM_Core_DAO
::executeQuery($query);
1236 * Function takes participant ids and statuses
1237 * update status from $fromStatusId to $toStatusId
1238 * and send mail + create activities.
1240 * @param array $participantIds
1242 * @param int $toStatusId
1244 * @param int $fromStatusId
1248 * @param bool $returnResult
1249 * @param bool $skipCascadeRule
1254 static function transitionParticipants(
1255 $participantIds, $toStatusId,
1256 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1258 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1262 //thumb rule is if we triggering primary participant need to triggered additional
1263 $allParticipantIds = $primaryANDAdditonalIds = array();
1264 foreach ($participantIds as $id) {
1265 $allParticipantIds[] = $id;
1266 if (self
::isPrimaryParticipant($id)) {
1267 //filter additional as per status transition rules, CRM-5403
1268 if ($skipCascadeRule) {
1269 $additionalIds = self
::getAdditionalParticipantIds($id);
1272 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1274 if (!empty($additionalIds)) {
1275 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1276 $primaryANDAdditonalIds[$id] = $additionalIds;
1281 //get the unique participant ids,
1282 $allParticipantIds = array_unique($allParticipantIds);
1284 //pull required participants, contacts, events data, if not in hand
1285 static $eventDetails = array();
1286 static $domainValues = array();
1287 static $contactDetails = array();
1289 $contactIds = $eventIds = $participantDetails = array();
1291 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1292 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1293 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1297 //first thing is pull all necessory data from db.
1298 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1300 //get all participants data.
1301 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1302 $dao = CRM_Core_DAO
::executeQuery($query);
1303 while ($dao->fetch()) {
1304 $participantDetails[$dao->id
] = array(
1306 'role' => $participantRoles[$dao->role_id
],
1307 'is_test' => $dao->is_test
,
1308 'event_id' => $dao->event_id
,
1309 'status_id' => $dao->status_id
,
1310 'fee_amount' => $dao->fee_amount
,
1311 'contact_id' => $dao->contact_id
,
1312 'register_date' => $dao->register_date
,
1313 'registered_by_id' => $dao->registered_by_id
,
1315 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1316 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1319 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1320 $eventIds[$dao->event_id
] = $dao->event_id
;
1324 //get the domain values.
1325 if (empty($domainValues)) {
1326 // making all tokens available to templates.
1327 $domain = CRM_Core_BAO_Domain
::getDomain();
1329 'domain' => array('name', 'phone', 'address', 'email'),
1330 'contact' => CRM_Core_SelectValues
::contactTokens(),
1333 foreach ($tokens['domain'] as $token) {
1334 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1338 //get all required contacts detail.
1339 if (!empty($contactIds)) {
1340 // get the contact details.
1341 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1344 'CRM_Event_BAO_Participant'
1346 foreach ($currentContactDetails as $contactId => $contactValues) {
1347 $contactDetails[$contactId] = $contactValues;
1351 //get all required events detail.
1352 if (!empty($eventIds)) {
1353 foreach ($eventIds as $eventId) {
1354 //retrieve event information
1355 $eventParams = array('id' => $eventId);
1356 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1358 //get default participant role.
1359 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1361 //get the location info
1362 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1363 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1367 //now we are ready w/ all required data.
1368 //take a decision as per statuses.
1371 $toStatus = $statusTypes[$toStatusId];
1372 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1374 switch ($toStatus) {
1375 case 'Pending from waitlist':
1376 case 'Pending from approval':
1377 switch ($fromStatus) {
1379 case 'Awaiting approval':
1380 $emailType = 'Confirm';
1386 //no matter from where u come send expired mail.
1387 $emailType = $toStatus;
1391 //no matter from where u come send cancel mail.
1392 $emailType = $toStatus;
1396 //as we process additional w/ primary, there might be case if user
1397 //select primary as well as additionals, so avoid double processing.
1398 $processedParticipantIds = array();
1399 $mailedParticipants = array();
1401 //send mails and update status.
1402 foreach ($participantDetails as $participantId => $participantValues) {
1403 $updateParticipantIds = array();
1404 if (in_array($participantId, $processedParticipantIds)) {
1408 //check is it primary and has additional.
1409 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1410 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1413 $mail = self
::sendTransitionParticipantMail($additonalId,
1414 $participantDetails[$additonalId],
1415 $eventDetails[$participantDetails[$additonalId]['event_id']],
1416 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1421 //get the mail participant ids
1423 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1426 $updateParticipantIds[] = $additonalId;
1427 $processedParticipantIds[] = $additonalId;
1431 //now send email appropriate mail to primary.
1433 $mail = self
::sendTransitionParticipantMail($participantId,
1435 $eventDetails[$participantValues['event_id']],
1436 $contactDetails[$participantValues['contact_id']],
1441 //get the mail participant ids
1443 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1447 //now update status of group/one at once.
1448 $updateParticipantIds[] = $participantId;
1450 //update the register date only when we,
1451 //move participant to pending class, CRM-6496
1452 $updateRegisterDate = FALSE;
1453 if (array_key_exists($toStatusId, $pendingStatuses)) {
1454 $updateRegisterDate = TRUE;
1456 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1457 $processedParticipantIds[] = $participantId;
1460 //return result for cron.
1461 if ($returnResult) {
1463 'mailedParticipants' => $mailedParticipants,
1464 'updatedParticipantIds' => $processedParticipantIds,
1472 * Send mail and create activity
1473 * when participant status changed.
1475 * @param int $participantId
1477 * @param array $participantValues
1478 * Participant detail values. status id for participants.
1479 * @param array $eventDetails
1480 * Required event details.
1481 * @param array $contactDetails
1482 * Required contact details.
1483 * @param array $domainValues
1484 * Required domain values.
1485 * @param string $mailType
1486 * (eg 'approval', 'confirm', 'expired' ).
1493 static function sendTransitionParticipantMail(
1504 //don't send confirmation mail to additional
1505 //since only primary able to confirm registration.
1506 if (!empty($participantValues['registered_by_id']) &&
1507 $mailType == 'Confirm'
1511 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1514 $contactId = $participantValues['contact_id'];
1515 $participantName = $contactDetails['display_name'];
1517 //calculate the checksum value.
1518 $checksumValue = NULL;
1519 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1520 $checksumLife = 'inf';
1521 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1523 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1525 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1528 //take a receipt from as event else domain.
1529 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1530 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1531 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1534 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1536 'groupName' => 'msg_tpl_workflow_event',
1537 'valueName' => 'participant_' . strtolower($mailType),
1538 'contactId' => $contactId,
1539 'tplParams' => array(
1540 'contact' => $contactDetails,
1541 'domain' => $domainValues,
1542 'participant' => $participantValues,
1543 'event' => $eventDetails,
1544 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1545 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1546 'isAdditional' => $participantValues['registered_by_id'],
1547 'isExpired' => $mailType == 'Expired',
1548 'isConfirm' => $mailType == 'Confirm',
1549 'checksumValue' => $checksumValue,
1551 'from' => $receiptFrom,
1552 'toName' => $participantName,
1553 'toEmail' => $toEmail,
1554 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1555 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1559 // 3. create activity record.
1561 $now = date('YmdHis');
1562 $activityType = 'Event Registration';
1563 $activityParams = array(
1564 'subject' => $subject,
1565 'source_contact_id' => $contactId,
1566 'source_record_id' => $participantId,
1567 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1571 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1572 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1573 'is_test' => $participantValues['is_test'],
1577 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1578 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1587 * Get participant status change message.
1589 * @param int $participantId
1590 * @param $statusChangeTo
1591 * @param int $fromStatusId
1595 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1597 $results = self
::transitionParticipants(array($participantId),
1598 $statusChangeTo, $fromStatusId, TRUE
1601 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1602 //give user message only when mail has sent.
1603 if (is_array($results) && !empty($results)) {
1604 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1605 foreach ($results['updatedParticipantIds'] as $processedId) {
1606 if (is_array($results['mailedParticipants']) &&
1607 array_key_exists($processedId, $results['mailedParticipants'])
1609 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1611 1 => $allStatuses[$statusChangeTo],
1612 2 => $results['mailedParticipants'][$processedId],
1624 * Get event full and waiting list message.
1626 * @param int $eventId
1627 * @param int $participantId
1631 public static function eventFullMessage($eventId, $participantId = NULL) {
1632 $eventfullMsg = $dbStatusId = NULL;
1633 $checkEventFull = TRUE;
1634 if ($participantId) {
1635 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1636 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1637 //participant already in counted status no need to check for event full messages.
1638 $checkEventFull = FALSE;
1643 if (!$eventId ||
!$checkEventFull) {
1644 return $eventfullMsg;
1647 //event is truly full.
1648 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1649 if (is_string($emptySeats) && $emptySeats !== NULL) {
1650 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1651 $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(
1652 1 => $maxParticipants
1656 $hasWaiting = FALSE;
1657 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1658 if (is_numeric($waitListedCount)) {
1660 //only current processing participant is on waitlist.
1661 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1662 $hasWaiting = FALSE;
1667 $waitingStatusId = array_search('On waitlist',
1668 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1670 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1671 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1674 $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.",
1676 1 => $viewWaitListUrl,
1677 2 => $waitListedCount,
1682 return $eventfullMsg;
1686 * Check for whether participant is primary or not
1688 * @param int $participantId
1690 * @return true if participant is primary
1692 public static function isPrimaryParticipant($participantId) {
1694 $participant = new CRM_Event_DAO_Participant();
1695 $participant->registered_by_id
= $participantId;
1697 if ($participant->find(TRUE)) {
1704 * Get additional participant Ids for cascading with primary participant status
1706 * @param int $participantId
1708 * @param int $oldStatusId
1710 * @param int $newStatusId
1713 * @return true if allowed
1715 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1717 $additionalParticipantIds = array();
1719 static $participantStatuses = array();
1721 if (empty($participantStatuses)) {
1722 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1725 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1726 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1728 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1731 return $additionalParticipantIds;
1735 * Get participant record count for a Contact
1737 * @param int $contactID
1739 * @return int count of participant records
1742 public static function getContactParticipantCount($contactID) {
1743 $query = "SELECT count(*)
1744 FROM civicrm_participant
1745 WHERE civicrm_participant.contact_id = {$contactID} AND
1746 civicrm_participant.is_test = 0";
1747 return CRM_Core_DAO
::singleValueQuery($query);
1751 * Get participant ids by contribution id
1753 * @param int $contributionId
1755 * @param bool $excludeCancelled
1756 * Exclude cancelled additional participant.
1758 * @return array $participantsId
1761 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1764 if (!$contributionId) {
1768 // get primary participant id
1769 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1770 $participantId = CRM_Core_DAO
::singleValueQuery($query);
1772 // get additional participant ids (including cancelled)
1773 if ($participantId) {
1774 $ids = array_merge(array(
1776 ), self
::getAdditionalParticipantIds($participantId,
1785 * Get additional Participant edit & view url .
1787 * @param array $participantIds
1788 * An array of additional participant ids.
1790 * @return array of Urls.
1793 public static function getAdditionalParticipantUrl($participantIds) {
1794 foreach ($participantIds as $value) {
1796 $details = self
::participantDetails($value);
1797 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1798 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1800 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1801 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1803 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1804 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1810 * To create trxn entry if an event has discount.
1812 * @param int $eventID
1814 * @param array $contributionParams
1815 * Contribution params.
1821 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel) {
1823 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID, 'civicrm_event');
1824 if (!empty($checkDiscount)) {
1825 $feeLevel = current($feeLevel);
1826 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1827 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1828 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1829 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1831 1 => array($priceSetId, 'Integer'),
1832 2 => array($feeLevel, 'String')
1834 $mainAmount = CRM_Core_DAO
::singleValueQuery($query, $params);
1835 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
1836 $contributionParams['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
1837 $contributionParams['contribution']->financial_type_id
, $relationTypeId);
1838 if (!empty($contributionParams['trxnParams']['from_financial_account_id'])) {
1839 $contributionParams['trxnParams']['total_amount'] = $mainAmount - $contributionParams['total_amount'];
1840 $contributionParams['trxnParams']['payment_processor_id'] = $contributionParams['trxnParams']['payment_instrument_id'] =
1841 $contributionParams['trxnParams']['check_number'] = $contributionParams['trxnParams']['trxn_id'] =
1842 $contributionParams['trxnParams']['net_amount'] = $contributionParams['trxnParams']['fee_amount'] = NULL;
1844 CRM_Core_BAO_FinancialTrxn
::create($contributionParams['trxnParams']);
1851 * Delete participants of contact
1855 * @param int $contactId
1860 public static function deleteContactParticipant($contactId) {
1861 $participant = new CRM_Event_DAO_Participant();
1862 $participant->contact_id
= $contactId;
1863 $participant->find();
1864 while ($participant->fetch()) {
1865 self
::deleteParticipant($participant->id
);
1870 * @param array $params
1871 * @param int $participantId
1872 * @param int $contributionId
1874 * @param array $lineItems
1875 * @param $paidAmount
1876 * @param int $priceSetId
1878 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) {
1879 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1880 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1881 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1882 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($participantId, 'participant');
1883 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
1887 // get the submitted
1888 foreach ($feeBlock as $id => $values) {
1889 CRM_Price_BAO_LineItem
::format($id, $params, $values, $submittedLineItems);
1890 $submittedFieldId[] = CRM_Utils_Array
::retrieveValueRecursive($submittedLineItems, 'price_field_id');
1892 if (!empty($submittedLineItems)) {
1893 $insertLines = $submittedLineItems;
1895 $submittedFieldValueIds = array_keys($submittedLineItems);
1896 $updateLines = array();
1897 foreach ($previousLineItems as $id => $previousLineItem) {
1898 // check through the submitted items if the previousItem exists,
1899 // if found in submitted items, do not use it for new item creations
1900 if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
1901 // if submitted line items are existing don't fire INSERT query
1902 unset($insertLines[$previousLineItem['price_field_value_id']]);
1903 // for updating the line items i.e. use-case - once deselect-option selecting again
1904 if (($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) ||
1905 ($submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1)
1907 $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
1908 $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
1913 $submittedFields = implode(', ', $submittedFieldId);
1914 $submittedFieldValues = implode(', ', $submittedFieldValueIds);
1916 if (!empty($submittedFields) && !empty($submittedFieldValues)) {
1917 $updateLineItem = "UPDATE civicrm_line_item li
1918 INNER JOIN civicrm_financial_item fi
1919 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1921 li.line_total = 0.00,
1922 li.tax_amount = NULL
1923 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
1924 (price_field_value_id NOT IN ({$submittedFieldValues}))
1926 CRM_Core_DAO
::executeQuery($updateLineItem);
1928 // gathering necessary info to record negative (deselected) financial_item
1929 $updateFinancialItem = "
1930 SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
1931 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1932 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
1933 GROUP BY li.entity_table, li.entity_id, price_field_value_id
1935 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1936 $trxn = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId, 'ASC', TRUE);
1937 $trxnId['id'] = $trxn['financialTrxnId'];
1938 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1939 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
1940 $updateFinancialItemInfoValues = array();
1942 while ($updateFinancialItemInfoDAO->fetch()) {
1943 $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
1944 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
1945 // the below params are not needed
1946 unset($updateFinancialItemInfoValues['id']);
1947 unset($updateFinancialItemInfoValues['created_date']);
1948 // if not submitted and difference is not 0 make it negative
1949 if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
1950 // INSERT negative financial_items
1951 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
1952 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1953 // INSERT negative financial_items for tax amount
1954 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
1955 $updateFinancialItemInfoValues['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
1956 $updateFinancialItemInfoValues['description'] = $taxTerm;
1957 if ($updateFinancialItemInfoValues['financial_type_id']) {
1958 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
1960 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1963 // if submitted and difference is 0 add a positive entry again
1964 elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
1965 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
1966 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1967 // INSERT financial_items for tax amount
1968 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
1969 isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
1971 $updateFinancialItemInfoValues['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
1972 $updateFinancialItemInfoValues['description'] = $taxTerm;
1973 if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
1974 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
1976 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1981 elseif (empty($submittedFields) && empty($submittedFieldValues)) {
1982 $updateLineItem = "UPDATE civicrm_line_item li
1983 INNER JOIN civicrm_financial_item fi
1984 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1986 li.line_total = 0.00,
1987 li.tax_amount = NULL
1988 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
1989 CRM_Core_DAO
::executeQuery($updateLineItem);
1991 if (!empty($updateLines)) {
1992 foreach ($updateLines as $valueId => $vals) {
1993 if (isset($vals['tax_amount'])) {
1994 $taxAmount = $vals['tax_amount'];
1997 $taxAmount = "NULL";
2000 UPDATE civicrm_line_item li
2001 SET li.qty = {$vals['qty']},
2002 li.line_total = {$vals['line_total']},
2003 li.tax_amount = {$taxAmount},
2004 li.unit_price = {$vals['unit_price']},
2005 li.label = '{$vals['label']}'
2006 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
2007 (price_field_value_id = {$valueId})
2009 CRM_Core_DAO
::executeQuery($updateLineItem);
2012 // insert new 'adjusted amount' transaction entry and update contribution entry.
2013 // ensure entity_financial_trxn table has a linking of it.
2014 // insert new line items
2015 if (!empty($insertLines)) {
2016 foreach ($insertLines as $valueId => $lineParams) {
2017 $lineParams['entity_table'] = 'civicrm_participant';
2018 $lineParams['entity_id'] = $participantId;
2019 $lineParams['contribution_id'] = $contributionId;
2020 $lineObj = CRM_Price_BAO_LineItem
::create($lineParams);
2024 // the recordAdjustedAmt code would execute over here
2025 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
2026 if (count($ids) > 1) {
2028 foreach ($ids as $val) {
2029 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, 'civicrm_participant');
2031 $updatedAmount = $total;
2034 $updatedAmount = $params['amount'];
2036 if (strlen($params['tax_amount']) != 0) {
2037 $taxAmount = $params['tax_amount'];
2040 $taxAmount = "NULL";
2042 self
::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount);
2044 $fetchCon = array('id' => $contributionId);
2045 $updatedContribution = CRM_Contribute_BAO_Contribution
::retrieve($fetchCon, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2046 // insert financial items
2047 if (!empty($insertLines)) {
2048 foreach ($insertLines as $valueId => $lineParams) {
2049 $lineParams['entity_table'] = 'civicrm_participant';
2050 $lineParams['entity_id'] = $participantId;
2051 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams, CRM_Core_DAO
::$_nullArray);
2052 // insert financial items
2053 // ensure entity_financial_trxn table has a linking of it.
2054 $prevItem = CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution);
2055 if (isset($lineObj->tax_amount
)) {
2056 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE);
2061 // update participant fee_amount column
2062 $partUpdateFeeAmt['id'] = $participantId;
2063 foreach ($lineItems as $lineValue) {
2064 if ($lineValue['price_field_value_id']) {
2065 $line[$lineValue['price_field_value_id']] = $lineValue['label'] . ' - ' . $lineValue['qty'];
2069 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
2070 $partUpdateFeeAmt['fee_amount'] = $params['amount'];
2071 self
::add($partUpdateFeeAmt);
2074 self
::addActivityForSelection($participantId, 'Change Registration');
2078 * @param $updatedAmount
2079 * @param $paidAmount
2080 * @param int $contributionId
2082 public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL) {
2083 $balanceAmt = $updatedAmount - $paidAmount;
2084 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2085 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
2086 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
2087 $completedStatusId = array_search('Completed', $contributionStatuses);
2089 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
2092 if ($balanceAmt > 0 && $paidAmount != 0) {
2093 $contributionStatusVal = $partiallyPaidStatusId;
2095 elseif ($balanceAmt < 0 && $paidAmount != 0) {
2096 $contributionStatusVal = $pendingRefundStatusId;
2098 elseif ($paidAmount == 0) {
2099 //skip updating the contribution status if no payment is made
2101 $updatedContributionDAO->cancel_date
= 'null';
2102 $updatedContributionDAO->cancel_reason
= NULL;
2104 // update contribution status and total amount without trigger financial code
2105 // as this is handled in current BAO function used for change selection
2106 $updatedContributionDAO->id
= $contributionId;
2108 $updatedContributionDAO->contribution_status_id
= $contributionStatusVal;
2110 $updatedContributionDAO->total_amount
= $updatedAmount;
2111 $updatedContributionDAO->tax_amount
= $taxAmount;
2112 $updatedContributionDAO->save();
2114 $ftDetail = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
2115 // adjusted amount financial_trxn creation
2116 if (empty($ftDetail['trxn_id'])) {
2117 $updatedContribution =
2118 CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contributionId), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2119 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2120 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($updatedContribution->financial_type_id
, $relationTypeId);
2122 $adjustedTrxnValues = array(
2123 'from_financial_account_id' => NULL,
2124 'to_financial_account_id' => $toFinancialAccount,
2125 'total_amount' => $balanceAmt,
2126 'status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
2127 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
2128 'contribution_id' => $updatedContribution->id
,
2129 'trxn_date' => date('YmdHis'),
2130 'currency' => $updatedContribution->currency
2132 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
2135 // update the financial trxn amount as well, as the fee selections has been updated
2136 if ($balanceAmt != $ftDetail['total_amount']) {
2137 CRM_Core_DAO
::setFieldValue('CRM_Core_BAO_FinancialTrxn', $ftDetail['trxn_id'], 'total_amount', $balanceAmt);
2144 * @param int $participantId
2145 * @param $activityType
2147 * @throws CRM_Core_Exception
2149 public static function addActivityForSelection($participantId, $activityType) {
2150 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
2151 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
2153 $date = CRM_Utils_Date
::currentDBDate();
2154 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
2155 $eventTitle = $event[$eventId];
2156 $subject = "Registration selections changed for $eventTitle";
2157 $targetCid = $contactId;
2158 $srcRecId = $participantId;
2161 $activityParams = array(
2162 'source_contact_id' => $targetCid,
2163 'source_record_id' => $srcRecId,
2164 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
2168 'subject' => $subject,
2169 'activity_date_time' => $date,
2170 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
2174 'skipRecentView' => TRUE,
2177 // create activity with target contacts
2178 $session = CRM_Core_Session
::singleton();
2179 $id = $session->get('userID');
2181 $activityParams['source_contact_id'] = $id;
2182 $activityParams['target_contact_id'][] = $targetCid;
2184 CRM_Activity_BAO_Activity
::create($activityParams);
2188 * Get options for a given field.
2189 * @see CRM_Core_DAO::buildOptions
2191 * @param string $fieldName
2192 * @param string $context
2193 * : @see CRM_Core_DAO::buildOptionsContext.
2194 * @param array $props
2195 * : whatever is known about this dao object.
2197 * @return Array|bool
2199 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2200 $params = array('condition' => array());
2202 if ($fieldName == 'status_id' && $context != 'validate') {
2203 // Get rid of cart-related option if disabled
2204 // FIXME: Why does this option even exist if cart is disabled?
2205 if (!CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
, 'enable_cart')) {
2206 $params['condition'][] = "name <> 'Pending in cart'";
2210 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);