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