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