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