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