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