3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
33 * @copyright CiviCRM LLC (c) 2004-2014
37 class CRM_Event_BAO_Participant
extends CRM_Event_DAO_Participant
{
40 * Static field for all the participant information that we can potentially import
45 static $_importableFields = NULL;
48 * Static field for all the participant information that we can potentially export
53 static $_exportableFields = NULL;
56 * Static array for valid status transitions rules
61 static $_statusTransitionsRules = array(
62 'Pending from pay later' => array('Registered', 'Cancelled'),
63 'Pending from incomplete transaction' => array('Registered', 'Cancelled'),
64 'On waitlist' => array('Cancelled', 'Pending from waitlist'),
65 'Pending from waitlist' => array('Registered', 'Cancelled'),
66 'Awaiting approval' => array('Cancelled', 'Pending from approval'),
67 'Pending from approval' => array('Registered', 'Cancelled'),
72 public function __construct() {
73 parent
::__construct();
77 * Takes an associative array and creates a participant object
79 * the function extract all the params it needs to initialize the create a
80 * participant object. the params array could contain additional unused name/value
83 * @param array $params
84 * (reference ) an assoc array of name/value pairs.
86 * @return CRM_Event_BAO_Participant
89 public static function &add(&$params) {
91 if (!empty($params['id'])) {
92 CRM_Utils_Hook
::pre('edit', 'Participant', $params['id'], $params);
95 CRM_Utils_Hook
::pre('create', 'Participant', NULL, $params);
98 // converting dates to mysql format
99 if (!empty($params['register_date'])) {
100 $params['register_date'] = CRM_Utils_Date
::isoToMysql($params['register_date']);
103 if (!empty($params['participant_fee_amount'])) {
104 $params['participant_fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['participant_fee_amount']);
107 if (!empty($params['fee_amount'])) {
108 $params['fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['fee_amount']);
111 // ensure that role ids are encoded as a string
112 if (isset($params['role_id']) && is_array($params['role_id'])) {
113 if (in_array(key($params['role_id']), CRM_Core_DAO
::acceptedSQLOperators())) {
114 $op = key($params['role_id']);
115 $params['role_id'] = $params['role_id'][$op];
117 $params['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['role_id']);
120 $participantBAO = new CRM_Event_BAO_Participant
;
121 if (!empty($params['id'])) {
122 $participantBAO->id
= CRM_Utils_Array
::value('id', $params);
123 $participantBAO->find(TRUE);
124 $participantBAO->register_date
= CRM_Utils_Date
::isoToMysql($participantBAO->register_date
);
127 $participantBAO->copyValues($params);
130 //1. If currency present, it should be valid one.
131 //2. We should have currency when amount is not null.
132 $currency = $participantBAO->fee_currency
;
134 !CRM_Utils_System
::isNull($participantBAO->fee_amount
)
136 if (!CRM_Utils_Rule
::currencyCode($currency)) {
137 $config = CRM_Core_Config
::singleton();
138 $currency = $config->defaultCurrency
;
141 $participantBAO->fee_currency
= $currency;
143 $participantBAO->save();
145 $session = CRM_Core_Session
::singleton();
147 // reset the group contact cache for this group
148 CRM_Contact_BAO_GroupContactCache
::remove();
150 if (!empty($params['id'])) {
151 CRM_Utils_Hook
::post('edit', 'Participant', $participantBAO->id
, $participantBAO);
154 CRM_Utils_Hook
::post('create', 'Participant', $participantBAO->id
, $participantBAO);
157 return $participantBAO;
161 * Given the list of params in the params array, fetch the object
162 * and store the values in the values array
164 * @param array $params
165 * Input parameters to find object.
166 * @param array $values
167 * Output values of the object.
171 * @return CRM_Event_BAO_Participant|null the found object or null
174 public static function getValues(&$params, &$values, &$ids) {
175 if (empty($params)) {
178 $participant = new CRM_Event_BAO_Participant();
179 $participant->copyValues($params);
180 $participant->find();
181 $participants = array();
182 while ($participant->fetch()) {
183 $ids['participant'] = $participant->id
;
184 CRM_Core_DAO
::storeValues($participant, $values[$participant->id
]);
185 $participants[$participant->id
] = $participant;
187 return $participants;
191 * Takes an associative array and creates a participant object
193 * @param array $params
194 * (reference ) an assoc array of name/value pairs.
196 * @return CRM_Event_BAO_Participant
199 public static function create(&$params) {
201 $transaction = new CRM_Core_Transaction();
204 if (!empty($params['id'])) {
205 $status = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
208 $participant = self
::add($params);
210 if (is_a($participant, 'CRM_Core_Error')) {
211 $transaction->rollback();
215 if ((!CRM_Utils_Array
::value('id', $params)) ||
216 (isset($params['status_id']) && $params['status_id'] != $status)
218 CRM_Activity_BAO_Activity
::addActivity($participant);
223 if (self
::isPrimaryParticipant($participant->id
) && $status) {
224 self
::updateParticipantStatus($participant->id
, $status, $participant->status_id
);
227 $session = CRM_Core_Session
::singleton();
228 $id = $session->get('userID');
230 $id = CRM_Utils_Array
::value('contact_id', $params);
233 // add custom field values
234 if (!empty($params['custom']) &&
235 is_array($params['custom'])
237 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_participant', $participant->id
);
240 //process note, CRM-7634
242 if (!empty($params['id'])) {
243 $note = CRM_Core_BAO_Note
::getNote($params['id'], 'civicrm_participant');
244 $noteId = key($note);
247 $hasNoteField = FALSE;
252 if (array_key_exists($noteFld, $params)) {
253 $noteValue = $params[$noteFld];
254 $hasNoteField = TRUE;
258 if ($noteId ||
$noteValue) {
261 'entity_table' => 'civicrm_participant',
262 'note' => $noteValue,
263 'entity_id' => $participant->id
,
265 'modified_date' => date('Ymd'),
269 $noteIDs['id'] = $noteId;
271 CRM_Core_BAO_Note
::add($noteParams, $noteIDs);
273 elseif ($noteId && $hasNoteField) {
274 CRM_Core_BAO_Note
::del($noteId, FALSE);
278 // Log the information on successful add/edit of Participant data.
280 'entity_table' => 'civicrm_participant',
281 'entity_id' => $participant->id
,
282 'data' => CRM_Event_PseudoConstant
::participantStatus($participant->status_id
),
283 'modified_id' => $id,
284 'modified_date' => date('Ymd'),
287 CRM_Core_BAO_Log
::add($logParams);
289 $params['participant_id'] = $participant->id
;
291 $transaction->commit();
293 // do not add to recent items for import, CRM-4399
294 if (empty($params['skipRecentView'])) {
296 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
297 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
300 $recentOther = array();
301 if (CRM_Core_Permission
::check('edit event participants')) {
302 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
303 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
306 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
307 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
308 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
312 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
314 if ($participant->role_id
) {
315 $role = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participant->role_id
);
317 foreach ($role as & $roleValue) {
318 if (isset($roleValue)) {
319 $roleValue = $participantRoles[$roleValue];
322 $roles = implode(', ', $role);
325 $roleString = empty($roles) ?
'' : $roles;
326 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $participant->event_id
, 'title');
327 $title = CRM_Contact_BAO_Contact
::displayName($participant->contact_id
) . ' (' . $roleString . ' - ' . $eventTitle . ')';
329 // add the recently created Participant
330 CRM_Utils_Recent
::add($title,
334 $participant->contact_id
,
344 * Check whether the event is full for participation and return as
347 * @param int $eventId
349 * @param bool $returnEmptySeats
350 * Are we require number if empty seats.
351 * @param bool $includeWaitingList
352 * Consider waiting list in event full.
353 * calculation or not. (it is for cron job purpose)
355 * @param bool $returnWaitingCount
356 * @param bool $considerTestParticipant
358 * @return bool|int|null|string
359 * 1. false => If event having some empty spaces.
362 static function eventFull(
364 $returnEmptySeats = FALSE,
365 $includeWaitingList = TRUE,
366 $returnWaitingCount = FALSE,
367 $considerTestParticipant = FALSE
374 // consider event is full when.
375 // 1. (count(is_counted) >= event_size) or
376 // 2. (count(participants-with-status-on-waitlist) > 0)
377 // It might be case there are some empty spaces and still event
378 // is full, as waitlist might represent group require spaces > empty.
380 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
381 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
382 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
383 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
385 //when we do require only waiting count don't consider counted.
386 if (!$returnWaitingCount && !empty($countedStatuses)) {
387 $allStatusIds = array_keys($countedStatuses);
390 $where = array(' event.id = %1 ');
391 if (!$considerTestParticipant) {
392 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
394 if (!empty($participantRoles)) {
395 $where[] = ' participant.role_id IN ( ' . implode(', ', array_keys($participantRoles)) . ' ) ';
398 $eventParams = array(1 => array($eventId, 'Positive'));
400 //in case any waiting, straight forward event is full.
401 if ($includeWaitingList && $onWaitlistStatusId) {
403 //build the where clause.
404 $whereClause = ' WHERE ' . implode(' AND ', $where);
405 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
406 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
409 SELECT participant.id id,
410 event.event_full_text as event_full_text
411 FROM civicrm_participant participant
412 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
415 $eventFullText = ts('This event is full.');
416 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
417 while ($participants->fetch()) {
418 //oops here event is full and we don't want waiting count.
419 if ($returnWaitingCount) {
420 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
423 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
428 //consider only counted participants.
429 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
430 $whereClause = ' WHERE ' . implode(' AND ', $where);
431 $eventSeatsWhere = implode(' AND ', $where);
434 SELECT participant.id id,
435 event.event_full_text as event_full_text,
436 event.max_participants as max_participants
437 FROM civicrm_participant participant
438 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
441 $eventMaxSeats = NULL;
442 $eventFullText = ts('This event is full.');
443 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
444 while ($participants->fetch()) {
445 if ($participants->event_full_text
) {
446 $eventFullText = $participants->event_full_text
;
448 $eventMaxSeats = $participants->max_participants
;
449 //don't have limit for event seats.
450 if ($participants->max_participants
== NULL) {
455 //get the total event seats occupied by these participants.
456 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
458 if ($eventRegisteredSeats) {
459 if ($eventRegisteredSeats >= $eventMaxSeats) {
460 $result = $eventFullText;
462 elseif ($returnEmptySeats) {
463 $result = $eventMaxSeats - $eventRegisteredSeats;
469 SELECT event.event_full_text,
470 event.max_participants
471 FROM civicrm_event event
472 WHERE event.id = %1';
473 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
474 while ($event->fetch()) {
475 $eventFullText = $event->event_full_text
;
476 $eventMaxSeats = $event->max_participants
;
480 // no limit for registration.
481 if ($eventMaxSeats == NULL) {
484 if ($eventMaxSeats) {
485 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
488 return $eventFullText;
492 * Return the array of all price set field options,
493 * with total participant count that field going to carry.
495 * @param int $eventId
497 * @param array $skipParticipantIds
498 * An array of participant ids those we should skip.
499 * @param bool $considerCounted
500 * @param bool $considerWaiting
501 * @param bool $considerTestParticipants
504 * an array of each option id and total count
507 static function priceSetOptionsCount(
509 $skipParticipantIds = array(),
510 $considerCounted = TRUE,
511 $considerWaiting = TRUE,
512 $considerTestParticipants = FALSE
514 $optionsCount = array();
516 return $optionsCount;
519 $allStatusIds = array();
520 if ($considerCounted) {
521 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
522 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
524 if ($considerWaiting) {
525 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
526 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
528 $statusIdClause = NULL;
529 if (!empty($allStatusIds)) {
530 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
533 $isTestClause = NULL;
534 if (!$considerTestParticipants) {
535 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
538 $skipParticipantClause = NULL;
539 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
540 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
544 SELECT line.id as lineId,
545 line.entity_id as entity_id,
550 FROM civicrm_line_item line
551 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
552 AND participant.id = line.entity_id )
553 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
554 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
555 WHERE participant.event_id = %1
558 {$skipParticipantClause}";
560 $lineItem = CRM_Core_DAO
::executeQuery($sql, array(1 => array($eventId, 'Positive')));
561 while ($lineItem->fetch()) {
562 $count = $lineItem->count
;
566 if ($lineItem->html_type
== 'Text') {
567 $count *= $lineItem->qty
;
569 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
572 return $optionsCount;
576 * Get the empty spaces for event those we can allocate
577 * to pending participant to become confirm.
579 * @param int $eventId
583 * $spaces Number of Empty Seats/null.
586 public static function pendingToConfirmSpaces($eventId) {
592 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
593 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
596 SELECT count(participant.id) as registered,
597 civicrm_event.max_participants
598 FROM civicrm_participant participant, civicrm_event
599 WHERE participant.event_id = {$eventId}
600 AND civicrm_event.id = participant.event_id
601 AND participant.status_id IN {$statusIds}
602 GROUP BY participant.event_id
604 $dao = CRM_Core_DAO
::executeQuery($query);
608 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
613 if ($dao->registered
>= $dao->max_participants
) {
618 return $dao->max_participants
- $dao->registered
;
621 //space in case no registeration yet.
622 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
626 * Combine all the importable fields from the lower levels object
628 * @param string $contactType
629 * @param bool $status
630 * @param bool $onlyParticipant
633 * array of importable Fields
636 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE) {
637 if (!self
::$_importableFields) {
638 if (!$onlyParticipant) {
640 $fields = array('' => array('title' => ts('- do not import -')));
643 $fields = array('' => array('title' => ts('- Participant Fields -')));
650 $tmpFields = CRM_Event_DAO_Participant
::import();
653 'participant_note' => array(
654 'title' => ts('Participant Note'),
655 'name' => 'participant_note',
656 'headerPattern' => '/(participant.)?note$/i',
660 // Split status and status id into 2 fields
661 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
662 $participantStatus = array(
663 'participant_status' => array(
664 'title' => ts('Participant Status'),
665 'name' => 'participant_status',
666 'data_type' => CRM_Utils_Type
::T_STRING
,
669 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
671 // Split role and role id into 2 fields
672 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
673 $participantRole = array(
674 'participant_role' => array(
675 'title' => ts('Participant Role'),
676 'name' => 'participant_role',
677 'data_type' => CRM_Utils_Type
::T_STRING
,
680 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
683 'event_type' => array(
684 'title' => ts('Event Type'),
685 'name' => 'event_type',
686 'data_type' => CRM_Utils_Type
::T_STRING
,
690 $tmpContactField = $contactFields = array();
691 $contactFields = array();
692 if (!$onlyParticipant) {
693 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
695 // Using new Dedupe rule.
697 'contact_type' => $contactType,
698 'used' => 'Unsupervised',
700 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
702 if (is_array($fieldsArray)) {
703 foreach ($fieldsArray as $value) {
704 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
709 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
710 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
712 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
715 $title = $tmpContactField[trim($value)]['title'];
718 $tmpContactField[trim($value)]['title'] = $title;
722 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
723 if ($extIdentifier) {
724 $tmpContactField['external_identifier'] = $extIdentifier;
725 $tmpContactField['external_identifier']['title'] =
726 CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
728 $tmpFields['participant_contact_id']['title'] =
729 $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
731 $fields = array_merge($fields, $tmpContactField);
732 $fields = array_merge($fields, $tmpFields);
733 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
734 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
736 self
::$_importableFields = $fields;
739 return self
::$_importableFields;
743 * Combine all the exportable fields from the lower levels object
746 * array of exportable Fields
749 public static function &exportableFields() {
750 if (!self
::$_exportableFields) {
751 if (!self
::$_exportableFields) {
752 self
::$_exportableFields = array();
757 $participantFields = CRM_Event_DAO_Participant
::export();
758 $eventFields = CRM_Event_DAO_Event
::export();
760 'participant_note' => array(
761 'title' => 'Participant Note',
762 'name' => 'participant_note',
763 'type' => CRM_Utils_Type
::T_STRING
,
766 $participantStatus = array(
767 'participant_status' => array(
768 'title' => 'Participant Status',
769 'name' => 'participant_status',
770 'type' => CRM_Utils_Type
::T_STRING
,
773 $participantRole = array(
774 'participant_role' => array(
775 'title' => 'Participant Role',
776 'name' => 'participant_role',
777 'type' => CRM_Utils_Type
::T_STRING
,
780 $discountFields = CRM_Core_DAO_Discount
::export();
782 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
785 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
786 self
::$_exportableFields = $fields;
789 return self
::$_exportableFields;
793 * Get the event name/sort name for a particular participation / participant
795 * @param int $participantId
796 * Id of the participant.
799 * associated array with sort_name and event title
802 public static function participantDetails($participantId) {
804 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
805 FROM civicrm_participant
806 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
807 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
808 WHERE civicrm_participant.id = {$participantId}
810 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
813 while ($dao->fetch()) {
814 $details['name'] = $dao->name
;
815 $details['title'] = $dao->title
;
816 $details['cid'] = $dao->cid
;
823 * Get the values for pseudoconstants for name->value and reverse.
825 * @param array $defaults
826 * (reference) the default values, some of which need to be resolved.
827 * @param bool $reverse
828 * True if we want to resolve the values in the reverse direction (value -> name).
833 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
834 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
835 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
836 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
840 * convert associative array names to values
843 * This function is used by both the web form layer and the api. Note that
844 * the api needs the name => value conversion, also the view layer typically
845 * requires value => name conversion
847 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
848 $id = $property . '_id';
850 $src = $reverse ?
$property : $id;
851 $dst = $reverse ?
$id : $property;
853 if (!array_key_exists($src, $defaults)) {
857 $look = $reverse ?
array_flip($lookup) : $lookup;
859 if (is_array($look)) {
860 if (!array_key_exists($defaults[$src], $look)) {
864 $defaults[$dst] = $look[$defaults[$src]];
869 * Delete the record that are associated with this participation
872 * Id of the participation to delete.
877 public static function deleteParticipant($id) {
878 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
880 $transaction = new CRM_Core_Transaction();
882 //delete activity record
884 'source_record_id' => $id,
885 // activity type id for event registration
886 'activity_type_id' => 5,
889 CRM_Activity_BAO_Activity
::deleteActivity($params);
891 // delete the participant payment record
892 // we need to do this since the cascaded constraints
893 // dont work with join tables
894 $p = array('participant_id' => $id);
895 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
897 // cleanup line items.
898 $participantsId = array();
899 $participantsId = self
::getAdditionalParticipantIds($id);
900 $participantsId[] = $id;
901 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
903 //delete note when participant deleted.
904 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
905 $noteId = key($note);
907 CRM_Core_BAO_Note
::del($noteId, FALSE);
910 $participant = new CRM_Event_DAO_Participant();
911 $participant->id
= $id;
912 $participant->delete();
914 $transaction->commit();
916 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
918 // delete the recently created Participant
919 $participantRecent = array(
921 'type' => 'Participant',
924 CRM_Utils_Recent
::del($participantRecent);
930 * Checks duplicate participants
932 * @param array $duplicates
933 * (reference ) an assoc array of name/value pairs.
934 * @param array $input
935 * An assosiative array of name /value pairs.
936 * from other function
938 * @return CRM_Contribute_BAO_Contribution
941 public static function checkDuplicate($input, &$duplicates) {
942 $eventId = CRM_Utils_Array
::value('event_id', $input);
943 $contactId = CRM_Utils_Array
::value('contact_id', $input);
949 $clause[] = "event_id = %1";
950 $input[1] = array($eventId, 'Integer');
954 $clause[] = "contact_id = %2";
955 $input[2] = array($contactId, 'Integer');
958 if (empty($clause)) {
962 $clause = implode(' AND ', $clause);
964 $query = "SELECT id FROM civicrm_participant WHERE $clause";
965 $dao = CRM_Core_DAO
::executeQuery($query, $input);
967 while ($dao->fetch()) {
968 $duplicates[] = $dao->id
;
975 * Fix the event level
977 * When price sets are used as event fee, fee_level is set as ^A
978 * separated string. We need to change that string to comma
979 * separated string before using fee_level in view mode.
981 * @param string $eventLevel
982 * Event_leval string from db.
988 public static function fixEventLevel(&$eventLevel) {
989 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
990 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
992 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
993 $pos = strrpos($eventLevel, '(multiple participants)', 0);
995 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
998 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
999 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1000 substr($eventLevel, 0, 1)
1003 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1004 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1005 substr($eventLevel, 0, -1)
1011 * Get the additional participant ids.
1013 * @param int $primaryParticipantId
1014 * Primary partycipant Id.
1015 * @param bool $excludeCancel
1016 * Do not include participant those are cancelled.
1018 * @param int $oldStatusId
1023 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
1024 $additionalParticipantIds = array();
1025 if (!$primaryParticipantId) {
1026 return $additionalParticipantIds;
1029 $where = "participant.registered_by_id={$primaryParticipantId}";
1030 if ($excludeCancel) {
1031 $cancelStatusId = 0;
1032 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1033 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1034 $where .= " AND participant.status_id != {$cancelStatusId}";
1038 $where .= " AND participant.status_id = {$oldStatusId}";
1042 SELECT participant.id
1043 FROM civicrm_participant participant
1046 $dao = CRM_Core_DAO
::executeQuery($query);
1047 while ($dao->fetch()) {
1048 $additionalParticipantIds[$dao->id
] = $dao->id
;
1050 return $additionalParticipantIds;
1054 * Get the event fee info for given participant ids
1055 * either from line item table / participant table.
1057 * @param array $participantIds
1059 * @param bool $hasLineItems
1060 * Do fetch from line items.
1065 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1066 $feeDetails = array();
1067 if (!is_array($participantIds) ||
empty($participantIds)) {
1072 SELECT participant.id as id,
1073 participant.fee_level as fee_level,
1074 participant.fee_amount as fee_amount';
1075 $from = 'FROM civicrm_participant participant';
1076 if ($hasLineItems) {
1078 lineItem.id as lineId,
1079 lineItem.label as label,
1080 lineItem.qty as qty,
1081 lineItem.unit_price as unit_price,
1082 lineItem.line_total as line_total,
1083 field.label as field_title,
1084 field.html_type as html_type,
1085 field.id as price_field_id,
1086 value.id as price_field_value_id,
1087 value.description as description,
1088 IF( value.count, value.count, 0 ) as participant_count';
1090 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1091 AND lineItem.entity_id = participant.id )
1092 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1093 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1096 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1097 $query = "$select $from $where";
1099 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1100 $feeProperties = array('fee_level', 'fee_amount');
1101 $lineProperties = array(
1110 'participant_count',
1111 'price_field_value_id',
1114 while ($feeInfo->fetch()) {
1115 if ($hasLineItems) {
1116 foreach ($lineProperties as $property) {
1117 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1121 foreach ($feeProperties as $property) {
1122 $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1131 * Retrieve additional participants display-names and URL to view their participant records.
1132 * (excludes cancelled participants automatically)
1134 * @param int $primaryParticipantID
1135 * Id of primary participant record.
1138 * $displayName => $viewUrl
1141 public static function getAdditionalParticipants($primaryParticipantID) {
1142 $additionalParticipantIDs = array();
1143 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1144 if (!empty($additionalParticipantIDs)) {
1145 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1146 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1147 $additionalParticipantID,
1150 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1151 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1152 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1155 $additionalParticipants[$additionalContactName] = $pViewURL;
1158 return $additionalParticipants;
1162 * Function for update primary and additional participant status
1164 * @param int $participantID
1165 * Primary participant's id.
1166 * @param int $oldStatusID
1167 * @param int $newStatusID
1168 * @param bool $updatePrimaryStatus
1173 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1174 if (!$participantID ||
!$oldStatusID) {
1178 if (!$newStatusID) {
1179 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1181 elseif ($updatePrimaryStatus) {
1182 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1185 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1187 if (!empty($cascadeAdditionalIds)) {
1188 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1189 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1190 $params = array(1 => array($newStatusID, 'Integer'));
1191 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1198 * Function for update status for given participant ids
1200 * @param int $participantIds
1201 * Array of participant ids.
1202 * @param int $statusId
1203 * Status id for participant.
1204 * @param bool $updateRegisterDate
1210 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1211 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1215 //lets update register date as we update status to keep track
1216 //when we did update status, useful for moving participant
1217 //from pending to expired.
1218 $setClause = "status_id = {$statusId}";
1219 if ($updateRegisterDate) {
1220 $setClause .= ", register_date = NOW()";
1223 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1226 UPDATE civicrm_participant
1228 WHERE id IN {$participantIdClause}";
1230 $dao = CRM_Core_DAO
::executeQuery($query);
1234 * Function takes participant ids and statuses
1235 * update status from $fromStatusId to $toStatusId
1236 * and send mail + create activities.
1238 * @param array $participantIds
1240 * @param int $toStatusId
1242 * @param int $fromStatusId
1246 * @param bool $returnResult
1247 * @param bool $skipCascadeRule
1252 static function transitionParticipants(
1253 $participantIds, $toStatusId,
1254 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1256 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1260 //thumb rule is if we triggering primary participant need to triggered additional
1261 $allParticipantIds = $primaryANDAdditonalIds = array();
1262 foreach ($participantIds as $id) {
1263 $allParticipantIds[] = $id;
1264 if (self
::isPrimaryParticipant($id)) {
1265 //filter additional as per status transition rules, CRM-5403
1266 if ($skipCascadeRule) {
1267 $additionalIds = self
::getAdditionalParticipantIds($id);
1270 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1272 if (!empty($additionalIds)) {
1273 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1274 $primaryANDAdditonalIds[$id] = $additionalIds;
1279 //get the unique participant ids,
1280 $allParticipantIds = array_unique($allParticipantIds);
1282 //pull required participants, contacts, events data, if not in hand
1283 static $eventDetails = array();
1284 static $domainValues = array();
1285 static $contactDetails = array();
1287 $contactIds = $eventIds = $participantDetails = array();
1289 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1290 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1291 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1295 //first thing is pull all necessory data from db.
1296 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1298 //get all participants data.
1299 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1300 $dao = CRM_Core_DAO
::executeQuery($query);
1301 while ($dao->fetch()) {
1302 $participantDetails[$dao->id
] = array(
1304 'role' => $participantRoles[$dao->role_id
],
1305 'is_test' => $dao->is_test
,
1306 'event_id' => $dao->event_id
,
1307 'status_id' => $dao->status_id
,
1308 'fee_amount' => $dao->fee_amount
,
1309 'contact_id' => $dao->contact_id
,
1310 'register_date' => $dao->register_date
,
1311 'registered_by_id' => $dao->registered_by_id
,
1313 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1314 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1317 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1318 $eventIds[$dao->event_id
] = $dao->event_id
;
1322 //get the domain values.
1323 if (empty($domainValues)) {
1324 // making all tokens available to templates.
1325 $domain = CRM_Core_BAO_Domain
::getDomain();
1327 'domain' => array('name', 'phone', 'address', 'email'),
1328 'contact' => CRM_Core_SelectValues
::contactTokens(),
1331 foreach ($tokens['domain'] as $token) {
1332 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1336 //get all required contacts detail.
1337 if (!empty($contactIds)) {
1338 // get the contact details.
1339 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1342 'CRM_Event_BAO_Participant'
1344 foreach ($currentContactDetails as $contactId => $contactValues) {
1345 $contactDetails[$contactId] = $contactValues;
1349 //get all required events detail.
1350 if (!empty($eventIds)) {
1351 foreach ($eventIds as $eventId) {
1352 //retrieve event information
1353 $eventParams = array('id' => $eventId);
1354 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1356 //get default participant role.
1357 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1359 //get the location info
1360 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1361 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1365 //now we are ready w/ all required data.
1366 //take a decision as per statuses.
1369 $toStatus = $statusTypes[$toStatusId];
1370 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1372 switch ($toStatus) {
1373 case 'Pending from waitlist':
1374 case 'Pending from approval':
1375 switch ($fromStatus) {
1377 case 'Awaiting approval':
1378 $emailType = 'Confirm';
1384 //no matter from where u come send expired mail.
1385 $emailType = $toStatus;
1389 //no matter from where u come send cancel mail.
1390 $emailType = $toStatus;
1394 //as we process additional w/ primary, there might be case if user
1395 //select primary as well as additionals, so avoid double processing.
1396 $processedParticipantIds = array();
1397 $mailedParticipants = array();
1399 //send mails and update status.
1400 foreach ($participantDetails as $participantId => $participantValues) {
1401 $updateParticipantIds = array();
1402 if (in_array($participantId, $processedParticipantIds)) {
1406 //check is it primary and has additional.
1407 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1408 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1411 $mail = self
::sendTransitionParticipantMail($additonalId,
1412 $participantDetails[$additonalId],
1413 $eventDetails[$participantDetails[$additonalId]['event_id']],
1414 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1419 //get the mail participant ids
1421 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1424 $updateParticipantIds[] = $additonalId;
1425 $processedParticipantIds[] = $additonalId;
1429 //now send email appropriate mail to primary.
1431 $mail = self
::sendTransitionParticipantMail($participantId,
1433 $eventDetails[$participantValues['event_id']],
1434 $contactDetails[$participantValues['contact_id']],
1439 //get the mail participant ids
1441 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1445 //now update status of group/one at once.
1446 $updateParticipantIds[] = $participantId;
1448 //update the register date only when we,
1449 //move participant to pending class, CRM-6496
1450 $updateRegisterDate = FALSE;
1451 if (array_key_exists($toStatusId, $pendingStatuses)) {
1452 $updateRegisterDate = TRUE;
1454 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1455 $processedParticipantIds[] = $participantId;
1458 //return result for cron.
1459 if ($returnResult) {
1461 'mailedParticipants' => $mailedParticipants,
1462 'updatedParticipantIds' => $processedParticipantIds,
1470 * Send mail and create activity
1471 * when participant status changed.
1473 * @param int $participantId
1475 * @param array $participantValues
1476 * Participant detail values. status id for participants.
1477 * @param array $eventDetails
1478 * Required event details.
1479 * @param array $contactDetails
1480 * Required contact details.
1481 * @param array $domainValues
1482 * Required domain values.
1483 * @param string $mailType
1484 * (eg 'approval', 'confirm', 'expired' ).
1491 static function sendTransitionParticipantMail(
1502 //don't send confirmation mail to additional
1503 //since only primary able to confirm registration.
1504 if (!empty($participantValues['registered_by_id']) &&
1505 $mailType == 'Confirm'
1509 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1512 $contactId = $participantValues['contact_id'];
1513 $participantName = $contactDetails['display_name'];
1515 //calculate the checksum value.
1516 $checksumValue = NULL;
1517 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1518 $checksumLife = 'inf';
1519 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1521 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1523 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1526 //take a receipt from as event else domain.
1527 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1528 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1529 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1532 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1534 'groupName' => 'msg_tpl_workflow_event',
1535 'valueName' => 'participant_' . strtolower($mailType),
1536 'contactId' => $contactId,
1537 'tplParams' => array(
1538 'contact' => $contactDetails,
1539 'domain' => $domainValues,
1540 'participant' => $participantValues,
1541 'event' => $eventDetails,
1542 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1543 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1544 'isAdditional' => $participantValues['registered_by_id'],
1545 'isExpired' => $mailType == 'Expired',
1546 'isConfirm' => $mailType == 'Confirm',
1547 'checksumValue' => $checksumValue,
1549 'from' => $receiptFrom,
1550 'toName' => $participantName,
1551 'toEmail' => $toEmail,
1552 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1553 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1557 // 3. create activity record.
1559 $now = date('YmdHis');
1560 $activityType = 'Event Registration';
1561 $activityParams = array(
1562 'subject' => $subject,
1563 'source_contact_id' => $contactId,
1564 'source_record_id' => $participantId,
1565 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1569 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1570 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1571 'is_test' => $participantValues['is_test'],
1575 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1576 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1585 * Get participant status change message.
1587 * @param int $participantId
1588 * @param $statusChangeTo
1589 * @param int $fromStatusId
1593 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1595 $results = self
::transitionParticipants(array($participantId),
1596 $statusChangeTo, $fromStatusId, TRUE
1599 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1600 //give user message only when mail has sent.
1601 if (is_array($results) && !empty($results)) {
1602 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1603 foreach ($results['updatedParticipantIds'] as $processedId) {
1604 if (is_array($results['mailedParticipants']) &&
1605 array_key_exists($processedId, $results['mailedParticipants'])
1607 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1609 1 => $allStatuses[$statusChangeTo],
1610 2 => $results['mailedParticipants'][$processedId],
1622 * Get event full and waiting list message.
1624 * @param int $eventId
1625 * @param int $participantId
1629 public static function eventFullMessage($eventId, $participantId = NULL) {
1630 $eventfullMsg = $dbStatusId = NULL;
1631 $checkEventFull = TRUE;
1632 if ($participantId) {
1633 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1634 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1635 //participant already in counted status no need to check for event full messages.
1636 $checkEventFull = FALSE;
1641 if (!$eventId ||
!$checkEventFull) {
1642 return $eventfullMsg;
1645 //event is truly full.
1646 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1647 if (is_string($emptySeats) && $emptySeats !== NULL) {
1648 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1649 $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(
1650 1 => $maxParticipants,
1654 $hasWaiting = FALSE;
1655 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1656 if (is_numeric($waitListedCount)) {
1658 //only current processing participant is on waitlist.
1659 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1660 $hasWaiting = FALSE;
1665 $waitingStatusId = array_search('On waitlist',
1666 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1668 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1669 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1672 $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.",
1674 1 => $viewWaitListUrl,
1675 2 => $waitListedCount,
1680 return $eventfullMsg;
1684 * Check for whether participant is primary or not
1686 * @param int $participantId
1689 * true if participant is primary
1691 public static function isPrimaryParticipant($participantId) {
1693 $participant = new CRM_Event_DAO_Participant();
1694 $participant->registered_by_id
= $participantId;
1696 if ($participant->find(TRUE)) {
1703 * Get additional participant Ids for cascading with primary participant status
1705 * @param int $participantId
1707 * @param int $oldStatusId
1709 * @param int $newStatusId
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
1740 * 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.
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.
1795 public static function getAdditionalParticipantUrl($participantIds) {
1796 foreach ($participantIds as $value) {
1798 $details = self
::participantDetails($value);
1799 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1800 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1802 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1803 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1805 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1806 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1812 * create trxn entry if an event has discount.
1814 * @param int $eventID
1816 * @param array $contributionParams
1817 * Contribution params.
1823 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel) {
1825 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID, 'civicrm_event');
1826 if (!empty($checkDiscount)) {
1827 $feeLevel = current($feeLevel);
1828 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1829 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1830 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1831 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1833 1 => array($priceSetId, 'Integer'),
1834 2 => array($feeLevel, 'String'),
1836 $mainAmount = CRM_Core_DAO
::singleValueQuery($query, $params);
1837 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
1838 $contributionParams['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
1839 $contributionParams['contribution']->financial_type_id
, $relationTypeId);
1840 if (!empty($contributionParams['trxnParams']['from_financial_account_id'])) {
1841 $contributionParams['trxnParams']['total_amount'] = $mainAmount - $contributionParams['total_amount'];
1842 $contributionParams['trxnParams']['payment_processor_id'] = $contributionParams['trxnParams']['payment_instrument_id'] =
1843 $contributionParams['trxnParams']['check_number'] = $contributionParams['trxnParams']['trxn_id'] =
1844 $contributionParams['trxnParams']['net_amount'] = $contributionParams['trxnParams']['fee_amount'] = NULL;
1846 CRM_Core_BAO_FinancialTrxn
::create($contributionParams['trxnParams']);
1853 * Delete participants of contact
1857 * @param int $contactId
1862 public static function deleteContactParticipant($contactId) {
1863 $participant = new CRM_Event_DAO_Participant();
1864 $participant->contact_id
= $contactId;
1865 $participant->find();
1866 while ($participant->fetch()) {
1867 self
::deleteParticipant($participant->id
);
1872 * @param array $params
1873 * @param int $participantId
1874 * @param int $contributionId
1876 * @param array $lineItems
1877 * @param $paidAmount
1878 * @param int $priceSetId
1880 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) {
1881 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1882 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1883 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1884 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($participantId, 'participant');
1885 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
1889 // get the submitted
1890 foreach ($feeBlock as $id => $values) {
1891 CRM_Price_BAO_LineItem
::format($id, $params, $values, $submittedLineItems);
1892 $submittedFieldId[] = CRM_Utils_Array
::retrieveValueRecursive($submittedLineItems, 'price_field_id');
1894 if (!empty($submittedLineItems)) {
1895 $insertLines = $submittedLineItems;
1897 $submittedFieldValueIds = array_keys($submittedLineItems);
1898 $updateLines = array();
1899 foreach ($previousLineItems as $id => $previousLineItem) {
1900 // check through the submitted items if the previousItem exists,
1901 // if found in submitted items, do not use it for new item creations
1902 if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
1903 // if submitted line items are existing don't fire INSERT query
1904 unset($insertLines[$previousLineItem['price_field_value_id']]);
1905 // for updating the line items i.e. use-case - once deselect-option selecting again
1906 if (($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) ||
1907 ($submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1)
1909 $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
1910 $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
1915 $submittedFields = implode(', ', $submittedFieldId);
1916 $submittedFieldValues = implode(', ', $submittedFieldValueIds);
1918 if (!empty($submittedFields) && !empty($submittedFieldValues)) {
1919 $updateLineItem = "UPDATE civicrm_line_item li
1920 INNER JOIN civicrm_financial_item fi
1921 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1923 li.line_total = 0.00,
1924 li.tax_amount = NULL
1925 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
1926 (price_field_value_id NOT IN ({$submittedFieldValues}))
1928 CRM_Core_DAO
::executeQuery($updateLineItem);
1930 // gathering necessary info to record negative (deselected) financial_item
1931 $updateFinancialItem = "
1932 SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
1933 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1934 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
1935 GROUP BY li.entity_table, li.entity_id, price_field_value_id
1937 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1938 $trxn = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId, 'ASC', TRUE);
1939 $trxnId['id'] = $trxn['financialTrxnId'];
1940 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1941 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
1942 $updateFinancialItemInfoValues = array();
1944 while ($updateFinancialItemInfoDAO->fetch()) {
1945 $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
1946 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
1947 // the below params are not needed
1948 unset($updateFinancialItemInfoValues['id']);
1949 unset($updateFinancialItemInfoValues['created_date']);
1950 // if not submitted and difference is not 0 make it negative
1951 if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
1952 // INSERT negative financial_items
1953 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
1954 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1955 // INSERT negative financial_items for tax amount
1956 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
1957 $updateFinancialItemInfoValues['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
1958 $updateFinancialItemInfoValues['description'] = $taxTerm;
1959 if ($updateFinancialItemInfoValues['financial_type_id']) {
1960 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
1962 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1965 // if submitted and difference is 0 add a positive entry again
1966 elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
1967 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
1968 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1969 // INSERT financial_items for tax amount
1970 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
1971 isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
1973 $updateFinancialItemInfoValues['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
1974 $updateFinancialItemInfoValues['description'] = $taxTerm;
1975 if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
1976 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
1978 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1983 elseif (empty($submittedFields) && empty($submittedFieldValues)) {
1984 $updateLineItem = "UPDATE civicrm_line_item li
1985 INNER JOIN civicrm_financial_item fi
1986 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1988 li.line_total = 0.00,
1989 li.tax_amount = NULL
1990 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
1991 CRM_Core_DAO
::executeQuery($updateLineItem);
1993 if (!empty($updateLines)) {
1994 foreach ($updateLines as $valueId => $vals) {
1995 if (isset($vals['tax_amount'])) {
1996 $taxAmount = $vals['tax_amount'];
1999 $taxAmount = "NULL";
2002 UPDATE civicrm_line_item li
2003 SET li.qty = {$vals['qty']},
2004 li.line_total = {$vals['line_total']},
2005 li.tax_amount = {$taxAmount},
2006 li.unit_price = {$vals['unit_price']},
2007 li.label = '{$vals['label']}'
2008 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
2009 (price_field_value_id = {$valueId})
2011 CRM_Core_DAO
::executeQuery($updateLineItem);
2014 // insert new 'adjusted amount' transaction entry and update contribution entry.
2015 // ensure entity_financial_trxn table has a linking of it.
2016 // insert new line items
2017 if (!empty($insertLines)) {
2018 foreach ($insertLines as $valueId => $lineParams) {
2019 $lineParams['entity_table'] = 'civicrm_participant';
2020 $lineParams['entity_id'] = $participantId;
2021 $lineParams['contribution_id'] = $contributionId;
2022 $lineObj = CRM_Price_BAO_LineItem
::create($lineParams);
2026 // the recordAdjustedAmt code would execute over here
2027 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
2028 if (count($ids) > 1) {
2030 foreach ($ids as $val) {
2031 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, 'civicrm_participant');
2033 $updatedAmount = $total;
2036 $updatedAmount = $params['amount'];
2038 if (strlen($params['tax_amount']) != 0) {
2039 $taxAmount = $params['tax_amount'];
2042 $taxAmount = "NULL";
2044 self
::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount);
2046 $fetchCon = array('id' => $contributionId);
2047 $updatedContribution = CRM_Contribute_BAO_Contribution
::retrieve($fetchCon, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2048 // insert financial items
2049 if (!empty($insertLines)) {
2050 foreach ($insertLines as $valueId => $lineParams) {
2051 $lineParams['entity_table'] = 'civicrm_participant';
2052 $lineParams['entity_id'] = $participantId;
2053 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams, CRM_Core_DAO
::$_nullArray);
2054 // insert financial items
2055 // ensure entity_financial_trxn table has a linking of it.
2056 $prevItem = CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution);
2057 if (isset($lineObj->tax_amount
)) {
2058 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE);
2063 // update participant fee_amount column
2064 $partUpdateFeeAmt['id'] = $participantId;
2065 foreach ($lineItems as $lineValue) {
2066 if ($lineValue['price_field_value_id']) {
2067 $line[$lineValue['price_field_value_id']] = $lineValue['label'] . ' - ' . $lineValue['qty'];
2071 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
2072 $partUpdateFeeAmt['fee_amount'] = $params['amount'];
2073 self
::add($partUpdateFeeAmt);
2076 self
::addActivityForSelection($participantId, 'Change Registration');
2080 * @param $updatedAmount
2081 * @param $paidAmount
2082 * @param int $contributionId
2084 public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL) {
2085 $balanceAmt = $updatedAmount - $paidAmount;
2086 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2087 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
2088 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
2089 $completedStatusId = array_search('Completed', $contributionStatuses);
2091 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
2094 if ($balanceAmt > 0 && $paidAmount != 0) {
2095 $contributionStatusVal = $partiallyPaidStatusId;
2097 elseif ($balanceAmt < 0 && $paidAmount != 0) {
2098 $contributionStatusVal = $pendingRefundStatusId;
2100 elseif ($paidAmount == 0) {
2101 //skip updating the contribution status if no payment is made
2103 $updatedContributionDAO->cancel_date
= 'null';
2104 $updatedContributionDAO->cancel_reason
= NULL;
2106 // update contribution status and total amount without trigger financial code
2107 // as this is handled in current BAO function used for change selection
2108 $updatedContributionDAO->id
= $contributionId;
2110 $updatedContributionDAO->contribution_status_id
= $contributionStatusVal;
2112 $updatedContributionDAO->total_amount
= $updatedAmount;
2113 $updatedContributionDAO->tax_amount
= $taxAmount;
2114 $updatedContributionDAO->save();
2116 $ftDetail = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
2117 // adjusted amount financial_trxn creation
2118 if (empty($ftDetail['trxn_id'])) {
2119 $updatedContribution =
2120 CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contributionId), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2121 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2122 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($updatedContribution->financial_type_id
, $relationTypeId);
2124 $adjustedTrxnValues = array(
2125 'from_financial_account_id' => NULL,
2126 'to_financial_account_id' => $toFinancialAccount,
2127 'total_amount' => $balanceAmt,
2128 'status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
2129 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
2130 'contribution_id' => $updatedContribution->id
,
2131 'trxn_date' => date('YmdHis'),
2132 'currency' => $updatedContribution->currency
,
2134 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
2137 // update the financial trxn amount as well, as the fee selections has been updated
2138 if ($balanceAmt != $ftDetail['total_amount']) {
2139 CRM_Core_DAO
::setFieldValue('CRM_Core_BAO_FinancialTrxn', $ftDetail['trxn_id'], 'total_amount', $balanceAmt);
2146 * @param int $participantId
2147 * @param $activityType
2149 * @throws CRM_Core_Exception
2151 public static function addActivityForSelection($participantId, $activityType) {
2152 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
2153 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
2155 $date = CRM_Utils_Date
::currentDBDate();
2156 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
2157 $eventTitle = $event[$eventId];
2158 $subject = "Registration selections changed for $eventTitle";
2159 $targetCid = $contactId;
2160 $srcRecId = $participantId;
2163 $activityParams = array(
2164 'source_contact_id' => $targetCid,
2165 'source_record_id' => $srcRecId,
2166 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
2170 'subject' => $subject,
2171 'activity_date_time' => $date,
2172 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
2176 'skipRecentView' => TRUE,
2179 // create activity with target contacts
2180 $session = CRM_Core_Session
::singleton();
2181 $id = $session->get('userID');
2183 $activityParams['source_contact_id'] = $id;
2184 $activityParams['target_contact_id'][] = $targetCid;
2186 CRM_Activity_BAO_Activity
::create($activityParams);
2190 * Get options for a given field.
2191 * @see CRM_Core_DAO::buildOptions
2193 * @param string $fieldName
2194 * @param string $context
2195 * @see CRM_Core_DAO::buildOptionsContext.
2196 * @param array $props
2197 * whatever is known about this dao object.
2199 * @return Array|bool
2201 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2202 $params = array('condition' => array());
2204 if ($fieldName == 'status_id' && $context != 'validate') {
2205 // Get rid of cart-related option if disabled
2206 // FIXME: Why does this option even exist if cart is disabled?
2207 if (!CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
, 'enable_cart')) {
2208 $params['condition'][] = "name <> 'Pending in cart'";
2212 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);