3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Event_BAO_Event
extends CRM_Event_DAO_Event
{
20 * Retrieve DB object and copy to defaults array.
22 * @param array $params
23 * Array of criteria values.
24 * @param array $defaults
25 * Array to be populated with found values.
28 * The DAO object, if found.
32 public static function retrieve($params, &$defaults) {
33 return self
::commonRetrieve(self
::class, $params, $defaults);
37 * Update the is_active flag in the db.
40 * Id of the database record.
41 * @param bool $is_active
42 * Value we want to set the is_active field.
45 * true if we found and updated the object, else false
47 public static function setIsActive($id, $is_active) {
48 return CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
54 * @param array $params
55 * Reference array contains the values submitted by the form.
57 * @return CRM_Event_DAO_Event
59 public static function add(&$params) {
60 $financialTypeId = NULL;
61 if (!empty($params['id'])) {
62 CRM_Utils_Hook
::pre('edit', 'Event', $params['id'], $params);
63 if (empty($params['skipFinancialType'])) {
64 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $params['id'], 'financial_type_id');
68 CRM_Utils_Hook
::pre('create', 'Event', NULL, $params);
71 $event = new CRM_Event_DAO_Event();
73 $event->copyValues($params);
74 $result = $event->save();
76 if (!empty($params['id'])) {
77 CRM_Utils_Hook
::post('edit', 'Event', $event->id
, $event);
80 CRM_Utils_Hook
::post('create', 'Event', $event->id
, $event);
82 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
83 CRM_Price_BAO_PriceFieldValue
::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
91 * @param array $params
92 * Reference array contains the values submitted by the form.
96 public static function create(&$params) {
97 $transaction = new CRM_Core_Transaction();
98 if (empty($params['is_template'])) {
99 $params['is_template'] = 0;
101 // check if new event, if so set the created_id (if not set)
102 // and always set created_date to now
103 if (empty($params['id'])) {
104 if (empty($params['created_id'])) {
105 $session = CRM_Core_Session
::singleton();
106 $params['created_id'] = $session->get('userID');
108 $params['created_date'] = date('YmdHis');
110 // Clone from template
111 if (!empty($params['template_id'])) {
112 $copy = self
::copy($params['template_id']);
113 $params['id'] = $copy->id
;
114 unset($params['template_id']);
116 //fix for api from template creation bug
117 civicrm_api4('ActionSchedule', 'update', [
118 'checkPermissions' => FALSE,
120 'mapping_id' => CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
,
123 ['entity_value', '=', $copy->id
],
124 ['mapping_id', '=', CRM_Event_ActionMapping
::EVENT_TPL_MAPPING_ID
],
131 $event = self
::add($params);
132 CRM_Price_BAO_PriceSet
::setPriceSets($params, $event, 'event');
133 if (is_a($event, 'CRM_Core_Error')) {
134 CRM_Core_DAO
::transaction('ROLLBACK');
138 $contactId = CRM_Core_Session
::getLoggedInContactID();
140 $contactId = $params['contact_id'] ??
NULL;
143 // Log the information on successful add/edit of Event
145 'entity_table' => 'civicrm_event',
146 'entity_id' => $event->id
,
147 'modified_id' => $contactId,
148 'modified_date' => date('Ymd'),
151 CRM_Core_BAO_Log
::add($logParams);
153 if (!empty($params['custom']) &&
154 is_array($params['custom'])
156 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_event', $event->id
);
159 $transaction->commit();
160 if (!empty($params['id'])) {
161 // Note that this will specifically clear cached event tokens.
162 Civi
::cache('metadata')->clear();
175 public static function del($id) {
180 CRM_Utils_Hook
::pre('delete', 'Event', $id);
182 $extends = ['event'];
183 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
184 foreach ($groupTree as $values) {
185 $query = "DELETE FROM %1 WHERE entity_id = %2";
186 CRM_Core_DAO
::executeQuery($query, [
187 1 => [$values['table_name'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
],
188 2 => [$id, 'Integer'],
192 // Clean up references to profiles used by the event (CRM-20935)
194 'module' => 'CiviEvent',
195 'entity_table' => 'civicrm_event',
198 CRM_Core_BAO_UFJoin
::deleteAll($ufJoinParams);
200 'module' => 'CiviEvent_Additional',
201 'entity_table' => 'civicrm_event',
204 CRM_Core_BAO_UFJoin
::deleteAll($ufJoinParams);
206 // price set cleanup, CRM-5527
207 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_event', $id);
209 $event = new CRM_Event_DAO_Event();
212 if ($event->find(TRUE)) {
213 $locBlockId = $event->loc_block_id
;
214 $result = $event->delete();
216 if (!is_null($locBlockId)) {
217 self
::deleteEventLocBlock($locBlockId, $id);
220 CRM_Utils_Hook
::post('delete', 'Event', $id, $event);
228 * Delete the location block associated with an event.
230 * Function checks that it is not being used by any other event.
232 * @param int $locBlockId
233 * Location block id to be deleted.
234 * @param int $eventId
235 * Event with which loc block is associated.
237 public static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
238 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
241 $query .= " AND ce.id != $eventId;";
244 $locCount = CRM_Core_DAO
::singleValueQuery($query);
246 if ($locCount == 0) {
247 CRM_Core_BAO_Location
::deleteLocBlock($locBlockId);
252 * Get current/future Events.
255 * 0 returns current and future events.
256 * 1 if events all are required
257 * 2 returns events since 3 months ago
258 * @param int|array $id single int event id or array of multiple event ids to return
259 * @param bool $isActive
260 * true if you need only active events.
261 * @param bool $checkPermission
262 * true if you need to check permission else false.
263 * @param bool $titleOnly
264 * true if you need only title not appended with start date
268 public static function getEvents(
272 $checkPermission = TRUE,
276 SELECT `id`, `title`, `start_date`
278 WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
281 $op = is_array($id) ?
'IN' : '=';
282 $where = CRM_Contact_BAO_Query
::buildClause('id', $op, $id);
283 $query .= " AND {$where}";
286 // find only events ending in the future
287 $endDate = date('YmdHis');
289 AND ( `end_date` >= {$endDate} OR
291 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
296 // find only events starting in the last 3 months
297 $startDate = date('YmdHis', strtotime('3 months ago'));
298 $query .= " AND ( `start_date` >= {$startDate} OR start_date IS NULL )";
301 $query .= " AND civicrm_event.is_active = 1";
304 $query .= " ORDER BY title asc";
307 $dao = CRM_Core_DAO
::executeQuery($query);
308 while ($dao->fetch()) {
309 if ((!$checkPermission ||
310 CRM_Event_BAO_Event
::checkPermission($dao->id
)
314 $events[$dao->id
] = $dao->title
;
316 $events[$dao->id
] .= ' - ' . CRM_Utils_Date
::customFormat($dao->start_date
);
325 * Get events Summary.
328 * Array of event summary values
330 * @throws \CiviCRM_API3_Exception
332 public static function getEventSummary() {
333 $eventSummary = $eventIds = [];
334 $config = CRM_Core_Config
::singleton();
336 // get permission and include them here
337 // does not scale, but rearranging code for now
338 // FIXME in a future release
339 $permissions = self
::getAllPermissions();
341 if (empty($permissions[CRM_Core_Permission
::VIEW
])) {
342 $eventSummary['total_events'] = 0;
343 return $eventSummary;
346 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission
::VIEW
])) . " ) ";
349 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
351 SELECT count(id) as total_events
353 WHERE civicrm_event.is_active = 1 AND
354 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
355 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
358 $dao = CRM_Core_DAO
::executeQuery($query);
361 $eventSummary['total_events'] = $dao->total_events
;
364 if (empty($eventSummary) ||
365 $dao->total_events
== 0
367 return $eventSummary;
370 //get the participant status type values.
371 $cpstObject = new CRM_Event_DAO_ParticipantStatusType();
372 $cpst = $cpstObject->getTableName();
373 $query = "SELECT id, name, label, class FROM $cpst";
374 $status = CRM_Core_DAO
::executeQuery($query);
376 while ($status->fetch()) {
377 $statusValues[$status->id
]['id'] = $status->id
;
378 $statusValues[$status->id
]['name'] = $status->name
;
379 $statusValues[$status->id
]['label'] = $status->label
;
380 $statusValues[$status->id
]['class'] = $status->class;
383 // Get the Id of Option Group for Event Types
384 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
385 $optionGroupDAO->name
= 'event_type';
386 $optionGroupId = NULL;
387 if ($optionGroupDAO->find(TRUE)) {
388 $optionGroupId = $optionGroupDAO->id
;
390 // Get the event summary display preferences
391 $show_max_events = Civi
::settings()->get('show_events');
392 // show all events if show_events is set to a negative value
393 if (isset($show_max_events) && $show_max_events >= 0) {
394 $event_summary_limit = "LIMIT 0, $show_max_events";
397 $event_summary_limit = "";
401 SELECT civicrm_event.id as id, civicrm_event.title as event_title, civicrm_event.is_public as is_public,
402 civicrm_event.max_participants as max_participants, civicrm_event.start_date as start_date,
403 civicrm_event.end_date as end_date, civicrm_event.is_online_registration, civicrm_event.is_monetary, civicrm_event.is_show_location,civicrm_event.is_map as is_map, civicrm_option_value.label as event_type, civicrm_tell_friend.is_active as is_friend_active,
404 civicrm_event.slot_label_id,
405 civicrm_event.summary as summary,
406 civicrm_pcp_block.id as is_pcp_enabled,
407 civicrm_recurring_entity.parent_id as is_repeating_event
409 LEFT JOIN civicrm_option_value ON (
410 civicrm_event.event_type_id = civicrm_option_value.value AND
411 civicrm_option_value.option_group_id = %1 )
412 LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_event.id AND civicrm_tell_friend.entity_table = 'civicrm_event' )
413 LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_event.id AND civicrm_pcp_block.entity_table = 'civicrm_event')
414 LEFT JOIN civicrm_recurring_entity ON ( civicrm_event.id = civicrm_recurring_entity.entity_id AND civicrm_recurring_entity.entity_table = 'civicrm_event' )
415 WHERE civicrm_event.is_active = 1 AND
416 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
417 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
419 ORDER BY civicrm_event.start_date ASC
422 $eventParticipant = [];
426 'eventTitle' => 'event_title',
427 'isPublic' => 'is_public',
428 'maxParticipants' => 'max_participants',
429 'startDate' => 'start_date',
430 'endDate' => 'end_date',
431 'eventType' => 'event_type',
433 'participants' => 'participants',
434 'notCountedDueToRole' => 'notCountedDueToRole',
435 'notCountedDueToStatus' => 'notCountedDueToStatus',
436 'notCountedParticipants' => 'notCountedParticipants',
439 $params = [1 => [$optionGroupId, 'Integer']];
440 $mapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings([
441 'id' => CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
,
443 $dao = CRM_Core_DAO
::executeQuery($query, $params);
444 while ($dao->fetch()) {
445 foreach ($properties as $property => $name) {
455 $eventSummary['events'][$dao->id
][$property] = $set;
459 if ($dao->$name && $config->mapAPIKey
) {
462 $params = ['entity_id' => $dao->id
, 'entity_table' => 'civicrm_event'];
463 $values['location'] = CRM_Core_BAO_Location
::getValues($params, TRUE);
464 if (is_numeric(CRM_Utils_Array
::value('geo_code_1', $values['location']['address'][1])) ||
466 !empty($values['location']['address'][1]['city']) &&
467 !empty($values['location']['address'][1]['state_province_id'])
470 $set = CRM_Utils_System
::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
474 $eventSummary['events'][$dao->id
][$property] = $set;
475 if (is_array($permissions[CRM_Core_Permission
::EDIT
])
476 && in_array($dao->id
, $permissions[CRM_Core_Permission
::EDIT
])) {
477 $eventSummary['events'][$dao->id
]['configure'] = CRM_Utils_System
::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
483 $eventSummary['events'][$dao->id
][$property] = CRM_Utils_Date
::customFormat($dao->$name,
489 case 'notCountedDueToRole':
490 case 'notCountedDueToStatus':
491 case 'notCountedParticipants':
494 if ($name == 'participants') {
495 $propertyCnt = self
::getParticipantCount($dao->id
);
497 $set = CRM_Utils_System
::url('civicrm/event/search',
498 "reset=1&force=1&event=$dao->id&status=true&role=true"
502 elseif ($name == 'notCountedParticipants') {
503 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, TRUE, FALSE);
505 // FIXME : selector fail to search w/ OR operator.
506 // $set = CRM_Utils_System::url( 'civicrm/event/search',
507 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
510 elseif ($name == 'notCountedDueToStatus') {
511 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, FALSE, FALSE);
513 $set = CRM_Utils_System
::url('civicrm/event/search',
514 "reset=1&force=1&event=$dao->id&status=false"
519 $propertyCnt = self
::getParticipantCount($dao->id
, FALSE, FALSE, TRUE, FALSE);
521 $set = CRM_Utils_System
::url('civicrm/event/search',
522 "reset=1&force=1&event=$dao->id&role=false"
527 $eventSummary['events'][$dao->id
][$property] = $propertyCnt;
528 $eventSummary['events'][$dao->id
][$name . '_url'] = $set;
532 $eventSummary['events'][$dao->id
][$property] = $dao->$name;
537 // prepare the area for per-status participant counts
538 $statusClasses = ['Positive', 'Pending', 'Waiting', 'Negative'];
539 $eventSummary['events'][$dao->id
]['statuses'] = array_fill_keys($statusClasses, []);
541 $eventSummary['events'][$dao->id
]['friend'] = $dao->is_friend_active
;
542 $eventSummary['events'][$dao->id
]['is_monetary'] = $dao->is_monetary
;
543 $eventSummary['events'][$dao->id
]['is_online_registration'] = $dao->is_online_registration
;
544 $eventSummary['events'][$dao->id
]['is_show_location'] = $dao->is_show_location
;
545 $eventSummary['events'][$dao->id
]['is_subevent'] = $dao->slot_label_id
;
546 $eventSummary['events'][$dao->id
]['is_pcp_enabled'] = $dao->is_pcp_enabled
;
547 $eventSummary['events'][$dao->id
]['reminder'] = CRM_Core_BAO_ActionSchedule
::isConfigured($dao->id
, $mapping->getId());
548 $eventSummary['events'][$dao->id
]['is_repeating_event'] = $dao->is_repeating_event
;
550 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
551 foreach ($statusValues as $statusId => $statusValue) {
552 if (!array_key_exists($statusId, $statusTypes)) {
555 $class = $statusValue['class'];
556 $statusCount = self
::eventTotalSeats($dao->id
, "( participant.status_id = {$statusId} )");
558 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
560 'url' => CRM_Utils_System
::url('civicrm/event/search', $urlString),
561 'name' => $statusValue['name'],
562 'label' => $statusValue['label'],
563 'count' => $statusCount,
565 $eventSummary['events'][$dao->id
]['statuses'][$class][] = $statusInfo;
570 $countedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
571 $nonCountedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
572 $countedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
573 $nonCountedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
575 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
576 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
578 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
579 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
580 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
581 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
583 return $eventSummary;
587 * Get participant count.
589 * @param int $eventId
590 * @param bool $considerStatus consider status for participant count.
591 * Consider status for participant count.
592 * @param bool $status counted participant.
593 * Consider counted participant.
594 * @param bool $considerRole consider role for participant count.
595 * Consider role for participant count.
596 * @param bool $role consider counted( is filter role) participant.
597 * Consider counted( is filter role) participant.
600 * array with count of participants for each event based on status/role
602 public static function getParticipantCount(
604 $considerStatus = TRUE,
606 $considerRole = TRUE,
610 // consider both role and status for counted participants, CRM-4924.
612 // not counted participant.
613 if ($considerStatus && $considerRole && !$status && !$role) {
617 if ($considerStatus) {
618 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
619 $statusClause = 'NOT IN';
621 $statusClause = 'IN';
623 $status = implode(',', array_keys($statusTypes));
624 if (empty($status)) {
627 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
631 $roleTypes = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
632 $roleClause = 'NOT IN';
637 if (!empty($roleTypes)) {
639 foreach (array_keys($roleTypes) as $roleType) {
640 $escapedRoles[] = CRM_Utils_Type
::escape($roleType, 'String');
643 $clause[] = "participant.role_id {$roleClause} ( '" . implode("', '", $escapedRoles) . "' ) ";
648 if (!empty($clause)) {
649 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
652 return self
::eventTotalSeats($eventId, $sqlClause);
656 * Get the information to map an event.
659 * For which we want map info.
663 public static function &getMapInfo(&$id) {
667 civicrm_event.id AS event_id,
668 civicrm_event.title AS display_name,
669 civicrm_address.street_address AS street_address,
670 civicrm_address.city AS city,
671 civicrm_address.postal_code AS postal_code,
672 civicrm_address.postal_code_suffix AS postal_code_suffix,
673 civicrm_address.geo_code_1 AS latitude,
674 civicrm_address.geo_code_2 AS longitude,
675 civicrm_state_province.abbreviation AS state,
676 civicrm_country.name AS country,
677 civicrm_location_type.name AS location_type
680 LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )
681 LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )
682 LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )
683 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
684 LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )
685 WHERE civicrm_address.geo_code_1 IS NOT NULL
686 AND civicrm_address.geo_code_2 IS NOT NULL
687 AND civicrm_event.id = " . CRM_Utils_Type
::escape($id, 'Integer');
689 $dao = new CRM_Core_DAO();
694 $config = CRM_Core_Config
::singleton();
696 while ($dao->fetch()) {
699 $location['displayName'] = addslashes($dao->display_name
);
700 $location['lat'] = $dao->latitude
;
701 $location['marker_class'] = 'Event';
702 $location['lng'] = $dao->longitude
;
704 $params = ['entity_id' => $id, 'entity_table' => 'civicrm_event'];
705 $addressValues = CRM_Core_BAO_Location
::getValues($params, TRUE);
706 $location['address'] = str_replace([
709 ], '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
711 $location['url'] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
);
712 $location['location_type'] = $dao->location_type
;
713 $eventImage = '<img src="' . $config->resourceBase
. 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
714 $location['image'] = $eventImage;
715 $location['displayAddress'] = str_replace('<br />', ', ', $location['address']);
716 $locations[] = $location;
722 * Get the complete information for one or more events.
725 * Get events with start date >= this date.
726 * @param int $type Get events on the a specific event type (by event_type_id).
727 * Get events on the a specific event type (by event_type_id).
728 * @param int $eventId Return a single event - by event id.
729 * Return a single event - by event id.
731 * Also get events with end date >= this date.
732 * @param bool $onlyPublic Include public events only, default TRUE.
733 * Include public events only, default TRUE.
736 * array of all the events that are searched
738 public static function getCompleteInfo(
745 $publicCondition = NULL;
747 $publicCondition = " AND civicrm_event.is_public = 1";
751 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
753 // get events with start_date >= requested start
754 $startDate = CRM_Utils_Type
::escape($start, 'Date');
755 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
759 // also get events with end_date <= requested end
760 $endDate = CRM_Utils_Type
::escape($end, 'Date');
761 $dateCondition .= " AND ( civicrm_event.end_date <= '{$endDate}' ) ";
764 // CRM-9421 and CRM-8620 Default mode for ical/rss feeds. No start or end filter passed.
765 // Need to exclude old events with only start date
766 // and not exclude events in progress (start <= today and end >= today). DGG
767 if (empty($start) && empty($end)) {
768 // get events with end date >= today, not sure of this logic
769 // but keeping this for backward compatibility as per issue CRM-5133
770 $today = date("Y-m-d G:i:s");
771 $dateCondition .= " AND ( civicrm_event.end_date >= '{$today}' OR civicrm_event.start_date >= '{$today}' ) ";
775 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
778 // Get the Id of Option Group for Event Types
779 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
780 $optionGroupDAO->name
= 'event_type';
781 $optionGroupId = NULL;
782 if ($optionGroupDAO->find(TRUE)) {
783 $optionGroupId = $optionGroupDAO->id
;
788 civicrm_event.id as event_id,
789 civicrm_email.email as email,
790 civicrm_event.title as title,
791 civicrm_event.summary as summary,
792 civicrm_event.start_date as start,
793 civicrm_event.end_date as end,
794 civicrm_event.description as description,
795 civicrm_event.is_show_location as is_show_location,
796 civicrm_event.is_online_registration as is_online_registration,
797 civicrm_event.registration_link_text as registration_link_text,
798 civicrm_event.registration_start_date as registration_start_date,
799 civicrm_event.registration_end_date as registration_end_date,
800 civicrm_option_value.label as event_type,
801 civicrm_address.name as address_name,
802 civicrm_address.street_address as street_address,
803 civicrm_address.supplemental_address_1 as supplemental_address_1,
804 civicrm_address.supplemental_address_2 as supplemental_address_2,
805 civicrm_address.supplemental_address_3 as supplemental_address_3,
806 civicrm_address.city as city,
807 civicrm_address.postal_code as postal_code,
808 civicrm_address.postal_code_suffix as postal_code_suffix,
809 civicrm_state_province.abbreviation as state,
810 civicrm_country.name AS country
812 LEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id
813 LEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id
814 LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
815 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
816 LEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id
817 LEFT JOIN civicrm_option_value ON (
818 civicrm_event.event_type_id = civicrm_option_value.value AND
819 civicrm_option_value.option_group_id = %1 )
820 WHERE civicrm_event.is_active = 1
821 AND (is_template = 0 OR is_template IS NULL)
825 if (isset($typeCondition)) {
826 $query .= $typeCondition;
829 if (isset($eventId)) {
830 $query .= " AND civicrm_event.id =$eventId ";
832 $query .= " ORDER BY civicrm_event.start_date ASC";
834 $params = [1 => [$optionGroupId, 'Integer']];
835 $dao = CRM_Core_DAO
::executeQuery($query, $params);
837 $config = CRM_Core_Config
::singleton();
839 $baseURL = parse_url($config->userFrameworkBaseURL
);
840 $url = "@" . $baseURL['host'];
841 if (!empty($baseURL['path'])) {
842 $url .= substr($baseURL['path'], 0, -1);
845 // check 'view event info' permission
846 //@todo - per CRM-14626 we have resolved that 'view event info' means 'view ALL event info'
847 if (CRM_Core_Permission
::check('view event info')) {
851 $permissions = CRM_Core_Permission
::event(CRM_Core_Permission
::VIEW
);
854 while ($dao->fetch()) {
855 if (!empty($permissions) && ($permissions === TRUE ||
in_array($dao->event_id
, $permissions))) {
857 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL
) . $url;
859 $info['title'] = $dao->title
;
860 $info['event_id'] = $dao->event_id
;
861 $info['summary'] = $dao->summary
;
862 $info['description'] = $dao->description
;
863 $info['start_date'] = $dao->start
;
864 $info['end_date'] = $dao->end
;
865 $info['contact_email'] = $dao->email
;
866 $info['event_type'] = $dao->event_type
;
867 $info['is_show_location'] = $dao->is_show_location
;
868 $info['is_online_registration'] = $dao->is_online_registration
;
869 $info['registration_link_text'] = $dao->registration_link_text
;
870 $info['registration_start_date'] = $dao->registration_start_date
;
871 $info['registration_end_date'] = $dao->registration_end_date
;
876 'address_name' => $dao->address_name
,
877 'street_address' => $dao->street_address
,
878 'supplemental_address_1' => $dao->supplemental_address_1
,
879 'supplemental_address_2' => $dao->supplemental_address_2
,
880 'supplemental_address_3' => $dao->supplemental_address_3
,
881 'city' => $dao->city
,
882 'state_province' => $dao->state
,
883 'postal_code' => $dao->postal_code
,
884 'postal_code_suffix' => $dao->postal_code_suffix
,
885 'country' => $dao->country
,
889 CRM_Utils_String
::append($address, ', ',
890 CRM_Utils_Address
::format($addrFields)
892 $info['location'] = $address;
893 $info['url'] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
895 // @todo Move to eventcart extension
896 // check if we're in shopping cart mode for events
897 if ((bool) Civi
::settings()->get('enable_cart')) {
898 $reg = CRM_Event_Cart_BAO_EventInCart
::get_registration_link($dao->event_id
);
899 $info['registration_link'] = CRM_Utils_System
::url($reg['path'], $reg['query'], TRUE);
900 $info['registration_link_text'] = $reg['label'];
911 * Make a copy of a Event.
913 * Include all the fields in the event Wizard.
916 * The event id to copy.
917 * @param array $params
919 * @return CRM_Event_DAO_Event
920 * @throws \CRM_Core_Exception
922 public static function copy($id, $params = []) {
923 $session = CRM_Core_Session
::singleton();
926 //get the required event values.
927 $eventParams = ['id' => $id];
928 $returnProperties = [
932 'default_discount_fee_id',
936 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
940 'title' => ts('Copy of') . ' ',
943 'created_id' => $session->get('userID'),
944 'created_date' => date('YmdHis'),
947 if (empty($eventValues['is_show_location'])) {
948 $fieldsFix['prefix']['is_show_location'] = 0;
951 $blockCopyOfCustomValue = (!empty($params['custom']));
953 /** @var \CRM_Event_DAO_Event $copyEvent */
954 $copyEvent = CRM_Core_DAO
::copyGeneric('CRM_Event_DAO_Event',
956 // since the location is sharable, lets use the same loc_block_id.
957 ['loc_block_id' => CRM_Utils_Array
::value('loc_block_id', $eventValues)] +
$params,
960 $blockCopyOfCustomValue
962 CRM_Price_BAO_PriceSet
::copyPriceSet('civicrm_event', $id, $copyEvent->id
);
963 CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_UFJoin',
966 'entity_table' => 'civicrm_event',
968 ['entity_id' => $copyEvent->id
]
971 CRM_Core_DAO
::copyGeneric('CRM_Friend_DAO_Friend',
974 'entity_table' => 'civicrm_event',
976 ['entity_id' => $copyEvent->id
]
979 CRM_Core_DAO
::copyGeneric('CRM_PCP_DAO_PCPBlock',
982 'entity_table' => 'civicrm_event',
984 ['entity_id' => $copyEvent->id
],
985 ['replace' => ['target_entity_id' => $copyEvent->id
]]
988 $oldMapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings([
989 'id' => ($eventValues['is_template'] ? CRM_Event_ActionMapping
::EVENT_TPL_MAPPING_ID
: CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
),
991 $copyMapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings([
992 'id' => ($copyEvent->is_template
== 1 ? CRM_Event_ActionMapping
::EVENT_TPL_MAPPING_ID
: CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
),
994 CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_ActionSchedule',
995 ['entity_value' => $id, 'mapping_id' => $oldMapping->getId()],
996 ['entity_value' => $copyEvent->id
, 'mapping_id' => $copyMapping->getId()]
1001 if ($blockCopyOfCustomValue) {
1002 foreach ($params['custom'] as &$values) {
1003 foreach ($values as &$value) {
1004 // Ensure we don't copy over the template's id if it is passed in
1005 // This is a bit hacky but it's unclear what the
1006 // right behaviour is given the whole 'custom'
1007 // field is form layer formatting that is reaching the BAO.
1008 $value['id'] = NULL;
1011 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_event', $copyEvent->id
);
1014 CRM_Utils_System
::flushCache();
1015 CRM_Utils_Hook
::copy('Event', $copyEvent);
1021 * This is sometimes called in a loop (during event search).
1023 * We cache the values to prevent repeated calls to the db.
1029 public static function isMonetary($id) {
1030 static $isMonetary = [];
1031 if (!array_key_exists($id, $isMonetary)) {
1032 $isMonetary[$id] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event',
1037 return $isMonetary[$id];
1041 * This is sometimes called in a loop (during event search).
1043 * We cache the values to prevent repeated calls to the db.
1049 public static function usesPriceSet($id) {
1050 static $usesPriceSet = [];
1051 if (!array_key_exists($id, $usesPriceSet)) {
1052 $usesPriceSet[$id] = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $id);
1054 return $usesPriceSet[$id];
1060 * @param int $contactID
1061 * @param array $values
1062 * @param int $participantId
1063 * @param bool $isTest
1064 * @param bool $returnMessageText
1066 * @return array|null
1067 * @throws \CiviCRM_API3_Exception
1069 public static function sendMail($contactID, $values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
1071 $template = CRM_Core_Smarty
::singleton();
1073 'custom_pre_id' => $values['custom_pre_id'],
1074 'custom_post_id' => $values['custom_post_id'],
1077 //get the params submitted by participant.
1078 $participantParams = CRM_Utils_Array
::value($participantId, $values['params'], []);
1080 if (!$returnMessageText) {
1081 //send notification email if field values are set (CRM-1941)
1082 foreach ($gIds as $key => $gIdValues) {
1084 if (!is_array($gIdValues)) {
1085 $gIdValues = [$gIdValues];
1088 foreach ($gIdValues as $gId) {
1089 $email = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1091 //get values of corresponding profile fields for notification
1092 [$profileValues] = self
::buildCustomDisplay($gId,
1101 [$profileValues] = $profileValues;
1104 'values' => $profileValues,
1107 CRM_Core_BAO_UFGroup
::commonSendMail($contactID, $val);
1114 if ($values['event']['is_email_confirm'] ||
$returnMessageText) {
1115 list($displayName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1116 $notifyEmail = CRM_Utils_Array
::valueByRegexKey('/^email-/', $participantParams) ??
$email;
1117 //send email only when email is present
1118 if (isset($notifyEmail) ||
$returnMessageText) {
1119 $preProfileID = $values['custom_pre_id'] ??
NULL;
1120 $postProfileID = $values['custom_post_id'] ??
NULL;
1122 if (!empty($values['params']['additionalParticipant'])) {
1123 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values, $preProfileID);
1124 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values, $postProfileID);
1127 $profilePre = self
::buildCustomDisplay($preProfileID,
1137 $profilePost = self
::buildCustomDisplay($postProfileID,
1147 $sessions = CRM_Event_Cart_BAO_Conference
::get_participant_sessions($participantId);
1149 // @todo - the goal is that all params available to the message template are explicitly defined here rather than
1150 // 'in a smattering of places'. Note that leakage can happen between mailings when not explicitly defined.
1151 if ($postProfileID) {
1152 $customPostTitles = empty($profilePost[1]) ?
NULL : [];
1153 foreach ($postProfileID as $offset => $id) {
1154 $customPostTitles[$offset] = CRM_Core_BAO_UFGroup
::getFrontEndTitle((int) $id);
1158 $customPostTitles = NULL;
1160 $tplParams = array_merge($values, $participantParams, [
1161 'email' => $notifyEmail,
1162 'confirm_email_text' => $values['event']['confirm_email_text'] ??
NULL,
1163 'isShowLocation' => $values['event']['is_show_location'] ??
NULL,
1164 // The concept of contributeMode is deprecated.
1165 'contributeMode' => $template->_tpl_vars
['contributeMode'] ??
NULL,
1166 'customPre' => $profilePre[0],
1167 'customPre_grouptitle' => empty($profilePre[1]) ?
NULL : [CRM_Core_BAO_UFGroup
::getFrontEndTitle((int) $preProfileID)],
1168 'customPost' => $profilePost[0],
1169 'customPost_grouptitle' => $customPostTitles,
1170 'participantID' => $participantId,
1171 'contactID' => $contactID,
1172 'conference_sessions' => $sessions,
1173 'credit_card_number' => CRM_Utils_System
::mungeCreditCard(CRM_Utils_Array
::value('credit_card_number', $participantParams)),
1174 'credit_card_exp_date' => CRM_Utils_Date
::mysqlToIso(CRM_Utils_Date
::format(CRM_Utils_Array
::value('credit_card_exp_date', $participantParams))),
1175 'selfcancelxfer_time' => abs($values['event']['selfcancelxfer_time']),
1176 'selfservice_preposition' => $values['event']['selfcancelxfer_time'] < 0 ?
ts('after') : ts('before'),
1177 'currency' => $values['event']['currency'] ?? CRM_Core_Config
::singleton()->defaultCurrency
,
1180 // CRM-13890 : NOTE wait list condition need to be given so that
1181 // wait list message is shown properly in email i.e. WRT online event registration template
1182 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
1183 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id', TRUE);
1184 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($statusId, NULL, 'label');
1186 //CRM-15754 - if participant_status contains status ID
1187 elseif (!empty($tplParams['participant_status']) && CRM_Utils_Rule
::integer($tplParams['participant_status'])) {
1188 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($tplParams['participant_status'], NULL, 'label');
1191 $sendTemplateParams = [
1192 'groupName' => 'msg_tpl_workflow_event',
1193 'valueName' => 'event_online_receipt',
1194 'contactId' => $contactID,
1195 'isTest' => $isTest,
1196 'tplParams' => $tplParams,
1197 'PDFFilename' => ts('confirmation') . '.pdf',
1200 // address required during receipt processing (pdf and email receipt)
1201 if ($displayAddress = CRM_Utils_Array
::value('address', $values)) {
1202 $sendTemplateParams['tplParams']['address'] = $displayAddress;
1203 // The concept of contributeMode is deprecated.
1204 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1207 // set lineItem details
1208 if ($lineItem = CRM_Utils_Array
::value('lineItem', $values)) {
1209 // check if additional participant, if so filter only to relevant ones
1211 if (!empty($values['params']['additionalParticipant'])) {
1213 foreach ($lineItem as $liKey => $liValue) {
1214 $firstElement = array_pop($liValue);
1215 if ($firstElement['entity_id'] == $participantId) {
1216 $ownLineItems[0] = $lineItem[$liKey];
1220 if (!empty($ownLineItems)) {
1221 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1225 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1229 if ($returnMessageText) {
1230 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1232 'subject' => $subject,
1234 'to' => $displayName,
1239 $sendTemplateParams['from'] = CRM_Utils_Array
::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array
::value('confirm_from_email', $values['event']) . ">";
1240 $sendTemplateParams['toName'] = $displayName;
1241 $sendTemplateParams['toEmail'] = $notifyEmail;
1242 $sendTemplateParams['autoSubmitted'] = TRUE;
1243 $sendTemplateParams['cc'] = CRM_Utils_Array
::value('cc_confirm',
1246 $sendTemplateParams['bcc'] = CRM_Utils_Array
::value('bcc_confirm',
1250 if (Civi
::settings()->get('invoice_is_email_pdf') && !empty($values['contributionId'])) {
1251 $sendTemplateParams['isEmailPdf'] = TRUE;
1252 $sendTemplateParams['contributionId'] = $values['contributionId'];
1254 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1261 * Add the custom fields OR array of participant's profile info.
1264 * @param string $name
1266 * @param \CRM_Core_Smarty $template
1267 * @param int $participantId
1268 * @param bool $isTest
1269 * @param bool $returnResults
1270 * @param array $participantParams
1272 * @return array|null
1273 * @throws \CRM_Core_Exception
1275 public static function buildCustomDisplay(
1282 $returnResults = FALSE,
1283 $participantParams = []
1286 return [NULL, NULL];
1289 if (!is_array($id)) {
1290 $id = CRM_Utils_Type
::escape($id, 'Positive');
1291 $profileIds = [$id];
1297 $val = $groupTitles = NULL;
1298 foreach ($profileIds as $gid) {
1299 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $cid)) {
1301 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
,
1302 NULL, NULL, FALSE, NULL,
1303 FALSE, NULL, CRM_Core_Permission
::CREATE
,
1307 //this condition is added, since same contact can have multiple event registrations..
1308 $params = [['participant_id', '=', $participantId, 0, 0]];
1310 //add participant id
1311 $fields['participant_id'] = [
1312 'name' => 'participant_id',
1313 'title' => ts('Participant ID'),
1315 //check whether its a text drive
1317 $params[] = ['participant_test', '=', 1, 0, 0];
1320 //display campaign on thankyou page.
1321 if (array_key_exists('participant_campaign_id', $fields)) {
1322 if ($participantId) {
1323 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1327 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1328 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array
::value($campaignId,
1332 unset($fields['participant_campaign_id']);
1336 foreach ($fields as $k => $v) {
1338 $groupTitle = $v['groupDisplayTitle'];
1340 // suppress all file fields from display
1342 CRM_Utils_Array
::value('data_type', $v, '') == 'File' ||
1343 CRM_Utils_Array
::value('name', $v, '') == 'image_URL' ||
1344 CRM_Utils_Array
::value('field_type', $v) == 'Formatting'
1351 $groupTitles[] = $groupTitle;
1353 //display profile groups those are subscribed by participant.
1354 if (($groups = CRM_Utils_Array
::value('group', $participantParams)) &&
1358 foreach ($groups as $grpId => $isSelected) {
1363 if (!empty($grpIds)) {
1364 //get the group titles.
1366 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1367 $grp = CRM_Core_DAO
::executeQuery($query);
1368 while ($grp->fetch()) {
1369 $grpTitles[] = $grp->title
;
1371 if (!empty($grpTitles) &&
1372 CRM_Utils_Array
::value('title', CRM_Utils_Array
::value('group', $fields))
1374 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1376 unset($fields['group']);
1380 CRM_Core_BAO_UFGroup
::getValues($cid, $fields, $values, FALSE, $params);
1383 //If the event profile includes a note field and the submitted value of
1384 //that field is "", then remove the old note returned by getValues.
1385 if (isset($participantParams['note']) && empty($participantParams['note'])) {
1386 $noteKeyPos = array_search('note', array_keys($fields));
1387 $valuesKeys = array_keys($values);
1388 $values[$valuesKeys[$noteKeyPos]] = "";
1391 if (isset($fields['participant_status_id']['title']) &&
1392 isset($values[$fields['participant_status_id']['title']]) &&
1393 is_numeric($values[$fields['participant_status_id']['title']])
1396 $status = CRM_Event_PseudoConstant
::participantStatus();
1397 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1400 if (isset($fields['participant_role_id']['title']) &&
1401 isset($values[$fields['participant_role_id']['title']]) &&
1402 is_numeric($values[$fields['participant_role_id']['title']])
1405 $roles = CRM_Event_PseudoConstant
::participantRole();
1406 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1409 if (isset($fields['participant_register_date']['title']) &&
1410 isset($values[$fields['participant_register_date']['title']])
1412 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date
::customFormat($values[$fields['participant_register_date']['title']]);
1415 //handle fee_level for price set
1416 if (isset($fields['participant_fee_level']['title']) &&
1417 isset($values[$fields['participant_fee_level']['title']])
1419 $feeLevel = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1420 $values[$fields['participant_fee_level']['title']]
1422 foreach ($feeLevel as $key => $value) {
1424 unset($feeLevel[$key]);
1427 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
1430 unset($values[$fields['participant_id']['title']]);
1437 $template->assign($name, $val);
1440 if (count($groupTitles)) {
1441 $template->assign($name . '_grouptitle', $groupTitles);
1444 //return if we only require array of participant's info.
1445 if ($returnResults) {
1447 return [$val, $groupTitles];
1456 * Build the array for display the profile fields.
1458 * @param array $params
1462 * @param array $groupTitle
1463 * Profile Group Title.
1464 * @param array $values
1465 * Formatted array of key value.
1467 * @param array $profileFields
1469 * @throws \CRM_Core_Exception
1470 * @throws \API_Exception
1471 * @throws \CiviCRM_API3_Exception
1473 public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = []) {
1475 $config = CRM_Core_Config
::singleton();
1476 $session = CRM_Core_Session
::singleton();
1477 $contactID = $session->get('userID');
1479 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $contactID)) {
1480 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
);
1484 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::ADD
);
1487 if (!empty($fields)) {
1488 $groupTitle['groupTitle'] = CRM_Core_BAO_UFGroup
::getFrontEndTitle((int) $gid);
1491 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1492 //start of code to set the default values
1493 foreach ($fields as $name => $field) {
1496 // skip fields that should not be displayed separately
1497 if ($field['skipDisplay']) {
1501 $index = $field['title'];
1502 if ($name === 'organization_name') {
1503 $values[$index] = $params[$name];
1506 if ('state_province' == substr($name, 0, 14)) {
1507 if ($params[$name]) {
1508 $values[$index] = CRM_Core_PseudoConstant
::stateProvince($params[$name]);
1511 $values[$index] = '';
1514 elseif ('date' == substr($name, -4)) {
1515 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::processDate($params[$name]),
1516 $config->dateformatFull
);
1518 elseif ('country' == substr($name, 0, 7)) {
1519 if ($params[$name]) {
1520 $values[$index] = CRM_Core_PseudoConstant
::country($params[$name]);
1523 $values[$index] = '';
1526 elseif ('county' == substr($name, 0, 6)) {
1527 if ($params[$name]) {
1528 $values[$index] = CRM_Core_PseudoConstant
::county($params[$name]);
1531 $values[$index] = '';
1534 elseif (in_array(substr($name, 0, -3), ['gender', 'prefix', 'suffix', 'communication_style'])) {
1535 $values[$index] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
1537 elseif (in_array($name, [
1542 $filterCondition = ['greeting_type' => $name];
1543 $greeting = CRM_Core_PseudoConstant
::greeting($filterCondition);
1544 $values[$index] = $greeting[$params[$name]];
1546 elseif ($name === 'preferred_communication_method') {
1547 $communicationFields = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1549 $pref = $params[$name];
1550 if (is_array($pref)) {
1551 foreach ($pref as $k => $v) {
1553 $compref[] = $communicationFields[$k];
1557 $values[$index] = implode(',', $compref);
1559 elseif ($name == 'contact_sub_type') {
1560 $values[$index] = implode(', ', $params[$name]);
1562 elseif ($name == 'group') {
1563 $groups = CRM_Contact_BAO_GroupContact
::getGroupList();
1565 foreach ($params[$name] as $gId => $dontCare) {
1567 $title[] = $groups[$gId];
1570 $values[$index] = implode(', ', $title);
1572 elseif ($name == 'tag') {
1573 $entityTags = $params[$name];
1574 $allTags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]);
1576 if (is_array($entityTags)) {
1577 foreach ($entityTags as $tagId => $dontCare) {
1578 $title[] = $allTags[$tagId];
1581 $values[$index] = implode(', ', $title);
1583 elseif ('participant_role_id' == $name or
1584 'participant_role' == $name
1586 $roles = CRM_Event_PseudoConstant
::participantRole();
1587 $values[$index] = $roles[$params[$name]];
1589 elseif ('participant_status_id' == $name or
1590 'participant_status' == $name
1592 $status = CRM_Event_PseudoConstant
::participantStatus();
1593 $values[$index] = $status[$params[$name]];
1595 elseif (substr($name, -11) == 'campaign_id') {
1596 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($params[$name]);
1597 $values[$index] = $campaigns[$params[$name]] ??
NULL;
1599 elseif (strpos($name, '-') !== FALSE) {
1600 list($fieldName, $id) = CRM_Utils_System
::explode('-', $name, 2);
1601 $detailName = str_replace(' ', '_', $name);
1602 if (in_array($fieldName, [
1607 $values[$index] = $params[$detailName];
1608 $idx = $detailName . '_id';
1609 $values[$index] = $params[$idx];
1611 elseif ($fieldName == 'im') {
1612 $providerName = NULL;
1613 if ($providerId = $detailName . '-provider_id') {
1614 $providerName = $imProviders[$params[$providerId]] ??
NULL;
1616 if ($providerName) {
1617 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1620 $values[$index] = $params[$detailName];
1623 elseif ($fieldName == 'phone') {
1624 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1625 if (isset($params[$phoneExtField])) {
1626 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1629 $values[$index] = $params[$detailName];
1633 $values[$index] = $params[$detailName];
1637 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1638 if ($params[$name]) {
1639 $values[$index] = '[ x ]';
1643 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
1645 SELECT html_type, data_type
1646 FROM civicrm_custom_field
1649 $dao = CRM_Core_DAO
::executeQuery($query);
1651 $htmlType = $dao->html_type
;
1653 if ($htmlType == 'File') {
1654 $path = $params[$name]['name'] ??
NULL;
1655 $fileType = $params[$name]['type'] ??
NULL;
1656 $values[$index] = CRM_Utils_File
::getFileURL($path, $fileType);
1659 if ($dao->data_type
== 'Int' ||
1660 $dao->data_type
== 'Boolean'
1662 $v = $params[$name];
1663 if (!CRM_Utils_System
::isNull($v)) {
1664 $customVal = (int) $v;
1667 elseif ($dao->data_type
== 'Float') {
1668 $customVal = (float) ($params[$name]);
1670 elseif ($dao->data_type
== 'Date') {
1671 //@todo note the currently we are using default date time formatting. Since you can select/set
1672 // different date and time format specific to custom field we should consider fixing this
1673 // sometime in the future
1674 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1675 CRM_Utils_Date
::processDate($params[$name]), $config->dateformatFull
);
1677 if (!empty($params[$name . '_time'])) {
1678 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1679 CRM_Utils_Date
::processDate($params[$name], $params[$name . '_time']),
1680 $config->dateformatDatetime
);
1684 // for checkboxes, change array of [key => bool] to array of [idx => key]
1685 elseif ($dao->html_type
== 'CheckBox') {
1686 $customVal = array_keys(array_filter($params[$name]));
1689 $customVal = $params[$name];
1691 //take the custom field options
1692 $returnProperties = [$name => 1];
1693 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
1695 $displayValue = CRM_Core_BAO_CustomField
::displayValue($customVal, $cfID);
1697 //Hack since we dont have function to check empty.
1698 //FIXME in 2.3 using crmIsEmptyArray()
1699 $customValue = TRUE;
1700 if (is_array($customVal) && is_array($displayValue)) {
1701 $customValue = array_diff($customVal, $displayValue);
1703 //use difference of arrays
1704 if (empty($customValue) ||
!$customValue) {
1705 $values[$index] = '';
1708 $values[$index] = $displayValue;
1712 elseif ($name == 'home_URL' &&
1713 !empty($params[$name])
1715 $url = CRM_Utils_System
::fixURL($params[$name]);
1716 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1718 elseif (in_array($name, [
1721 'participant_register_date',
1723 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::format($params[$name]));
1726 $values[$index] = $params[$name] ??
NULL;
1730 $profileFields[$name] = $field;
1736 * Build the array for Additional participant's information array of primary and additional Ids.
1738 * @param int $participantId
1739 * Id of Primary participant.
1740 * @param array $values
1741 * Key/value event info.
1742 * @param int $contactId
1743 * Contact id of Primary participant.
1744 * @param bool $isTest
1745 * Whether test or live transaction.
1746 * @param bool $isIdsArray
1747 * To return an array of Ids.
1749 * @param bool $skipCancel
1752 * array of Additional participant's info OR array of Ids.
1754 public static function buildCustomProfile(
1759 $isIdsArray = FALSE,
1763 $customProfile = $additionalIDs = [];
1764 if (!$participantId) {
1765 throw new CRM_Core_Exception(ts('Cannot find participant ID'));
1768 //set Ids of Primary Participant also.
1769 if ($isIdsArray && $contactId) {
1770 $additionalIDs[$participantId] = $contactId;
1773 //hack to skip cancelled participants, CRM-4320
1774 $where = "participant.registered_by_id={$participantId}";
1776 $cancelStatusId = 0;
1777 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1778 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1779 $where .= " AND participant.status_id != {$cancelStatusId}";
1782 SELECT participant.id, participant.contact_id
1783 FROM civicrm_participant participant
1786 $dao = CRM_Core_DAO
::executeQuery($query);
1787 while ($dao->fetch()) {
1788 $additionalIDs[$dao->id
] = $dao->contact_id
;
1791 //return if only array is required.
1792 if ($isIdsArray && $contactId) {
1793 return $additionalIDs;
1796 $preProfileID = $values['additional_custom_pre_id'] ??
NULL;
1797 $postProfileID = $values['additional_custom_post_id'] ??
NULL;
1798 //else build array of Additional participant's information.
1799 if (count($additionalIDs)) {
1800 if ($preProfileID ||
$postProfileID) {
1801 $template = CRM_Core_Smarty
::singleton();
1803 $isCustomProfile = TRUE;
1805 $title = $groupTitles = [];
1806 foreach ($additionalIDs as $pId => $cId) {
1807 //get the params submitted by participant.
1808 $participantParams = NULL;
1809 if (isset($values['params'])) {
1810 $participantParams = CRM_Utils_Array
::value($pId, $values['params'], []);
1813 list($profilePre, $groupTitles) = self
::buildCustomDisplay($preProfileID,
1814 'additionalCustomPre',
1824 $profile = $profilePre;
1825 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1827 $title = $groupTitles;
1831 list($profilePost, $groupTitles) = self
::buildCustomDisplay($postProfileID,
1832 'additionalCustomPost',
1842 if (isset($profilePre)) {
1843 $profile = array_merge($profilePre, $profilePost);
1845 $title = array_merge($title, $groupTitles);
1849 $profile = $profilePost;
1851 $title = $groupTitles;
1855 $profiles[] = $profile;
1858 $customProfile['title'] = $title;
1859 $customProfile['profile'] = $profiles;
1863 return $customProfile;
1867 * Retrieve all event addresses.
1871 public static function getLocationEvents() {
1875 'loc_block_id.address_id.name',
1876 'loc_block_id.address_id.street_address',
1877 'loc_block_id.address_id.supplemental_address_1',
1878 'loc_block_id.address_id.supplemental_address_2',
1879 'loc_block_id.address_id.supplemental_address_3',
1880 'loc_block_id.address_id.city',
1881 'loc_block_id.address_id.state_province_id.name',
1884 $result = civicrm_api3('Event', 'get', [
1885 'check_permissions' => TRUE,
1887 'loc_block_id.address_id' => ['IS NOT NULL' => 1],
1893 foreach ($result['values'] as $event) {
1895 foreach ($ret as $field) {
1896 if ($field != 'loc_block_id' && !empty($event[$field])) {
1897 $address .= ($address ?
' :: ' : '') . $event[$field];
1901 $events[$event['loc_block_id']] = $address;
1905 return CRM_Utils_Array
::asort($events);
1909 * @param int $locBlockId
1911 * @return int|null|string
1913 public static function countEventsUsingLocBlockId($locBlockId) {
1918 $locBlockId = CRM_Utils_Type
::escape($locBlockId, 'Integer');
1921 SELECT count(*) FROM civicrm_event ce
1922 WHERE ce.loc_block_id = $locBlockId";
1924 return CRM_Core_DAO
::singleValueQuery($query);
1928 * Check if event registration is valid according to permissions AND Dates.
1930 * @param array $values
1931 * @param int $eventID
1934 public static function validRegistrationRequest($values, $eventID) {
1935 // check that the user has permission to register for this event
1936 $hasPermission = CRM_Core_Permission
::event(CRM_Core_Permission
::EDIT
,
1937 $eventID, 'register for events'
1940 return $hasPermission && self
::validRegistrationDate($values);
1948 public static function validRegistrationDate(&$values) {
1949 // make sure that we are between registration start date and end dates
1950 // and that if the event has ended, registration is still specifically open
1951 $startDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_start_date', $values));
1952 $endDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_end_date', $values));
1953 $eventEnd = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('end_date', $values));
1956 if ($startDate && $startDate >= $now) {
1959 elseif ($endDate && $endDate < $now) {
1962 elseif ($eventEnd && $eventEnd < $now && !$endDate) {
1969 /* Function to Show - Hide the Registration Link.
1971 * @param array $values
1972 * Key/value event info.
1974 * true if allow registration otherwise false
1982 public static function showHideRegistrationLink($values) {
1984 $session = CRM_Core_Session
::singleton();
1985 $contactID = $session->get('userID');
1986 $alreadyRegistered = FALSE;
1989 $params = ['contact_id' => $contactID];
1991 if ($eventId = CRM_Utils_Array
::value('id', $values['event'])) {
1992 $params['event_id'] = $eventId;
1994 if ($roleId = CRM_Utils_Array
::value('default_role_id', $values['event'])) {
1995 $params['role_id'] = $roleId;
1997 $alreadyRegistered = self
::checkRegistration($params);
2000 if (!empty($values['event']['allow_same_participant_emails']) ||
2008 /* Function to check if given contact is already registered.
2010 * @param array $params
2011 * Key/value participant info.
2016 * @param array $params
2020 public static function checkRegistration($params) {
2021 $alreadyRegistered = FALSE;
2022 if (empty($params['contact_id'])) {
2023 return $alreadyRegistered;
2026 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
2028 $participant = new CRM_Event_DAO_Participant();
2029 $participant->copyValues($params);
2031 $participant->is_test
= CRM_Utils_Array
::value('is_test', $params, 0);
2032 $participant->selectAdd();
2033 $participant->selectAdd('status_id');
2034 if ($participant->find(TRUE) && array_key_exists($participant->status_id
, $statusTypes)) {
2035 $alreadyRegistered = TRUE;
2038 return $alreadyRegistered;
2042 * Make sure that the user has permission to access this event.
2043 * FIXME: We have separate caches for checkPermission('permission') and getAllPermissions['permissions'] so they don't interfere.
2044 * But it would be nice to clean this up some more.
2046 * @param int $eventId
2047 * @param int $permissionType
2049 * @return bool|array
2050 * Whether the user has permission for this event (or if eventId=NULL an array of permissions)
2051 * @throws \CiviCRM_API3_Exception
2053 public static function checkPermission(int $eventId, $permissionType = CRM_Core_Permission
::VIEW
) {
2054 switch ($permissionType) {
2055 case CRM_Core_Permission
::EDIT
:
2056 // We also set the cached "view" permission to TRUE if "edit" is TRUE
2057 if (isset(Civi
::$statics[__CLASS__
]['permission']['edit'][$eventId])) {
2058 return Civi
::$statics[__CLASS__
]['permission']['edit'][$eventId];
2060 Civi
::$statics[__CLASS__
]['permission']['edit'][$eventId] = FALSE;
2062 list($allEvents, $createdEvents) = self
::checkPermissionGetInfo($eventId);
2063 // Note: for a multisite setup, a user with edit all events, can edit all events
2064 // including those from other sites
2065 if (($permissionType == CRM_Core_Permission
::EDIT
) && CRM_Core_Permission
::check('edit all events')) {
2066 Civi
::$statics[__CLASS__
]['permission']['edit'][$eventId] = TRUE;
2067 Civi
::$statics[__CLASS__
]['permission']['view'][$eventId] = TRUE;
2069 elseif (in_array($eventId, CRM_ACL_API
::group(CRM_Core_Permission
::EDIT
, NULL, 'civicrm_event', $allEvents, $createdEvents))) {
2070 Civi
::$statics[__CLASS__
]['permission']['edit'][$eventId] = TRUE;
2071 Civi
::$statics[__CLASS__
]['permission']['view'][$eventId] = TRUE;
2073 return Civi
::$statics[__CLASS__
]['permission']['edit'][$eventId];
2075 case CRM_Core_Permission
::VIEW
:
2076 if (isset(Civi
::$statics[__CLASS__
]['permission']['view'][$eventId])) {
2077 return Civi
::$statics[__CLASS__
]['permission']['view'][$eventId];
2079 Civi
::$statics[__CLASS__
]['permission']['view'][$eventId] = FALSE;
2081 list($allEvents, $createdEvents) = self
::checkPermissionGetInfo($eventId);
2082 if (CRM_Core_Permission
::check('access CiviEvent')) {
2083 if (in_array($eventId, CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_event', $allEvents, array_keys($createdEvents)))) {
2084 // User created this event so has permission to view it
2085 return Civi
::$statics[__CLASS__
]['permission']['view'][$eventId] = TRUE;
2087 if (CRM_Core_Permission
::check('view event participants')) {
2088 // User has permission to view all events
2089 // use case: allow "view all events" but NOT "edit all events"
2090 // so for a normal site allow users with these two permissions to view all events AND
2091 // at the same time also allow any hook to override if needed.
2092 if (in_array($eventId, CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_event', $allEvents, array_keys($allEvents)))) {
2093 Civi
::$statics[__CLASS__
]['permission']['view'][$eventId] = TRUE;
2097 return Civi
::$statics[__CLASS__
]['permission']['view'][$eventId];
2099 case CRM_Core_Permission
::DELETE
:
2100 if (isset(Civi
::$statics[__CLASS__
]['permission']['delete'][$eventId])) {
2101 return Civi
::$statics[__CLASS__
]['permission']['delete'][$eventId];
2103 Civi
::$statics[__CLASS__
]['permission']['delete'][$eventId] = FALSE;
2104 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
2105 Civi
::$statics[__CLASS__
]['permission']['delete'][$eventId] = TRUE;
2107 return Civi
::$statics[__CLASS__
]['permission']['delete'][$eventId];
2115 * This is a helper for refactoring checkPermission
2116 * FIXME: We should be able to get rid of these arrays, but that would require understanding how CRM_ACL_API::group actually works!
2118 * @param int $eventId
2120 * @return array $allEvents, $createdEvents
2121 * @throws \CiviCRM_API3_Exception
2123 private static function checkPermissionGetInfo($eventId = NULL) {
2125 'check_permissions' => 1,
2126 'return' => 'id, created_id',
2127 'options' => ['limit' => 0],
2130 $params['id'] = $eventId;
2134 $createdEvents = [];
2135 $eventResult = civicrm_api3('Event', 'get', $params);
2136 if ($eventResult['count'] > 0) {
2137 $contactId = CRM_Core_Session
::getLoggedInContactID();
2138 foreach ($eventResult['values'] as $eventId => $eventDetail) {
2139 $allEvents[$eventId] = $eventId;
2140 if (isset($eventDetail['created_id']) && $contactId == $eventDetail['created_id']) {
2141 $createdEvents[$eventId] = $eventId;
2145 return [$allEvents, $createdEvents];
2149 * Make sure that the user has permission to access this event.
2150 * TODO: This function needs refactoring / cleaning up after being split from checkPermissions()
2153 * Array of events with permissions (array_keys=permissions)
2154 * @throws \CiviCRM_API3_Exception
2156 public static function getAllPermissions() {
2157 if (!isset(Civi
::$statics[__CLASS__
]['permissions'])) {
2158 list($allEvents, $createdEvents) = self
::checkPermissionGetInfo();
2160 // Note: for a multisite setup, a user with edit all events, can edit all events
2161 // including those from other sites
2162 if (CRM_Core_Permission
::check('edit all events')) {
2163 Civi
::$statics[__CLASS__
]['permissions'][CRM_Core_Permission
::EDIT
] = array_keys($allEvents);
2166 Civi
::$statics[__CLASS__
]['permissions'][CRM_Core_Permission
::EDIT
] = CRM_ACL_API
::group(CRM_Core_Permission
::EDIT
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2169 if (CRM_Core_Permission
::check('edit all events')) {
2170 Civi
::$statics[__CLASS__
]['permissions'][CRM_Core_Permission
::VIEW
] = array_keys($allEvents);
2173 if (CRM_Core_Permission
::check('access CiviEvent') &&
2174 CRM_Core_Permission
::check('view event participants')
2176 // use case: allow "view all events" but NOT "edit all events"
2177 // so for a normal site allow users with these two permissions to view all events AND
2178 // at the same time also allow any hook to override if needed.
2179 $createdEvents = array_keys($allEvents);
2181 Civi
::$statics[__CLASS__
]['permissions'][CRM_Core_Permission
::VIEW
] = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2184 Civi
::$statics[__CLASS__
]['permissions'][CRM_Core_Permission
::DELETE
] = [];
2185 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
2186 // Note: we want to restrict the scope of delete permission to
2187 // events that are editable/viewable (usecase multisite).
2188 // We can remove array_intersect once we have ACL support for delete functionality.
2189 Civi
::$statics[__CLASS__
]['permissions'][CRM_Core_Permission
::DELETE
] = array_intersect(Civi
::$statics[__CLASS__
]['permissions'][CRM_Core_Permission
::EDIT
],
2190 Civi
::$statics[__CLASS__
]['permissions'][CRM_Core_Permission
::VIEW
]
2195 return Civi
::$statics[__CLASS__
]['permissions'];
2199 * Build From Email as the combination of all the email ids of the logged in user,
2200 * the domain email id and the email id configured for the event
2202 * @param int $eventId
2203 * The id of the event.
2206 * an array of email ids
2208 public static function getFromEmailIds($eventId = NULL) {
2209 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email
::getFromEmail();
2212 // add the email id configured for the event
2213 $params = ['id' => $eventId];
2214 $returnProperties = ['confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm'];
2217 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
2218 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
2219 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
2221 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
2223 'cc' => $eventEmail['cc_confirm'] ??
NULL,
2224 'bcc' => $eventEmail['bcc_confirm'] ??
NULL,
2226 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2230 return $fromEmailValues;
2234 * Calculate event total seats occupied.
2236 * @param int $eventId
2238 * @param string $extraWhereClause
2239 * Extra filter on participants.
2242 * event total seats w/ given criteria.
2244 public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
2245 if (empty($eventId)) {
2249 $extraWhereClause = trim($extraWhereClause);
2250 if (!empty($extraWhereClause)) {
2251 $extraWhereClause = " AND ( {$extraWhereClause} )";
2254 //event seats calculation :
2255 //1. consider event seat as a single when participant does not have line item.
2256 //2. consider event seat as a single when participant has line items but does not
2257 // have count for corresponding price field value ( ie price field value does not carry any seat )
2258 //3. consider event seat as a sum of all seats from line items in case price field value carries count.
2263 -- If the line item count * the line item quantity is not 0
2264 (SUM(price_field_value.`count` * lineItem.qty),
2265 -- then use the count * the quantity, ensuring each
2266 -- actual participant record gets a result
2267 SUM(price_field_value.`count` * lineItem.qty)
2268 + COUNT(DISTINCT participant.id )
2269 - COUNT(DISTINCT IF (price_field_value.`count`, participant.id, NULL)),
2270 -- if the line item count is NULL or 0 then count the participants
2271 COUNT(DISTINCT participant.id))
2272 FROM civicrm_participant participant
2273 INNER JOIN civicrm_contact contact ON (contact.id = participant.contact_id AND contact.is_deleted = 0)
2274 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
2275 LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id AND lineItem.entity_table = 'civicrm_participant' )
2276 LEFT JOIN civicrm_price_field_value price_field_value ON (price_field_value.id = lineItem.price_field_value_id AND price_field_value.`count`)
2277 WHERE (participant.event_id = %1) AND participant.is_test = 0
2279 GROUP BY participant.event_id";
2281 return (int) CRM_Core_DAO
::singleValueQuery($query, [1 => [$eventId, 'Positive']]);
2285 * Retrieve event template default values to be set.
2286 * as default values for current new event.
2288 * @param int $templateId
2289 * Event template id.
2292 * Array of custom data defaults.
2294 public static function getTemplateDefaultValues($templateId) {
2300 $templateParams = ['id' => $templateId];
2301 CRM_Event_BAO_Event
::retrieve($templateParams, $defaults);
2302 $fieldsToExclude = [
2305 'default_discount_fee_id',
2311 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2312 foreach ($defaults as $key => $value) {
2313 $customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
2314 if (!empty($customFieldInfo[1])) {
2315 $defaults[str_replace($customFieldInfo[1], '-' . $customFieldInfo[1], $key)] = $value;
2316 unset($defaults[$key]);
2323 * @param int $event_id
2327 public static function get_sub_events($event_id) {
2328 $params = ['parent_event_id' => $event_id];
2330 return CRM_Event_BAO_Event
::retrieve($params, $defaults);
2334 * Update the Campaign Id of all the participants of the given event.
2336 * @param int $eventID
2338 * @param int $eventCampaignID
2339 * Campaign id of that event.
2341 public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
2343 $params[1] = [$eventID, 'Integer'];
2345 if (empty($eventCampaignID)) {
2346 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2349 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2350 $params[2] = [$eventCampaignID, 'Integer'];
2352 CRM_Core_DAO
::executeQuery($query, $params);
2356 * Get options for a given field.
2357 * @see CRM_Core_DAO::buildOptions
2359 * @param string $fieldName
2360 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2361 * @param array $props : whatever is known about this dao object
2363 * @return array|bool
2365 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2367 // Special logic for fields whose options depend on context or properties
2368 switch ($fieldName) {
2369 case 'financial_type_id':
2370 // https://lab.civicrm.org/dev/core/issues/547 if CiviContribute not enabled this causes an invalid query
2371 // @todo - the component is enabled check should be done within getIncomeFinancialType
2372 // It looks to me like test cover was NOT added to cover the change
2373 // that added this so we need to assume there is no test cover
2374 if (CRM_Core_Component
::isEnabled('CiviContribute')) {
2375 return CRM_Financial_BAO_FinancialType
::getIncomeFinancialType($props['check_permissions'] ??
TRUE);
2379 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
2385 public static function getEntityRefFilters() {
2387 ['key' => 'event_type_id', 'value' => ts('Event Type')],
2389 'key' => 'start_date',
2390 'value' => ts('Start Date'),
2392 ['key' => '{">":"now"}', 'value' => ts('Upcoming')],
2394 'key' => '{"BETWEEN":["now - 3 month","now"]}',
2395 'value' => ts('Past 3 Months'),
2398 'key' => '{"BETWEEN":["now - 6 month","now"]}',
2399 'value' => ts('Past 6 Months'),
2402 'key' => '{"BETWEEN":["now - 1 year","now"]}',
2403 'value' => ts('Past Year'),
2411 * Get the appropriate links to iCal pages/feeds.
2413 * @param int $eventId
2416 * All of the icons to show.
2418 public static function getICalLinks($eventId = NULL) {
2424 $query['id'] = $eventId;
2427 'url' => CRM_Utils_System
::url('civicrm/event/ical', $query, TRUE, NULL, TRUE),
2428 'text' => $eventId ?
ts('Download iCalendar entry for this event.') : ts('Download iCalendar entry for current and future public events.'),
2429 'icon' => 'fa-download',
2433 'url' => CRM_Utils_System
::url('civicrm/event/ical', ['gCalendar' => 1] +
$query, TRUE, NULL, TRUE),
2434 'text' => ts('Add event to Google Calendar'),
2435 'icon' => 'fa-share',
2440 'url' => CRM_Utils_System
::url('civicrm/event/ical', $query, TRUE, NULL, TRUE),
2441 'text' => ts('iCalendar feed for current and future public events'),
2442 'icon' => 'fa-link',