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