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