revert 20476
[civicrm-core.git] / CRM / Event / BAO / Event.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17class CRM_Event_BAO_Event extends CRM_Event_DAO_Event {
18
6a488035 19 /**
4f940304 20 * Retrieve DB object and copy to defaults array.
6a488035 21 *
d4dd1e85 22 * @param array $params
4f940304 23 * Array of criteria values.
d4dd1e85 24 * @param array $defaults
4f940304 25 * Array to be populated with found values.
6a488035 26 *
4f940304
CW
27 * @return self|null
28 * The DAO object, if found.
29 *
30 * @deprecated
6a488035 31 */
4f940304
CW
32 public static function retrieve($params, &$defaults) {
33 return self::commonRetrieve(self::class, $params, $defaults);
6a488035
TO
34 }
35
36 /**
fe482240 37 * Update the is_active flag in the db.
6a488035 38 *
d4dd1e85
TO
39 * @param int $id
40 * Id of the database record.
41 * @param bool $is_active
42 * Value we want to set the is_active field.
6a488035 43 *
8a4fede3 44 * @return bool
45 * true if we found and updated the object, else false
6a488035 46 */
00be9182 47 public static function setIsActive($id, $is_active) {
6a488035
TO
48 return CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
49 }
50
51 /**
66f9e52b 52 * Add the event.
6a488035 53 *
d4dd1e85
TO
54 * @param array $params
55 * Reference array contains the values submitted by the form.
6a488035 56 *
3d469574 57 * @return CRM_Event_DAO_Event
6a488035 58 */
00be9182 59 public static function add(&$params) {
cc9b58f3 60 $financialTypeId = NULL;
a7488080 61 if (!empty($params['id'])) {
6a488035 62 CRM_Utils_Hook::pre('edit', 'Event', $params['id'], $params);
a7488080 63 if (empty($params['skipFinancialType'])) {
cc9b58f3
PN
64 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['id'], 'financial_type_id');
65 }
6a488035
TO
66 }
67 else {
68 CRM_Utils_Hook::pre('create', 'Event', NULL, $params);
69 }
70
71 $event = new CRM_Event_DAO_Event();
72
73 $event->copyValues($params);
74 $result = $event->save();
75
a7488080 76 if (!empty($params['id'])) {
6a488035
TO
77 CRM_Utils_Hook::post('edit', 'Event', $event->id, $event);
78 }
79 else {
80 CRM_Utils_Hook::post('create', 'Event', $event->id, $event);
81 }
8cc574cf 82 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
e1c77163 83 CRM_Price_BAO_PriceFieldValue::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
cc9b58f3 84 }
6a488035
TO
85 return $result;
86 }
87
88 /**
66f9e52b 89 * Create the event.
6a488035 90 *
d4dd1e85
TO
91 * @param array $params
92 * Reference array contains the values submitted by the form.
6a488035 93 *
9637d4be 94 * @return object
6a488035
TO
95 */
96 public static function create(&$params) {
97 $transaction = new CRM_Core_Transaction();
98 if (empty($params['is_template'])) {
99 $params['is_template'] = 0;
100 }
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');
107 }
108 $params['created_date'] = date('YmdHis');
26c0fc1a
CW
109
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']);
115 }
6a488035
TO
116 }
117
118 $event = self::add($params);
b2cdd843 119 CRM_Price_BAO_PriceSet::setPriceSets($params, $event, 'event');
6a488035
TO
120 if (is_a($event, 'CRM_Core_Error')) {
121 CRM_Core_DAO::transaction('ROLLBACK');
122 return $event;
123 }
124
3bdcd4ec 125 $contactId = CRM_Core_Session::getLoggedInContactID();
6a488035 126 if (!$contactId) {
9c1bc317 127 $contactId = $params['contact_id'] ?? NULL;
6a488035
TO
128 }
129
130 // Log the information on successful add/edit of Event
be2fb01f 131 $logParams = [
6a488035
TO
132 'entity_table' => 'civicrm_event',
133 'entity_id' => $event->id,
134 'modified_id' => $contactId,
135 'modified_date' => date('Ymd'),
be2fb01f 136 ];
6a488035
TO
137
138 CRM_Core_BAO_Log::add($logParams);
139
a7488080 140 if (!empty($params['custom']) &&
6a488035
TO
141 is_array($params['custom'])
142 ) {
143 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_event', $event->id);
144 }
145
146 $transaction->commit();
06009655
EM
147 if (!empty($params['id'])) {
148 // Note that this will specifically clear cached event tokens.
149 Civi::cache('metadata')->clear();
150 }
6a488035
TO
151 return $event;
152 }
153
154 /**
66f9e52b 155 * Delete the event.
6a488035 156 *
d4dd1e85
TO
157 * @param int $id
158 * Event id.
6a488035 159 *
77b97be7 160 * @return mixed|null
6a488035 161 */
00be9182 162 public static function del($id) {
6a488035
TO
163 if (!$id) {
164 return NULL;
165 }
166
be12df5a 167 CRM_Utils_Hook::pre('delete', 'Event', $id);
6a488035 168
be2fb01f 169 $extends = ['event'];
6a488035
TO
170 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
171 foreach ($groupTree as $values) {
52b54dda 172 $query = "DELETE FROM %1 WHERE entity_id = %2";
be2fb01f
CW
173 CRM_Core_DAO::executeQuery($query, [
174 1 => [$values['table_name'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
175 2 => [$id, 'Integer'],
176 ]);
6a488035
TO
177 }
178
52b54dda 179 // Clean up references to profiles used by the event (CRM-20935)
be2fb01f 180 $ufJoinParams = [
52b54dda
J
181 'module' => 'CiviEvent',
182 'entity_table' => 'civicrm_event',
183 'entity_id' => $id,
be2fb01f 184 ];
52b54dda 185 CRM_Core_BAO_UFJoin::deleteAll($ufJoinParams);
be2fb01f 186 $ufJoinParams = [
52b54dda
J
187 'module' => 'CiviEvent_Additional',
188 'entity_table' => 'civicrm_event',
189 'entity_id' => $id,
be2fb01f 190 ];
52b54dda
J
191 CRM_Core_BAO_UFJoin::deleteAll($ufJoinParams);
192
6a488035 193 // price set cleanup, CRM-5527
9da8dc8c 194 CRM_Price_BAO_PriceSet::removeFrom('civicrm_event', $id);
6a488035
TO
195
196 $event = new CRM_Event_DAO_Event();
197 $event->id = $id;
198
199 if ($event->find(TRUE)) {
200 $locBlockId = $event->loc_block_id;
201 $result = $event->delete();
202
203 if (!is_null($locBlockId)) {
204 self::deleteEventLocBlock($locBlockId, $id);
205 }
206
207 CRM_Utils_Hook::post('delete', 'Event', $id, $event);
208 return $result;
209 }
210
211 return NULL;
212 }
213
214 /**
3bdf1f3a 215 * Delete the location block associated with an event.
216 *
217 * Function checks that it is not being used by any other event.
6a488035 218 *
3bdf1f3a 219 * @param int $locBlockId
d4dd1e85
TO
220 * Location block id to be deleted.
221 * @param int $eventId
222 * Event with which loc block is associated.
6a488035 223 */
00be9182 224 public static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
6a488035
TO
225 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
226
227 if ($eventId) {
228 $query .= " AND ce.id != $eventId;";
229 }
230
231 $locCount = CRM_Core_DAO::singleValueQuery($query);
232
233 if ($locCount == 0) {
234 CRM_Core_BAO_Location::deleteLocBlock($locBlockId);
235 }
236 }
237
238 /**
3bdf1f3a 239 * Get current/future Events.
6a488035 240 *
5a4f6742
CW
241 * @param int $all
242 * 0 returns current and future events.
c2be40dc
AH
243 * 1 if events all are required
244 * 2 returns events since 3 months ago
97c1cf60 245 * @param int|array $id single int event id or array of multiple event ids to return
5a4f6742
CW
246 * @param bool $isActive
247 * true if you need only active events.
248 * @param bool $checkPermission
249 * true if you need to check permission else false.
97c1cf60 250 * @param bool $titleOnly
251 * true if you need only title not appended with start date
6a488035 252 *
77b97be7 253 * @return array
6a488035 254 */
5396af74 255 public static function getEvents(
ddca8f33 256 $all = 0,
97c1cf60 257 $id = NULL,
353ffa53 258 $isActive = TRUE,
97c1cf60 259 $checkPermission = TRUE,
260 $titleOnly = FALSE
6a488035
TO
261 ) {
262 $query = "
263SELECT `id`, `title`, `start_date`
264FROM `civicrm_event`
265WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
266
97c1cf60 267 if (!empty($id)) {
836f1f3f 268 $op = is_array($id) ? 'IN' : '=';
269 $where = CRM_Contact_BAO_Query::buildClause('id', $op, $id);
270 $query .= " AND {$where}";
6a488035 271 }
c2be40dc
AH
272 elseif ($all == 0) {
273 // find only events ending in the future
6a488035 274 $endDate = date('YmdHis');
b093546a
BS
275 $query .= "
276 AND ( `end_date` >= {$endDate} OR
277 (
278 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
279 )
280 )";
6a488035 281 }
c2be40dc
AH
282 elseif ($all == 2) {
283 // find only events starting in the last 3 months
284 $startDate = date('YmdHis', strtotime('3 months ago'));
285 $query .= " AND ( `start_date` >= {$startDate} OR start_date IS NULL )";
286 }
6a488035
TO
287 if ($isActive) {
288 $query .= " AND civicrm_event.is_active = 1";
289 }
290
291 $query .= " ORDER BY title asc";
be2fb01f 292 $events = [];
6a488035
TO
293
294 $dao = CRM_Core_DAO::executeQuery($query);
295 while ($dao->fetch()) {
296 if ((!$checkPermission ||
297 CRM_Event_BAO_Event::checkPermission($dao->id)
298 ) &&
299 $dao->title
300 ) {
97c1cf60 301 $events[$dao->id] = $dao->title;
302 if (!$titleOnly) {
303 $events[$dao->id] .= ' - ' . CRM_Utils_Date::customFormat($dao->start_date);
304 }
6a488035
TO
305 }
306 }
307
308 return $events;
309 }
310
311 /**
66f9e52b 312 * Get events Summary.
6a488035 313 *
a6c01b45
CW
314 * @return array
315 * Array of event summary values
d9550294 316 *
317 * @throws \CiviCRM_API3_Exception
6a488035 318 */
00be9182 319 public static function getEventSummary() {
be2fb01f 320 $eventSummary = $eventIds = [];
6a488035
TO
321 $config = CRM_Core_Config::singleton();
322
323 // get permission and include them here
324 // does not scale, but rearranging code for now
325 // FIXME in a future release
d9550294 326 $permissions = self::getAllPermissions();
6a488035
TO
327 $validEventIDs = '';
328 if (empty($permissions[CRM_Core_Permission::VIEW])) {
329 $eventSummary['total_events'] = 0;
330 return $eventSummary;
331 }
332 else {
333 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission::VIEW])) . " ) ";
334 }
335
336 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
337 $query = "
338SELECT count(id) as total_events
339FROM civicrm_event
340WHERE civicrm_event.is_active = 1 AND
341 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
342 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
343 $validEventIDs";
344
345 $dao = CRM_Core_DAO::executeQuery($query);
346
347 if ($dao->fetch()) {
348 $eventSummary['total_events'] = $dao->total_events;
349 }
350
351 if (empty($eventSummary) ||
352 $dao->total_events == 0
353 ) {
354 return $eventSummary;
355 }
356
357 //get the participant status type values.
29b6b1dd 358 $cpstObject = new CRM_Event_DAO_ParticipantStatusType();
359 $cpst = $cpstObject->getTableName();
360 $query = "SELECT id, name, label, class FROM $cpst";
d7d7d5ab 361 $status = CRM_Core_DAO::executeQuery($query);
be2fb01f 362 $statusValues = [];
6a488035
TO
363 while ($status->fetch()) {
364 $statusValues[$status->id]['id'] = $status->id;
365 $statusValues[$status->id]['name'] = $status->name;
afc3dfa7 366 $statusValues[$status->id]['label'] = $status->label;
6a488035
TO
367 $statusValues[$status->id]['class'] = $status->class;
368 }
369
370 // Get the Id of Option Group for Event Types
371 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
372 $optionGroupDAO->name = 'event_type';
373 $optionGroupId = NULL;
374 if ($optionGroupDAO->find(TRUE)) {
375 $optionGroupId = $optionGroupDAO->id;
376 }
b8ce3328 377 // Get the event summary display preferences
aaffa79f 378 $show_max_events = Civi::settings()->get('show_events');
b8ce3328 379 // show all events if show_events is set to a negative value
fff710f5 380 if (isset($show_max_events) && $show_max_events >= 0) {
b8ce3328 381 $event_summary_limit = "LIMIT 0, $show_max_events";
382 }
383 else {
384 $event_summary_limit = "";
385 }
6a488035
TO
386
387 $query = "
388SELECT civicrm_event.id as id, civicrm_event.title as event_title, civicrm_event.is_public as is_public,
389 civicrm_event.max_participants as max_participants, civicrm_event.start_date as start_date,
390 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,
391 civicrm_event.slot_label_id,
392 civicrm_event.summary as summary,
72c67af6 393 civicrm_pcp_block.id as is_pcp_enabled,
30051f5b 394 civicrm_recurring_entity.parent_id as is_repeating_event
6a488035
TO
395FROM civicrm_event
396LEFT JOIN civicrm_option_value ON (
397 civicrm_event.event_type_id = civicrm_option_value.value AND
398 civicrm_option_value.option_group_id = %1 )
399LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_event.id AND civicrm_tell_friend.entity_table = 'civicrm_event' )
400LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_event.id AND civicrm_pcp_block.entity_table = 'civicrm_event')
72c67af6 401LEFT JOIN civicrm_recurring_entity ON ( civicrm_event.id = civicrm_recurring_entity.entity_id AND civicrm_recurring_entity.entity_table = 'civicrm_event' )
6a488035
TO
402WHERE civicrm_event.is_active = 1 AND
403 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
404 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
405 $validEventIDs
6a488035 406ORDER BY civicrm_event.start_date ASC
b8ce3328 407$event_summary_limit
6a488035 408";
be2fb01f 409 $eventParticipant = [];
6a488035 410
be2fb01f 411 $properties = [
d7d7d5ab 412 'id' => 'id',
413 'eventTitle' => 'event_title',
414 'isPublic' => 'is_public',
415 'maxParticipants' => 'max_participants',
416 'startDate' => 'start_date',
417 'endDate' => 'end_date',
418 'eventType' => 'event_type',
419 'isMap' => 'is_map',
420 'participants' => 'participants',
6a488035
TO
421 'notCountedDueToRole' => 'notCountedDueToRole',
422 'notCountedDueToStatus' => 'notCountedDueToStatus',
423 'notCountedParticipants' => 'notCountedParticipants',
be2fb01f 424 ];
6a488035 425
be2fb01f
CW
426 $params = [1 => [$optionGroupId, 'Integer']];
427 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
46f5566c 428 'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
be2fb01f 429 ]));
6a488035
TO
430 $dao = CRM_Core_DAO::executeQuery($query, $params);
431 while ($dao->fetch()) {
432 foreach ($properties as $property => $name) {
433 $set = NULL;
434 switch ($name) {
435 case 'is_public':
436 if ($dao->$name) {
437 $set = 'Yes';
438 }
439 else {
440 $set = 'No';
441 }
442 $eventSummary['events'][$dao->id][$property] = $set;
443 break;
444
445 case 'is_map':
446 if ($dao->$name && $config->mapAPIKey) {
be2fb01f
CW
447 $values = [];
448 $ids = [];
449 $params = ['entity_id' => $dao->id, 'entity_table' => 'civicrm_event'];
6a488035
TO
450 $values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
451 if (is_numeric(CRM_Utils_Array::value('geo_code_1', $values['location']['address'][1])) ||
f425e142 452 (
6a488035
TO
453 !empty($values['location']['address'][1]['city']) &&
454 !empty($values['location']['address'][1]['state_province_id'])
455 )
456 ) {
457 $set = CRM_Utils_System::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
458 }
459 }
460
461 $eventSummary['events'][$dao->id][$property] = $set;
c613b5fb
MW
462 if (is_array($permissions[CRM_Core_Permission::EDIT])
463 && in_array($dao->id, $permissions[CRM_Core_Permission::EDIT])) {
7431d9cc 464 $eventSummary['events'][$dao->id]['configure'] = CRM_Utils_System::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
6a488035
TO
465 }
466 break;
467
468 case 'end_date':
469 case 'start_date':
470 $eventSummary['events'][$dao->id][$property] = CRM_Utils_Date::customFormat($dao->$name,
be2fb01f 471 NULL, ['d']
6a488035
TO
472 );
473 break;
474
475 case 'participants':
476 case 'notCountedDueToRole':
477 case 'notCountedDueToStatus':
478 case 'notCountedParticipants':
479 $set = NULL;
480 $propertyCnt = 0;
481 if ($name == 'participants') {
482 $propertyCnt = self::getParticipantCount($dao->id);
483 if ($propertyCnt) {
484 $set = CRM_Utils_System::url('civicrm/event/search',
485 "reset=1&force=1&event=$dao->id&status=true&role=true"
486 );
487 }
488 }
489 elseif ($name == 'notCountedParticipants') {
490 $propertyCnt = self::getParticipantCount($dao->id, TRUE, FALSE, TRUE, FALSE);
491 if ($propertyCnt) {
492 // FIXME : selector fail to search w/ OR operator.
493 // $set = CRM_Utils_System::url( 'civicrm/event/search',
494 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
495 }
496 }
497 elseif ($name == 'notCountedDueToStatus') {
498 $propertyCnt = self::getParticipantCount($dao->id, TRUE, FALSE, FALSE, FALSE);
499 if ($propertyCnt) {
500 $set = CRM_Utils_System::url('civicrm/event/search',
501 "reset=1&force=1&event=$dao->id&status=false"
502 );
503 }
504 }
505 else {
506 $propertyCnt = self::getParticipantCount($dao->id, FALSE, FALSE, TRUE, FALSE);
507 if ($propertyCnt) {
508 $set = CRM_Utils_System::url('civicrm/event/search',
509 "reset=1&force=1&event=$dao->id&role=false"
510 );
511 }
512 }
513
514 $eventSummary['events'][$dao->id][$property] = $propertyCnt;
515 $eventSummary['events'][$dao->id][$name . '_url'] = $set;
516 break;
517
518 default:
519 $eventSummary['events'][$dao->id][$property] = $dao->$name;
520 break;
521 }
522 }
523
524 // prepare the area for per-status participant counts
be2fb01f
CW
525 $statusClasses = ['Positive', 'Pending', 'Waiting', 'Negative'];
526 $eventSummary['events'][$dao->id]['statuses'] = array_fill_keys($statusClasses, []);
6a488035
TO
527
528 $eventSummary['events'][$dao->id]['friend'] = $dao->is_friend_active;
529 $eventSummary['events'][$dao->id]['is_monetary'] = $dao->is_monetary;
530 $eventSummary['events'][$dao->id]['is_online_registration'] = $dao->is_online_registration;
531 $eventSummary['events'][$dao->id]['is_show_location'] = $dao->is_show_location;
532 $eventSummary['events'][$dao->id]['is_subevent'] = $dao->slot_label_id;
533 $eventSummary['events'][$dao->id]['is_pcp_enabled'] = $dao->is_pcp_enabled;
9e1bf145 534 $eventSummary['events'][$dao->id]['reminder'] = CRM_Core_BAO_ActionSchedule::isConfigured($dao->id, $mapping->getId());
72c67af6 535 $eventSummary['events'][$dao->id]['is_repeating_event'] = $dao->is_repeating_event;
eea16664 536
6a488035
TO
537 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
538 foreach ($statusValues as $statusId => $statusValue) {
539 if (!array_key_exists($statusId, $statusTypes)) {
540 continue;
541 }
542 $class = $statusValue['class'];
543 $statusCount = self::eventTotalSeats($dao->id, "( participant.status_id = {$statusId} )");
544 if ($statusCount) {
545 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
be2fb01f 546 $statusInfo = [
ddca8f33 547 'url' => CRM_Utils_System::url('civicrm/event/search', $urlString),
6a488035 548 'name' => $statusValue['name'],
afc3dfa7 549 'label' => $statusValue['label'],
6a488035 550 'count' => $statusCount,
be2fb01f 551 ];
6a488035
TO
552 $eventSummary['events'][$dao->id]['statuses'][$class][] = $statusInfo;
553 }
554 }
555 }
556
d7d7d5ab 557 $countedRoles = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
558 $nonCountedRoles = CRM_Event_PseudoConstant::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
559 $countedStatus = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
6a488035
TO
560 $nonCountedStatus = CRM_Event_PseudoConstant::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
561
562 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
563 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
564
565 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
566 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
567 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
568 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
569
570 return $eventSummary;
571 }
572
573 /**
66f9e52b 574 * Get participant count.
6a488035 575 *
100fef9d 576 * @param int $eventId
5396af74 577 * @param bool $considerStatus consider status for participant count.
d4dd1e85 578 * Consider status for participant count.
5396af74 579 * @param bool $status counted participant.
d4dd1e85 580 * Consider counted participant.
5396af74 581 * @param bool $considerRole consider role for participant count.
d4dd1e85 582 * Consider role for participant count.
5396af74 583 * @param bool $role consider counted( is filter role) participant.
d4dd1e85 584 * Consider counted( is filter role) participant.
77b97be7 585 *
a6c01b45
CW
586 * @return array
587 * array with count of participants for each event based on status/role
6a488035 588 */
ddca8f33
TO
589 public static function getParticipantCount(
590 $eventId,
353ffa53
TO
591 $considerStatus = TRUE,
592 $status = TRUE,
593 $considerRole = TRUE,
594 $role = TRUE
6a488035
TO
595 ) {
596
597 // consider both role and status for counted participants, CRM-4924.
598 $operator = " AND ";
599 // not counted participant.
600 if ($considerStatus && $considerRole && !$status && !$role) {
601 $operator = " OR ";
602 }
be2fb01f 603 $clause = [];
6a488035
TO
604 if ($considerStatus) {
605 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
606 $statusClause = 'NOT IN';
607 if ($status) {
608 $statusClause = 'IN';
609 }
610 $status = implode(',', array_keys($statusTypes));
611 if (empty($status)) {
612 $status = 0;
613 }
614 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
615 }
616
617 if ($considerRole) {
618 $roleTypes = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
619 $roleClause = 'NOT IN';
620 if ($role) {
621 $roleClause = 'IN';
622 }
0906de17
MM
623
624 if (!empty($roleTypes)) {
be2fb01f 625 $escapedRoles = [];
0906de17
MM
626 foreach (array_keys($roleTypes) as $roleType) {
627 $escapedRoles[] = CRM_Utils_Type::escape($roleType, 'String');
628 }
629
aba574d4 630 $clause[] = "participant.role_id {$roleClause} ( '" . implode("', '", $escapedRoles) . "' ) ";
6a488035 631 }
6a488035
TO
632 }
633
634 $sqlClause = '';
635 if (!empty($clause)) {
636 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
637 }
638
639 return self::eventTotalSeats($eventId, $sqlClause);
640 }
641
642 /**
64f4eebe 643 * Get the information to map an event.
6a488035 644 *
d4dd1e85
TO
645 * @param int $id
646 * For which we want map info.
6a488035 647 *
64f4eebe 648 * @return array
6a488035 649 */
00be9182 650 public static function &getMapInfo(&$id) {
6a488035
TO
651
652 $sql = "
653SELECT
654 civicrm_event.id AS event_id,
655 civicrm_event.title AS display_name,
656 civicrm_address.street_address AS street_address,
657 civicrm_address.city AS city,
658 civicrm_address.postal_code AS postal_code,
659 civicrm_address.postal_code_suffix AS postal_code_suffix,
660 civicrm_address.geo_code_1 AS latitude,
661 civicrm_address.geo_code_2 AS longitude,
662 civicrm_state_province.abbreviation AS state,
663 civicrm_country.name AS country,
664 civicrm_location_type.name AS location_type
665FROM
666 civicrm_event
667 LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )
668 LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )
669 LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )
670 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
671 LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )
672WHERE civicrm_address.geo_code_1 IS NOT NULL
673 AND civicrm_address.geo_code_2 IS NOT NULL
674 AND civicrm_event.id = " . CRM_Utils_Type::escape($id, 'Integer');
675
676 $dao = new CRM_Core_DAO();
677 $dao->query($sql);
678
be2fb01f 679 $locations = [];
6a488035
TO
680
681 $config = CRM_Core_Config::singleton();
682
683 while ($dao->fetch()) {
684
be2fb01f 685 $location = [];
6a488035
TO
686 $location['displayName'] = addslashes($dao->display_name);
687 $location['lat'] = $dao->latitude;
688 $location['marker_class'] = 'Event';
689 $location['lng'] = $dao->longitude;
690
be2fb01f 691 $params = ['entity_id' => $id, 'entity_table' => 'civicrm_event'];
6a488035 692 $addressValues = CRM_Core_BAO_Location::getValues($params, TRUE);
be2fb01f 693 $location['address'] = str_replace([
353ffa53
TO
694 "\r",
695 "\n",
be2fb01f 696 ], '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
6a488035
TO
697
698 $location['url'] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id);
699 $location['location_type'] = $dao->location_type;
700 $eventImage = '<img src="' . $config->resourceBase . 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
701 $location['image'] = $eventImage;
702 $location['displayAddress'] = str_replace('<br />', ', ', $location['address']);
703 $locations[] = $location;
704 }
705 return $locations;
706 }
707
708 /**
66f9e52b 709 * Get the complete information for one or more events.
6a488035 710 *
d4dd1e85
TO
711 * @param date $start
712 * Get events with start date >= this date.
5396af74 713 * @param int $type Get events on the a specific event type (by event_type_id).
d4dd1e85 714 * Get events on the a specific event type (by event_type_id).
5396af74 715 * @param int $eventId Return a single event - by event id.
d4dd1e85
TO
716 * Return a single event - by event id.
717 * @param date $end
718 * Also get events with end date >= this date.
5396af74 719 * @param bool $onlyPublic Include public events only, default TRUE.
d4dd1e85 720 * Include public events only, default TRUE.
6a488035 721 *
a6c01b45
CW
722 * @return array
723 * array of all the events that are searched
6a488035 724 */
7ad3182b 725 public static function getCompleteInfo(
0ae0bb0e
DL
726 $start = NULL,
727 $type = NULL,
728 $eventId = NULL,
729 $end = NULL,
730 $onlyPublic = TRUE
731 ) {
732 $publicCondition = NULL;
733 if ($onlyPublic) {
734 $publicCondition = " AND civicrm_event.is_public = 1";
735 }
736
6a488035
TO
737 $dateCondition = '';
738 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
739 if ($start) {
740 // get events with start_date >= requested start
741 $startDate = CRM_Utils_Type::escape($start, 'Date');
742 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
743 }
744
745 if ($end) {
746 // also get events with end_date <= requested end
747 $endDate = CRM_Utils_Type::escape($end, 'Date');
748 $dateCondition .= " AND ( civicrm_event.end_date <= '{$endDate}' ) ";
749 }
750
0ae0bb0e
DL
751 // CRM-9421 and CRM-8620 Default mode for ical/rss feeds. No start or end filter passed.
752 // Need to exclude old events with only start date
6a488035
TO
753 // and not exclude events in progress (start <= today and end >= today). DGG
754 if (empty($start) && empty($end)) {
755 // get events with end date >= today, not sure of this logic
756 // but keeping this for backward compatibility as per issue CRM-5133
757 $today = date("Y-m-d G:i:s");
758 $dateCondition .= " AND ( civicrm_event.end_date >= '{$today}' OR civicrm_event.start_date >= '{$today}' ) ";
759 }
760
761 if ($type) {
762 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type::escape($type, 'Integer');
763 }
764
765 // Get the Id of Option Group for Event Types
766 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
767 $optionGroupDAO->name = 'event_type';
768 $optionGroupId = NULL;
769 if ($optionGroupDAO->find(TRUE)) {
770 $optionGroupId = $optionGroupDAO->id;
771 }
772
773 $query = "
774SELECT
775 civicrm_event.id as event_id,
776 civicrm_email.email as email,
777 civicrm_event.title as title,
778 civicrm_event.summary as summary,
779 civicrm_event.start_date as start,
780 civicrm_event.end_date as end,
781 civicrm_event.description as description,
782 civicrm_event.is_show_location as is_show_location,
783 civicrm_event.is_online_registration as is_online_registration,
784 civicrm_event.registration_link_text as registration_link_text,
785 civicrm_event.registration_start_date as registration_start_date,
786 civicrm_event.registration_end_date as registration_end_date,
787 civicrm_option_value.label as event_type,
788 civicrm_address.name as address_name,
789 civicrm_address.street_address as street_address,
790 civicrm_address.supplemental_address_1 as supplemental_address_1,
791 civicrm_address.supplemental_address_2 as supplemental_address_2,
207f62c6 792 civicrm_address.supplemental_address_3 as supplemental_address_3,
6a488035
TO
793 civicrm_address.city as city,
794 civicrm_address.postal_code as postal_code,
795 civicrm_address.postal_code_suffix as postal_code_suffix,
796 civicrm_state_province.abbreviation as state,
797 civicrm_country.name AS country
798FROM civicrm_event
799LEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id
800LEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id
801LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
802LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
803LEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id
804LEFT JOIN civicrm_option_value ON (
805 civicrm_event.event_type_id = civicrm_option_value.value AND
806 civicrm_option_value.option_group_id = %1 )
807WHERE civicrm_event.is_active = 1
6a488035 808 AND (is_template = 0 OR is_template IS NULL)
0ae0bb0e 809 {$publicCondition}
6a488035
TO
810 {$dateCondition}";
811
812 if (isset($typeCondition)) {
813 $query .= $typeCondition;
814 }
815
816 if (isset($eventId)) {
817 $query .= " AND civicrm_event.id =$eventId ";
818 }
819 $query .= " ORDER BY civicrm_event.start_date ASC";
820
be2fb01f 821 $params = [1 => [$optionGroupId, 'Integer']];
ddca8f33 822 $dao = CRM_Core_DAO::executeQuery($query, $params);
be2fb01f 823 $all = [];
6a488035
TO
824 $config = CRM_Core_Config::singleton();
825
826 $baseURL = parse_url($config->userFrameworkBaseURL);
827 $url = "@" . $baseURL['host'];
a7488080 828 if (!empty($baseURL['path'])) {
6a488035
TO
829 $url .= substr($baseURL['path'], 0, -1);
830 }
831
832 // check 'view event info' permission
e2d09ab4 833 //@todo - per CRM-14626 we have resolved that 'view event info' means 'view ALL event info'
7ad3182b 834 if (CRM_Core_Permission::check('view event info')) {
835 $permissions = TRUE;
836 }
837 else {
838 $permissions = CRM_Core_Permission::event(CRM_Core_Permission::VIEW);
839 }
6a488035 840
6a488035 841 while ($dao->fetch()) {
7ad3182b 842 if (!empty($permissions) && ($permissions === TRUE || in_array($dao->event_id, $permissions))) {
be2fb01f 843 $info = [];
6a488035
TO
844 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL) . $url;
845
846 $info['title'] = $dao->title;
847 $info['event_id'] = $dao->event_id;
848 $info['summary'] = $dao->summary;
849 $info['description'] = $dao->description;
850 $info['start_date'] = $dao->start;
851 $info['end_date'] = $dao->end;
852 $info['contact_email'] = $dao->email;
853 $info['event_type'] = $dao->event_type;
854 $info['is_show_location'] = $dao->is_show_location;
855 $info['is_online_registration'] = $dao->is_online_registration;
856 $info['registration_link_text'] = $dao->registration_link_text;
857 $info['registration_start_date'] = $dao->registration_start_date;
858 $info['registration_end_date'] = $dao->registration_end_date;
859
860 $address = '';
861
be2fb01f 862 $addrFields = [
6a488035
TO
863 'address_name' => $dao->address_name,
864 'street_address' => $dao->street_address,
865 'supplemental_address_1' => $dao->supplemental_address_1,
866 'supplemental_address_2' => $dao->supplemental_address_2,
207f62c6 867 'supplemental_address_3' => $dao->supplemental_address_3,
6a488035
TO
868 'city' => $dao->city,
869 'state_province' => $dao->state,
870 'postal_code' => $dao->postal_code,
871 'postal_code_suffix' => $dao->postal_code_suffix,
872 'country' => $dao->country,
873 'county' => NULL,
be2fb01f 874 ];
6a488035
TO
875
876 CRM_Utils_String::append($address, ', ',
877 CRM_Utils_Address::format($addrFields)
878 );
879 $info['location'] = $address;
880 $info['url'] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
881
7fffa5fa 882 // @todo Move to eventcart extension
883 // check if we're in shopping cart mode for events
884 if ((bool) Civi::settings()->get('enable_cart')) {
6a488035
TO
885 $reg = CRM_Event_Cart_BAO_EventInCart::get_registration_link($dao->event_id);
886 $info['registration_link'] = CRM_Utils_System::url($reg['path'], $reg['query'], TRUE);
887 $info['registration_link_text'] = $reg['label'];
888 }
889
890 $all[] = $info;
891 }
892 }
893
894 return $all;
895 }
896
897 /**
3bdf1f3a 898 * Make a copy of a Event.
899 *
900 * Include all the fields in the event Wizard.
6a488035 901 *
d4dd1e85
TO
902 * @param int $id
903 * The event id to copy.
90b461f1 904 * @param array $params
ca99831f 905 *
10525e44 906 * @return CRM_Event_DAO_Event
ae70f47e 907 * @throws \CRM_Core_Exception
6a488035 908 */
2e45b2f8 909 public static function copy($id, $params = []) {
997602c9 910 $session = CRM_Core_Session::singleton();
be2fb01f 911 $eventValues = [];
6a488035 912
ca99831f 913 //get the required event values.
be2fb01f
CW
914 $eventParams = ['id' => $id];
915 $returnProperties = [
ddca8f33
TO
916 'loc_block_id',
917 'is_show_location',
918 'default_fee_id',
919 'default_discount_fee_id',
21dfd5f5 920 'is_template',
be2fb01f 921 ];
6a488035
TO
922
923 CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
924
997602c9
J
925 $fieldsFix = [
926 'prefix' => [
927 'title' => ts('Copy of') . ' ',
928 ],
929 'replace' => [
930 'created_id' => $session->get('userID'),
931 'created_date' => date('YmdHis'),
932 ],
933 ];
a7488080 934 if (empty($eventValues['is_show_location'])) {
6a488035
TO
935 $fieldsFix['prefix']['is_show_location'] = 0;
936 }
937
8c605c27
MD
938 $blockCopyOfCustomValue = (!empty($params['custom']));
939
cfd0c4dd 940 /** @var \CRM_Event_DAO_Event $copyEvent */
ae70f47e 941 $copyEvent = CRM_Core_DAO::copyGeneric('CRM_Event_DAO_Event',
be2fb01f 942 ['id' => $id],
ae70f47e 943 // since the location is sharable, lets use the same loc_block_id.
be2fb01f 944 ['loc_block_id' => CRM_Utils_Array::value('loc_block_id', $eventValues)] + $params,
8c605c27
MD
945 $fieldsFix,
946 NULL,
947 $blockCopyOfCustomValue
ae70f47e 948 );
9da8dc8c 949 CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_event', $id, $copyEvent->id);
ae70f47e 950 CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin',
be2fb01f 951 [
6a488035
TO
952 'entity_id' => $id,
953 'entity_table' => 'civicrm_event',
be2fb01f
CW
954 ],
955 ['entity_id' => $copyEvent->id]
6a488035
TO
956 );
957
ae70f47e 958 CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend',
be2fb01f 959 [
6a488035
TO
960 'entity_id' => $id,
961 'entity_table' => 'civicrm_event',
be2fb01f
CW
962 ],
963 ['entity_id' => $copyEvent->id]
6a488035
TO
964 );
965
ae70f47e 966 CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock',
be2fb01f 967 [
6a488035
TO
968 'entity_id' => $id,
969 'entity_table' => 'civicrm_event',
be2fb01f
CW
970 ],
971 ['entity_id' => $copyEvent->id],
972 ['replace' => ['target_entity_id' => $copyEvent->id]]
6a488035
TO
973 );
974
be2fb01f 975 $oldMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
46f5566c 976 'id' => ($eventValues['is_template'] ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID),
be2fb01f
CW
977 ]));
978 $copyMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
46f5566c 979 'id' => ($copyEvent->is_template == 1 ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID),
be2fb01f 980 ]));
ae70f47e 981 CRM_Core_DAO::copyGeneric('CRM_Core_DAO_ActionSchedule',
be2fb01f
CW
982 ['entity_value' => $id, 'mapping_id' => $oldMapping->getId()],
983 ['entity_value' => $copyEvent->id, 'mapping_id' => $copyMapping->getId()]
6a488035 984 );
4a94edec 985
6a488035
TO
986 $copyEvent->save();
987
8c605c27 988 if ($blockCopyOfCustomValue) {
e9fc038f
EM
989 foreach ($params['custom'] as &$values) {
990 foreach ($values as &$value) {
991 // Ensure we don't copy over the template's id if it is passed in
992 // This is a bit hacky but it's unclear what the
993 // right behaviour is given the whole 'custom'
994 // field is form layer formatting that is reaching the BAO.
995 $value['id'] = NULL;
996 }
997 }
8c605c27
MD
998 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_event', $copyEvent->id);
999 }
1000
6a488035 1001 CRM_Utils_System::flushCache();
ae70f47e
MWMC
1002 CRM_Utils_Hook::copy('Event', $copyEvent);
1003
6a488035
TO
1004 return $copyEvent;
1005 }
4a94edec 1006
6a488035 1007 /**
3bdf1f3a 1008 * This is sometimes called in a loop (during event search).
1009 *
1010 * We cache the values to prevent repeated calls to the db.
ea3ddccf 1011 *
1012 * @param int $id
1013 *
3d469574 1014 * @return bool
6a488035 1015 */
00be9182 1016 public static function isMonetary($id) {
be2fb01f 1017 static $isMonetary = [];
6a488035
TO
1018 if (!array_key_exists($id, $isMonetary)) {
1019 $isMonetary[$id] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
1020 $id,
1021 'is_monetary'
1022 );
1023 }
1024 return $isMonetary[$id];
1025 }
1026
1027 /**
3bdf1f3a 1028 * This is sometimes called in a loop (during event search).
1029 *
1030 * We cache the values to prevent repeated calls to the db.
54957108 1031 *
1032 * @param int $id
1033 *
1034 * @return bool
6a488035 1035 */
00be9182 1036 public static function usesPriceSet($id) {
be2fb01f 1037 static $usesPriceSet = [];
6a488035 1038 if (!array_key_exists($id, $usesPriceSet)) {
9da8dc8c 1039 $usesPriceSet[$id] = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $id);
6a488035
TO
1040 }
1041 return $usesPriceSet[$id];
1042 }
1043
1044 /**
3bdf1f3a 1045 * Send e-mails.
6a488035 1046 *
100fef9d 1047 * @param int $contactID
3bdf1f3a 1048 * @param array $values
100fef9d 1049 * @param int $participantId
dd244018
EM
1050 * @param bool $isTest
1051 * @param bool $returnMessageText
ed7e2e99 1052 *
d0887629 1053 * @return array|null
ed7e2e99 1054 * @throws \CiviCRM_API3_Exception
6a488035 1055 */
e579af79 1056 public static function sendMail($contactID, $values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
6a488035
TO
1057
1058 $template = CRM_Core_Smarty::singleton();
be2fb01f 1059 $gIds = [
6a488035
TO
1060 'custom_pre_id' => $values['custom_pre_id'],
1061 'custom_post_id' => $values['custom_post_id'],
be2fb01f 1062 ];
6a488035
TO
1063
1064 //get the params submitted by participant.
be2fb01f 1065 $participantParams = CRM_Utils_Array::value($participantId, $values['params'], []);
6a488035
TO
1066
1067 if (!$returnMessageText) {
1068 //send notification email if field values are set (CRM-1941)
1069 foreach ($gIds as $key => $gIdValues) {
1070 if ($gIdValues) {
1071 if (!is_array($gIdValues)) {
be2fb01f 1072 $gIdValues = [$gIdValues];
6a488035
TO
1073 }
1074
1075 foreach ($gIdValues as $gId) {
0479b4c8
TO
1076 $email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1077 if ($email) {
1078 //get values of corresponding profile fields for notification
7ad3182b 1079 [$profileValues] = self::buildCustomDisplay($gId,
ddca8f33
TO
1080 NULL,
1081 $contactID,
1082 $template,
1083 $participantId,
1084 $isTest,
1085 TRUE,
1086 $participantParams
0479b4c8 1087 );
06009655 1088 [$profileValues] = $profileValues;
be2fb01f 1089 $val = [
ddca8f33
TO
1090 'id' => $gId,
1091 'values' => $profileValues,
1092 'email' => $email,
be2fb01f 1093 ];
0479b4c8
TO
1094 CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val);
1095 }
6a488035
TO
1096 }
1097 }
1098 }
1099 }
6a488035
TO
1100
1101 if ($values['event']['is_email_confirm'] || $returnMessageText) {
1102 list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
2ba7b9e8 1103 $notifyEmail = CRM_Utils_Array::valueByRegexKey('/^email-/', $participantParams) ?? $email;
6a488035 1104 //send email only when email is present
2ba7b9e8 1105 if (isset($notifyEmail) || $returnMessageText) {
9c1bc317
CW
1106 $preProfileID = $values['custom_pre_id'] ?? NULL;
1107 $postProfileID = $values['custom_post_id'] ?? NULL;
6a488035 1108
a7488080 1109 if (!empty($values['params']['additionalParticipant'])) {
ddca8f33
TO
1110 $preProfileID = CRM_Utils_Array::value('additional_custom_pre_id', $values, $preProfileID);
1111 $postProfileID = CRM_Utils_Array::value('additional_custom_post_id', $values, $postProfileID);
6a488035
TO
1112 }
1113
ed7e2e99 1114 $profilePre = self::buildCustomDisplay($preProfileID,
6a488035
TO
1115 'customPre',
1116 $contactID,
1117 $template,
1118 $participantId,
1119 $isTest,
ed7e2e99 1120 TRUE,
6a488035
TO
1121 $participantParams
1122 );
1123
ed7e2e99 1124 $profilePost = self::buildCustomDisplay($postProfileID,
6a488035
TO
1125 'customPost',
1126 $contactID,
1127 $template,
1128 $participantId,
1129 $isTest,
ed7e2e99 1130 TRUE,
6a488035
TO
1131 $participantParams
1132 );
1133
1134 $sessions = CRM_Event_Cart_BAO_Conference::get_participant_sessions($participantId);
1135
ed7e2e99 1136 // @todo - the goal is that all params available to the message template are explicitly defined here rather than
1137 // 'in a smattering of places'. Note that leakage can happen between mailings when not explicitly defined.
91a4b4c6
TO
1138 if ($postProfileID) {
1139 $customPostTitles = empty($profilePost[1]) ? NULL : [];
1140 foreach ($postProfileID as $offset => $id) {
1141 $customPostTitles[$offset] = CRM_Core_BAO_UFGroup::getFrontEndTitle((int) $id);
1142 }
1143 }
1144 else {
1145 $customPostTitles = NULL;
2de68f74 1146 }
be2fb01f 1147 $tplParams = array_merge($values, $participantParams, [
2ba7b9e8 1148 'email' => $notifyEmail,
6b409353
CW
1149 'confirm_email_text' => $values['event']['confirm_email_text'] ?? NULL,
1150 'isShowLocation' => $values['event']['is_show_location'] ?? NULL,
0f2b049e 1151 // The concept of contributeMode is deprecated.
6b409353 1152 'contributeMode' => $template->_tpl_vars['contributeMode'] ?? NULL,
ed7e2e99 1153 'customPre' => $profilePre[0],
1154 'customPre_grouptitle' => empty($profilePre[1]) ? NULL : [CRM_Core_BAO_UFGroup::getFrontEndTitle((int) $preProfileID)],
1155 'customPost' => $profilePost[0],
2de68f74 1156 'customPost_grouptitle' => $customPostTitles,
ddca8f33 1157 'participantID' => $participantId,
7a2ee417 1158 'contactID' => $contactID,
ddca8f33 1159 'conference_sessions' => $sessions,
ed7e2e99 1160 'credit_card_number' => CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $participantParams)),
1161 'credit_card_exp_date' => CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $participantParams))),
a54cf42b 1162 'selfcancelxfer_time' => abs($values['event']['selfcancelxfer_time']),
6c3c43d6 1163 'selfservice_preposition' => $values['event']['selfcancelxfer_time'] < 0 ? ts('after') : ts('before'),
ff708ff0 1164 'currency' => $values['event']['currency'] ?? CRM_Core_Config::singleton()->defaultCurrency,
be2fb01f 1165 ]);
6a488035 1166
9e58e6ff
PJ
1167 // CRM-13890 : NOTE wait list condition need to be given so that
1168 // wait list message is shown properly in email i.e. WRT online event registration template
10c7ceab 1169 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
66df7769 1170 $statusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id', TRUE);
9e58e6ff
PJ
1171 $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($statusId, NULL, 'label');
1172 }
10c7ceab 1173 //CRM-15754 - if participant_status contains status ID
26fe6f4c 1174 elseif (!empty($tplParams['participant_status']) && CRM_Utils_Rule::integer($tplParams['participant_status'])) {
10c7ceab 1175 $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($tplParams['participant_status'], NULL, 'label');
1176 }
9e58e6ff 1177
be2fb01f 1178 $sendTemplateParams = [
6a488035
TO
1179 'groupName' => 'msg_tpl_workflow_event',
1180 'valueName' => 'event_online_receipt',
1181 'contactId' => $contactID,
1182 'isTest' => $isTest,
1183 'tplParams' => $tplParams,
ddca8f33 1184 'PDFFilename' => ts('confirmation') . '.pdf',
be2fb01f 1185 ];
6a488035
TO
1186
1187 // address required during receipt processing (pdf and email receipt)
1188 if ($displayAddress = CRM_Utils_Array::value('address', $values)) {
1189 $sendTemplateParams['tplParams']['address'] = $displayAddress;
0f2b049e 1190 // The concept of contributeMode is deprecated.
6a488035
TO
1191 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1192 }
1193
1194 // set lineItem details
1195 if ($lineItem = CRM_Utils_Array::value('lineItem', $values)) {
0f2b049e 1196 // check if additional participant, if so filter only to relevant ones
6a488035 1197 // CRM-9902
a7488080 1198 if (!empty($values['params']['additionalParticipant'])) {
be2fb01f 1199 $ownLineItems = [];
ddca8f33
TO
1200 foreach ($lineItem as $liKey => $liValue) {
1201 $firstElement = array_pop($liValue);
1202 if ($firstElement['entity_id'] == $participantId) {
6a488035
TO
1203 $ownLineItems[0] = $lineItem[$liKey];
1204 break;
1205 }
1206 }
ddca8f33 1207 if (!empty($ownLineItems)) {
6a488035
TO
1208 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1209 }
1210 }
1211 else {
1212 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1213 }
1214 }
1215
1216 if ($returnMessageText) {
c6327d7d 1217 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
be2fb01f 1218 return [
6a488035
TO
1219 'subject' => $subject,
1220 'body' => $message,
1221 'to' => $displayName,
1222 'html' => $html,
be2fb01f 1223 ];
6a488035
TO
1224 }
1225 else {
e4933c3f 1226 $sendTemplateParams['from'] = CRM_Utils_Array::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array::value('confirm_from_email', $values['event']) . ">";
6a488035 1227 $sendTemplateParams['toName'] = $displayName;
2ba7b9e8 1228 $sendTemplateParams['toEmail'] = $notifyEmail;
6a488035
TO
1229 $sendTemplateParams['autoSubmitted'] = TRUE;
1230 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm',
1231 $values['event']
1232 );
1233 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm',
1234 $values['event']
1235 );
1ed8d778 1236
0fba5cf8 1237 if (Civi::settings()->get('invoice_is_email_pdf') && !empty($values['contributionId'])) {
0479b4c8 1238 $sendTemplateParams['isEmailPdf'] = TRUE;
d75f2f47 1239 $sendTemplateParams['contributionId'] = $values['contributionId'];
9161952c 1240 }
c6327d7d 1241 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
1242 }
1243 }
1244 }
1245 }
1246
1247 /**
3d469574 1248 * Add the custom fields OR array of participant's profile info.
6a488035 1249 *
100fef9d
CW
1250 * @param int $id
1251 * @param string $name
1252 * @param int $cid
64f4eebe 1253 * @param \CRM_Core_Smarty $template
100fef9d 1254 * @param int $participantId
3d469574 1255 * @param bool $isTest
ed7e2e99 1256 * @param bool $returnResults
dd244018 1257 * @param array $participantParams
3d469574 1258 *
1259 * @return array|null
ed7e2e99 1260 * @throws \CRM_Core_Exception
6a488035 1261 */
5396af74 1262 public static function buildCustomDisplay(
ddca8f33 1263 $id,
6a488035
TO
1264 $name,
1265 $cid,
1266 &$template,
1267 $participantId,
1268 $isTest,
ed7e2e99 1269 $returnResults = FALSE,
be2fb01f 1270 $participantParams = []
6a488035
TO
1271 ) {
1272 if (!$id) {
be2fb01f 1273 return [NULL, NULL];
6a488035
TO
1274 }
1275
1276 if (!is_array($id)) {
1277 $id = CRM_Utils_Type::escape($id, 'Positive');
be2fb01f 1278 $profileIds = [$id];
6a488035
TO
1279 }
1280 else {
1281 $profileIds = $id;
1282 }
1283
5efc507e 1284 $val = $groupTitles = NULL;
6a488035
TO
1285 foreach ($profileIds as $gid) {
1286 if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $cid)) {
be2fb01f 1287 $values = [];
6a488035
TO
1288 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW,
1289 NULL, NULL, FALSE, NULL,
1290 FALSE, NULL, CRM_Core_Permission::CREATE,
1291 'field_name', TRUE
1292 );
1293
1294 //this condition is added, since same contact can have multiple event registrations..
be2fb01f 1295 $params = [['participant_id', '=', $participantId, 0, 0]];
6a488035
TO
1296
1297 //add participant id
be2fb01f 1298 $fields['participant_id'] = [
6a488035 1299 'name' => 'participant_id',
aa6228f8 1300 'title' => ts('Participant ID'),
be2fb01f 1301 ];
6a488035
TO
1302 //check whether its a text drive
1303 if ($isTest) {
be2fb01f 1304 $params[] = ['participant_test', '=', 1, 0, 0];
6a488035
TO
1305 }
1306
1307 //display campaign on thankyou page.
1308 if (array_key_exists('participant_campaign_id', $fields)) {
1309 if ($participantId) {
1310 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1311 $participantId,
1312 'campaign_id'
1313 );
1314 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
1315 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array::value($campaignId,
1316 $campaigns
1317 );
1318 }
1319 unset($fields['participant_campaign_id']);
1320 }
1321
1322 $groupTitle = NULL;
1323 foreach ($fields as $k => $v) {
1324 if (!$groupTitle) {
6b04b7ea 1325 $groupTitle = $v['groupDisplayTitle'];
6a488035
TO
1326 }
1327 // suppress all file fields from display
1328 if (
1329 CRM_Utils_Array::value('data_type', $v, '') == 'File' ||
1330 CRM_Utils_Array::value('name', $v, '') == 'image_URL' ||
1331 CRM_Utils_Array::value('field_type', $v) == 'Formatting'
1332 ) {
1333 unset($fields[$k]);
1334 }
1335 }
1336
1337 if ($groupTitle) {
1338 $groupTitles[] = $groupTitle;
1339 }
1340 //display profile groups those are subscribed by participant.
1341 if (($groups = CRM_Utils_Array::value('group', $participantParams)) &&
1342 is_array($groups)
1343 ) {
be2fb01f 1344 $grpIds = [];
6a488035
TO
1345 foreach ($groups as $grpId => $isSelected) {
1346 if ($isSelected) {
1347 $grpIds[] = $grpId;
1348 }
1349 }
1350 if (!empty($grpIds)) {
1351 //get the group titles.
be2fb01f 1352 $grpTitles = [];
ddca8f33
TO
1353 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1354 $grp = CRM_Core_DAO::executeQuery($query);
6a488035
TO
1355 while ($grp->fetch()) {
1356 $grpTitles[] = $grp->title;
1357 }
1358 if (!empty($grpTitles) &&
1359 CRM_Utils_Array::value('title', CRM_Utils_Array::value('group', $fields))
1360 ) {
1361 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1362 }
1363 unset($fields['group']);
1364 }
1365 }
1366
1367 CRM_Core_BAO_UFGroup::getValues($cid, $fields, $values, FALSE, $params);
1368
eba56939
BS
1369 //dev/event#10
1370 //If the event profile includes a note field and the submitted value of
1371 //that field is "", then remove the old note returned by getValues.
1372 if (isset($participantParams['note']) && empty($participantParams['note'])) {
1373 $noteKeyPos = array_search('note', array_keys($fields));
1374 $valuesKeys = array_keys($values);
1375 $values[$valuesKeys[$noteKeyPos]] = "";
1376 }
1377
6a488035
TO
1378 if (isset($fields['participant_status_id']['title']) &&
1379 isset($values[$fields['participant_status_id']['title']]) &&
1380 is_numeric($values[$fields['participant_status_id']['title']])
1381 ) {
be2fb01f 1382 $status = [];
6a488035
TO
1383 $status = CRM_Event_PseudoConstant::participantStatus();
1384 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1385 }
1386
1387 if (isset($fields['participant_role_id']['title']) &&
1388 isset($values[$fields['participant_role_id']['title']]) &&
1389 is_numeric($values[$fields['participant_role_id']['title']])
1390 ) {
be2fb01f 1391 $roles = [];
6a488035
TO
1392 $roles = CRM_Event_PseudoConstant::participantRole();
1393 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1394 }
1395
1396 if (isset($fields['participant_register_date']['title']) &&
1397 isset($values[$fields['participant_register_date']['title']])
1398 ) {
1399 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date::customFormat($values[$fields['participant_register_date']['title']]);
1400 }
1401
1402 //handle fee_level for price set
1403 if (isset($fields['participant_fee_level']['title']) &&
1404 isset($values[$fields['participant_fee_level']['title']])
1405 ) {
1406 $feeLevel = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1407 $values[$fields['participant_fee_level']['title']]
1408 );
1409 foreach ($feeLevel as $key => $value) {
1410 if (!$value) {
1411 unset($feeLevel[$key]);
1412 }
1413 }
7431d9cc 1414 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
6a488035
TO
1415 }
1416
1417 unset($values[$fields['participant_id']['title']]);
1418
1419 $val[] = $values;
1420 }
1421 }
1422
1423 if (count($val)) {
1424 $template->assign($name, $val);
1425 }
1426
1427 if (count($groupTitles)) {
1428 $template->assign($name . '_grouptitle', $groupTitles);
1429 }
1430
1431 //return if we only require array of participant's info.
ed7e2e99 1432 if ($returnResults) {
6a488035 1433 if (count($val)) {
be2fb01f 1434 return [$val, $groupTitles];
6a488035
TO
1435 }
1436 else {
1437 return NULL;
1438 }
1439 }
1440 }
1441
1442 /**
66f9e52b 1443 * Build the array for display the profile fields.
6a488035 1444 *
d4dd1e85
TO
1445 * @param array $params
1446 * Key value.
1447 * @param int $gid
1448 * Profile Id.
1449 * @param array $groupTitle
1450 * Profile Group Title.
1451 * @param array $values
1452 * Formatted array of key value.
6a488035 1453 *
77b97be7 1454 * @param array $profileFields
301906ab 1455 *
1456 * @throws \CRM_Core_Exception
1457 * @throws \API_Exception
1458 * @throws \CiviCRM_API3_Exception
6a488035 1459 */
be2fb01f 1460 public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = []) {
6a488035 1461 if ($gid) {
f5f3f029 1462 $config = CRM_Core_Config::singleton();
6a488035
TO
1463 $session = CRM_Core_Session::singleton();
1464 $contactID = $session->get('userID');
1465 if ($contactID) {
1466 if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) {
1467 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW);
1468 }
1469 }
1470 else {
1471 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::ADD);
1472 }
1473
6d2e7dc0 1474 if (!empty($fields)) {
e1a29ba1 1475 $groupTitle['groupTitle'] = CRM_Core_BAO_UFGroup::getFrontEndTitle((int) $gid);
6a488035 1476 }
29c4866a 1477
ddca8f33 1478 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
6a488035
TO
1479 //start of code to set the default values
1480 foreach ($fields as $name => $field) {
29c4866a 1481 $customVal = '';
9e7eeb0f 1482 $skip = FALSE;
6a488035
TO
1483 // skip fields that should not be displayed separately
1484 if ($field['skipDisplay']) {
1485 continue;
1486 }
1487
1488 $index = $field['title'];
1489 if ($name === 'organization_name') {
1490 $values[$index] = $params[$name];
1491 }
1492
1493 if ('state_province' == substr($name, 0, 14)) {
1494 if ($params[$name]) {
1495 $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]);
1496 }
1497 else {
1498 $values[$index] = '';
1499 }
1500 }
1501 elseif ('date' == substr($name, -4)) {
f5f3f029
KJ
1502 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]),
1503 $config->dateformatFull);
6a488035
TO
1504 }
1505 elseif ('country' == substr($name, 0, 7)) {
1506 if ($params[$name]) {
1507 $values[$index] = CRM_Core_PseudoConstant::country($params[$name]);
1508 }
1509 else {
1510 $values[$index] = '';
1511 }
1512 }
1513 elseif ('county' == substr($name, 0, 6)) {
1514 if ($params[$name]) {
1515 $values[$index] = CRM_Core_PseudoConstant::county($params[$name]);
1516 }
1517 else {
1518 $values[$index] = '';
1519 }
1520 }
be2fb01f 1521 elseif (in_array(substr($name, 0, -3), ['gender', 'prefix', 'suffix', 'communication_style'])) {
36c514a1 1522 $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
6a488035 1523 }
be2fb01f 1524 elseif (in_array($name, [
ddca8f33
TO
1525 'addressee',
1526 'email_greeting',
21dfd5f5 1527 'postal_greeting',
be2fb01f
CW
1528 ])) {
1529 $filterCondition = ['greeting_type' => $name];
ddca8f33
TO
1530 $greeting = CRM_Core_PseudoConstant::greeting($filterCondition);
1531 $values[$index] = $greeting[$params[$name]];
6a488035
TO
1532 }
1533 elseif ($name === 'preferred_communication_method') {
e7e657f0 1534 $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
be2fb01f 1535 $compref = [];
ddca8f33 1536 $pref = $params[$name];
6a488035
TO
1537 if (is_array($pref)) {
1538 foreach ($pref as $k => $v) {
1539 if ($v) {
1540 $compref[] = $communicationFields[$k];
1541 }
1542 }
1543 }
1544 $values[$index] = implode(',', $compref);
1545 }
1546 elseif ($name == 'contact_sub_type') {
1547 $values[$index] = implode(', ', $params[$name]);
1548 }
1549 elseif ($name == 'group') {
1550 $groups = CRM_Contact_BAO_GroupContact::getGroupList();
be2fb01f 1551 $title = [];
6a488035
TO
1552 foreach ($params[$name] as $gId => $dontCare) {
1553 if ($dontCare) {
1554 $title[] = $groups[$gId];
1555 }
1556 }
1557 $values[$index] = implode(', ', $title);
1558 }
1559 elseif ($name == 'tag') {
1560 $entityTags = $params[$name];
be2fb01f
CW
1561 $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]);
1562 $title = [];
6a488035
TO
1563 if (is_array($entityTags)) {
1564 foreach ($entityTags as $tagId => $dontCare) {
1565 $title[] = $allTags[$tagId];
1566 }
1567 }
1568 $values[$index] = implode(', ', $title);
1569 }
90b461f1 1570 elseif ('participant_role_id' == $name or
6a488035
TO
1571 'participant_role' == $name
1572 ) {
1573 $roles = CRM_Event_PseudoConstant::participantRole();
1574 $values[$index] = $roles[$params[$name]];
1575 }
90b461f1 1576 elseif ('participant_status_id' == $name or
6a488035
TO
1577 'participant_status' == $name
1578 ) {
1579 $status = CRM_Event_PseudoConstant::participantStatus();
1580 $values[$index] = $status[$params[$name]];
1581 }
1582 elseif (substr($name, -11) == 'campaign_id') {
1583 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($params[$name]);
9c1bc317 1584 $values[$index] = $campaigns[$params[$name]] ?? NULL;
6a488035
TO
1585 }
1586 elseif (strpos($name, '-') !== FALSE) {
1587 list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2);
1588 $detailName = str_replace(' ', '_', $name);
be2fb01f 1589 if (in_array($fieldName, [
ddca8f33
TO
1590 'state_province',
1591 'country',
21dfd5f5 1592 'county',
be2fb01f 1593 ])) {
6a488035 1594 $values[$index] = $params[$detailName];
ddca8f33 1595 $idx = $detailName . '_id';
6a488035
TO
1596 $values[$index] = $params[$idx];
1597 }
1598 elseif ($fieldName == 'im') {
1599 $providerName = NULL;
1600 if ($providerId = $detailName . '-provider_id') {
9c1bc317 1601 $providerName = $imProviders[$params[$providerId]] ?? NULL;
6a488035
TO
1602 }
1603 if ($providerName) {
1604 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1605 }
1606 else {
1607 $values[$index] = $params[$detailName];
1608 }
1609 }
1610 elseif ($fieldName == 'phone') {
1611 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1612 if (isset($params[$phoneExtField])) {
1613 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1614 }
1615 else {
1616 $values[$index] = $params[$detailName];
1617 }
1618 }
1619 else {
1620 $values[$index] = $params[$detailName];
1621 }
1622 }
1623 else {
1624 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1625 if ($params[$name]) {
1626 $values[$index] = '[ x ]';
1627 }
1628 }
1629 else {
1630 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
1631 $query = "
5f0aaea4 1632SELECT html_type, data_type
6a488035
TO
1633FROM civicrm_custom_field
1634WHERE id = $cfID
1635";
1636 $dao = CRM_Core_DAO::executeQuery($query);
1637 $dao->fetch();
1638 $htmlType = $dao->html_type;
6a488035
TO
1639
1640 if ($htmlType == 'File') {
9c1bc317
CW
1641 $path = $params[$name]['name'] ?? NULL;
1642 $fileType = $params[$name]['type'] ?? NULL;
f5a47ead 1643 $values[$index] = CRM_Utils_File::getFileURL($path, $fileType);
6a488035
TO
1644 }
1645 else {
1646 if ($dao->data_type == 'Int' ||
1647 $dao->data_type == 'Boolean'
1648 ) {
01e21c0a
PJ
1649 $v = $params[$name];
1650 if (!CRM_Utils_System::isNull($v)) {
0479b4c8 1651 $customVal = (int) $v;
01e21c0a 1652 }
6a488035
TO
1653 }
1654 elseif ($dao->data_type == 'Float') {
64f4eebe 1655 $customVal = (float) ($params[$name]);
6a488035
TO
1656 }
1657 elseif ($dao->data_type == 'Date') {
5f0aaea4
KJ
1658 //@todo note the currently we are using default date time formatting. Since you can select/set
1659 // different date and time format specific to custom field we should consider fixing this
1660 // sometime in the future
f5f3f029
KJ
1661 $customVal = $displayValue = CRM_Utils_Date::customFormat(
1662 CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull);
1663
9e7eeb0f 1664 if (!empty($params[$name . '_time'])) {
f5f3f029
KJ
1665 $customVal = $displayValue = CRM_Utils_Date::customFormat(
1666 CRM_Utils_Date::processDate($params[$name], $params[$name . '_time']),
156d7175 1667 $config->dateformatDatetime);
6a488035 1668 }
9e7eeb0f 1669 $skip = TRUE;
6a488035 1670 }
c67b54a2
SV
1671 // for checkboxes, change array of [key => bool] to array of [idx => key]
1672 elseif ($dao->html_type == 'CheckBox') {
4139dd45 1673 $customVal = array_keys(array_filter($params[$name]));
c67b54a2 1674 }
6a488035
TO
1675 else {
1676 $customVal = $params[$name];
1677 }
1678 //take the custom field options
be2fb01f 1679 $returnProperties = [$name => 1];
ddca8f33 1680 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
9e7eeb0f 1681 if (!$skip) {
8cee0c70 1682 $displayValue = CRM_Core_BAO_CustomField::displayValue($customVal, $cfID);
9e7eeb0f 1683 }
6a488035
TO
1684 //Hack since we dont have function to check empty.
1685 //FIXME in 2.3 using crmIsEmptyArray()
1686 $customValue = TRUE;
1687 if (is_array($customVal) && is_array($displayValue)) {
1688 $customValue = array_diff($customVal, $displayValue);
1689 }
1690 //use difference of arrays
1691 if (empty($customValue) || !$customValue) {
1692 $values[$index] = '';
1693 }
1694 else {
1695 $values[$index] = $displayValue;
1696 }
1697 }
1698 }
1699 elseif ($name == 'home_URL' &&
1700 !empty($params[$name])
1701 ) {
1702 $url = CRM_Utils_System::fixURL($params[$name]);
1703 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1704 }
be2fb01f 1705 elseif (in_array($name, [
ddca8f33
TO
1706 'birth_date',
1707 'deceased_date',
21dfd5f5 1708 'participant_register_date',
be2fb01f 1709 ])) {
6a488035
TO
1710 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name]));
1711 }
1712 else {
9c1bc317 1713 $values[$index] = $params[$name] ?? NULL;
6a488035
TO
1714 }
1715 }
1716 }
1717 $profileFields[$name] = $field;
1718 }
1719 }
1720 }
1721
1722 /**
3d469574 1723 * Build the array for Additional participant's information array of primary and additional Ids.
6a488035 1724 *
d4dd1e85
TO
1725 * @param int $participantId
1726 * Id of Primary participant.
1727 * @param array $values
1728 * Key/value event info.
1729 * @param int $contactId
1730 * Contact id of Primary participant.
1731 * @param bool $isTest
1732 * Whether test or live transaction.
1733 * @param bool $isIdsArray
1734 * To return an array of Ids.
77b97be7
EM
1735 *
1736 * @param bool $skipCancel
6a488035 1737 *
a6c01b45
CW
1738 * @return array
1739 * array of Additional participant's info OR array of Ids.
6a488035 1740 */
5396af74 1741 public static function buildCustomProfile(
ddca8f33 1742 $participantId,
6a488035 1743 $values,
0479b4c8
TO
1744 $contactId = NULL,
1745 $isTest = FALSE,
6a488035
TO
1746 $isIdsArray = FALSE,
1747 $skipCancel = TRUE
1748 ) {
1749
be2fb01f 1750 $customProfile = $additionalIDs = [];
6a488035 1751 if (!$participantId) {
a39a65ee 1752 throw new CRM_Core_Exception(ts('Cannot find participant ID'));
6a488035
TO
1753 }
1754
1755 //set Ids of Primary Participant also.
1756 if ($isIdsArray && $contactId) {
1757 $additionalIDs[$participantId] = $contactId;
1758 }
1759
1760 //hack to skip cancelled participants, CRM-4320
1761 $where = "participant.registered_by_id={$participantId}";
1762 if ($skipCancel) {
ddca8f33 1763 $cancelStatusId = 0;
6a488035 1764 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
ddca8f33 1765 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
6a488035
TO
1766 $where .= " AND participant.status_id != {$cancelStatusId}";
1767 }
1768 $query = "
1769 SELECT participant.id, participant.contact_id
1770 FROM civicrm_participant participant
1771 WHERE {$where}";
1772
1773 $dao = CRM_Core_DAO::executeQuery($query);
1774 while ($dao->fetch()) {
1775 $additionalIDs[$dao->id] = $dao->contact_id;
1776 }
1777
1778 //return if only array is required.
1779 if ($isIdsArray && $contactId) {
1780 return $additionalIDs;
1781 }
1782
9c1bc317
CW
1783 $preProfileID = $values['additional_custom_pre_id'] ?? NULL;
1784 $postProfileID = $values['additional_custom_post_id'] ?? NULL;
6a488035
TO
1785 //else build array of Additional participant's information.
1786 if (count($additionalIDs)) {
1787 if ($preProfileID || $postProfileID) {
1788 $template = CRM_Core_Smarty::singleton();
1789
1790 $isCustomProfile = TRUE;
ddca8f33 1791 $i = 1;
be2fb01f 1792 $title = $groupTitles = [];
6a488035
TO
1793 foreach ($additionalIDs as $pId => $cId) {
1794 //get the params submitted by participant.
9b44a9bb 1795 $participantParams = NULL;
07c35283 1796 if (isset($values['params'])) {
be2fb01f 1797 $participantParams = CRM_Utils_Array::value($pId, $values['params'], []);
9b44a9bb 1798 }
6a488035
TO
1799
1800 list($profilePre, $groupTitles) = self::buildCustomDisplay($preProfileID,
1801 'additionalCustomPre',
1802 $cId,
1803 $template,
1804 $pId,
1805 $isTest,
1806 $isCustomProfile,
1807 $participantParams
1808 );
1809
1810 if ($profilePre) {
1811 $profile = $profilePre;
1812 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1813 if ($i === 1) {
1814 $title = $groupTitles;
1815 }
1816 }
1817
1818 list($profilePost, $groupTitles) = self::buildCustomDisplay($postProfileID,
1819 'additionalCustomPost',
1820 $cId,
1821 $template,
1822 $pId,
1823 $isTest,
1824 $isCustomProfile,
1825 $participantParams
1826 );
1827
1828 if ($profilePost) {
1829 if (isset($profilePre)) {
1830 $profile = array_merge($profilePre, $profilePost);
1831 if ($i === 1) {
1832 $title = array_merge($title, $groupTitles);
1833 }
1834 }
1835 else {
1836 $profile = $profilePost;
1837 if ($i === 1) {
1838 $title = $groupTitles;
1839 }
1840 }
1841 }
1842 $profiles[] = $profile;
1843 $i++;
1844 }
1845 $customProfile['title'] = $title;
1846 $customProfile['profile'] = $profiles;
1847 }
1848 }
1849
1850 return $customProfile;
1851 }
1852
0cf587a7 1853 /**
5836c35a
CW
1854 * Retrieve all event addresses.
1855 *
0cf587a7
EM
1856 * @return array
1857 */
00be9182 1858 public static function getLocationEvents() {
be2fb01f
CW
1859 $events = [];
1860 $ret = [
5836c35a
CW
1861 'loc_block_id',
1862 'loc_block_id.address_id.name',
1863 'loc_block_id.address_id.street_address',
1864 'loc_block_id.address_id.supplemental_address_1',
1865 'loc_block_id.address_id.supplemental_address_2',
1866 'loc_block_id.address_id.supplemental_address_3',
1867 'loc_block_id.address_id.city',
1868 'loc_block_id.address_id.state_province_id.name',
be2fb01f 1869 ];
6a488035 1870
be2fb01f 1871 $result = civicrm_api3('Event', 'get', [
5836c35a
CW
1872 'check_permissions' => TRUE,
1873 'return' => $ret,
be2fb01f
CW
1874 'loc_block_id.address_id' => ['IS NOT NULL' => 1],
1875 'options' => [
942cf6ea 1876 'limit' => 0,
be2fb01f
CW
1877 ],
1878 ]);
5836c35a
CW
1879
1880 foreach ($result['values'] as $event) {
1881 $address = '';
1882 foreach ($ret as $field) {
1883 if ($field != 'loc_block_id' && !empty($event[$field])) {
1884 $address .= ($address ? ' :: ' : '') . $event[$field];
1885 }
1886 }
1887 if ($address) {
1888 $events[$event['loc_block_id']] = $address;
1889 }
6a488035
TO
1890 }
1891
5836c35a 1892 return CRM_Utils_Array::asort($events);
6a488035
TO
1893 }
1894
0cf587a7 1895 /**
100fef9d 1896 * @param int $locBlockId
0cf587a7
EM
1897 *
1898 * @return int|null|string
1899 */
00be9182 1900 public static function countEventsUsingLocBlockId($locBlockId) {
6a488035
TO
1901 if (!$locBlockId) {
1902 return 0;
1903 }
1904
1905 $locBlockId = CRM_Utils_Type::escape($locBlockId, 'Integer');
1906
1907 $query = "
1908SELECT count(*) FROM civicrm_event ce
1909WHERE ce.loc_block_id = $locBlockId";
1910
1911 return CRM_Core_DAO::singleValueQuery($query);
1912 }
1913
e2d09ab4 1914 /**
66f9e52b 1915 * Check if event registration is valid according to permissions AND Dates.
e2d09ab4
EM
1916 *
1917 * @param array $values
d4dd1e85 1918 * @param int $eventID
5396af74 1919 * @return bool
e2d09ab4 1920 */
00be9182 1921 public static function validRegistrationRequest($values, $eventID) {
6a488035
TO
1922 // check that the user has permission to register for this event
1923 $hasPermission = CRM_Core_Permission::event(CRM_Core_Permission::EDIT,
e2d09ab4 1924 $eventID, 'register for events'
6a488035
TO
1925 );
1926
1927 return $hasPermission && self::validRegistrationDate($values);
1928 }
1929
0cf587a7
EM
1930 /**
1931 * @param $values
1932 *
1933 * @return bool
1934 */
00be9182 1935 public static function validRegistrationDate(&$values) {
ec7a3e9b
J
1936 // make sure that we are between registration start date and end dates
1937 // and that if the event has ended, registration is still specifically open
6a488035 1938 $startDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('registration_start_date', $values));
ddca8f33
TO
1939 $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('registration_end_date', $values));
1940 $eventEnd = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $values));
1941 $now = time();
6a488035
TO
1942 $validDate = TRUE;
1943 if ($startDate && $startDate >= $now) {
1944 $validDate = FALSE;
1945 }
ec7a3e9b
J
1946 elseif ($endDate && $endDate < $now) {
1947 $validDate = FALSE;
1948 }
1949 elseif ($eventEnd && $eventEnd < $now && !$endDate) {
6a488035
TO
1950 $validDate = FALSE;
1951 }
1952
1953 return $validDate;
1954 }
1955
1956 /* Function to Show - Hide the Registration Link.
1957 *
d4dd1e85
TO
1958 * @param array $values
1959 * Key/value event info.
a6c01b45
CW
1960 * @return boolean
1961 * true if allow registration otherwise false
6a488035 1962 */
90b461f1 1963
0cf587a7
EM
1964 /**
1965 * @param $values
1966 *
1967 * @return bool
1968 */
00be9182 1969 public static function showHideRegistrationLink($values) {
6a488035 1970
ddca8f33
TO
1971 $session = CRM_Core_Session::singleton();
1972 $contactID = $session->get('userID');
6a488035
TO
1973 $alreadyRegistered = FALSE;
1974
1975 if ($contactID) {
be2fb01f 1976 $params = ['contact_id' => $contactID];
6a488035
TO
1977
1978 if ($eventId = CRM_Utils_Array::value('id', $values['event'])) {
1979 $params['event_id'] = $eventId;
1980 }
1981 if ($roleId = CRM_Utils_Array::value('default_role_id', $values['event'])) {
1982 $params['role_id'] = $roleId;
1983 }
1984 $alreadyRegistered = self::checkRegistration($params);
1985 }
1986
a7488080 1987 if (!empty($values['event']['allow_same_participant_emails']) ||
6a488035
TO
1988 !$alreadyRegistered
1989 ) {
1990 return TRUE;
1991 }
1992 return FALSE;
1993 }
1994
1995 /* Function to check if given contact is already registered.
1996 *
d4dd1e85
TO
1997 * @param array $params
1998 * Key/value participant info.
a6c01b45 1999 * @return boolean
6a488035 2000 */
90b461f1 2001
0cf587a7 2002 /**
c490a46a 2003 * @param array $params
0cf587a7
EM
2004 *
2005 * @return bool
2006 */
00be9182 2007 public static function checkRegistration($params) {
6a488035 2008 $alreadyRegistered = FALSE;
a7488080 2009 if (empty($params['contact_id'])) {
6a488035
TO
2010 return $alreadyRegistered;
2011 }
2012
2013 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
2014
2015 $participant = new CRM_Event_DAO_Participant();
2016 $participant->copyValues($params);
2017
2018 $participant->is_test = CRM_Utils_Array::value('is_test', $params, 0);
2019 $participant->selectAdd();
2020 $participant->selectAdd('status_id');
2021 if ($participant->find(TRUE) && array_key_exists($participant->status_id, $statusTypes)) {
2022 $alreadyRegistered = TRUE;
2023 }
2024
2025 return $alreadyRegistered;
2026 }
2027
2028 /**
66f9e52b 2029 * Make sure that the user has permission to access this event.
35b3710f
MWMC
2030 * FIXME: We have separate caches for checkPermission('permission') and getAllPermissions['permissions'] so they don't interfere.
2031 * But it would be nice to clean this up some more.
6a488035 2032 *
c490a46a 2033 * @param int $eventId
35b3710f 2034 * @param int $permissionType
77b97be7 2035 *
35b3710f
MWMC
2036 * @return bool|array
2037 * Whether the user has permission for this event (or if eventId=NULL an array of permissions)
2038 * @throws \CiviCRM_API3_Exception
6a488035 2039 */
f6807038 2040 public static function checkPermission(int $eventId, $permissionType = CRM_Core_Permission::VIEW) {
35b3710f
MWMC
2041 switch ($permissionType) {
2042 case CRM_Core_Permission::EDIT:
2043 // We also set the cached "view" permission to TRUE if "edit" is TRUE
2044 if (isset(Civi::$statics[__CLASS__]['permission']['edit'][$eventId])) {
2045 return Civi::$statics[__CLASS__]['permission']['edit'][$eventId];
2046 }
2047 Civi::$statics[__CLASS__]['permission']['edit'][$eventId] = FALSE;
2048
2049 list($allEvents, $createdEvents) = self::checkPermissionGetInfo($eventId);
2050 // Note: for a multisite setup, a user with edit all events, can edit all events
2051 // including those from other sites
2052 if (($permissionType == CRM_Core_Permission::EDIT) && CRM_Core_Permission::check('edit all events')) {
2053 Civi::$statics[__CLASS__]['permission']['edit'][$eventId] = TRUE;
2054 Civi::$statics[__CLASS__]['permission']['view'][$eventId] = TRUE;
2055 }
2056 elseif (in_array($eventId, CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_event', $allEvents, $createdEvents))) {
2057 Civi::$statics[__CLASS__]['permission']['edit'][$eventId] = TRUE;
2058 Civi::$statics[__CLASS__]['permission']['view'][$eventId] = TRUE;
2059 }
2060 return Civi::$statics[__CLASS__]['permission']['edit'][$eventId];
2061
2062 case CRM_Core_Permission::VIEW:
2063 if (isset(Civi::$statics[__CLASS__]['permission']['view'][$eventId])) {
2064 return Civi::$statics[__CLASS__]['permission']['view'][$eventId];
2065 }
2066 Civi::$statics[__CLASS__]['permission']['view'][$eventId] = FALSE;
2067
2068 list($allEvents, $createdEvents) = self::checkPermissionGetInfo($eventId);
2069 if (CRM_Core_Permission::check('access CiviEvent')) {
2070 if (in_array($eventId, CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_event', $allEvents, array_keys($createdEvents)))) {
2071 // User created this event so has permission to view it
2072 return Civi::$statics[__CLASS__]['permission']['view'][$eventId] = TRUE;
2073 }
2074 if (CRM_Core_Permission::check('view event participants')) {
2075 // User has permission to view all events
2076 // use case: allow "view all events" but NOT "edit all events"
2077 // so for a normal site allow users with these two permissions to view all events AND
2078 // at the same time also allow any hook to override if needed.
2079 if (in_array($eventId, CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_event', $allEvents, array_keys($allEvents)))) {
2080 Civi::$statics[__CLASS__]['permission']['view'][$eventId] = TRUE;
2081 }
2082 }
2083 }
2084 return Civi::$statics[__CLASS__]['permission']['view'][$eventId];
2085
2086 case CRM_Core_Permission::DELETE:
2087 if (isset(Civi::$statics[__CLASS__]['permission']['delete'][$eventId])) {
2088 return Civi::$statics[__CLASS__]['permission']['delete'][$eventId];
2089 }
2090 Civi::$statics[__CLASS__]['permission']['delete'][$eventId] = FALSE;
2091 if (CRM_Core_Permission::check('delete in CiviEvent')) {
2092 Civi::$statics[__CLASS__]['permission']['delete'][$eventId] = TRUE;
2093 }
2094 return Civi::$statics[__CLASS__]['permission']['delete'][$eventId];
2095
2096 default:
2097 return FALSE;
2098 }
2099 }
043d767f 2100
35b3710f
MWMC
2101 /**
2102 * This is a helper for refactoring checkPermission
2103 * FIXME: We should be able to get rid of these arrays, but that would require understanding how CRM_ACL_API::group actually works!
2104 *
2105 * @param int $eventId
2106 *
2107 * @return array $allEvents, $createdEvents
2108 * @throws \CiviCRM_API3_Exception
2109 */
2110 private static function checkPermissionGetInfo($eventId = NULL) {
2111 $params = [
2112 'check_permissions' => 1,
2113 'return' => 'id, created_id',
2114 'options' => ['limit' => 0],
2115 ];
2116 if ($eventId) {
2117 $params['id'] = $eventId;
2118 }
2119
2120 $allEvents = [];
2121 $createdEvents = [];
2122 $eventResult = civicrm_api3('Event', 'get', $params);
2123 if ($eventResult['count'] > 0) {
2124 $contactId = CRM_Core_Session::getLoggedInContactID();
2125 foreach ($eventResult['values'] as $eventId => $eventDetail) {
2126 $allEvents[$eventId] = $eventId;
2127 if (isset($eventDetail['created_id']) && $contactId == $eventDetail['created_id']) {
2128 $createdEvents[$eventId] = $eventId;
2129 }
2130 }
2131 }
2132 return [$allEvents, $createdEvents];
2133 }
5836c35a 2134
35b3710f
MWMC
2135 /**
2136 * Make sure that the user has permission to access this event.
2137 * TODO: This function needs refactoring / cleaning up after being split from checkPermissions()
2138 *
2139 * @return array
2140 * Array of events with permissions (array_keys=permissions)
2141 * @throws \CiviCRM_API3_Exception
2142 */
2143 public static function getAllPermissions() {
2144 if (!isset(Civi::$statics[__CLASS__]['permissions'])) {
2145 list($allEvents, $createdEvents) = self::checkPermissionGetInfo();
6a488035
TO
2146
2147 // Note: for a multisite setup, a user with edit all events, can edit all events
2148 // including those from other sites
2149 if (CRM_Core_Permission::check('edit all events')) {
1580a51e 2150 Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::EDIT] = array_keys($allEvents);
6a488035
TO
2151 }
2152 else {
1580a51e 2153 Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::EDIT] = CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_event', $allEvents, $createdEvents);
6a488035
TO
2154 }
2155
2156 if (CRM_Core_Permission::check('edit all events')) {
1580a51e 2157 Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::VIEW] = array_keys($allEvents);
6a488035
TO
2158 }
2159 else {
2160 if (CRM_Core_Permission::check('access CiviEvent') &&
2161 CRM_Core_Permission::check('view event participants')
2162 ) {
2163 // use case: allow "view all events" but NOT "edit all events"
2164 // so for a normal site allow users with these two permissions to view all events AND
2165 // at the same time also allow any hook to override if needed.
2166 $createdEvents = array_keys($allEvents);
2167 }
1580a51e 2168 Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::VIEW] = CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_event', $allEvents, $createdEvents);
6a488035
TO
2169 }
2170
be2fb01f 2171 Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::DELETE] = [];
6a488035
TO
2172 if (CRM_Core_Permission::check('delete in CiviEvent')) {
2173 // Note: we want to restrict the scope of delete permission to
2174 // events that are editable/viewable (usecase multisite).
2175 // We can remove array_intersect once we have ACL support for delete functionality.
1580a51e
AF
2176 Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::DELETE] = array_intersect(Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::EDIT],
2177 Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::VIEW]
6a488035
TO
2178 );
2179 }
2180 }
2181
1580a51e 2182 return Civi::$statics[__CLASS__]['permissions'];
6a488035
TO
2183 }
2184
2185 /**
2186 * Build From Email as the combination of all the email ids of the logged in user,
2187 * the domain email id and the email id configured for the event
2188 *
d4dd1e85
TO
2189 * @param int $eventId
2190 * The id of the event.
6a488035 2191 *
a6c01b45
CW
2192 * @return array
2193 * an array of email ids
6a488035 2194 */
00be9182 2195 public static function getFromEmailIds($eventId = NULL) {
6a488035
TO
2196 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email::getFromEmail();
2197
2198 if ($eventId) {
2199 // add the email id configured for the event
be2fb01f
CW
2200 $params = ['id' => $eventId];
2201 $returnProperties = ['confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm'];
2202 $eventEmail = [];
6a488035
TO
2203
2204 CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
8cc574cf 2205 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
6a488035
TO
2206 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
2207
2208 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
be2fb01f 2209 $fromEmailId = [
6b409353
CW
2210 'cc' => $eventEmail['cc_confirm'] ?? NULL,
2211 'bcc' => $eventEmail['bcc_confirm'] ?? NULL,
be2fb01f 2212 ];
6a488035
TO
2213 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2214 }
2215 }
2216
2217 return $fromEmailValues;
2218 }
2219
2220 /**
100fef9d 2221 * Calculate event total seats occupied.
6a488035 2222 *
d4dd1e85
TO
2223 * @param int $eventId
2224 * Event id.
64f4eebe 2225 * @param string $extraWhereClause
d4dd1e85 2226 * Extra filter on participants.
6a488035 2227 *
a6c01b45
CW
2228 * @return int
2229 * event total seats w/ given criteria.
6a488035 2230 */
00be9182 2231 public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
6a488035
TO
2232 if (empty($eventId)) {
2233 return 0;
2234 }
2235
2236 $extraWhereClause = trim($extraWhereClause);
2237 if (!empty($extraWhereClause)) {
2238 $extraWhereClause = " AND ( {$extraWhereClause} )";
2239 }
2240
2241 //event seats calculation :
2242 //1. consider event seat as a single when participant does not have line item.
2243 //2. consider event seat as a single when participant has line items but does not
2244 // have count for corresponding price field value ( ie price field value does not carry any seat )
2245 //3. consider event seat as a sum of all seats from line items in case price field value carries count.
2246
2247 $query = "
2248 SELECT IF ( SUM( value.count*lineItem.qty ),
2249 SUM( value.count*lineItem.qty ) +
2250 COUNT( DISTINCT participant.id ) -
2251 COUNT( DISTINCT IF ( value.count, participant.id, NULL ) ),
2252 COUNT( DISTINCT participant.id ) )
2253 FROM civicrm_participant participant
2254INNER JOIN civicrm_contact contact ON ( contact.id = participant.contact_id AND contact.is_deleted = 0 )
2255INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
2256LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id
2257 AND lineItem.entity_table = 'civicrm_participant' )
2258LEFT JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id AND value.count )
2259 WHERE ( participant.event_id = %1 )
4962bc92 2260 AND participant.is_test = 0
6a488035
TO
2261 {$extraWhereClause}
2262 GROUP BY participant.event_id";
2263
be2fb01f 2264 return (int) CRM_Core_DAO::singleValueQuery($query, [1 => [$eventId, 'Positive']]);
6a488035
TO
2265 }
2266
c490a46a 2267 /**
66f9e52b 2268 * Retrieve event template default values to be set.
6a488035
TO
2269 * as default values for current new event.
2270 *
d4dd1e85
TO
2271 * @param int $templateId
2272 * Event template id.
6a488035 2273 *
a6c01b45 2274 * @return array
16b10e64 2275 * Array of custom data defaults.
0cf587a7 2276 */
00be9182 2277 public static function getTemplateDefaultValues($templateId) {
be2fb01f 2278 $defaults = [];
6a488035
TO
2279 if (!$templateId) {
2280 return $defaults;
2281 }
2282
be2fb01f 2283 $templateParams = ['id' => $templateId];
6a488035 2284 CRM_Event_BAO_Event::retrieve($templateParams, $defaults);
be2fb01f 2285 $fieldsToExclude = [
6a488035
TO
2286 'id',
2287 'default_fee_id',
2288 'default_discount_fee_id',
2289 'created_date',
2290 'created_id',
2291 'is_template',
2292 'template_title',
be2fb01f 2293 ];
6a488035 2294 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
426cf44f 2295 foreach ($defaults as $key => $value) {
2296 $customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, TRUE);
2297 if (!empty($customFieldInfo[1])) {
2298 $defaults[str_replace($customFieldInfo[1], '-' . $customFieldInfo[1], $key)] = $value;
2299 unset($defaults[$key]);
2300 }
2301 }
6a488035
TO
2302 return $defaults;
2303 }
2304
0cf587a7 2305 /**
100fef9d 2306 * @param int $event_id
0cf587a7
EM
2307 *
2308 * @return object
2309 */
00be9182 2310 public static function get_sub_events($event_id) {
be2fb01f
CW
2311 $params = ['parent_event_id' => $event_id];
2312 $defaults = [];
6a488035
TO
2313 return CRM_Event_BAO_Event::retrieve($params, $defaults);
2314 }
49f68a22 2315
c490a46a 2316 /**
66f9e52b 2317 * Update the Campaign Id of all the participants of the given event.
49f68a22 2318 *
d4dd1e85
TO
2319 * @param int $eventID
2320 * Event id.
2321 * @param int $eventCampaignID
2322 * Campaign id of that event.
0cf587a7 2323 */
00be9182 2324 public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
be2fb01f
CW
2325 $params = [];
2326 $params[1] = [$eventID, 'Integer'];
49f68a22 2327
ddca8f33 2328 if (empty($eventCampaignID)) {
49f68a22
DL
2329 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2330 }
2331 else {
2332 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
be2fb01f 2333 $params[2] = [$eventCampaignID, 'Integer'];
49f68a22
DL
2334 }
2335 CRM_Core_DAO::executeQuery($query, $params);
2336 }
e1462487
CW
2337
2338 /**
2339 * Get options for a given field.
2340 * @see CRM_Core_DAO::buildOptions
2341 *
d4dd1e85 2342 * @param string $fieldName
ddca8f33
TO
2343 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2344 * @param array $props : whatever is known about this dao object
e1462487
CW
2345 *
2346 * @return array|bool
2347 */
be2fb01f
CW
2348 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2349 $params = [];
e1462487
CW
2350 // Special logic for fields whose options depend on context or properties
2351 switch ($fieldName) {
2352 case 'financial_type_id':
87e130bb
EM
2353 // https://lab.civicrm.org/dev/core/issues/547 if CiviContribute not enabled this causes an invalid query
2354 // @todo - the component is enabled check should be done within getIncomeFinancialType
2355 // It looks to me like test cover was NOT added to cover the change
2356 // that added this so we need to assume there is no test cover
cabcfae5 2357 if (CRM_Core_Component::isEnabled('CiviContribute')) {
87e130bb 2358 return CRM_Financial_BAO_FinancialType::getIncomeFinancialType($props['check_permissions'] ?? TRUE);
341a4d71
MW
2359 }
2360 return [];
e1462487
CW
2361 }
2362 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
2363 }
d75f2f47 2364
1d6f94ab
CW
2365 /**
2366 * @return array
2367 */
2368 public static function getEntityRefFilters() {
2369 return [
2370 ['key' => 'event_type_id', 'value' => ts('Event Type')],
2371 [
2372 'key' => 'start_date',
2373 'value' => ts('Start Date'),
2374 'options' => [
2375 ['key' => '{">":"now"}', 'value' => ts('Upcoming')],
2376 [
2377 'key' => '{"BETWEEN":["now - 3 month","now"]}',
2378 'value' => ts('Past 3 Months'),
2379 ],
2380 [
2381 'key' => '{"BETWEEN":["now - 6 month","now"]}',
2382 'value' => ts('Past 6 Months'),
2383 ],
2384 [
2385 'key' => '{"BETWEEN":["now - 1 year","now"]}',
2386 'value' => ts('Past Year'),
2387 ],
2388 ],
2389 ],
2390 ];
2391 }
2392
679bd095
AH
2393 /**
2394 * Get the appropriate links to iCal pages/feeds.
2395 *
2396 * @param int $eventId
2397 *
2398 * @return array
2399 * All of the icons to show.
2400 */
2401 public static function getICalLinks($eventId = NULL) {
2402 $return = $eventId ? [] : [
2403 [
2404 'url' => CRM_Utils_System::url('civicrm/event/ical', 'reset=1&list=1&html=1', TRUE, NULL, TRUE),
2405 'text' => ts('HTML listing of current and future public events.'),
2406 'icon' => 'fa-th-list',
2407 ],
2408 [
2409 'url' => CRM_Utils_System::url('civicrm/event/ical', 'reset=1&list=1&rss=1', TRUE, NULL, TRUE),
2410 'text' => ts('Get RSS 2.0 feed for current and future public events.'),
2411 'icon' => 'fa-rss',
2412 ],
2413 ];
2414 $query = [
2415 'reset' => 1,
2416 ];
2417 if ($eventId) {
2418 $query['id'] = $eventId;
2419 }
2420 $return[] = [
2421 'url' => CRM_Utils_System::url('civicrm/event/ical', $query, TRUE, NULL, TRUE),
2422 'text' => $eventId ? ts('Download iCalendar entry for this event.') : ts('Download iCalendar entry for current and future public events.'),
2423 'icon' => 'fa-download',
2424 ];
2425 $query['list'] = 1;
2426 $return[] = [
2427 'url' => CRM_Utils_System::url('civicrm/event/ical', $query, TRUE, NULL, TRUE),
2428 'text' => $eventId ? ts('iCalendar feed for this event.') : ts('iCalendar feed for current and future public events.'),
2429 'icon' => 'fa-link',
2430 ];
2431 return $return;
2432 }
2433
d75f2f47 2434}