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