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