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