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