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