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