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