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