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