3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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'),
69 function __construct() {
70 parent
::__construct();
74 * takes an associative array and creates a participant object
76 * the function extract all the params it needs to initialize the create a
77 * participant object. the params array could contain additional unused name/value
80 * @param array $params (reference ) an assoc array of name/value pairs
81 * @param array $ids the array that holds all the db ids
83 * @return object CRM_Event_BAO_Participant object
87 static function &add(&$params) {
89 if (CRM_Utils_Array
::value('id', $params)) {
90 CRM_Utils_Hook
::pre('edit', 'Participant', $params['id'], $params);
93 CRM_Utils_Hook
::pre('create', 'Participant', NULL, $params);
96 // converting dates to mysql format
97 if (CRM_Utils_Array
::value('register_date', $params)) {
98 $params['register_date'] = CRM_Utils_Date
::isoToMysql($params['register_date']);
101 if (CRM_Utils_Array
::value('participant_fee_amount', $params)) {
102 $params['participant_fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['participant_fee_amount']);
105 if (CRM_Utils_Array
::value('fee_amount', $params)) {
106 $params['fee_amount'] = CRM_Utils_Rule
::cleanMoney($params['fee_amount']);
109 // ensure that role ids are encoded as a string
110 if (isset($params['role_id']) && is_array($params['role_id'])) {
111 $params['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['role_id']);
114 $participantBAO = new CRM_Event_BAO_Participant
;
115 if (CRM_Utils_Array
::value('id', $params)) {
116 $participantBAO->id
= CRM_Utils_Array
::value('id', $params);
117 $participantBAO->find(TRUE);
118 $participantBAO->register_date
= CRM_Utils_Date
::isoToMysql($participantBAO->register_date
);
121 $participantBAO->copyValues($params);
124 //1. If currency present, it should be valid one.
125 //2. We should have currency when amount is not null.
126 $currency = $participantBAO->fee_currency
;
128 !CRM_Utils_System
::isNull($participantBAO->fee_amount
)
130 if (!CRM_Utils_Rule
::currencyCode($currency)) {
131 $config = CRM_Core_Config
::singleton();
132 $currency = $config->defaultCurrency
;
135 $participantBAO->fee_currency
= $currency;
137 $participantBAO->save();
139 $session = CRM_Core_Session
::singleton();
141 // reset the group contact cache for this group
142 CRM_Contact_BAO_GroupContactCache
::remove();
144 if (CRM_Utils_Array
::value('id', $params)) {
145 CRM_Utils_Hook
::post('edit', 'Participant', $participantBAO->id
, $participantBAO);
148 CRM_Utils_Hook
::post('create', 'Participant', $participantBAO->id
, $participantBAO);
151 return $participantBAO;
155 * Given the list of params in the params array, fetch the object
156 * and store the values in the values array
158 * @param array $params input parameters to find object
159 * @param array $values output values of the object
161 * @return CRM_Event_BAO_Participant|null the found object or null
165 static function getValues(&$params, &$values, &$ids) {
166 if (empty($params)) {
169 $participant = new CRM_Event_BAO_Participant();
170 $participant->copyValues($params);
171 $participant->find();
172 $participants = array();
173 while ($participant->fetch()) {
174 $ids['participant'] = $participant->id
;
175 CRM_Core_DAO
::storeValues($participant, $values[$participant->id
]);
176 $participants[$participant->id
] = $participant;
178 return $participants;
182 * takes an associative array and creates a participant object
184 * @param array $params (reference ) an assoc array of name/value pairs
185 * @param array $ids the array that holds all the db ids
187 * @return object CRM_Event_BAO_Participant object
191 static function &create(&$params) {
193 $transaction = new CRM_Core_Transaction();
196 if (CRM_Utils_Array
::value('id', $params)) {
197 $status = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
200 $participant = self
::add($params);
202 if (is_a($participant, 'CRM_Core_Error')) {
203 $transaction->rollback();
207 if ((!CRM_Utils_Array
::value('id', $params)) ||
208 ($params['status_id'] != $status)
210 CRM_Activity_BAO_Activity
::addActivity($participant);
215 if (self
::isPrimaryParticipant($participant->id
) && $status) {
216 self
::updateParticipantStatus($participant->id
, $status, $participant->status_id
);
219 $session = CRM_Core_Session
::singleton();
220 $id = $session->get('userID');
222 $id = CRM_Utils_Array
::value('contact_id', $params);
225 // add custom field values
226 if (CRM_Utils_Array
::value('custom', $params) &&
227 is_array($params['custom'])
229 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_participant', $participant->id
);
232 //process note, CRM-7634
234 if (CRM_Utils_Array
::value('id', $params)) {
235 $note = CRM_Core_BAO_Note
::getNote($params['id'], 'civicrm_participant');
236 $noteId = key($note);
239 $hasNoteField = FALSE;
241 'note', 'participant_note') as $noteFld) {
242 if (array_key_exists($noteFld, $params)) {
243 $noteValue = $params[$noteFld];
244 $hasNoteField = TRUE;
248 if ($noteId ||
$noteValue) {
251 'entity_table' => 'civicrm_participant',
252 'note' => $noteValue,
253 'entity_id' => $participant->id
,
255 'modified_date' => date('Ymd'),
259 $noteIDs['id'] = $noteId;
261 CRM_Core_BAO_Note
::add($noteParams, $noteIDs);
263 elseif ($noteId && $hasNoteField) {
264 CRM_Core_BAO_Note
::del($noteId, FALSE);
268 // Log the information on successful add/edit of Participant data.
270 'entity_table' => 'civicrm_participant',
271 'entity_id' => $participant->id
,
272 'data' => CRM_Event_PseudoConstant
::participantStatus($participant->status_id
),
273 'modified_id' => $id,
274 'modified_date' => date('Ymd'),
277 CRM_Core_BAO_Log
::add($logParams);
279 $params['participant_id'] = $participant->id
;
281 $transaction->commit();
283 // do not add to recent items for import, CRM-4399
284 if (!CRM_Utils_Array
::value('skipRecentView', $params)) {
286 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
287 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
290 $recentOther = array();
291 if (CRM_Core_Permission
::check('edit event participants')) {
292 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
293 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
296 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
297 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/participant',
298 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
302 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
304 if ($participant->role_id
) {
305 $role = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participant->role_id
);
307 foreach ($role as & $roleValue) {
308 if (isset($roleValue)) {
309 $roleValue = $participantRoles[$roleValue];
312 $roles = implode(', ', $role);
315 $roleString = empty($roles) ?
'' : $roles;
316 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $participant->event_id
, 'title');
317 $title = CRM_Contact_BAO_Contact
::displayName($participant->contact_id
) . ' (' . $roleString . ' - ' . $eventTitle . ')';
319 // add the recently created Participant
320 CRM_Utils_Recent
::add($title,
324 $participant->contact_id
,
334 * Check whether the event is full for participation and return as
337 * @param int $eventId event id.
338 * @param boolean $returnEmptySeats are we require number if empty seats.
339 * @param boolean $includeWaitingList consider waiting list in event full
340 * calculation or not. (it is for cron job purpose)
343 * 1. false => If event having some empty spaces.
344 * 2. null => If no registration yet or no limit.
345 * 3. Event Full Message => If event is full.
346 * 4. Number of Empty Seats => If we are interested in empty spaces.( w/ include/exclude waitings. )
351 static function eventFull(
353 $returnEmptySeats = FALSE,
354 $includeWaitingList = TRUE,
355 $returnWaitingCount = FALSE,
356 $considerTestParticipant = FALSE
363 // consider event is full when.
364 // 1. (count(is_counted) >= event_size) or
365 // 2. (count(participants-with-status-on-waitlist) > 0)
366 // It might be case there are some empty spaces and still event
367 // is full, as waitlist might represent group require spaces > empty.
369 $participantRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
370 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
371 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
372 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
374 //when we do require only waiting count don't consider counted.
375 if (!$returnWaitingCount && !empty($countedStatuses)) {
376 $allStatusIds = array_keys($countedStatuses);
379 $where = array(' event.id = %1 ');
380 if (!$considerTestParticipant) {
381 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
383 if (!empty($participantRoles)) {
384 $where[] = ' participant.role_id IN ( ' . implode(', ', array_keys($participantRoles)) . ' ) ';
387 $eventParams = array(1 => array($eventId, 'Positive'));
389 //in case any waiting, straight forward event is full.
390 if ($includeWaitingList && $onWaitlistStatusId) {
392 //build the where clause.
393 $whereClause = ' WHERE ' . implode(' AND ', $where);
394 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
395 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
398 SELECT participant.id id,
399 event.event_full_text as event_full_text
400 FROM civicrm_participant participant
401 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
404 $eventFullText = ts('This event is full!!!');
405 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
406 while ($participants->fetch()) {
407 //oops here event is full and we don't want waiting count.
408 if ($returnWaitingCount) {
409 return CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
412 return ($participants->event_full_text
) ?
$participants->event_full_text
: $eventFullText;
417 //consider only counted participants.
418 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
419 $whereClause = ' WHERE ' . implode(' AND ', $where);
420 $eventSeatsWhere = implode(' AND ', $where);
423 SELECT participant.id id,
424 event.event_full_text as event_full_text,
425 event.max_participants as max_participants
426 FROM civicrm_participant participant
427 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
430 $eventMaxSeats = NULL;
431 $eventFullText = ts('This event is full !!!');
432 $participants = CRM_Core_DAO
::executeQuery($query, $eventParams);
433 while ($participants->fetch()) {
434 if ($participants->event_full_text
) {
435 $eventFullText = $participants->event_full_text
;
437 $eventMaxSeats = $participants->max_participants
;
438 //don't have limit for event seats.
439 if ($participants->max_participants
== NULL) {
444 //get the total event seats occupied by these participants.
445 $eventRegisteredSeats = CRM_Event_BAO_Event
::eventTotalSeats($eventId, $eventSeatsWhere);
447 if ($eventRegisteredSeats) {
448 if ($eventRegisteredSeats >= $eventMaxSeats) {
449 $result = $eventFullText;
451 elseif ($returnEmptySeats) {
452 $result = $eventMaxSeats - $eventRegisteredSeats;
458 SELECT event.event_full_text,
459 event.max_participants
460 FROM civicrm_event event
461 WHERE event.id = %1';
462 $event = CRM_Core_DAO
::executeQuery($query, $eventParams);
463 while ($event->fetch()) {
464 $eventFullText = $event->event_full_text
;
465 $eventMaxSeats = $event->max_participants
;
469 // no limit for registration.
470 if ($eventMaxSeats == NULL) {
473 if ($eventMaxSeats) {
474 return ($returnEmptySeats) ?
(int) $eventMaxSeats : FALSE;
477 return $eventFullText;
481 * Return the array of all price set field options,
482 * with total participant count that field going to carry.
484 * @param int $eventId event id.
485 * @param array $skipParticipants an array of participant ids those we should skip.
486 * @param int $isTest would you like to consider test participants.
488 * @return array $optionsCount an array of each option id and total count
492 static function priceSetOptionsCount(
494 $skipParticipantIds = array(),
495 $considerCounted = TRUE,
496 $considerWaiting = TRUE,
497 $considerTestParticipants = FALSE
499 $optionsCount = array();
501 return $optionsCount;
504 $allStatusIds = array();
505 if ($considerCounted) {
506 $countedStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
507 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
509 if ($considerWaiting) {
510 $waitingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'");
511 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
513 $statusIdClause = NULL;
514 if (!empty($allStatusIds)) {
515 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
518 $isTestClause = NULL;
519 if (!$considerTestParticipants) {
520 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
523 $skipParticipantClause = NULL;
524 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
525 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
529 SELECT line.id as lineId,
530 line.entity_id as entity_id,
535 FROM civicrm_line_item line
536 INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
537 AND participant.id = line.entity_id )
538 INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
539 INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
540 WHERE participant.event_id = %1
543 {$skipParticipantClause}";
545 $lineItem = CRM_Core_DAO
::executeQuery($sql, array(1 => array($eventId, 'Positive')));
546 while ($lineItem->fetch()) {
547 $count = $lineItem->count
;
551 if ($lineItem->html_type
== 'Text') {
552 $count *= $lineItem->qty
;
554 $optionsCount[$lineItem->valueId
] = $count + CRM_Utils_Array
::value($lineItem->valueId
, $optionsCount, 0);
557 return $optionsCount;
561 * Get the empty spaces for event those we can allocate
562 * to pending participant to become confirm.
564 * @param int $eventId event id.
566 * @return int $spaces Number of Empty Seats/null.
570 static function pendingToConfirmSpaces($eventId) {
576 $positiveStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Positive'");
577 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
580 SELECT count(participant.id) as registered,
581 civicrm_event.max_participants
582 FROM civicrm_participant participant, civicrm_event
583 WHERE participant.event_id = {$eventId}
584 AND civicrm_event.id = participant.event_id
585 AND participant.status_id IN {$statusIds}
586 GROUP BY participant.event_id
588 $dao = CRM_Core_DAO
::executeQuery($query);
592 if ($dao->max_participants
== NULL ||
$dao->max_participants
<= 0) {
597 if ($dao->registered
>= $dao->max_participants
) {
602 return $dao->max_participants
- $dao->registered
;
605 //space in case no registeration yet.
606 return CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
610 * combine all the importable fields from the lower levels object
612 * @return array array of importable Fields
616 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' => 'Participant Note',
635 'name' => 'participant_note',
636 'headerPattern' => '/(participant.)?note$/i',
639 $participantStatus = array(
640 'participant_status' => array(
641 'title' => 'Participant Status',
642 'name' => 'participant_status',
643 'data_type' => CRM_Utils_Type
::T_STRING
,
646 $participantRole = array(
647 'participant_role' => array(
648 'title' => 'Participant Role',
649 'name' => 'participant_role',
650 'data_type' => CRM_Utils_Type
::T_STRING
,
654 'event_type' => array(
655 'title' => 'Event Type',
656 'name' => 'event_type',
657 'data_type' => CRM_Utils_Type
::T_STRING
,
660 $tmpContactField = $contactFields = array();
661 $contactFields = array( );
662 if (!$onlyParticipant) {
663 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
665 // Using new Dedupe rule.
667 'contact_type' => $contactType,
668 'used' => 'Unsupervised',
670 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
672 if (is_array($fieldsArray)) {
673 foreach ($fieldsArray as $value) {
674 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
679 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
680 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
682 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
685 $title = $tmpContactField[trim($value)]['title'];
688 $tmpContactField[trim($value)]['title'] = $title;
692 $extIdentifier = CRM_Utils_Array
::value('external_identifier', $contactFields);
693 if ($extIdentifier) {
694 $tmpContactField['external_identifier'] = $extIdentifier;
695 $tmpContactField['external_identifier']['title'] =
696 CRM_Utils_Array
::value('title', $extIdentifier) . ' (match to contact)';
698 $tmpFields['participant_contact_id']['title'] =
699 $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
701 $fields = array_merge($fields, $tmpContactField);
702 $fields = array_merge($fields, $tmpFields);
703 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
704 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
706 self
::$_importableFields = $fields;
709 return self
::$_importableFields;
713 * combine all the exportable fields from the lower levels object
715 * @return array array of exportable Fields
719 static function &exportableFields() {
720 if (!self
::$_exportableFields) {
721 if (!self
::$_exportableFields) {
722 self
::$_exportableFields = array();
727 $participantFields = CRM_Event_DAO_Participant
::export();
729 'participant_note' => array('title' => 'Participant Note',
730 'name' => 'participant_note',
733 $participantStatus = array(
734 'participant_status' => array('title' => 'Participant Status',
735 'name' => 'participant_status',
738 $participantRole = array(
739 'participant_role' => array('title' => 'Participant Role',
740 'name' => 'participant_role',
743 $discountFields = CRM_Core_DAO_Discount
::export();
745 $fields = array_merge($participantFields, $participantStatus, $participantRole, $noteField, $discountFields);
748 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Participant'));
749 self
::$_exportableFields = $fields;
752 return self
::$_exportableFields;
756 * function to get the event name/sort name for a particular participation / participant
758 * @param int $participantId id of the participant
761 * @return array $name associated array with sort_name and event title
765 static function participantDetails($participantId) {
767 SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
768 FROM civicrm_participant
769 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
770 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
771 WHERE civicrm_participant.id = {$participantId}
773 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
776 while ($dao->fetch()) {
777 $details['name'] = $dao->name
;
778 $details['title'] = $dao->title
;
779 $details['cid'] = $dao->cid
;
786 * Get the values for pseudoconstants for name->value and reverse.
788 * @param array $defaults (reference) the default values, some of which need to be resolved.
789 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
795 static function resolveDefaults(&$defaults, $reverse = FALSE) {
796 self
::lookupValue($defaults, 'event', CRM_Event_PseudoConstant
::event(), $reverse);
797 self
::lookupValue($defaults, 'status', CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label'), $reverse);
798 self
::lookupValue($defaults, 'role', CRM_Event_PseudoConstant
::participantRole(), $reverse);
802 * This function is used to convert associative array names to values
805 * This function is used by both the web form layer and the api. Note that
806 * the api needs the name => value conversion, also the view layer typically
807 * requires value => name conversion
809 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
810 $id = $property . '_id';
812 $src = $reverse ?
$property : $id;
813 $dst = $reverse ?
$id : $property;
815 if (!array_key_exists($src, $defaults)) {
819 $look = $reverse ?
array_flip($lookup) : $lookup;
821 if (is_array($look)) {
822 if (!array_key_exists($defaults[$src], $look)) {
826 $defaults[$dst] = $look[$defaults[$src]];
831 * Delete the record that are associated with this participation
833 * @param int $id id of the participation to delete
839 static function deleteParticipant($id) {
840 CRM_Utils_Hook
::pre('delete', 'Participant', $id, CRM_Core_DAO
::$_nullArray);
842 $transaction = new CRM_Core_Transaction();
844 //delete activity record
846 'source_record_id' => $id,
847 // activity type id for event registration
848 'activity_type_id' => 5,
851 CRM_Activity_BAO_Activity
::deleteActivity($params);
853 // delete the participant payment record
854 // we need to do this since the cascaded constraints
855 // dont work with join tables
856 $p = array('participant_id' => $id);
857 CRM_Event_BAO_ParticipantPayment
::deleteParticipantPayment($p);
859 // cleanup line items.
860 $participantsId = array();
861 $participantsId = self
::getAdditionalParticipantIds($id);
862 $participantsId[] = $id;
863 CRM_Price_BAO_LineItem
::deleteLineItems($participantsId, 'civicrm_participant');
865 //delete note when participant deleted.
866 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_participant');
867 $noteId = key($note);
869 CRM_Core_BAO_Note
::del($noteId, FALSE);
872 $participant = new CRM_Event_DAO_Participant();
873 $participant->id
= $id;
874 $participant->delete();
876 $transaction->commit();
878 CRM_Utils_Hook
::post('delete', 'Participant', $participant->id
, $participant);
880 // delete the recently created Participant
881 $participantRecent = array(
883 'type' => 'Participant',
886 CRM_Utils_Recent
::del($participantRecent);
892 *Checks duplicate participants
894 * @param array $duplicates (reference ) an assoc array of name/value pairs
895 * @param array $input an assosiative array of name /value pairs
896 * from other function
898 * @return object CRM_Contribute_BAO_Contribution object
902 static function checkDuplicate($input, &$duplicates) {
903 $eventId = CRM_Utils_Array
::value('event_id', $input);
904 $contactId = CRM_Utils_Array
::value('contact_id', $input);
910 $clause[] = "event_id = %1";
911 $input[1] = array($eventId, 'Integer');
915 $clause[] = "contact_id = %2";
916 $input[2] = array($contactId, 'Integer');
919 if (empty($clause)) {
923 $clause = implode(' AND ', $clause);
925 $query = "SELECT id FROM civicrm_participant WHERE $clause";
926 $dao = CRM_Core_DAO
::executeQuery($query, $input);
928 while ($dao->fetch()) {
929 $duplicates[] = $dao->id
;
936 * fix the event level
938 * When price sets are used as event fee, fee_level is set as ^A
939 * seperated string. We need to change that string to comma
940 * separated string before using fee_level in view mode.
942 * @param string $eventLevel event_leval string from db
948 static function fixEventLevel(&$eventLevel) {
949 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
) &&
950 (substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)
952 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
953 substr($eventLevel, 1, -1)
955 if ($pos = strrpos($eventLevel, '(multiple participants)', 0)) {
956 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
959 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
960 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
961 substr($eventLevel, 0, 1)
964 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO
::VALUE_SEPARATOR
)) {
965 $eventLevel = implode(', ', explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
966 substr($eventLevel, 0, -1)
972 * get the additional participant ids.
974 * @param int $primaryParticipantId primary partycipant Id
975 * @param boolean $excludeCancel do not include participant those are cancelled.
977 * @return array $additionalParticipantIds
980 static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
981 $additionalParticipantIds = array();
982 if (!$primaryParticipantId) {
983 return $additionalParticipantIds;
986 $where = "participant.registered_by_id={$primaryParticipantId}";
987 if ($excludeCancel) {
989 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
990 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
991 $where .= " AND participant.status_id != {$cancelStatusId}";
995 $where .= " AND participant.status_id = {$oldStatusId}";
999 SELECT participant.id
1000 FROM civicrm_participant participant
1003 $dao = CRM_Core_DAO
::executeQuery($query);
1004 while ($dao->fetch()) {
1005 $additionalParticipantIds[$dao->id
] = $dao->id
;
1007 return $additionalParticipantIds;
1011 * Get the event fee info for given participant ids
1012 * either from line item table / participant table.
1014 * @param array $participantIds participant ids.
1015 * @param boolean $hasLineItems do fetch from line items.
1017 * @return array $feeDetails
1020 function getFeeDetails($participantIds, $hasLineItems = FALSE) {
1021 $feeDetails = array();
1022 if (!is_array($participantIds) ||
empty($participantIds)) {
1027 SELECT participant.id as id,
1028 participant.fee_level as fee_level,
1029 participant.fee_amount as fee_amount';
1030 $from = 'FROM civicrm_participant participant';
1031 if ($hasLineItems) {
1033 lineItem.id as lineId,
1034 lineItem.label as label,
1035 lineItem.qty as qty,
1036 lineItem.unit_price as unit_price,
1037 lineItem.line_total as line_total,
1038 field.label as field_title,
1039 field.html_type as html_type,
1040 field.id as price_field_id,
1041 value.id as price_field_value_id,
1042 value.description as description,
1043 IF( value.count, value.count, 0 ) as participant_count';
1045 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1046 AND lineItem.entity_id = participant.id )
1047 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1048 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1051 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1052 $query = "$select $from $where";
1054 $feeInfo = CRM_Core_DAO
::executeQuery($query);
1055 $feeProperties = array('fee_level', 'fee_amount');
1056 $lineProperties = array(
1057 'lineId', 'label', 'qty', 'unit_price',
1058 'line_total', 'field_title', 'html_type',
1059 'price_field_id', 'participant_count', 'price_field_value_id', 'description',
1061 while ($feeInfo->fetch()) {
1062 if ($hasLineItems) {
1063 foreach ($lineProperties as $property) {
1064 $feeDetails[$feeInfo->id
][$feeInfo->lineId
][$property] = $feeInfo->$property;
1068 foreach ($feeProperties as $property) $feeDetails[$feeInfo->id
][$property] = $feeInfo->$property;
1076 * Retrieve additional participants display-names and URL to view their participant records.
1077 * (excludes cancelled participants automatically)
1079 * @param int $primaryParticipantID id of primary participant record
1081 * @return array $additionalParticipants $displayName => $viewUrl
1084 static function getAdditionalParticipants($primaryParticipantID) {
1085 $additionalParticipantIDs = array();
1086 $additionalParticipantIDs = self
::getAdditionalParticipantIds($primaryParticipantID);
1087 if (!empty($additionalParticipantIDs)) {
1088 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1089 $additionalContactID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1090 $additionalParticipantID,
1093 $additionalContactName = CRM_Contact_BAO_Contact
::displayName($additionalContactID);
1094 $pViewURL = CRM_Utils_System
::url('civicrm/contact/view/participant',
1095 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1098 $additionalParticipants[$additionalContactName] = $pViewURL;
1101 return $additionalParticipants;
1105 * Function for update primary and additional participant status
1107 * @param int $participantID primary participant's id
1108 * @param int $statusId status id for participant
1113 static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
1114 if (!$participantID ||
!$oldStatusID) {
1118 if (!$newStatusID) {
1119 $newStatusID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1121 elseif ($updatePrimaryStatus) {
1122 CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1125 $cascadeAdditionalIds = self
::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1127 if (!empty($cascadeAdditionalIds)) {
1128 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1129 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1130 $params = array(1 => array($newStatusID, 'Integer'));
1131 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1138 * Function for update status for given participant ids
1140 * @param int $participantIds array of participant ids
1141 * @param int $statusId status id for participant
1142 * @params boolean $updateRegisterDate way to track when status changed.
1148 static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
1149 if (!is_array($participantIds) ||
empty($participantIds) ||
!$statusId) {
1153 //lets update register date as we update status to keep track
1154 //when we did update status, useful for moving participant
1155 //from pending to expired.
1156 $setClause = "status_id = {$statusId}";
1157 if ($updateRegisterDate) {
1158 $setClause .= ", register_date = NOW()";
1161 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1164 UPDATE civicrm_participant
1166 WHERE id IN {$participantIdClause}";
1168 $dao = CRM_Core_DAO
::executeQuery($query);
1172 * Function takes participant ids and statuses
1173 * update status from $fromStatusId to $toStatusId
1174 * and send mail + create activities.
1176 * @param array $participantIds participant ids.
1177 * @param int $toStatusId update status id.
1178 * @param int $fromStatusId from status id
1184 static function transitionParticipants($participantIds, $toStatusId,
1185 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1187 if (!is_array($participantIds) ||
empty($participantIds) ||
!$toStatusId) {
1191 //thumb rule is if we triggering primary participant need to triggered additional
1192 $allParticipantIds = $primaryANDAdditonalIds = array();
1193 foreach ($participantIds as $id) {
1194 $allParticipantIds[] = $id;
1195 if (self
::isPrimaryParticipant($id)) {
1196 //filter additional as per status transition rules, CRM-5403
1197 if ($skipCascadeRule) {
1198 $additionalIds = self
::getAdditionalParticipantIds($id);
1201 $additionalIds = self
::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1203 if (!empty($additionalIds)) {
1204 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1205 $primaryANDAdditonalIds[$id] = $additionalIds;
1210 //get the unique participant ids,
1211 $allParticipantIds = array_unique($allParticipantIds);
1213 //pull required participants, contacts, events data, if not in hand
1214 static $eventDetails = array();
1215 static $domainValues = array();
1216 static $contactDetails = array();
1218 $contactIds = $eventIds = $participantDetails = array();
1220 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
1221 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
1222 $pendingStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL,
1226 //first thing is pull all necessory data from db.
1227 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1229 //get all participants data.
1230 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1231 $dao = CRM_Core_DAO
::executeQuery($query);
1232 while ($dao->fetch()) {
1233 $participantDetails[$dao->id
] = array(
1235 'role' => $participantRoles[$dao->role_id
],
1236 'is_test' => $dao->is_test
,
1237 'event_id' => $dao->event_id
,
1238 'status_id' => $dao->status_id
,
1239 'fee_amount' => $dao->fee_amount
,
1240 'contact_id' => $dao->contact_id
,
1241 'register_date' => $dao->register_date
,
1242 'registered_by_id' => $dao->registered_by_id
,
1244 if (!array_key_exists($dao->contact_id
, $contactDetails)) {
1245 $contactIds[$dao->contact_id
] = $dao->contact_id
;
1248 if (!array_key_exists($dao->event_id
, $eventDetails)) {
1249 $eventIds[$dao->event_id
] = $dao->event_id
;
1253 //get the domain values.
1254 if (empty($domainValues)) {
1255 // making all tokens available to templates.
1256 $domain = CRM_Core_BAO_Domain
::getDomain();
1257 $tokens = array('domain' => array('name', 'phone', 'address', 'email'),
1258 'contact' => CRM_Core_SelectValues
::contactTokens(),
1261 foreach ($tokens['domain'] as $token) {
1262 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
1266 //get all required contacts detail.
1267 if (!empty($contactIds)) {
1268 // get the contact details.
1269 list($currentContactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds, NULL,
1272 'CRM_Event_BAO_Participant'
1274 foreach ($currentContactDetails as $contactId => $contactValues) {
1275 $contactDetails[$contactId] = $contactValues;
1279 //get all required events detail.
1280 if (!empty($eventIds)) {
1281 foreach ($eventIds as $eventId) {
1282 //retrieve event information
1283 $eventParams = array('id' => $eventId);
1284 CRM_Event_BAO_Event
::retrieve($eventParams, $eventDetails[$eventId]);
1286 //get default participant role.
1287 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array
::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1289 //get the location info
1290 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1291 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location
::getValues($locParams, TRUE);
1295 //now we are ready w/ all required data.
1296 //take a decision as per statuses.
1299 $toStatus = $statusTypes[$toStatusId];
1300 $fromStatus = CRM_Utils_Array
::value($fromStatusId, $statusTypes);
1302 switch ($toStatus) {
1303 case 'Pending from waitlist':
1304 case 'Pending from approval':
1305 switch ($fromStatus) {
1307 case 'Awaiting approval':
1308 $emailType = 'Confirm';
1314 //no matter from where u come send expired mail.
1315 $emailType = $toStatus;
1319 //no matter from where u come send cancel mail.
1320 $emailType = $toStatus;
1324 //as we process additional w/ primary, there might be case if user
1325 //select primary as well as additionals, so avoid double processing.
1326 $processedParticipantIds = array();
1327 $mailedParticipants = array();
1329 //send mails and update status.
1330 foreach ($participantDetails as $participantId => $participantValues) {
1331 $updateParticipantIds = array();
1332 if (in_array($participantId, $processedParticipantIds)) {
1336 //check is it primary and has additional.
1337 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1338 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1341 $mail = self
::sendTransitionParticipantMail($additonalId,
1342 $participantDetails[$additonalId],
1343 $eventDetails[$participantDetails[$additonalId]['event_id']],
1344 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1349 //get the mail participant ids
1351 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1354 $updateParticipantIds[] = $additonalId;
1355 $processedParticipantIds[] = $additonalId;
1359 //now send email appropriate mail to primary.
1361 $mail = self
::sendTransitionParticipantMail($participantId,
1363 $eventDetails[$participantValues['event_id']],
1364 $contactDetails[$participantValues['contact_id']],
1369 //get the mail participant ids
1371 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1375 //now update status of group/one at once.
1376 $updateParticipantIds[] = $participantId;
1378 //update the register date only when we,
1379 //move participant to pending class, CRM-6496
1380 $updateRegisterDate = FALSE;
1381 if (array_key_exists($toStatusId, $pendingStatuses)) {
1382 $updateRegisterDate = TRUE;
1384 self
::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1385 $processedParticipantIds[] = $participantId;
1388 //return result for cron.
1389 if ($returnResult) {
1391 'mailedParticipants' => $mailedParticipants,
1392 'updatedParticipantIds' => $processedParticipantIds,
1400 * Function to send mail and create activity
1401 * when participant status changed.
1403 * @param int $participantId participant id.
1404 * @param array $participantValues participant detail values. status id for participants
1405 * @param array $eventDetails required event details
1406 * @param array $contactDetails required contact details
1407 * @param array $domainValues required domain values.
1408 * @param string $mailType (eg 'approval', 'confirm', 'expired' )
1414 static function sendTransitionParticipantMail(
1425 //don't send confirmation mail to additional
1426 //since only primary able to confirm registration.
1427 if (CRM_Utils_Array
::value('registered_by_id', $participantValues) &&
1428 $mailType == 'Confirm'
1433 if ($toEmail = CRM_Utils_Array
::value('email', $contactDetails)) {
1435 $contactId = $participantValues['contact_id'];
1436 $participantName = $contactDetails['display_name'];
1438 //calculate the checksum value.
1439 $checksumValue = NULL;
1440 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1441 $checksumLife = 'inf';
1442 if ($endDate = CRM_Utils_Array
::value('end_date', $eventDetails)) {
1443 $checksumLife = (CRM_Utils_Date
::unixTime($endDate) - time()) / (60 * 60);
1445 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactId, NULL, $checksumLife);
1448 //take a receipt from as event else domain.
1449 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
1450 if (CRM_Utils_Array
::value('confirm_from_name', $eventDetails) &&
1451 CRM_Utils_Array
::value('confirm_from_email', $eventDetails)
1453 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1456 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1458 'groupName' => 'msg_tpl_workflow_event',
1459 'valueName' => 'participant_' . strtolower($mailType),
1460 'contactId' => $contactId,
1461 'tplParams' => array(
1462 'contact' => $contactDetails,
1463 'domain' => $domainValues,
1464 'participant' => $participantValues,
1465 'event' => $eventDetails,
1466 'paidEvent' => CRM_Utils_Array
::value('is_monetary', $eventDetails),
1467 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $eventDetails),
1468 'isAdditional' => $participantValues['registered_by_id'],
1469 'isExpired' => $mailType == 'Expired',
1470 'isConfirm' => $mailType == 'Confirm',
1471 'checksumValue' => $checksumValue,
1473 'from' => $receiptFrom,
1474 'toName' => $participantName,
1475 'toEmail' => $toEmail,
1476 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventDetails),
1477 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventDetails),
1481 // 3. create activity record.
1483 $now = date('YmdHis');
1484 $activityType = 'Event Registration';
1485 $activityParams = array(
1486 'subject' => $subject,
1487 'source_contact_id' => $contactId,
1488 'source_record_id' => $participantId,
1489 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1493 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1494 'due_date_time' => CRM_Utils_Date
::isoToMysql($participantValues['register_date']),
1495 'is_test' => $participantValues['is_test'],
1499 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
1500 CRM_Core_Error
::fatal('Failed creating Activity for expiration mail');
1509 * get participant status change message.
1514 function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
1516 $results = self
::transitionParticipants(array($participantId),
1517 $statusChangeTo, $fromStatusId, TRUE
1520 $allStatuses = CRM_Event_PseudoConstant
::participantStatus();
1521 //give user message only when mail has sent.
1522 if (is_array($results) && !empty($results)) {
1523 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1524 foreach ($results['updatedParticipantIds'] as $processedId) {
1525 if (is_array($results['mailedParticipants']) &&
1526 array_key_exists($processedId, $results['mailedParticipants'])
1528 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
1530 1 => $allStatuses[$statusChangeTo],
1531 2 => $results['mailedParticipants'][$processedId],
1543 * get event full and waiting list message.
1548 static function eventFullMessage($eventId, $participantId = NULL) {
1549 $eventfullMsg = $dbStatusId = NULL;
1550 $checkEventFull = TRUE;
1551 if ($participantId) {
1552 $dbStatusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1553 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1'))) {
1554 //participant already in counted status no need to check for event full messages.
1555 $checkEventFull = FALSE;
1560 if (!$eventId ||
!$checkEventFull) {
1561 return $eventfullMsg;
1564 //event is truly full.
1565 $emptySeats = self
::eventFull($eventId, FALSE, FALSE);
1566 if (is_string($emptySeats) && $emptySeats !== NULL) {
1567 $maxParticipants = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1568 $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(
1569 1 => $maxParticipants)) . '<br />';
1572 $hasWaiting = FALSE;
1573 $waitListedCount = self
::eventFull($eventId, FALSE, TRUE, TRUE);
1574 if (is_numeric($waitListedCount)) {
1576 //only current processing participant is on waitlist.
1577 if ($waitListedCount == 1 && CRM_Event_PseudoConstant
::participantStatus($dbStatusId) == 'On waitlist') {
1578 $hasWaiting = FALSE;
1583 $waitingStatusId = array_search('On waitlist',
1584 CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Waiting'")
1586 $viewWaitListUrl = CRM_Utils_System
::url('civicrm/event/search',
1587 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1590 $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.",
1592 1 => $viewWaitListUrl,
1593 2 => $waitListedCount,
1598 return $eventfullMsg;
1602 * check for whether participant is primary or not
1604 * @param $participantId
1606 * @return true if participant is primary
1609 static function isPrimaryParticipant($participantId) {
1611 $participant = new CRM_Event_DAO_Participant();
1612 $participant->registered_by_id
= $participantId;
1614 if ($participant->find(TRUE)) {
1621 * get additional participant Ids for cascading with primary participant status
1623 * @param int $participantId participant id.
1624 * @param int $oldStatusId previous status
1625 * @param int $newStatusId new status
1627 * @return true if allowed
1630 static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
1632 $additionalParticipantIds = array();
1634 static $participantStatuses = array();
1636 if (empty($participantStatuses)) {
1637 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1640 if (CRM_Utils_Array
::value($participantStatuses[$oldStatusId], self
::$_statusTransitionsRules) &&
1641 in_array($participantStatuses[$newStatusId], self
::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1643 $additionalParticipantIds = self
::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1646 return $additionalParticipantIds;
1650 * Function to get participant record count for a Contact
1652 * @param int $contactId Contact ID
1654 * @return int count of participant records
1658 static function getContactParticipantCount($contactID) {
1659 $query = "SELECT count(*)
1660 FROM civicrm_participant
1661 WHERE civicrm_participant.contact_id = {$contactID} AND
1662 civicrm_participant.is_test = 0";
1663 return CRM_Core_DAO
::singleValueQuery($query);
1667 * Function to get participant ids by contribution id
1669 * @param int $contributionId Contribution Id
1670 * @param bool $excludeCancelled Exclude cancelled additional participant
1672 * @return int $participantsId
1676 static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
1679 if (!$contributionId) {
1683 // get primary participant id
1684 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1685 $participantId = CRM_Core_DAO
::singleValueQuery($query);
1687 // get additional participant ids (including cancelled)
1688 if ($participantId) {
1689 $ids = array_merge(array(
1690 $participantId), self
::getAdditionalParticipantIds($participantId,
1699 * Function to get additional Participant edit & view url .
1701 * @param array $paticipantIds an array of additional participant ids.
1703 * @return array of Urls.
1707 static function getAdditionalParticipantUrl($participantIds) {
1708 foreach ($participantIds as $value) {
1710 $details = self
::participantDetails($value);
1711 $viewUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1712 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1714 $editUrl = CRM_Utils_System
::url('civicrm/contact/view/participant',
1715 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1717 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1718 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1724 * to create trxn entry if an event has discount.
1726 * @param int $eventID event id
1727 * @param array $contributionParams contribution params.
1731 static function createDiscountTrxn($eventID, $contributionParams, $feeLevel) {
1733 $checkDiscount = CRM_Core_BAO_Discount
::findSet($eventID,'civicrm_event');
1734 if (!empty($checkDiscount)) {
1735 $feeLevel = current($feeLevel);
1736 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $eventID, NULL);
1737 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1738 LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1739 WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1740 $params = array(1 => array($priceSetId, 'Integer'),
1741 2 => array($feeLevel, 'String'));
1742 $mainAmount = CRM_Core_DAO
::singleValueQuery($query, $params);
1743 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
1744 $contributionParams['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
1745 $contributionParams['contribution']->financial_type_id
, $relationTypeId);
1746 if (CRM_Utils_Array
::value('from_financial_account_id', $contributionParams['trxnParams'])) {
1747 $contributionParams['trxnParams']['total_amount'] = $mainAmount - $contributionParams['total_amount'];
1748 $contributionParams['trxnParams']['payment_processor_id'] = $contributionParams['trxnParams']['payment_instrument_id'] =
1749 $contributionParams['trxnParams']['check_number'] = $contributionParams['trxnParams']['trxn_id'] =
1750 $contributionParams['trxnParams']['net_amount'] = $contributionParams['trxnParams']['fee_amount'] = NULL;
1752 CRM_Core_BAO_FinancialTrxn
::create($contributionParams['trxnParams']);
1759 * Function to delete participants of contact
1763 * @param integer $contactId contact id
1768 static function deleteContactParticipant($contactId) {
1769 $participant = new CRM_Event_DAO_Participant();
1770 $participant->contact_id
= $contactId;
1771 $participant->find();
1772 while ($participant->fetch()) {
1773 self
::deleteParticipant($participant->id
);