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