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.
358 static function eventFull(
360 $returnEmptySeats = FALSE,
361 $includeWaitingList = TRUE,
362 $returnWaitingCount = FALSE,
363 $considerTestParticipant = FALSE
370 // consider event is full when.
371 // 1. (count(is_counted) >= event_size) or
372 // 2. (count(participants-with-status-on-waitlist) > 0)
373 // It might be case there are some empty spaces and still event
374 // is full, as waitlist might represent group require spaces > empty.
376 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
377 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
378 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
379 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
381 //when we do require only waiting count don't consider counted.
382 if (!$returnWaitingCount && !empty($countedStatuses)) {
383 $allStatusIds = array_keys($countedStatuses);
386 $where = array(' event.id = %1 ');
387 if (!$considerTestParticipant) {
388 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
390 if (!empty($participantRoles)) {
391 $where[] = ' participant.role_id IN ( ' . implode(', ', array_keys($participantRoles)) . ' ) ';
394 $eventParams = array(1 => array($eventId, 'Positive'));
396 //in case any waiting, straight forward event is full.
397 if ($includeWaitingList && $onWaitlistStatusId) {
399 //build the where clause.
400 $whereClause = ' WHERE ' . implode(' AND ', $where);
401 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
402 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
405 SELECT participant.id id,
406 event.event_full_text as event_full_text
407 FROM civicrm_participant participant
408 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
411 $eventFullText = ts('This event is full.');
412 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
413 while ($participants->fetch()) {
414 //oops here event is full and we don't want waiting count.
415 if ($returnWaitingCount) {
416 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
419 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
424 //consider only counted participants.
425 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
426 $whereClause = ' WHERE ' . implode(' AND ', $where);
427 $eventSeatsWhere = implode(' AND ', $where);
430 SELECT participant.id id,
431 event.event_full_text as event_full_text,
432 event.max_participants as max_participants
433 FROM civicrm_participant participant
434 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
437 $eventMaxSeats = NULL;
438 $eventFullText = ts('This event is full.');
439 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
440 while ($participants->fetch()) {
441 if ($participants->event_full_text
) {
442 $eventFullText = $participants->event_full_text
;
444 $eventMaxSeats = $participants->max_participants
;
445 //don't have limit for event seats.
446 if ($participants->max_participants
== NULL) {
451 //get the total event seats occupied by these participants.
452 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
454 if ($eventRegisteredSeats) {
455 if ($eventRegisteredSeats >= $eventMaxSeats) {
456 $result = $eventFullText;
458 elseif ($returnEmptySeats) {
459 $result = $eventMaxSeats - $eventRegisteredSeats;
465 SELECT event.event_full_text,
466 event.max_participants
467 FROM civicrm_event event
468 WHERE event.id = %1';
469 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
470 while ($event->fetch()) {
471 $eventFullText = $event->event_full_text
;
472 $eventMaxSeats = $event->max_participants
;
476 // no limit for registration.
477 if ($eventMaxSeats == NULL) {
480 if ($eventMaxSeats) {
481 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
484 return $eventFullText;
488 * Return the array of all price set field options,
489 * with total participant count that field going to carry.
491 * @param int $eventId
493 * @param array $skipParticipantIds
494 * An array of participant ids those we should skip.
495 * @param bool $considerCounted
496 * @param bool $considerWaiting
497 * @param bool $considerTestParticipants
499 * @return array $optionsCount an array of each option id and total count
502 static function priceSetOptionsCount(
504 $skipParticipantIds = array(),
505 $considerCounted = TRUE,
506 $considerWaiting = TRUE,
507 $considerTestParticipants = FALSE
509 $optionsCount = array();
511 return $optionsCount;
514 $allStatusIds = array();
515 if ($considerCounted) {
516 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
517 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
519 if ($considerWaiting) {
520 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
521 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
523 $statusIdClause = NULL;
524 if (!empty($allStatusIds)) {
525 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
528 $isTestClause = NULL;
529 if (!$considerTestParticipants) {
530 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
533 $skipParticipantClause = NULL;
534 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
535 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
539 SELECT line.id as lineId,
540 line.entity_id as entity_id,
545 FROM civicrm_line_item line
546 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
547 AND participant.id = line.entity_id )
548 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
549 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
550 WHERE participant.event_id = %1
553 {$skipParticipantClause}";
555 $lineItem = CRM_Core_DAO
::executeQuery($sql, array(1 => array($eventId, 'Positive')));
556 while ($lineItem->fetch()) {
557 $count = $lineItem->count
;
561 if ($lineItem->html_type
== 'Text') {
562 $count *= $lineItem->qty
;
564 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
567 return $optionsCount;
571 * Get the empty spaces for event those we can allocate
572 * to pending participant to become confirm.
574 * @param int $eventId
577 * @return int $spaces Number of Empty Seats/null.
580 public static function pendingToConfirmSpaces($eventId) {
586 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
587 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
590 SELECT count(participant.id) as registered,
591 civicrm_event.max_participants
592 FROM civicrm_participant participant, civicrm_event
593 WHERE participant.event_id = {$eventId}
594 AND civicrm_event.id = participant.event_id
595 AND participant.status_id IN {$statusIds}
596 GROUP BY participant.event_id
598 $dao = CRM_Core_DAO
::executeQuery($query);
602 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
607 if ($dao->registered
>= $dao->max_participants
) {
612 return $dao->max_participants
- $dao->registered
;
615 //space in case no registeration yet.
616 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
620 * Combine all the importable fields from the lower levels object
622 * @param string $contactType
623 * @param bool $status
624 * @param bool $onlyParticipant
626 * @return array array of importable Fields
629 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE) {
630 if (!self
::$_importableFields) {
631 if (!$onlyParticipant) {
633 $fields = array('' => array('title' => ts('- do not import -')));
636 $fields = array('' => array('title' => ts('- Participant Fields -')));
643 $tmpFields = CRM_Event_DAO_Participant
::import();
646 'participant_note' => array(
647 'title' => ts('Participant Note'),
648 'name' => 'participant_note',
649 'headerPattern' => '/(participant.)?note$/i',
653 // Split status and status id into 2 fields
654 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
655 $participantStatus = array(
656 'participant_status' => array(
657 'title' => ts('Participant Status'),
658 'name' => 'participant_status',
659 'data_type' => CRM_Utils_Type
::T_STRING
,
662 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
664 // Split role and role id into 2 fields
665 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
666 $participantRole = array(
667 'participant_role' => array(
668 'title' => ts('Participant Role'),
669 'name' => 'participant_role',
670 'data_type' => CRM_Utils_Type
::T_STRING
,
673 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
676 'event_type' => array(
677 'title' => ts('Event Type'),
678 'name' => 'event_type',
679 'data_type' => CRM_Utils_Type
::T_STRING
,
683 $tmpContactField = $contactFields = array();
684 $contactFields = array();
685 if (!$onlyParticipant) {
686 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
688 // Using new Dedupe rule.
690 'contact_type' => $contactType,
691 'used' => 'Unsupervised',
693 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
695 if (is_array($fieldsArray)) {
696 foreach ($fieldsArray as $value) {
697 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
702 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
703 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
705 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
708 $title = $tmpContactField[trim($value)]['title'];
711 $tmpContactField[trim($value)]['title'] = $title;
715 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
716 if ($extIdentifier) {
717 $tmpContactField['external_identifier'] = $extIdentifier;
718 $tmpContactField['external_identifier']['title'] =
719 CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
721 $tmpFields['participant_contact_id']['title'] =
722 $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
724 $fields = array_merge($fields, $tmpContactField);
725 $fields = array_merge($fields, $tmpFields);
726 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
727 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
729 self
::$_importableFields = $fields;
732 return self
::$_importableFields;
736 * Combine all the exportable fields from the lower levels object
738 * @return array array of exportable Fields
741 public static function &exportableFields() {
742 if (!self
::$_exportableFields) {
743 if (!self
::$_exportableFields) {
744 self
::$_exportableFields = array();
749 $participantFields = CRM_Event_DAO_Participant
::export();
751 'participant_note' => array(
752 'title' => 'Participant Note',
753 'name' => 'participant_note',
757 $participantStatus = array(
758 'participant_status' => array(
759 'title' => 'Participant Status',
760 'name' => 'participant_status',
764 $participantRole = array(
765 'participant_role' => array(
766 'title' => 'Participant Role',
767 'name' => 'participant_role',
771 //CRM-13595 add event id to participant export
774 'title' => 'Event ID',
775 'name' => 'event_id',
779 'event_title' => array(
780 'title' => 'Event Title',
781 'name' => 'event_title',
785 $discountFields = CRM_Core_DAO_Discount
::export();
787 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventid, $eventtitle, $noteField, $discountFields);
790 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
791 self
::$_exportableFields = $fields;
794 return self
::$_exportableFields;
798 * Get the event name/sort name for a particular participation / participant
800 * @param int $participantId
801 * Id of the participant.
803 * @return array $name associated array with sort_name and event title
806 public static function participantDetails($participantId) {
808 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
809 FROM civicrm_participant
810 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
811 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
812 WHERE civicrm_participant.id = {$participantId}
814 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
817 while ($dao->fetch()) {
818 $details['name'] = $dao->name
;
819 $details['title'] = $dao->title
;
820 $details['cid'] = $dao->cid
;
827 * Get the values for pseudoconstants for name->value and reverse.
829 * @param array $defaults
830 * (reference) the default values, some of which need to be resolved.
831 * @param bool $reverse
832 * True if we want to resolve the values in the reverse direction (value -> name).
837 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
838 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
839 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
840 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
844 * This function is used to convert associative array names to values
847 * This function is used by both the web form layer and the api. Note that
848 * the api needs the name => value conversion, also the view layer typically
849 * requires value => name conversion
851 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
852 $id = $property . '_id';
854 $src = $reverse ?
$property : $id;
855 $dst = $reverse ?
$id : $property;
857 if (!array_key_exists($src, $defaults)) {
861 $look = $reverse ?
array_flip($lookup) : $lookup;
863 if (is_array($look)) {
864 if (!array_key_exists($defaults[$src], $look)) {
868 $defaults[$dst] = $look[$defaults[$src]];
873 * Delete the record that are associated with this participation
876 * Id of the participation to delete.
881 public static function deleteParticipant($id) {
882 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
884 $transaction = new CRM_Core_Transaction();
886 //delete activity record
888 'source_record_id' => $id,
889 // activity type id for event registration
890 'activity_type_id' => 5,
893 CRM_Activity_BAO_Activity
::deleteActivity($params);
895 // delete the participant payment record
896 // we need to do this since the cascaded constraints
897 // dont work with join tables
898 $p = array('participant_id' => $id);
899 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
901 // cleanup line items.
902 $participantsId = array();
903 $participantsId = self
::getAdditionalParticipantIds($id);
904 $participantsId[] = $id;
905 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
907 //delete note when participant deleted.
908 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
909 $noteId = key($note);
911 CRM_Core_BAO_Note
::del($noteId, FALSE);
914 $participant = new CRM_Event_DAO_Participant();
915 $participant->id
= $id;
916 $participant->delete();
918 $transaction->commit();
920 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
922 // delete the recently created Participant
923 $participantRecent = array(
925 'type' => 'Participant',
928 CRM_Utils_Recent
::del($participantRecent);
934 * Checks duplicate participants
936 * @param array $duplicates
937 * (reference ) an assoc array of name/value pairs.
938 * @param array $input
939 * An assosiative array of name /value pairs.
940 * from other function
942 * @return CRM_Contribute_BAO_Contribution object
945 public static function checkDuplicate($input, &$duplicates) {
946 $eventId = CRM_Utils_Array
::value('event_id', $input);
947 $contactId = CRM_Utils_Array
::value('contact_id', $input);
953 $clause[] = "event_id = %1";
954 $input[1] = array($eventId, 'Integer');
958 $clause[] = "contact_id = %2";
959 $input[2] = array($contactId, 'Integer');
962 if (empty($clause)) {
966 $clause = implode(' AND ', $clause);
968 $query = "SELECT id FROM civicrm_participant WHERE $clause";
969 $dao = CRM_Core_DAO
::executeQuery($query, $input);
971 while ($dao->fetch()) {
972 $duplicates[] = $dao->id
;
979 * Fix the event level
981 * When price sets are used as event fee, fee_level is set as ^A
982 * separated string. We need to change that string to comma
983 * separated string before using fee_level in view mode.
985 * @param string $eventLevel
986 * Event_leval string from db.
992 public static function fixEventLevel(&$eventLevel) {
993 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
994 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
996 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
997 $pos = strrpos($eventLevel, '(multiple participants)', 0);
999 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
1002 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1003 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1004 substr($eventLevel, 0, 1)
1007 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1008 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1009 substr($eventLevel, 0, -1)
1015 * Get the additional participant ids.
1017 * @param int $primaryParticipantId
1018 * Primary partycipant Id.
1019 * @param bool $excludeCancel
1020 * Do not include participant those are cancelled.
1022 * @param int $oldStatusId
1024 * @return array $additionalParticipantIds
1027 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1028 $additionalParticipantIds = array();
1029 if (!$primaryParticipantId) {
1030 return $additionalParticipantIds;
1033 $where = "participant.registered_by_id={$primaryParticipantId}";
1034 if ($excludeCancel) {
1035 $cancelStatusId = 0;
1036 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1037 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1038 $where .= " AND participant.status_id != {$cancelStatusId}";
1042 $where .= " AND participant.status_id = {$oldStatusId}";
1046 SELECT participant.id
1047 FROM civicrm_participant participant
1050 $dao = CRM_Core_DAO
::executeQuery($query);
1051 while ($dao->fetch()) {
1052 $additionalParticipantIds[$dao->id
] = $dao->id
;
1054 return $additionalParticipantIds;
1058 * Get the event fee info for given participant ids
1059 * either from line item table / participant table.
1061 * @param array $participantIds
1063 * @param bool $hasLineItems
1064 * Do fetch from line items.
1066 * @return array $feeDetails
1069 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1070 $feeDetails = array();
1071 if (!is_array($participantIds) ||
empty($participantIds)) {
1076 SELECT participant.id as id,
1077 participant.fee_level as fee_level,
1078 participant.fee_amount as fee_amount';
1079 $from = 'FROM civicrm_participant participant';
1080 if ($hasLineItems) {
1082 lineItem.id as lineId,
1083 lineItem.label as label,
1084 lineItem.qty as qty,
1085 lineItem.unit_price as unit_price,
1086 lineItem.line_total as line_total,
1087 field.label as field_title,
1088 field.html_type as html_type,
1089 field.id as price_field_id,
1090 value.id as price_field_value_id,
1091 value.description as description,
1092 IF( value.count, value.count, 0 ) as participant_count';
1094 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1095 AND lineItem.entity_id = participant.id )
1096 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1097 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1100 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1101 $query = "$select $from $where";
1103 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1104 $feeProperties = array('fee_level', 'fee_amount');
1105 $lineProperties = array(
1114 'participant_count',
1115 'price_field_value_id',
1118 while ($feeInfo->fetch()) {
1119 if ($hasLineItems) {
1120 foreach ($lineProperties as $property) {
1121 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1125 foreach ($feeProperties as $property) {
1126 $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1135 * Retrieve additional participants display-names and URL to view their participant records.
1136 * (excludes cancelled participants automatically)
1138 * @param int $primaryParticipantID
1139 * Id of primary participant record.
1141 * @return array $additionalParticipants $displayName => $viewUrl
1144 public static function getAdditionalParticipants($primaryParticipantID) {
1145 $additionalParticipantIDs = array();
1146 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1147 if (!empty($additionalParticipantIDs)) {
1148 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1149 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1150 $additionalParticipantID,
1153 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1154 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1155 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1158 $additionalParticipants[$additionalContactName] = $pViewURL;
1161 return $additionalParticipants;
1165 * Function for update primary and additional participant status
1167 * @param int $participantID
1168 * Primary participant's id.
1169 * @param int $oldStatusID
1170 * @param int $newStatusID
1171 * @param bool $updatePrimaryStatus
1176 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1177 if (!$participantID ||
!$oldStatusID) {
1181 if (!$newStatusID) {
1182 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1184 elseif ($updatePrimaryStatus) {
1185 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1188 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1190 if (!empty($cascadeAdditionalIds)) {
1191 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1192 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1193 $params = array(1 => array($newStatusID, 'Integer'));
1194 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1201 * Function for update status for given participant ids
1203 * @param int $participantIds
1204 * Array of participant ids.
1205 * @param int $statusId
1206 * Status id for participant.
1207 * @param bool $updateRegisterDate
1213 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1214 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1218 //lets update register date as we update status to keep track
1219 //when we did update status, useful for moving participant
1220 //from pending to expired.
1221 $setClause = "status_id = {$statusId}";
1222 if ($updateRegisterDate) {
1223 $setClause .= ", register_date = NOW()";
1226 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1229 UPDATE civicrm_participant
1231 WHERE id IN {$participantIdClause}";
1233 $dao = CRM_Core_DAO
::executeQuery($query);
1237 * Function takes participant ids and statuses
1238 * update status from $fromStatusId to $toStatusId
1239 * and send mail + create activities.
1241 * @param array $participantIds
1243 * @param int $toStatusId
1245 * @param int $fromStatusId
1249 * @param bool $returnResult
1250 * @param bool $skipCascadeRule
1255 static function transitionParticipants(
1256 $participantIds, $toStatusId,
1257 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1259 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1263 //thumb rule is if we triggering primary participant need to triggered additional
1264 $allParticipantIds = $primaryANDAdditonalIds = array();
1265 foreach ($participantIds as $id) {
1266 $allParticipantIds[] = $id;
1267 if (self
::isPrimaryParticipant($id)) {
1268 //filter additional as per status transition rules, CRM-5403
1269 if ($skipCascadeRule) {
1270 $additionalIds = self
::getAdditionalParticipantIds($id);
1273 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1275 if (!empty($additionalIds)) {
1276 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1277 $primaryANDAdditonalIds[$id] = $additionalIds;
1282 //get the unique participant ids,
1283 $allParticipantIds = array_unique($allParticipantIds);
1285 //pull required participants, contacts, events data, if not in hand
1286 static $eventDetails = array();
1287 static $domainValues = array();
1288 static $contactDetails = array();
1290 $contactIds = $eventIds = $participantDetails = array();
1292 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1293 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1294 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1298 //first thing is pull all necessory data from db.
1299 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1301 //get all participants data.
1302 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1303 $dao = CRM_Core_DAO
::executeQuery($query);
1304 while ($dao->fetch()) {
1305 $participantDetails[$dao->id
] = array(
1307 'role' => $participantRoles[$dao->role_id
],
1308 'is_test' => $dao->is_test
,
1309 'event_id' => $dao->event_id
,
1310 'status_id' => $dao->status_id
,
1311 'fee_amount' => $dao->fee_amount
,
1312 'contact_id' => $dao->contact_id
,
1313 'register_date' => $dao->register_date
,
1314 'registered_by_id' => $dao->registered_by_id
,
1316 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1317 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1320 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1321 $eventIds[$dao->event_id
] = $dao->event_id
;
1325 //get the domain values.
1326 if (empty($domainValues)) {
1327 // making all tokens available to templates.
1328 $domain = CRM_Core_BAO_Domain
::getDomain();
1330 'domain' => array('name', 'phone', 'address', 'email'),
1331 'contact' => CRM_Core_SelectValues
::contactTokens(),
1334 foreach ($tokens['domain'] as $token) {
1335 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1339 //get all required contacts detail.
1340 if (!empty($contactIds)) {
1341 // get the contact details.
1342 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1345 'CRM_Event_BAO_Participant'
1347 foreach ($currentContactDetails as $contactId => $contactValues) {
1348 $contactDetails[$contactId] = $contactValues;
1352 //get all required events detail.
1353 if (!empty($eventIds)) {
1354 foreach ($eventIds as $eventId) {
1355 //retrieve event information
1356 $eventParams = array('id' => $eventId);
1357 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1359 //get default participant role.
1360 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1362 //get the location info
1363 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1364 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1368 //now we are ready w/ all required data.
1369 //take a decision as per statuses.
1372 $toStatus = $statusTypes[$toStatusId];
1373 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1375 switch ($toStatus) {
1376 case 'Pending from waitlist':
1377 case 'Pending from approval':
1378 switch ($fromStatus) {
1380 case 'Awaiting approval':
1381 $emailType = 'Confirm';
1387 //no matter from where u come send expired mail.
1388 $emailType = $toStatus;
1392 //no matter from where u come send cancel mail.
1393 $emailType = $toStatus;
1397 //as we process additional w/ primary, there might be case if user
1398 //select primary as well as additionals, so avoid double processing.
1399 $processedParticipantIds = array();
1400 $mailedParticipants = array();
1402 //send mails and update status.
1403 foreach ($participantDetails as $participantId => $participantValues) {
1404 $updateParticipantIds = array();
1405 if (in_array($participantId, $processedParticipantIds)) {
1409 //check is it primary and has additional.
1410 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1411 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1414 $mail = self
::sendTransitionParticipantMail($additonalId,
1415 $participantDetails[$additonalId],
1416 $eventDetails[$participantDetails[$additonalId]['event_id']],
1417 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1422 //get the mail participant ids
1424 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1427 $updateParticipantIds[] = $additonalId;
1428 $processedParticipantIds[] = $additonalId;
1432 //now send email appropriate mail to primary.
1434 $mail = self
::sendTransitionParticipantMail($participantId,
1436 $eventDetails[$participantValues['event_id']],
1437 $contactDetails[$participantValues['contact_id']],
1442 //get the mail participant ids
1444 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1448 //now update status of group/one at once.
1449 $updateParticipantIds[] = $participantId;
1451 //update the register date only when we,
1452 //move participant to pending class, CRM-6496
1453 $updateRegisterDate = FALSE;
1454 if (array_key_exists($toStatusId, $pendingStatuses)) {
1455 $updateRegisterDate = TRUE;
1457 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1458 $processedParticipantIds[] = $participantId;
1461 //return result for cron.
1462 if ($returnResult) {
1464 'mailedParticipants' => $mailedParticipants,
1465 'updatedParticipantIds' => $processedParticipantIds,
1473 * Send mail and create activity
1474 * when participant status changed.
1476 * @param int $participantId
1478 * @param array $participantValues
1479 * Participant detail values. status id for participants.
1480 * @param array $eventDetails
1481 * Required event details.
1482 * @param array $contactDetails
1483 * Required contact details.
1484 * @param array $domainValues
1485 * Required domain values.
1486 * @param string $mailType
1487 * (eg 'approval', 'confirm', 'expired' ).
1494 static function sendTransitionParticipantMail(
1505 //don't send confirmation mail to additional
1506 //since only primary able to confirm registration.
1507 if (!empty($participantValues['registered_by_id']) &&
1508 $mailType == 'Confirm'
1512 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1515 $contactId = $participantValues['contact_id'];
1516 $participantName = $contactDetails['display_name'];
1518 //calculate the checksum value.
1519 $checksumValue = NULL;
1520 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1521 $checksumLife = 'inf';
1522 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1524 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1526 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1529 //take a receipt from as event else domain.
1530 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1531 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1532 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1535 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1537 'groupName' => 'msg_tpl_workflow_event',
1538 'valueName' => 'participant_' . strtolower($mailType),
1539 'contactId' => $contactId,
1540 'tplParams' => array(
1541 'contact' => $contactDetails,
1542 'domain' => $domainValues,
1543 'participant' => $participantValues,
1544 'event' => $eventDetails,
1545 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1546 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1547 'isAdditional' => $participantValues['registered_by_id'],
1548 'isExpired' => $mailType == 'Expired',
1549 'isConfirm' => $mailType == 'Confirm',
1550 'checksumValue' => $checksumValue,
1552 'from' => $receiptFrom,
1553 'toName' => $participantName,
1554 'toEmail' => $toEmail,
1555 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1556 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1560 // 3. create activity record.
1562 $now = date('YmdHis');
1563 $activityType = 'Event Registration';
1564 $activityParams = array(
1565 'subject' => $subject,
1566 'source_contact_id' => $contactId,
1567 'source_record_id' => $participantId,
1568 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1572 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1573 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1574 'is_test' => $participantValues['is_test'],
1578 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1579 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1588 * Get participant status change message.
1590 * @param int $participantId
1591 * @param $statusChangeTo
1592 * @param int $fromStatusId
1596 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1598 $results = self
::transitionParticipants(array($participantId),
1599 $statusChangeTo, $fromStatusId, TRUE
1602 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1603 //give user message only when mail has sent.
1604 if (is_array($results) && !empty($results)) {
1605 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1606 foreach ($results['updatedParticipantIds'] as $processedId) {
1607 if (is_array($results['mailedParticipants']) &&
1608 array_key_exists($processedId, $results['mailedParticipants'])
1610 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1612 1 => $allStatuses[$statusChangeTo],
1613 2 => $results['mailedParticipants'][$processedId],
1625 * Get event full and waiting list message.
1627 * @param int $eventId
1628 * @param int $participantId
1632 public static function eventFullMessage($eventId, $participantId = NULL) {
1633 $eventfullMsg = $dbStatusId = NULL;
1634 $checkEventFull = TRUE;
1635 if ($participantId) {
1636 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1637 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1638 //participant already in counted status no need to check for event full messages.
1639 $checkEventFull = FALSE;
1644 if (!$eventId ||
!$checkEventFull) {
1645 return $eventfullMsg;
1648 //event is truly full.
1649 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1650 if (is_string($emptySeats) && $emptySeats !== NULL) {
1651 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1652 $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(
1653 1 => $maxParticipants,
1657 $hasWaiting = FALSE;
1658 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1659 if (is_numeric($waitListedCount)) {
1661 //only current processing participant is on waitlist.
1662 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1663 $hasWaiting = FALSE;
1668 $waitingStatusId = array_search('On waitlist',
1669 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1671 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1672 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1675 $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.",
1677 1 => $viewWaitListUrl,
1678 2 => $waitListedCount,
1683 return $eventfullMsg;
1687 * Check for whether participant is primary or not
1689 * @param int $participantId
1691 * @return true if participant is primary
1693 public static function isPrimaryParticipant($participantId) {
1695 $participant = new CRM_Event_DAO_Participant();
1696 $participant->registered_by_id
= $participantId;
1698 if ($participant->find(TRUE)) {
1705 * Get additional participant Ids for cascading with primary participant status
1707 * @param int $participantId
1709 * @param int $oldStatusId
1711 * @param int $newStatusId
1714 * @return true if allowed
1716 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1718 $additionalParticipantIds = array();
1720 static $participantStatuses = array();
1722 if (empty($participantStatuses)) {
1723 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1726 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1727 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1729 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1732 return $additionalParticipantIds;
1736 * Get participant record count for a Contact
1738 * @param int $contactID
1740 * @return int count of participant records
1743 public static function getContactParticipantCount($contactID) {
1744 $query = "SELECT count(*)
1745 FROM civicrm_participant
1746 WHERE civicrm_participant.contact_id = {$contactID} AND
1747 civicrm_participant.is_test = 0";
1748 return CRM_Core_DAO
::singleValueQuery($query);
1752 * Get participant ids by contribution id
1754 * @param int $contributionId
1756 * @param bool $excludeCancelled
1757 * Exclude cancelled additional participant.
1759 * @return array $participantsId
1762 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1765 if (!$contributionId) {
1769 // get primary participant id
1770 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1771 $participantId = CRM_Core_DAO
::singleValueQuery($query);
1773 // get additional participant ids (including cancelled)
1774 if ($participantId) {
1775 $ids = array_merge(array(
1777 ), self
::getAdditionalParticipantIds($participantId,
1786 * Get additional Participant edit & view url .
1788 * @param array $participantIds
1789 * An array of additional participant ids.
1791 * @return array of Urls.
1794 public static function getAdditionalParticipantUrl($participantIds) {
1795 foreach ($participantIds as $value) {
1797 $details = self
::participantDetails($value);
1798 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1799 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1801 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1802 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1804 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1805 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1811 * To create trxn entry if an event has discount.
1813 * @param int $eventID
1815 * @param array $contributionParams
1816 * Contribution params.
1822 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel) {
1824 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID, 'civicrm_event');
1825 if (!empty($checkDiscount)) {
1826 $feeLevel = current($feeLevel);
1827 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1828 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1829 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1830 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1832 1 => array($priceSetId, 'Integer'),
1833 2 => array($feeLevel, 'String'),
1835 $mainAmount = CRM_Core_DAO
::singleValueQuery($query, $params);
1836 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
1837 $contributionParams['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
1838 $contributionParams['contribution']->financial_type_id
, $relationTypeId);
1839 if (!empty($contributionParams['trxnParams']['from_financial_account_id'])) {
1840 $contributionParams['trxnParams']['total_amount'] = $mainAmount - $contributionParams['total_amount'];
1841 $contributionParams['trxnParams']['payment_processor_id'] = $contributionParams['trxnParams']['payment_instrument_id'] =
1842 $contributionParams['trxnParams']['check_number'] = $contributionParams['trxnParams']['trxn_id'] =
1843 $contributionParams['trxnParams']['net_amount'] = $contributionParams['trxnParams']['fee_amount'] = NULL;
1845 CRM_Core_BAO_FinancialTrxn
::create($contributionParams['trxnParams']);
1852 * Delete participants of contact
1856 * @param int $contactId
1861 public static function deleteContactParticipant($contactId) {
1862 $participant = new CRM_Event_DAO_Participant();
1863 $participant->contact_id
= $contactId;
1864 $participant->find();
1865 while ($participant->fetch()) {
1866 self
::deleteParticipant($participant->id
);
1871 * @param array $params
1872 * @param int $participantId
1873 * @param int $contributionId
1875 * @param array $lineItems
1876 * @param $paidAmount
1877 * @param int $priceSetId
1879 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) {
1880 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1881 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1882 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1883 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($participantId, 'participant');
1884 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
1888 // get the submitted
1889 foreach ($feeBlock as $id => $values) {
1890 CRM_Price_BAO_LineItem
::format($id, $params, $values, $submittedLineItems);
1891 $submittedFieldId[] = CRM_Utils_Array
::retrieveValueRecursive($submittedLineItems, 'price_field_id');
1893 if (!empty($submittedLineItems)) {
1894 $insertLines = $submittedLineItems;
1896 $submittedFieldValueIds = array_keys($submittedLineItems);
1897 $updateLines = array();
1898 foreach ($previousLineItems as $id => $previousLineItem) {
1899 // check through the submitted items if the previousItem exists,
1900 // if found in submitted items, do not use it for new item creations
1901 if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
1902 // if submitted line items are existing don't fire INSERT query
1903 unset($insertLines[$previousLineItem['price_field_value_id']]);
1904 // for updating the line items i.e. use-case - once deselect-option selecting again
1905 if (($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) ||
1906 ($submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1)
1908 $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
1909 $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
1914 $submittedFields = implode(', ', $submittedFieldId);
1915 $submittedFieldValues = implode(', ', $submittedFieldValueIds);
1917 if (!empty($submittedFields) && !empty($submittedFieldValues)) {
1918 $updateLineItem = "UPDATE civicrm_line_item li
1919 INNER JOIN civicrm_financial_item fi
1920 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1922 li.line_total = 0.00,
1923 li.tax_amount = NULL
1924 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
1925 (price_field_value_id NOT IN ({$submittedFieldValues}))
1927 CRM_Core_DAO
::executeQuery($updateLineItem);
1929 // gathering necessary info to record negative (deselected) financial_item
1930 $updateFinancialItem = "
1931 SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
1932 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1933 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
1934 GROUP BY li.entity_table, li.entity_id, price_field_value_id
1936 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1937 $trxn = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId, 'ASC', TRUE);
1938 $trxnId['id'] = $trxn['financialTrxnId'];
1939 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1940 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
1941 $updateFinancialItemInfoValues = array();
1943 while ($updateFinancialItemInfoDAO->fetch()) {
1944 $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
1945 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
1946 // the below params are not needed
1947 unset($updateFinancialItemInfoValues['id']);
1948 unset($updateFinancialItemInfoValues['created_date']);
1949 // if not submitted and difference is not 0 make it negative
1950 if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
1951 // INSERT negative financial_items
1952 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
1953 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1954 // INSERT negative financial_items for tax amount
1955 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
1956 $updateFinancialItemInfoValues['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
1957 $updateFinancialItemInfoValues['description'] = $taxTerm;
1958 if ($updateFinancialItemInfoValues['financial_type_id']) {
1959 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
1961 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1964 // if submitted and difference is 0 add a positive entry again
1965 elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
1966 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
1967 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1968 // INSERT financial_items for tax amount
1969 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
1970 isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
1972 $updateFinancialItemInfoValues['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
1973 $updateFinancialItemInfoValues['description'] = $taxTerm;
1974 if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
1975 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
1977 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1982 elseif (empty($submittedFields) && empty($submittedFieldValues)) {
1983 $updateLineItem = "UPDATE civicrm_line_item li
1984 INNER JOIN civicrm_financial_item fi
1985 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1987 li.line_total = 0.00,
1988 li.tax_amount = NULL
1989 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
1990 CRM_Core_DAO
::executeQuery($updateLineItem);
1992 if (!empty($updateLines)) {
1993 foreach ($updateLines as $valueId => $vals) {
1994 if (isset($vals['tax_amount'])) {
1995 $taxAmount = $vals['tax_amount'];
1998 $taxAmount = "NULL";
2001 UPDATE civicrm_line_item li
2002 SET li.qty = {$vals['qty']},
2003 li.line_total = {$vals['line_total']},
2004 li.tax_amount = {$taxAmount},
2005 li.unit_price = {$vals['unit_price']},
2006 li.label = '{$vals['label']}'
2007 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
2008 (price_field_value_id = {$valueId})
2010 CRM_Core_DAO
::executeQuery($updateLineItem);
2013 // insert new 'adjusted amount' transaction entry and update contribution entry.
2014 // ensure entity_financial_trxn table has a linking of it.
2015 // insert new line items
2016 if (!empty($insertLines)) {
2017 foreach ($insertLines as $valueId => $lineParams) {
2018 $lineParams['entity_table'] = 'civicrm_participant';
2019 $lineParams['entity_id'] = $participantId;
2020 $lineParams['contribution_id'] = $contributionId;
2021 $lineObj = CRM_Price_BAO_LineItem
::create($lineParams);
2025 // the recordAdjustedAmt code would execute over here
2026 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
2027 if (count($ids) > 1) {
2029 foreach ($ids as $val) {
2030 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, 'civicrm_participant');
2032 $updatedAmount = $total;
2035 $updatedAmount = $params['amount'];
2037 if (strlen($params['tax_amount']) != 0) {
2038 $taxAmount = $params['tax_amount'];
2041 $taxAmount = "NULL";
2043 self
::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount);
2045 $fetchCon = array('id' => $contributionId);
2046 $updatedContribution = CRM_Contribute_BAO_Contribution
::retrieve($fetchCon, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2047 // insert financial items
2048 if (!empty($insertLines)) {
2049 foreach ($insertLines as $valueId => $lineParams) {
2050 $lineParams['entity_table'] = 'civicrm_participant';
2051 $lineParams['entity_id'] = $participantId;
2052 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams, CRM_Core_DAO
::$_nullArray);
2053 // insert financial items
2054 // ensure entity_financial_trxn table has a linking of it.
2055 $prevItem = CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution);
2056 if (isset($lineObj->tax_amount
)) {
2057 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE);
2062 // update participant fee_amount column
2063 $partUpdateFeeAmt['id'] = $participantId;
2064 foreach ($lineItems as $lineValue) {
2065 if ($lineValue['price_field_value_id']) {
2066 $line[$lineValue['price_field_value_id']] = $lineValue['label'] . ' - ' . $lineValue['qty'];
2070 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
2071 $partUpdateFeeAmt['fee_amount'] = $params['amount'];
2072 self
::add($partUpdateFeeAmt);
2075 self
::addActivityForSelection($participantId, 'Change Registration');
2079 * @param $updatedAmount
2080 * @param $paidAmount
2081 * @param int $contributionId
2083 public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL) {
2084 $balanceAmt = $updatedAmount - $paidAmount;
2085 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2086 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
2087 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
2088 $completedStatusId = array_search('Completed', $contributionStatuses);
2090 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
2093 if ($balanceAmt > 0 && $paidAmount != 0) {
2094 $contributionStatusVal = $partiallyPaidStatusId;
2096 elseif ($balanceAmt < 0 && $paidAmount != 0) {
2097 $contributionStatusVal = $pendingRefundStatusId;
2099 elseif ($paidAmount == 0) {
2100 //skip updating the contribution status if no payment is made
2102 $updatedContributionDAO->cancel_date
= 'null';
2103 $updatedContributionDAO->cancel_reason
= NULL;
2105 // update contribution status and total amount without trigger financial code
2106 // as this is handled in current BAO function used for change selection
2107 $updatedContributionDAO->id
= $contributionId;
2109 $updatedContributionDAO->contribution_status_id
= $contributionStatusVal;
2111 $updatedContributionDAO->total_amount
= $updatedAmount;
2112 $updatedContributionDAO->tax_amount
= $taxAmount;
2113 $updatedContributionDAO->save();
2115 $ftDetail = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
2116 // adjusted amount financial_trxn creation
2117 if (empty($ftDetail['trxn_id'])) {
2118 $updatedContribution =
2119 CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contributionId), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2120 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2121 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($updatedContribution->financial_type_id
, $relationTypeId);
2123 $adjustedTrxnValues = array(
2124 'from_financial_account_id' => NULL,
2125 'to_financial_account_id' => $toFinancialAccount,
2126 'total_amount' => $balanceAmt,
2127 'status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
2128 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
2129 'contribution_id' => $updatedContribution->id
,
2130 'trxn_date' => date('YmdHis'),
2131 'currency' => $updatedContribution->currency
,
2133 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
2136 // update the financial trxn amount as well, as the fee selections has been updated
2137 if ($balanceAmt != $ftDetail['total_amount']) {
2138 CRM_Core_DAO
::setFieldValue('CRM_Core_BAO_FinancialTrxn', $ftDetail['trxn_id'], 'total_amount', $balanceAmt);
2145 * @param int $participantId
2146 * @param $activityType
2148 * @throws CRM_Core_Exception
2150 public static function addActivityForSelection($participantId, $activityType) {
2151 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
2152 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
2154 $date = CRM_Utils_Date
::currentDBDate();
2155 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
2156 $eventTitle = $event[$eventId];
2157 $subject = "Registration selections changed for $eventTitle";
2158 $targetCid = $contactId;
2159 $srcRecId = $participantId;
2162 $activityParams = array(
2163 'source_contact_id' => $targetCid,
2164 'source_record_id' => $srcRecId,
2165 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
2169 'subject' => $subject,
2170 'activity_date_time' => $date,
2171 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
2175 'skipRecentView' => TRUE,
2178 // create activity with target contacts
2179 $session = CRM_Core_Session
::singleton();
2180 $id = $session->get('userID');
2182 $activityParams['source_contact_id'] = $id;
2183 $activityParams['target_contact_id'][] = $targetCid;
2185 CRM_Activity_BAO_Activity
::create($activityParams);
2189 * Get options for a given field.
2190 * @see CRM_Core_DAO::buildOptions
2192 * @param string $fieldName
2193 * @param string $context
2194 * : @see CRM_Core_DAO::buildOptionsContext.
2195 * @param array $props
2196 * : whatever is known about this dao object.
2198 * @return Array|bool
2200 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2201 $params = array('condition' => array());
2203 if ($fieldName == 'status_id' && $context != 'validate') {
2204 // Get rid of cart-related option if disabled
2205 // FIXME: Why does this option even exist if cart is disabled?
2206 if (!CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
, 'enable_cart')) {
2207 $params['condition'][] = "name <> 'Pending in cart'";
2211 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);