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