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 (reference ) an assoc array of name/value pairs
86 * @return CRM_Event_BAO_Participant object
89 public static function &add(&$params) {
91 if (!empty($params['id'])) {
92 CRM_Utils_Hook
::pre('edit', 'Participant', $params['id'], $params);
95 CRM_Utils_Hook
::pre('create', 'Participant', NULL, $params);
98 // converting dates to mysql format
99 if (!empty($params['register_date'])) {
100 $params['register_date'] = CRM_Utils_Date
::isoToMysql($params['register_date']);
103 if (!empty($params['participant_fee_amount'])) {
104 $params['participant_fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['participant_fee_amount']);
107 if (!empty($params['fee_amount'])) {
108 $params['fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['fee_amount']);
111 // ensure that role ids are encoded as a string
112 if (isset($params['role_id']) && is_array($params['role_id'])) {
113 $params['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['role_id']);
116 $participantBAO = new CRM_Event_BAO_Participant
;
117 if (!empty($params['id'])) {
118 $participantBAO->id
= CRM_Utils_Array
::value('id', $params);
119 $participantBAO->find(TRUE);
120 $participantBAO->register_date
= CRM_Utils_Date
::isoToMysql($participantBAO->register_date
);
123 $participantBAO->copyValues($params);
126 //1. If currency present, it should be valid one.
127 //2. We should have currency when amount is not null.
128 $currency = $participantBAO->fee_currency
;
130 !CRM_Utils_System
::isNull($participantBAO->fee_amount
)
132 if (!CRM_Utils_Rule
::currencyCode($currency)) {
133 $config = CRM_Core_Config
::singleton();
134 $currency = $config->defaultCurrency
;
137 $participantBAO->fee_currency
= $currency;
139 $participantBAO->save();
141 $session = CRM_Core_Session
::singleton();
143 // reset the group contact cache for this group
144 CRM_Contact_BAO_GroupContactCache
::remove();
146 if (!empty($params['id'])) {
147 CRM_Utils_Hook
::post('edit', 'Participant', $participantBAO->id
, $participantBAO);
150 CRM_Utils_Hook
::post('create', 'Participant', $participantBAO->id
, $participantBAO);
153 return $participantBAO;
157 * Given the list of params in the params array, fetch the object
158 * and store the values in the values array
160 * @param array $params input parameters to find object
161 * @param array $values output values of the object
165 * @return CRM_Event_BAO_Participant|null the found object or null
168 public static function getValues(&$params, &$values, &$ids) {
169 if (empty($params)) {
172 $participant = new CRM_Event_BAO_Participant();
173 $participant->copyValues($params);
174 $participant->find();
175 $participants = array();
176 while ($participant->fetch()) {
177 $ids['participant'] = $participant->id
;
178 CRM_Core_DAO
::storeValues($participant, $values[$participant->id
]);
179 $participants[$participant->id
] = $participant;
181 return $participants;
185 * Takes an associative array and creates a participant object
187 * @param array $params (reference ) an assoc array of name/value pairs
189 * @return CRM_Event_BAO_Participant object
192 public static function create(&$params) {
194 $transaction = new CRM_Core_Transaction();
197 if (!empty($params['id'])) {
198 $status = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
201 $participant = self
::add($params);
203 if (is_a($participant, 'CRM_Core_Error')) {
204 $transaction->rollback();
208 if ((!CRM_Utils_Array
::value('id', $params)) ||
209 (isset($params['status_id']) && $params['status_id'] != $status)
211 CRM_Activity_BAO_Activity
::addActivity($participant);
216 if (self
::isPrimaryParticipant($participant->id
) && $status) {
217 self
::updateParticipantStatus($participant->id
, $status, $participant->status_id
);
220 $session = CRM_Core_Session
::singleton();
221 $id = $session->get('userID');
223 $id = CRM_Utils_Array
::value('contact_id', $params);
226 // add custom field values
227 if (!empty($params['custom']) &&
228 is_array($params['custom'])
230 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_participant', $participant->id
);
233 //process note, CRM-7634
235 if (!empty($params['id'])) {
236 $note = CRM_Core_BAO_Note
::getNote($params['id'], 'civicrm_participant');
237 $noteId = key($note);
240 $hasNoteField = FALSE;
242 'note', 'participant_note') as $noteFld) {
243 if (array_key_exists($noteFld, $params)) {
244 $noteValue = $params[$noteFld];
245 $hasNoteField = TRUE;
249 if ($noteId ||
$noteValue) {
252 'entity_table' => 'civicrm_participant',
253 'note' => $noteValue,
254 'entity_id' => $participant->id
,
256 'modified_date' => date('Ymd'),
260 $noteIDs['id'] = $noteId;
262 CRM_Core_BAO_Note
::add($noteParams, $noteIDs);
264 elseif ($noteId && $hasNoteField) {
265 CRM_Core_BAO_Note
::del($noteId, FALSE);
269 // Log the information on successful add/edit of Participant data.
271 'entity_table' => 'civicrm_participant',
272 'entity_id' => $participant->id
,
273 'data' => CRM_Event_PseudoConstant
::participantStatus($participant->status_id
),
274 'modified_id' => $id,
275 'modified_date' => date('Ymd'),
278 CRM_Core_BAO_Log
::add($logParams);
280 $params['participant_id'] = $participant->id
;
282 $transaction->commit();
284 // do not add to recent items for import, CRM-4399
285 if (empty($params['skipRecentView'])) {
287 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
288 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
291 $recentOther = array();
292 if (CRM_Core_Permission
::check('edit event participants')) {
293 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
294 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
297 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
298 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
299 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
303 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
305 if ($participant->role_id
) {
306 $role = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participant->role_id
);
308 foreach ($role as & $roleValue) {
309 if (isset($roleValue)) {
310 $roleValue = $participantRoles[$roleValue];
313 $roles = implode(', ', $role);
316 $roleString = empty($roles) ?
'' : $roles;
317 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $participant->event_id
, 'title');
318 $title = CRM_Contact_BAO_Contact
::displayName($participant->contact_id
) . ' (' . $roleString . ' - ' . $eventTitle . ')';
320 // add the recently created Participant
321 CRM_Utils_Recent
::add($title,
325 $participant->contact_id
,
335 * Check whether the event is full for participation and return as
338 * @param int $eventId event id.
339 * @param boolean $returnEmptySeats are we require number if empty seats.
340 * @param boolean $includeWaitingList consider waiting list in event full
341 * calculation or not. (it is for cron job purpose)
343 * @param bool $returnWaitingCount
344 * @param bool $considerTestParticipant
346 * @return bool|int|null|string 1. false => If event having some empty spaces.@static
348 static function eventFull(
350 $returnEmptySeats = FALSE,
351 $includeWaitingList = TRUE,
352 $returnWaitingCount = FALSE,
353 $considerTestParticipant = FALSE
360 // consider event is full when.
361 // 1. (count(is_counted) >= event_size) or
362 // 2. (count(participants-with-status-on-waitlist) > 0)
363 // It might be case there are some empty spaces and still event
364 // is full, as waitlist might represent group require spaces > empty.
366 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
367 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
368 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
369 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
371 //when we do require only waiting count don't consider counted.
372 if (!$returnWaitingCount && !empty($countedStatuses)) {
373 $allStatusIds = array_keys($countedStatuses);
376 $where = array(' event.id = %1 ');
377 if (!$considerTestParticipant) {
378 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
380 if (!empty($participantRoles)) {
381 $where[] = ' participant.role_id IN ( ' . implode(', ', array_keys($participantRoles)) . ' ) ';
384 $eventParams = array(1 => array($eventId, 'Positive'));
386 //in case any waiting, straight forward event is full.
387 if ($includeWaitingList && $onWaitlistStatusId) {
389 //build the where clause.
390 $whereClause = ' WHERE ' . implode(' AND ', $where);
391 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
392 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
395 SELECT participant.id id,
396 event.event_full_text as event_full_text
397 FROM civicrm_participant participant
398 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
401 $eventFullText = ts('This event is full.');
402 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
403 while ($participants->fetch()) {
404 //oops here event is full and we don't want waiting count.
405 if ($returnWaitingCount) {
406 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
409 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
414 //consider only counted participants.
415 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
416 $whereClause = ' WHERE ' . implode(' AND ', $where);
417 $eventSeatsWhere = implode(' AND ', $where);
420 SELECT participant.id id,
421 event.event_full_text as event_full_text,
422 event.max_participants as max_participants
423 FROM civicrm_participant participant
424 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
427 $eventMaxSeats = NULL;
428 $eventFullText = ts('This event is full.');
429 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
430 while ($participants->fetch()) {
431 if ($participants->event_full_text
) {
432 $eventFullText = $participants->event_full_text
;
434 $eventMaxSeats = $participants->max_participants
;
435 //don't have limit for event seats.
436 if ($participants->max_participants
== NULL) {
441 //get the total event seats occupied by these participants.
442 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
444 if ($eventRegisteredSeats) {
445 if ($eventRegisteredSeats >= $eventMaxSeats) {
446 $result = $eventFullText;
448 elseif ($returnEmptySeats) {
449 $result = $eventMaxSeats - $eventRegisteredSeats;
455 SELECT event.event_full_text,
456 event.max_participants
457 FROM civicrm_event event
458 WHERE event.id = %1';
459 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
460 while ($event->fetch()) {
461 $eventFullText = $event->event_full_text
;
462 $eventMaxSeats = $event->max_participants
;
466 // no limit for registration.
467 if ($eventMaxSeats == NULL) {
470 if ($eventMaxSeats) {
471 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
474 return $eventFullText;
478 * Return the array of all price set field options,
479 * with total participant count that field going to carry.
481 * @param int $eventId event id.
482 * @param array $skipParticipantIds an array of participant ids those we should skip.
483 * @param bool $considerCounted
484 * @param bool $considerWaiting
485 * @param bool $considerTestParticipants
487 * @return array $optionsCount an array of each option id and total count
490 static function priceSetOptionsCount(
492 $skipParticipantIds = array(),
493 $considerCounted = TRUE,
494 $considerWaiting = TRUE,
495 $considerTestParticipants = FALSE
497 $optionsCount = array();
499 return $optionsCount;
502 $allStatusIds = array();
503 if ($considerCounted) {
504 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
505 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
507 if ($considerWaiting) {
508 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
509 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
511 $statusIdClause = NULL;
512 if (!empty($allStatusIds)) {
513 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
516 $isTestClause = NULL;
517 if (!$considerTestParticipants) {
518 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
521 $skipParticipantClause = NULL;
522 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
523 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
527 SELECT line.id as lineId,
528 line.entity_id as entity_id,
533 FROM civicrm_line_item line
534 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
535 AND participant.id = line.entity_id )
536 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
537 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
538 WHERE participant.event_id = %1
541 {$skipParticipantClause}";
543 $lineItem = CRM_Core_DAO
::executeQuery($sql, array(1 => array($eventId, 'Positive')));
544 while ($lineItem->fetch()) {
545 $count = $lineItem->count
;
549 if ($lineItem->html_type
== 'Text') {
550 $count *= $lineItem->qty
;
552 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
555 return $optionsCount;
559 * Get the empty spaces for event those we can allocate
560 * to pending participant to become confirm.
562 * @param int $eventId event id.
564 * @return int $spaces Number of Empty Seats/null.
567 public static function pendingToConfirmSpaces($eventId) {
573 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
574 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
577 SELECT count(participant.id) as registered,
578 civicrm_event.max_participants
579 FROM civicrm_participant participant, civicrm_event
580 WHERE participant.event_id = {$eventId}
581 AND civicrm_event.id = participant.event_id
582 AND participant.status_id IN {$statusIds}
583 GROUP BY participant.event_id
585 $dao = CRM_Core_DAO
::executeQuery($query);
589 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
594 if ($dao->registered
>= $dao->max_participants
) {
599 return $dao->max_participants
- $dao->registered
;
602 //space in case no registeration yet.
603 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
607 * Combine all the importable fields from the lower levels object
609 * @param string $contactType
610 * @param bool $status
611 * @param bool $onlyParticipant
613 * @return array array of importable Fields
616 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE) {
617 if (!self
::$_importableFields) {
618 if (!$onlyParticipant) {
620 $fields = array('' => array('title' => ts('- do not import -')));
623 $fields = array('' => array('title' => ts('- Participant Fields -')));
630 $tmpFields = CRM_Event_DAO_Participant
::import();
633 'participant_note' => array(
634 'title' => ts('Participant Note'),
635 'name' => 'participant_note',
636 'headerPattern' => '/(participant.)?note$/i',
639 // Split status and status id into 2 fields
640 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
641 $participantStatus = array(
642 'participant_status' => array(
643 'title' => ts('Participant Status'),
644 'name' => 'participant_status',
645 'data_type' => CRM_Utils_Type
::T_STRING
,
647 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
649 // Split role and role id into 2 fields
650 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
651 $participantRole = array(
652 'participant_role' => array(
653 'title' => ts('Participant Role'),
654 'name' => 'participant_role',
655 'data_type' => CRM_Utils_Type
::T_STRING
,
657 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
660 'event_type' => array(
661 'title' => ts('Event Type'),
662 'name' => 'event_type',
663 'data_type' => CRM_Utils_Type
::T_STRING
,
666 $tmpContactField = $contactFields = array();
667 $contactFields = array( );
668 if (!$onlyParticipant) {
669 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
671 // Using new Dedupe rule.
673 'contact_type' => $contactType,
674 'used' => 'Unsupervised',
676 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
678 if (is_array($fieldsArray)) {
679 foreach ($fieldsArray as $value) {
680 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
685 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
686 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
688 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
691 $title = $tmpContactField[trim($value)]['title'];
694 $tmpContactField[trim($value)]['title'] = $title;
698 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
699 if ($extIdentifier) {
700 $tmpContactField['external_identifier'] = $extIdentifier;
701 $tmpContactField['external_identifier']['title'] =
702 CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
704 $tmpFields['participant_contact_id']['title'] =
705 $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
707 $fields = array_merge($fields, $tmpContactField);
708 $fields = array_merge($fields, $tmpFields);
709 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
710 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
712 self
::$_importableFields = $fields;
715 return self
::$_importableFields;
719 * Combine all the exportable fields from the lower levels object
721 * @return array array of exportable Fields
724 public static function &exportableFields() {
725 if (!self
::$_exportableFields) {
726 if (!self
::$_exportableFields) {
727 self
::$_exportableFields = array();
732 $participantFields = CRM_Event_DAO_Participant
::export();
734 'participant_note' => array('title' => 'Participant Note',
735 'name' => 'participant_note',
738 $participantStatus = array(
739 'participant_status' => array('title' => 'Participant Status',
740 'name' => 'participant_status',
743 $participantRole = array(
744 'participant_role' => array('title' => 'Participant Role',
745 'name' => 'participant_role',
748 //CRM-13595 add event id to participant export
750 'event_id' => array('title' => 'Event ID',
751 'name' => 'event_id',
754 'event_title' => array('title' => 'Event Title',
755 'name' => 'event_title',
758 $discountFields = CRM_Core_DAO_Discount
::export();
760 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventid, $eventtitle, $noteField, $discountFields);
763 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
764 self
::$_exportableFields = $fields;
767 return self
::$_exportableFields;
771 * Get the event name/sort name for a particular participation / participant
773 * @param int $participantId id of the participant
776 * @return array $name associated array with sort_name and event title
779 public static function participantDetails($participantId) {
781 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
782 FROM civicrm_participant
783 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
784 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
785 WHERE civicrm_participant.id = {$participantId}
787 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
790 while ($dao->fetch()) {
791 $details['name'] = $dao->name
;
792 $details['title'] = $dao->title
;
793 $details['cid'] = $dao->cid
;
800 * Get the values for pseudoconstants for name->value and reverse.
802 * @param array $defaults (reference) the default values, some of which need to be resolved.
803 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
808 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
809 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
810 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
811 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
815 * This function is used to convert associative array names to values
818 * This function is used by both the web form layer and the api. Note that
819 * the api needs the name => value conversion, also the view layer typically
820 * requires value => name conversion
822 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
823 $id = $property . '_id';
825 $src = $reverse ?
$property : $id;
826 $dst = $reverse ?
$id : $property;
828 if (!array_key_exists($src, $defaults)) {
832 $look = $reverse ?
array_flip($lookup) : $lookup;
834 if (is_array($look)) {
835 if (!array_key_exists($defaults[$src], $look)) {
839 $defaults[$dst] = $look[$defaults[$src]];
844 * Delete the record that are associated with this participation
846 * @param int $id id of the participation to delete
851 public static function deleteParticipant($id) {
852 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
854 $transaction = new CRM_Core_Transaction();
856 //delete activity record
858 'source_record_id' => $id,
859 // activity type id for event registration
860 'activity_type_id' => 5,
863 CRM_Activity_BAO_Activity
::deleteActivity($params);
865 // delete the participant payment record
866 // we need to do this since the cascaded constraints
867 // dont work with join tables
868 $p = array('participant_id' => $id);
869 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
871 // cleanup line items.
872 $participantsId = array();
873 $participantsId = self
::getAdditionalParticipantIds($id);
874 $participantsId[] = $id;
875 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
877 //delete note when participant deleted.
878 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
879 $noteId = key($note);
881 CRM_Core_BAO_Note
::del($noteId, FALSE);
884 $participant = new CRM_Event_DAO_Participant();
885 $participant->id
= $id;
886 $participant->delete();
888 $transaction->commit();
890 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
892 // delete the recently created Participant
893 $participantRecent = array(
895 'type' => 'Participant',
898 CRM_Utils_Recent
::del($participantRecent);
904 * Checks duplicate participants
906 * @param array $duplicates (reference ) an assoc array of name/value pairs
907 * @param array $input an assosiative array of name /value pairs
908 * from other function
910 * @return CRM_Contribute_BAO_Contribution object
913 public static function checkDuplicate($input, &$duplicates) {
914 $eventId = CRM_Utils_Array
::value('event_id', $input);
915 $contactId = CRM_Utils_Array
::value('contact_id', $input);
921 $clause[] = "event_id = %1";
922 $input[1] = array($eventId, 'Integer');
926 $clause[] = "contact_id = %2";
927 $input[2] = array($contactId, 'Integer');
930 if (empty($clause)) {
934 $clause = implode(' AND ', $clause);
936 $query = "SELECT id FROM civicrm_participant WHERE $clause";
937 $dao = CRM_Core_DAO
::executeQuery($query, $input);
939 while ($dao->fetch()) {
940 $duplicates[] = $dao->id
;
947 * Fix the event level
949 * When price sets are used as event fee, fee_level is set as ^A
950 * separated string. We need to change that string to comma
951 * separated string before using fee_level in view mode.
953 * @param string $eventLevel event_leval string from db
959 public static function fixEventLevel(&$eventLevel) {
960 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
961 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
963 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($eventLevel, 1, -1)));
964 $pos = strrpos($eventLevel, '(multiple participants)', 0);
966 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
969 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
970 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
971 substr($eventLevel, 0, 1)
974 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
975 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
976 substr($eventLevel, 0, -1)
982 * Get the additional participant ids.
984 * @param int $primaryParticipantId primary partycipant Id
985 * @param boolean $excludeCancel do not include participant those are cancelled.
987 * @param int $oldStatusId
989 * @return array $additionalParticipantIds
992 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
993 $additionalParticipantIds = array();
994 if (!$primaryParticipantId) {
995 return $additionalParticipantIds;
998 $where = "participant.registered_by_id={$primaryParticipantId}";
999 if ($excludeCancel) {
1000 $cancelStatusId = 0;
1001 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1002 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1003 $where .= " AND participant.status_id != {$cancelStatusId}";
1007 $where .= " AND participant.status_id = {$oldStatusId}";
1011 SELECT participant.id
1012 FROM civicrm_participant participant
1015 $dao = CRM_Core_DAO
::executeQuery($query);
1016 while ($dao->fetch()) {
1017 $additionalParticipantIds[$dao->id
] = $dao->id
;
1019 return $additionalParticipantIds;
1023 * Get the event fee info for given participant ids
1024 * either from line item table / participant table.
1026 * @param array $participantIds participant ids.
1027 * @param boolean $hasLineItems do fetch from line items.
1029 * @return array $feeDetails
1032 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1033 $feeDetails = array();
1034 if (!is_array($participantIds) ||
empty($participantIds)) {
1039 SELECT participant.id as id,
1040 participant.fee_level as fee_level,
1041 participant.fee_amount as fee_amount';
1042 $from = 'FROM civicrm_participant participant';
1043 if ($hasLineItems) {
1045 lineItem.id as lineId,
1046 lineItem.label as label,
1047 lineItem.qty as qty,
1048 lineItem.unit_price as unit_price,
1049 lineItem.line_total as line_total,
1050 field.label as field_title,
1051 field.html_type as html_type,
1052 field.id as price_field_id,
1053 value.id as price_field_value_id,
1054 value.description as description,
1055 IF( value.count, value.count, 0 ) as participant_count';
1057 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1058 AND lineItem.entity_id = participant.id )
1059 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1060 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1063 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1064 $query = "$select $from $where";
1066 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1067 $feeProperties = array('fee_level', 'fee_amount');
1068 $lineProperties = array(
1069 'lineId', 'label', 'qty', 'unit_price',
1070 'line_total', 'field_title', 'html_type',
1071 'price_field_id', 'participant_count', 'price_field_value_id', 'description',
1073 while ($feeInfo->fetch()) {
1074 if ($hasLineItems) {
1075 foreach ($lineProperties as $property) {
1076 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1080 foreach ($feeProperties as $property) $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1088 * Retrieve additional participants display-names and URL to view their participant records.
1089 * (excludes cancelled participants automatically)
1091 * @param int $primaryParticipantID id of primary participant record
1093 * @return array $additionalParticipants $displayName => $viewUrl
1096 public static function getAdditionalParticipants($primaryParticipantID) {
1097 $additionalParticipantIDs = array();
1098 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1099 if (!empty($additionalParticipantIDs)) {
1100 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1101 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1102 $additionalParticipantID,
1105 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1106 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1107 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1110 $additionalParticipants[$additionalContactName] = $pViewURL;
1113 return $additionalParticipants;
1117 * Function for update primary and additional participant status
1119 * @param int $participantID primary participant's id
1120 * @param int $oldStatusID
1121 * @param int $newStatusID
1122 * @param bool $updatePrimaryStatus
1127 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1128 if (!$participantID ||
!$oldStatusID) {
1132 if (!$newStatusID) {
1133 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1135 elseif ($updatePrimaryStatus) {
1136 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1139 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1141 if (!empty($cascadeAdditionalIds)) {
1142 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1143 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1144 $params = array(1 => array($newStatusID, 'Integer'));
1145 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1152 * Function for update status for given participant ids
1154 * @param int $participantIds array of participant ids
1155 * @param int $statusId status id for participant
1156 * @param bool $updateRegisterDate
1162 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1163 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1167 //lets update register date as we update status to keep track
1168 //when we did update status, useful for moving participant
1169 //from pending to expired.
1170 $setClause = "status_id = {$statusId}";
1171 if ($updateRegisterDate) {
1172 $setClause .= ", register_date = NOW()";
1175 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1178 UPDATE civicrm_participant
1180 WHERE id IN {$participantIdClause}";
1182 $dao = CRM_Core_DAO
::executeQuery($query);
1186 * Function takes participant ids and statuses
1187 * update status from $fromStatusId to $toStatusId
1188 * and send mail + create activities.
1190 * @param array $participantIds participant ids.
1191 * @param int $toStatusId update status id.
1192 * @param int $fromStatusId from status id
1195 * @param bool $returnResult
1196 * @param bool $skipCascadeRule
1201 static function transitionParticipants($participantIds, $toStatusId,
1202 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1204 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1208 //thumb rule is if we triggering primary participant need to triggered additional
1209 $allParticipantIds = $primaryANDAdditonalIds = array();
1210 foreach ($participantIds as $id) {
1211 $allParticipantIds[] = $id;
1212 if (self
::isPrimaryParticipant($id)) {
1213 //filter additional as per status transition rules, CRM-5403
1214 if ($skipCascadeRule) {
1215 $additionalIds = self
::getAdditionalParticipantIds($id);
1218 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1220 if (!empty($additionalIds)) {
1221 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1222 $primaryANDAdditonalIds[$id] = $additionalIds;
1227 //get the unique participant ids,
1228 $allParticipantIds = array_unique($allParticipantIds);
1230 //pull required participants, contacts, events data, if not in hand
1231 static $eventDetails = array();
1232 static $domainValues = array();
1233 static $contactDetails = array();
1235 $contactIds = $eventIds = $participantDetails = array();
1237 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1238 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1239 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1243 //first thing is pull all necessory data from db.
1244 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1246 //get all participants data.
1247 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1248 $dao = CRM_Core_DAO
::executeQuery($query);
1249 while ($dao->fetch()) {
1250 $participantDetails[$dao->id
] = array(
1252 'role' => $participantRoles[$dao->role_id
],
1253 'is_test' => $dao->is_test
,
1254 'event_id' => $dao->event_id
,
1255 'status_id' => $dao->status_id
,
1256 'fee_amount' => $dao->fee_amount
,
1257 'contact_id' => $dao->contact_id
,
1258 'register_date' => $dao->register_date
,
1259 'registered_by_id' => $dao->registered_by_id
,
1261 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1262 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1265 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1266 $eventIds[$dao->event_id
] = $dao->event_id
;
1270 //get the domain values.
1271 if (empty($domainValues)) {
1272 // making all tokens available to templates.
1273 $domain = CRM_Core_BAO_Domain
::getDomain();
1274 $tokens = array('domain' => array('name', 'phone', 'address', 'email'),
1275 'contact' => CRM_Core_SelectValues
::contactTokens(),
1278 foreach ($tokens['domain'] as $token) {
1279 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1283 //get all required contacts detail.
1284 if (!empty($contactIds)) {
1285 // get the contact details.
1286 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1289 'CRM_Event_BAO_Participant'
1291 foreach ($currentContactDetails as $contactId => $contactValues) {
1292 $contactDetails[$contactId] = $contactValues;
1296 //get all required events detail.
1297 if (!empty($eventIds)) {
1298 foreach ($eventIds as $eventId) {
1299 //retrieve event information
1300 $eventParams = array('id' => $eventId);
1301 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1303 //get default participant role.
1304 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1306 //get the location info
1307 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1308 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1312 //now we are ready w/ all required data.
1313 //take a decision as per statuses.
1316 $toStatus = $statusTypes[$toStatusId];
1317 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1319 switch ($toStatus) {
1320 case 'Pending from waitlist':
1321 case 'Pending from approval':
1322 switch ($fromStatus) {
1324 case 'Awaiting approval':
1325 $emailType = 'Confirm';
1331 //no matter from where u come send expired mail.
1332 $emailType = $toStatus;
1336 //no matter from where u come send cancel mail.
1337 $emailType = $toStatus;
1341 //as we process additional w/ primary, there might be case if user
1342 //select primary as well as additionals, so avoid double processing.
1343 $processedParticipantIds = array();
1344 $mailedParticipants = array();
1346 //send mails and update status.
1347 foreach ($participantDetails as $participantId => $participantValues) {
1348 $updateParticipantIds = array();
1349 if (in_array($participantId, $processedParticipantIds)) {
1353 //check is it primary and has additional.
1354 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1355 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1358 $mail = self
::sendTransitionParticipantMail($additonalId,
1359 $participantDetails[$additonalId],
1360 $eventDetails[$participantDetails[$additonalId]['event_id']],
1361 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1366 //get the mail participant ids
1368 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1371 $updateParticipantIds[] = $additonalId;
1372 $processedParticipantIds[] = $additonalId;
1376 //now send email appropriate mail to primary.
1378 $mail = self
::sendTransitionParticipantMail($participantId,
1380 $eventDetails[$participantValues['event_id']],
1381 $contactDetails[$participantValues['contact_id']],
1386 //get the mail participant ids
1388 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1392 //now update status of group/one at once.
1393 $updateParticipantIds[] = $participantId;
1395 //update the register date only when we,
1396 //move participant to pending class, CRM-6496
1397 $updateRegisterDate = FALSE;
1398 if (array_key_exists($toStatusId, $pendingStatuses)) {
1399 $updateRegisterDate = TRUE;
1401 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1402 $processedParticipantIds[] = $participantId;
1405 //return result for cron.
1406 if ($returnResult) {
1408 'mailedParticipants' => $mailedParticipants,
1409 'updatedParticipantIds' => $processedParticipantIds,
1417 * Send mail and create activity
1418 * when participant status changed.
1420 * @param int $participantId participant id.
1421 * @param array $participantValues participant detail values. status id for participants
1422 * @param array $eventDetails required event details
1423 * @param array $contactDetails required contact details
1424 * @param array $domainValues required domain values.
1425 * @param string $mailType (eg 'approval', 'confirm', 'expired' )
1432 static function sendTransitionParticipantMail(
1443 //don't send confirmation mail to additional
1444 //since only primary able to confirm registration.
1445 if (!empty($participantValues['registered_by_id']) &&
1446 $mailType == 'Confirm'
1450 $toEmail = CRM_Utils_Array
::value('email', $contactDetails);
1453 $contactId = $participantValues['contact_id'];
1454 $participantName = $contactDetails['display_name'];
1456 //calculate the checksum value.
1457 $checksumValue = NULL;
1458 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1459 $checksumLife = 'inf';
1460 $endDate = CRM_Utils_Array
::value('end_date', $eventDetails);
1462 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1464 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1467 //take a receipt from as event else domain.
1468 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1469 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
1470 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1473 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1475 'groupName' => 'msg_tpl_workflow_event',
1476 'valueName' => 'participant_' . strtolower($mailType),
1477 'contactId' => $contactId,
1478 'tplParams' => array(
1479 'contact' => $contactDetails,
1480 'domain' => $domainValues,
1481 'participant' => $participantValues,
1482 'event' => $eventDetails,
1483 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1484 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1485 'isAdditional' => $participantValues['registered_by_id'],
1486 'isExpired' => $mailType == 'Expired',
1487 'isConfirm' => $mailType == 'Confirm',
1488 'checksumValue' => $checksumValue,
1490 'from' => $receiptFrom,
1491 'toName' => $participantName,
1492 'toEmail' => $toEmail,
1493 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1494 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1498 // 3. create activity record.
1500 $now = date('YmdHis');
1501 $activityType = 'Event Registration';
1502 $activityParams = array(
1503 'subject' => $subject,
1504 'source_contact_id' => $contactId,
1505 'source_record_id' => $participantId,
1506 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1510 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1511 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1512 'is_test' => $participantValues['is_test'],
1516 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1517 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1526 * Get participant status change message.
1528 * @param int $participantId
1529 * @param $statusChangeTo
1530 * @param int $fromStatusId
1534 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1536 $results = self
::transitionParticipants(array($participantId),
1537 $statusChangeTo, $fromStatusId, TRUE
1540 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1541 //give user message only when mail has sent.
1542 if (is_array($results) && !empty($results)) {
1543 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1544 foreach ($results['updatedParticipantIds'] as $processedId) {
1545 if (is_array($results['mailedParticipants']) &&
1546 array_key_exists($processedId, $results['mailedParticipants'])
1548 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1550 1 => $allStatuses[$statusChangeTo],
1551 2 => $results['mailedParticipants'][$processedId],
1563 * Get event full and waiting list message.
1565 * @param int $eventId
1566 * @param int $participantId
1570 public static function eventFullMessage($eventId, $participantId = NULL) {
1571 $eventfullMsg = $dbStatusId = NULL;
1572 $checkEventFull = TRUE;
1573 if ($participantId) {
1574 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1575 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1576 //participant already in counted status no need to check for event full messages.
1577 $checkEventFull = FALSE;
1582 if (!$eventId ||
!$checkEventFull) {
1583 return $eventfullMsg;
1586 //event is truly full.
1587 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1588 if (is_string($emptySeats) && $emptySeats !== NULL) {
1589 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1590 $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(
1591 1 => $maxParticipants)) . '<br />';
1594 $hasWaiting = FALSE;
1595 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1596 if (is_numeric($waitListedCount)) {
1598 //only current processing participant is on waitlist.
1599 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1600 $hasWaiting = FALSE;
1605 $waitingStatusId = array_search('On waitlist',
1606 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1608 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1609 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1612 $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.",
1614 1 => $viewWaitListUrl,
1615 2 => $waitListedCount,
1620 return $eventfullMsg;
1624 * Check for whether participant is primary or not
1626 * @param int $participantId
1628 * @return true if participant is primary
1630 public static function isPrimaryParticipant($participantId) {
1632 $participant = new CRM_Event_DAO_Participant();
1633 $participant->registered_by_id
= $participantId;
1635 if ($participant->find(TRUE)) {
1642 * Get additional participant Ids for cascading with primary participant status
1644 * @param int $participantId participant id.
1645 * @param int $oldStatusId previous status
1646 * @param int $newStatusId new status
1648 * @return true if allowed
1650 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1652 $additionalParticipantIds = array();
1654 static $participantStatuses = array();
1656 if (empty($participantStatuses)) {
1657 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1660 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1661 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1663 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1666 return $additionalParticipantIds;
1670 * Get participant record count for a Contact
1672 * @param int $contactID
1674 * @return int count of participant records
1677 public static function getContactParticipantCount($contactID) {
1678 $query = "SELECT count(*)
1679 FROM civicrm_participant
1680 WHERE civicrm_participant.contact_id = {$contactID} AND
1681 civicrm_participant.is_test = 0";
1682 return CRM_Core_DAO
::singleValueQuery($query);
1686 * Get participant ids by contribution id
1688 * @param int $contributionId Contribution Id
1689 * @param bool $excludeCancelled Exclude cancelled additional participant
1691 * @return array $participantsId
1694 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1697 if (!$contributionId) {
1701 // get primary participant id
1702 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1703 $participantId = CRM_Core_DAO
::singleValueQuery($query);
1705 // get additional participant ids (including cancelled)
1706 if ($participantId) {
1707 $ids = array_merge(array(
1708 $participantId), self
::getAdditionalParticipantIds($participantId,
1717 * Get additional Participant edit & view url .
1719 * @param array $participantIds an array of additional participant ids.
1721 * @return array of Urls.
1724 public static function getAdditionalParticipantUrl($participantIds) {
1725 foreach ($participantIds as $value) {
1727 $details = self
::participantDetails($value);
1728 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1729 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1731 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1732 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1734 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1735 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1741 * To create trxn entry if an event has discount.
1743 * @param int $eventID event id
1744 * @param array $contributionParams contribution params.
1750 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel) {
1752 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID,'civicrm_event');
1753 if (!empty($checkDiscount)) {
1754 $feeLevel = current($feeLevel);
1755 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1756 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1757 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1758 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1759 $params = array(1 => array($priceSetId, 'Integer'),
1760 2 => array($feeLevel, 'String'));
1761 $mainAmount = CRM_Core_DAO
::singleValueQuery($query, $params);
1762 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
1763 $contributionParams['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
1764 $contributionParams['contribution']->financial_type_id
, $relationTypeId);
1765 if (!empty($contributionParams['trxnParams']['from_financial_account_id'])) {
1766 $contributionParams['trxnParams']['total_amount'] = $mainAmount - $contributionParams['total_amount'];
1767 $contributionParams['trxnParams']['payment_processor_id'] = $contributionParams['trxnParams']['payment_instrument_id'] =
1768 $contributionParams['trxnParams']['check_number'] = $contributionParams['trxnParams']['trxn_id'] =
1769 $contributionParams['trxnParams']['net_amount'] = $contributionParams['trxnParams']['fee_amount'] = NULL;
1771 CRM_Core_BAO_FinancialTrxn
::create($contributionParams['trxnParams']);
1778 * Delete participants of contact
1782 * @param integer $contactId contact id
1786 public static function deleteContactParticipant($contactId) {
1787 $participant = new CRM_Event_DAO_Participant();
1788 $participant->contact_id
= $contactId;
1789 $participant->find();
1790 while ($participant->fetch()) {
1791 self
::deleteParticipant($participant->id
);
1796 * @param array $params
1797 * @param int $participantId
1798 * @param int $contributionId
1800 * @param array $lineItems
1801 * @param $paidAmount
1802 * @param int $priceSetId
1804 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) {
1805 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1806 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1807 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1808 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($participantId, 'participant');
1809 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
1813 // get the submitted
1814 foreach ($feeBlock as $id => $values) {
1815 CRM_Price_BAO_LineItem
::format($id, $params, $values, $submittedLineItems);
1816 $submittedFieldId[] = CRM_Utils_Array
::retrieveValueRecursive($submittedLineItems, 'price_field_id');
1818 if (!empty($submittedLineItems)) {
1819 $insertLines = $submittedLineItems;
1821 $submittedFieldValueIds = array_keys($submittedLineItems);
1822 $updateLines = array();
1823 foreach ($previousLineItems as $id => $previousLineItem) {
1824 // check through the submitted items if the previousItem exists,
1825 // if found in submitted items, do not use it for new item creations
1826 if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
1827 // if submitted line items are existing don't fire INSERT query
1828 unset($insertLines[$previousLineItem['price_field_value_id']]);
1829 // for updating the line items i.e. use-case - once deselect-option selecting again
1830 if (($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) ||
1831 ($submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1)) {
1832 $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
1833 $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
1838 $submittedFields = implode(', ', $submittedFieldId);
1839 $submittedFieldValues = implode(', ', $submittedFieldValueIds);
1841 if (!empty($submittedFields) && !empty($submittedFieldValues)) {
1842 $updateLineItem = "UPDATE civicrm_line_item li
1843 INNER JOIN civicrm_financial_item fi
1844 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1846 li.line_total = 0.00,
1847 li.tax_amount = NULL
1848 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
1849 (price_field_value_id NOT IN ({$submittedFieldValues}))
1851 CRM_Core_DAO
::executeQuery($updateLineItem);
1853 // gathering necessary info to record negative (deselected) financial_item
1854 $updateFinancialItem = "
1855 SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
1856 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1857 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
1858 GROUP BY li.entity_table, li.entity_id, price_field_value_id
1860 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1861 $trxn = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId, 'ASC', TRUE);
1862 $trxnId['id'] = $trxn['financialTrxnId'];
1863 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1864 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
1865 $updateFinancialItemInfoValues = array();
1867 while ($updateFinancialItemInfoDAO->fetch()) {
1868 $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
1869 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
1870 // the below params are not needed
1871 unset($updateFinancialItemInfoValues['id']);
1872 unset($updateFinancialItemInfoValues['created_date']);
1873 // if not submitted and difference is not 0 make it negative
1874 if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
1875 // INSERT negative financial_items
1876 $updateFinancialItemInfoValues['amount'] = - $updateFinancialItemInfoValues['amount'];
1877 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1878 // INSERT negative financial_items for tax amount
1879 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
1880 $updateFinancialItemInfoValues['amount'] = - ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
1881 $updateFinancialItemInfoValues['description'] = $taxTerm;
1882 if ($updateFinancialItemInfoValues['financial_type_id']) {
1883 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
1885 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1888 // if submitted and difference is 0 add a positive entry again
1889 elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
1890 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
1891 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1892 // INSERT financial_items for tax amount
1893 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
1894 isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
1896 $updateFinancialItemInfoValues['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
1897 $updateFinancialItemInfoValues['description'] = $taxTerm;
1898 if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
1899 $updateFinancialItemInfoValues['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
1901 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues, NULL, $trxnId);
1906 elseif (empty($submittedFields) && empty($submittedFieldValues)){
1907 $updateLineItem = "UPDATE civicrm_line_item li
1908 INNER JOIN civicrm_financial_item fi
1909 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1911 li.line_total = 0.00,
1912 li.tax_amount = NULL
1913 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
1914 CRM_Core_DAO
::executeQuery($updateLineItem);
1916 if (!empty($updateLines)) {
1917 foreach ($updateLines as $valueId => $vals) {
1918 if (isset($vals['tax_amount'])) {
1919 $taxAmount = $vals['tax_amount'];
1922 $taxAmount = "NULL";
1925 UPDATE civicrm_line_item li
1926 SET li.qty = {$vals['qty']},
1927 li.line_total = {$vals['line_total']},
1928 li.tax_amount = {$taxAmount},
1929 li.unit_price = {$vals['unit_price']},
1930 li.label = '{$vals['label']}'
1931 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
1932 (price_field_value_id = {$valueId})
1934 CRM_Core_DAO
::executeQuery($updateLineItem);
1937 // insert new 'adjusted amount' transaction entry and update contribution entry.
1938 // ensure entity_financial_trxn table has a linking of it.
1939 // insert new line items
1940 if (!empty($insertLines)) {
1941 foreach ($insertLines as $valueId => $lineParams) {
1942 $lineParams['entity_table'] = 'civicrm_participant';
1943 $lineParams['entity_id'] = $participantId;
1944 $lineParams['contribution_id'] = $contributionId;
1945 $lineObj = CRM_Price_BAO_LineItem
::create($lineParams);
1949 // the recordAdjustedAmt code would execute over here
1950 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
1951 if (count($ids) > 1) {
1953 foreach ($ids as $val) {
1954 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, 'civicrm_participant');
1956 $updatedAmount = $total;
1959 $updatedAmount = $params['amount'];
1961 if (strlen($params['tax_amount']) != 0) {
1962 $taxAmount = $params['tax_amount'];
1965 $taxAmount = "NULL";
1967 self
::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount);
1969 $fetchCon = array('id' => $contributionId);
1970 $updatedContribution = CRM_Contribute_BAO_Contribution
::retrieve($fetchCon, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
1971 // insert financial items
1972 if (!empty($insertLines)) {
1973 foreach ($insertLines as $valueId => $lineParams) {
1974 $lineParams['entity_table'] = 'civicrm_participant';
1975 $lineParams['entity_id'] = $participantId;
1976 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams, CRM_Core_DAO
::$_nullArray);
1977 // insert financial items
1978 // ensure entity_financial_trxn table has a linking of it.
1979 $prevItem = CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution);
1980 if (isset($lineObj->tax_amount
)) {
1981 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE);
1986 // update participant fee_amount column
1987 $partUpdateFeeAmt['id'] = $participantId;
1988 foreach ($lineItems as $lineValue) {
1989 if ($lineValue['price_field_value_id']) {
1990 $line[$lineValue['price_field_value_id']] = $lineValue['label'] . ' - '. $lineValue['qty'];
1994 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
1995 $partUpdateFeeAmt['fee_amount'] = $params['amount'];
1996 self
::add($partUpdateFeeAmt);
1999 self
::addActivityForSelection($participantId, 'Change Registration');
2003 * @param $updatedAmount
2004 * @param $paidAmount
2005 * @param int $contributionId
2007 public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL) {
2008 $balanceAmt = $updatedAmount - $paidAmount;
2009 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2010 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
2011 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
2012 $completedStatusId = array_search('Completed', $contributionStatuses);
2014 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
2017 if ($balanceAmt > 0 && $paidAmount != 0) {
2018 $contributionStatusVal = $partiallyPaidStatusId;
2020 elseif ($balanceAmt < 0 && $paidAmount != 0) {
2021 $contributionStatusVal = $pendingRefundStatusId;
2023 elseif ($paidAmount == 0) {
2024 //skip updating the contribution status if no payment is made
2026 $updatedContributionDAO->cancel_date
= 'null';
2027 $updatedContributionDAO->cancel_reason
= NULL;
2029 // update contribution status and total amount without trigger financial code
2030 // as this is handled in current BAO function used for change selection
2031 $updatedContributionDAO->id
= $contributionId;
2033 $updatedContributionDAO->contribution_status_id
= $contributionStatusVal;
2035 $updatedContributionDAO->total_amount
= $updatedAmount;
2036 $updatedContributionDAO->tax_amount
= $taxAmount;
2037 $updatedContributionDAO->save();
2039 $ftDetail = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
2040 // adjusted amount financial_trxn creation
2041 if (empty($ftDetail['trxn_id'])) {
2042 $updatedContribution =
2043 CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contributionId), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
2044 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2045 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($updatedContribution->financial_type_id
, $relationTypeId);
2047 $adjustedTrxnValues = array(
2048 'from_financial_account_id' => NULL,
2049 'to_financial_account_id' => $toFinancialAccount,
2050 'total_amount' => $balanceAmt,
2051 'status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
2052 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
2053 'contribution_id' => $updatedContribution->id
,
2054 'trxn_date' => date('YmdHis'),
2055 'currency' => $updatedContribution->currency
2057 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
2060 // update the financial trxn amount as well, as the fee selections has been updated
2061 if ($balanceAmt != $ftDetail['total_amount']) {
2062 CRM_Core_DAO
::setFieldValue('CRM_Core_BAO_FinancialTrxn', $ftDetail['trxn_id'], 'total_amount', $balanceAmt);
2069 * @param int $participantId
2070 * @param $activityType
2072 * @throws CRM_Core_Exception
2074 public static function addActivityForSelection($participantId, $activityType) {
2075 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
2076 $contactId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
2078 $date = CRM_Utils_Date
::currentDBDate();
2079 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
2080 $eventTitle = $event[$eventId];
2081 $subject = "Registration selections changed for $eventTitle";
2082 $targetCid = $contactId;
2083 $srcRecId = $participantId;
2086 $activityParams = array(
2087 'source_contact_id' => $targetCid,
2088 'source_record_id' => $srcRecId,
2089 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
2093 'subject' => $subject,
2094 'activity_date_time' => $date,
2095 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
2099 'skipRecentView' => TRUE,
2102 // create activity with target contacts
2103 $session = CRM_Core_Session
::singleton();
2104 $id = $session->get('userID');
2106 $activityParams['source_contact_id'] = $id;
2107 $activityParams['target_contact_id'][] = $targetCid;
2109 CRM_Activity_BAO_Activity
::create($activityParams);
2113 * Get options for a given field.
2114 * @see CRM_Core_DAO::buildOptions
2116 * @param String $fieldName
2117 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
2118 * @param Array $props : whatever is known about this dao object
2120 * @return Array|bool
2122 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2123 $params = array('condition' => array());
2125 if ($fieldName == 'status_id' && $context != 'validate') {
2126 // Get rid of cart-related option if disabled
2127 // FIXME: Why does this option even exist if cart is disabled?
2128 if (!CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
, 'enable_cart')) {
2129 $params['condition'][] = "name <> 'Pending in cart'";
2133 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);