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