3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Event_BAO_Event
extends CRM_Event_DAO_Event
{
40 public function __construct() {
41 parent
::__construct();
45 * Fetch object based on array of properties
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
50 * @return CRM_Event_BAO_ManageEvent object
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);
64 * Update the is_active flag in the db
66 * @param int $id id of the database record
67 * @param boolean $is_active value we want to set the is_active field
69 * @return Object DAO object on sucess, null otherwise
72 public static function setIsActive($id, $is_active) {
73 return CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
79 * @param array $params reference array contains the values submitted by the form
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');
95 CRM_Utils_Hook
::pre('create', 'Event', NULL, $params);
98 $event = new CRM_Event_DAO_Event();
100 $event->copyValues($params);
101 $result = $event->save();
103 if (!empty($params['id'])) {
104 CRM_Utils_Hook
::post('edit', 'Event', $event->id
, $event);
107 CRM_Utils_Hook
::post('create', 'Event', $event->id
, $event);
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']);
118 * @param array $params reference array contains the values submitted by the form
124 public static function create(&$params) {
125 $transaction = new CRM_Core_Transaction();
126 if (empty($params['is_template'])) {
127 $params['is_template'] = 0;
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');
136 $params['created_date'] = date('YmdHis');
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');
146 $session = CRM_Core_Session
::singleton();
147 $contactId = $session->get('userID');
149 $contactId = CRM_Utils_Array
::value('contact_id', $params);
152 // Log the information on successful add/edit of Event
154 'entity_table' => 'civicrm_event',
155 'entity_id' => $event->id
,
156 'modified_id' => $contactId,
157 'modified_date' => date('Ymd'),
160 CRM_Core_BAO_Log
::add($logParams);
162 if (!empty($params['custom']) &&
163 is_array($params['custom'])
165 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_event', $event->id
);
168 $transaction->commit();
176 * @param int $id event id
182 public static function del($id) {
187 CRM_Utils_Hook
::pre('delete', 'Event', $id, CRM_Core_DAO
::$_nullArray);
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;
194 $params = array(1 => array($values['table_name'], 'string'),
195 2 => array($id, 'integer'),
198 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
201 // price set cleanup, CRM-5527
202 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_event', $id);
204 $event = new CRM_Event_DAO_Event();
207 if ($event->find(TRUE)) {
208 $locBlockId = $event->loc_block_id
;
209 $result = $event->delete();
211 if (!is_null($locBlockId)) {
212 self
::deleteEventLocBlock($locBlockId, $id);
215 CRM_Utils_Hook
::post('delete', 'Event', $id, $event);
223 * Delete the location block associated with an event,
224 * if not being used by any other event.
226 * @param $locBlockId location block id to be deleted
227 * @param int $eventId event with which loc block is associated
231 public static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
232 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
235 $query .= " AND ce.id != $eventId;";
238 $locCount = CRM_Core_DAO
::singleValueQuery($query);
240 if ($locCount == 0) {
241 CRM_Core_BAO_Location
::deleteLocBlock($locBlockId);
246 * Get current/future Events
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
258 static function getEvents($all = 0,
261 $checkPermission = TRUE
264 SELECT `id`, `title`, `start_date`
266 WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
269 $query .= " AND `id` = {$id}";
272 // find only events ending in the future
273 $endDate = date('YmdHis');
275 AND ( `end_date` >= {$endDate} OR
277 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
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 )";
287 $query .= " AND civicrm_event.is_active = 1";
290 $query .= " ORDER BY title asc";
293 $dao = CRM_Core_DAO
::executeQuery($query);
294 while ($dao->fetch()) {
295 if ((!$checkPermission ||
296 CRM_Event_BAO_Event
::checkPermission($dao->id
)
300 $events[$dao->id
] = $dao->title
. ' - ' . CRM_Utils_Date
::customFormat($dao->start_date
);
312 * @return array Array of event summary values
314 public static function getEventSummary() {
315 $eventSummary = $eventIds = array();
316 $config = CRM_Core_Config
::singleton();
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();
323 if (empty($permissions[CRM_Core_Permission
::VIEW
])) {
324 $eventSummary['total_events'] = 0;
325 return $eventSummary;
328 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission
::VIEW
])) . " ) ";
331 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
333 SELECT count(id) as total_events
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 )
340 $dao = CRM_Core_DAO
::executeQuery($query);
343 $eventSummary['total_events'] = $dao->total_events
;
346 if (empty($eventSummary) ||
347 $dao->total_events
== 0
349 return $eventSummary;
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;
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
;
372 // Get the event summary display preferences
373 $show_max_events = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
,
376 // default to 10 if no option is set
377 if (is_null($show_max_events)) {
378 $show_max_events = 10;
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";
385 $event_summary_limit = "";
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
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 )
407 GROUP BY civicrm_event.id
408 ORDER BY civicrm_event.start_date ASC
411 $eventParticipant = array();
415 'eventTitle' => 'event_title',
416 'isPublic' => 'is_public',
417 'maxParticipants' => 'max_participants',
418 'startDate' => 'start_date',
419 'endDate' => 'end_date',
420 'eventType' => 'event_type',
422 'participants' => 'participants',
423 'notCountedDueToRole' => 'notCountedDueToRole',
424 'notCountedDueToStatus' => 'notCountedDueToStatus',
425 'notCountedParticipants' => 'notCountedParticipants',
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) {
442 $eventSummary['events'][$dao->id
][$property] = $set;
446 if ($dao->$name && $config->mapAPIKey
) {
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'])
457 $set = CRM_Utils_System
::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
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");
469 $eventSummary['events'][$dao->id
][$property] = CRM_Utils_Date
::customFormat($dao->$name,
475 case 'notCountedDueToRole':
476 case 'notCountedDueToStatus':
477 case 'notCountedParticipants':
480 if ($name == 'participants') {
481 $propertyCnt = self
::getParticipantCount($dao->id
);
483 $set = CRM_Utils_System
::url('civicrm/event/search',
484 "reset=1&force=1&event=$dao->id&status=true&role=true"
488 elseif ($name == 'notCountedParticipants') {
489 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, TRUE, FALSE);
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" );
496 elseif ($name == 'notCountedDueToStatus') {
497 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, FALSE, FALSE);
499 $set = CRM_Utils_System
::url('civicrm/event/search',
500 "reset=1&force=1&event=$dao->id&status=false"
505 $propertyCnt = self
::getParticipantCount($dao->id
, FALSE, FALSE, TRUE, FALSE);
507 $set = CRM_Utils_System
::url('civicrm/event/search',
508 "reset=1&force=1&event=$dao->id&role=false"
513 $eventSummary['events'][$dao->id
][$property] = $propertyCnt;
514 $eventSummary['events'][$dao->id
][$name . '_url'] = $set;
518 $eventSummary['events'][$dao->id
][$property] = $dao->$name;
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());
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
;
536 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
537 foreach ($statusValues as $statusId => $statusValue) {
538 if (!array_key_exists($statusId, $statusTypes)) {
541 $class = $statusValue['class'];
542 $statusCount = self
::eventTotalSeats($dao->id
, "( participant.status_id = {$statusId} )");
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,
550 $eventSummary['events'][$dao->id
]['statuses'][$class][] = $statusInfo;
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 )');
560 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
561 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
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));
568 return $eventSummary;
572 * Get participant count
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.
581 * @return array array with count of participants for each event based on status/role
583 public static function getParticipantCount($eventId,
584 $considerStatus = TRUE,
586 $considerRole = TRUE,
590 // consider both role and status for counted participants, CRM-4924.
592 // not counted participant.
593 if ($considerStatus && $considerRole && !$status && !$role) {
597 if ($considerStatus) {
598 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
599 $statusClause = 'NOT IN';
601 $statusClause = 'IN';
603 $status = implode(',', array_keys($statusTypes));
604 if (empty($status)) {
607 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
611 $roleTypes = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
612 $roleClause = 'NOT IN';
616 $roles = implode(',', array_keys($roleTypes));
620 $clause[] = "participant.role_id {$roleClause} ( $roles )";
624 if (!empty($clause)) {
625 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
628 return self
::eventTotalSeats($eventId, $sqlClause);
632 * Get the information to map a event
634 * @param int $id for which we want map info
636 * @return null|string title of the event
639 public static function &getMapInfo(&$id) {
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
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');
665 $dao = new CRM_Core_DAO();
668 $locations = array();
670 $config = CRM_Core_Config
::singleton();
672 while ($dao->fetch()) {
675 $location['displayName'] = addslashes($dao->display_name
);
676 $location['lat'] = $dao->latitude
;
677 $location['marker_class'] = 'Event';
678 $location['lng'] = $dao->longitude
;
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'])));
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;
695 * Get the complete information for one or more events
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
703 * @return array $all array of all the events that are searched
706 static function &getCompleteInfo(
713 $publicCondition = NULL;
715 $publicCondition = " AND civicrm_event.is_public = 1";
719 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
721 // get events with start_date >= requested start
722 $startDate = CRM_Utils_Type
::escape($start, 'Date');
723 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
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}' ) ";
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}' ) ";
743 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
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
;
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
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)
792 if (isset($typeCondition)) {
793 $query .= $typeCondition;
796 if (isset($eventId)) {
797 $query .= " AND civicrm_event.id =$eventId ";
799 $query .= " ORDER BY civicrm_event.start_date ASC";
802 $params = array(1 => array($optionGroupId, 'Integer'));
803 $dao = CRM_Core_DAO
::executeQuery($query, $params);
805 $config = CRM_Core_Config
::singleton();
807 $baseURL = parse_url($config->userFrameworkBaseURL
);
808 $url = "@" . $baseURL['host'];
809 if (!empty($baseURL['path'])) {
810 $url .= substr($baseURL['path'], 0, -1);
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
);
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
,
827 while ($dao->fetch()) {
828 if (!empty($permissions) && in_array($dao->event_id
, $permissions)) {
830 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL
) . $url;
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
;
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
,
861 CRM_Utils_String
::append($address, ', ',
862 CRM_Utils_Address
::format($addrFields)
864 $info['location'] = $address;
865 $info['url'] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
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'];
881 * This function is to make a copy of a Event, including
882 * all the fields in the event Wizard
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
892 public static function copy($id, $newEvent = NULL, $afterCreate = FALSE) {
894 $defaults = $eventValues = array();
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');
900 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
902 // since the location is sharable, lets use the same loc_block_id.
903 $locBlockId = CRM_Utils_Array
::value('loc_block_id', $eventValues);
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;
910 if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
911 $copyEvent = $newEvent;
914 if (!isset($copyEvent)) {
915 $copyEvent = &CRM_Core_DAO
::copyGeneric('CRM_Event_DAO_Event',
919 ($locBlockId) ?
$locBlockId : NULL,
924 CRM_Price_BAO_PriceSet
::copyPriceSet('civicrm_event', $id, $copyEvent->id
);
925 $copyUF = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_UFJoin',
928 'entity_table' => 'civicrm_event',
930 array('entity_id' => $copyEvent->id
)
933 $copyTellFriend = &CRM_Core_DAO
::copyGeneric('CRM_Friend_DAO_Friend',
936 'entity_table' => 'civicrm_event',
938 array('entity_id' => $copyEvent->id
)
941 $copyPCP = &CRM_Core_DAO
::copyGeneric('CRM_PCP_DAO_PCPBlock',
944 'entity_table' => 'civicrm_event',
946 array('entity_id' => $copyEvent->id
),
947 array('replace' => array('target_entity_id' => $copyEvent->id
))
950 if ($eventValues['is_template']) {
951 $field = 'event_template';
954 $field = 'civicrm_event';
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';
962 $field = 'civicrm_event';
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',
973 $extends = array('event');
974 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
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'];
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);
996 CRM_Utils_System
::flushCache();
998 CRM_Utils_Hook
::copy('Event', $copyEvent);
1004 * This is sometimes called in a loop (during event search)
1005 * hence we cache the values to prevent repeated calls to the db
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',
1015 return $isMonetary[$id];
1019 * This is sometimes called in a loop (during event search)
1020 * hence we cache the values to prevent repeated calls to the db
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);
1027 return $usesPriceSet[$id];
1031 * Process that send e-mails
1033 * @param int $contactID
1035 * @param int $participantId
1036 * @param bool $isTest
1037 * @param bool $returnMessageText
1041 public static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
1043 $template = CRM_Core_Smarty
::singleton();
1045 'custom_pre_id' => $values['custom_pre_id'],
1046 'custom_post_id' => $values['custom_post_id'],
1049 //get the params submitted by participant.
1050 $participantParams = CRM_Utils_Array
::value($participantId, $values['params'], array());
1052 if (!$returnMessageText) {
1053 //send notification email if field values are set (CRM-1941)
1054 foreach ($gIds as $key => $gIdValues) {
1056 if (!is_array($gIdValues)) {
1057 $gIdValues = array( $gIdValues );
1060 foreach ($gIdValues as $gId) {
1061 $email = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1063 //get values of corresponding profile fields for notification
1064 list($profileValues) = self
::buildCustomDisplay($gId,
1073 list($profileValues) = $profileValues;
1076 'values' => $profileValues,
1079 CRM_Core_BAO_UFGroup
::commonSendMail($contactID, $val);
1086 if ($values['event']['is_email_confirm'] ||
$returnMessageText) {
1087 list($displayName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
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);
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 );
1099 self
::buildCustomDisplay($preProfileID,
1109 self
::buildCustomDisplay($postProfileID,
1119 $sessions = CRM_Event_Cart_BAO_Conference
::get_participant_sessions($participantId);
1121 $tplParams = array_merge($values, $participantParams, array(
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))),
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');
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');
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',
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;
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
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];
1176 if ( ! empty( $ownLineItems ) ) {
1177 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1181 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1185 if ($returnMessageText) {
1186 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1188 'subject' => $subject,
1190 'to' => $displayName,
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',
1202 $sendTemplateParams['bcc'] = CRM_Utils_Array
::value('bcc_confirm',
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'];
1214 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1221 * Add the custom fields OR array of participant's
1225 * @param string $name
1228 * @param int $participantId
1230 * @param bool $isCustomProfile
1231 * @param array $participantParams
1235 static function buildCustomDisplay($id,
1241 $isCustomProfile = FALSE,
1242 $participantParams = array()
1245 return array(NULL, NULL);
1248 if (!is_array($id)) {
1249 $id = CRM_Utils_Type
::escape($id, 'Positive');
1250 $profileIds = array($id);
1256 foreach ($profileIds as $gid) {
1257 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $cid)) {
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
,
1265 //this condition is added, since same contact can have multiple event registrations..
1266 $params = array(array('participant_id', '=', $participantId, 0, 0));
1268 //add participant id
1269 $fields['participant_id'] = array(
1270 'name' => 'participant_id',
1271 'title' => ts('Participant ID'),
1273 //check whether its a text drive
1275 $params[] = array('participant_test', '=', 1, 0, 0);
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',
1285 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1286 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array
::value($campaignId,
1290 unset($fields['participant_campaign_id']);
1294 foreach ($fields as $k => $v) {
1296 $groupTitle = $v['groupTitle'];
1298 // suppress all file fields from display
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'
1309 $groupTitles[] = $groupTitle;
1311 //display profile groups those are subscribed by participant.
1312 if (($groups = CRM_Utils_Array
::value('group', $participantParams)) &&
1316 foreach ($groups as $grpId => $isSelected) {
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
;
1329 if (!empty($grpTitles) &&
1330 CRM_Utils_Array
::value('title', CRM_Utils_Array
::value('group', $fields))
1332 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1334 unset($fields['group']);
1338 CRM_Core_BAO_UFGroup
::getValues($cid, $fields, $values, FALSE, $params);
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']])
1345 $status = CRM_Event_PseudoConstant
::participantStatus();
1346 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
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']])
1354 $roles = CRM_Event_PseudoConstant
::participantRole();
1355 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1358 if (isset($fields['participant_register_date']['title']) &&
1359 isset($values[$fields['participant_register_date']['title']])
1361 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date
::customFormat($values[$fields['participant_register_date']['title']]);
1364 //handle fee_level for price set
1365 if (isset($fields['participant_fee_level']['title']) &&
1366 isset($values[$fields['participant_fee_level']['title']])
1368 $feeLevel = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1369 $values[$fields['participant_fee_level']['title']]
1371 foreach ($feeLevel as $key => $value) {
1373 unset($feeLevel[$key]);
1376 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
1379 unset($values[$fields['participant_id']['title']]);
1386 $template->assign($name, $val);
1389 if (count($groupTitles)) {
1390 $template->assign($name . '_grouptitle', $groupTitles);
1393 //return if we only require array of participant's info.
1394 if ($isCustomProfile) {
1396 return array($val, $groupTitles);
1405 * Build the array for display the profile fields
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
1412 * @param array $profileFields
1417 public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
1419 $config = CRM_Core_Config
::singleton();
1420 $session = CRM_Core_Session
::singleton();
1421 $contactID = $session->get('userID');
1423 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $contactID)) {
1424 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
);
1428 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::ADD
);
1431 foreach ($fields as $v) {
1432 if (!empty($v['groupTitle'])) {
1433 $groupTitle['groupTitle'] = $v['groupTitle'];
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) {
1442 // skip fields that should not be displayed separately
1443 if ($field['skipDisplay']) {
1447 $index = $field['title'];
1448 if ($name === 'organization_name') {
1449 $values[$index] = $params[$name];
1452 if ('state_province' == substr($name, 0, 14)) {
1453 if ($params[$name]) {
1454 $values[$index] = CRM_Core_PseudoConstant
::stateProvince($params[$name]);
1457 $values[$index] = '';
1460 elseif ('date' == substr($name, -4)) {
1461 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::processDate($params[$name]),
1462 $config->dateformatFull
);
1464 elseif ('country' == substr($name, 0, 7)) {
1465 if ($params[$name]) {
1466 $values[$index] = CRM_Core_PseudoConstant
::country($params[$name]);
1469 $values[$index] = '';
1472 elseif ('county' == substr($name, 0, 6)) {
1473 if ($params[$name]) {
1474 $values[$index] = CRM_Core_PseudoConstant
::county($params[$name]);
1477 $values[$index] = '';
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]);
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]];
1489 elseif ($name === 'preferred_communication_method') {
1490 $communicationFields = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1492 $pref = $params[$name];
1493 if (is_array($pref)) {
1494 foreach ($pref as $k => $v) {
1496 $compref[] = $communicationFields[$k];
1500 $values[$index] = implode(',', $compref);
1502 elseif ($name == 'contact_sub_type') {
1503 $values[$index] = implode(', ', $params[$name]);
1505 elseif ($name == 'group') {
1506 $groups = CRM_Contact_BAO_GroupContact
::getGroupList();
1508 foreach ($params[$name] as $gId => $dontCare) {
1510 $title[] = $groups[$gId];
1513 $values[$index] = implode(', ', $title);
1515 elseif ($name == 'tag') {
1516 $entityTags = $params[$name];
1517 $allTags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
1519 if (is_array($entityTags)) {
1520 foreach ($entityTags as $tagId => $dontCare) {
1521 $title[] = $allTags[$tagId];
1524 $values[$index] = implode(', ', $title);
1526 elseif ('participant_role_id' == $name OR
1527 'participant_role' == $name
1529 $roles = CRM_Event_PseudoConstant
::participantRole();
1530 $values[$index] = $roles[$params[$name]];
1532 elseif ('participant_status_id' == $name OR
1533 'participant_status' == $name
1535 $status = CRM_Event_PseudoConstant
::participantStatus();
1536 $values[$index] = $status[$params[$name]];
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);
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];
1551 elseif ($fieldName == 'im') {
1552 $providerName = NULL;
1553 if ($providerId = $detailName . '-provider_id') {
1554 $providerName = CRM_Utils_Array
::value($params[$providerId], $imProviders);
1556 if ($providerName) {
1557 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1560 $values[$index] = $params[$detailName];
1563 elseif ($fieldName == 'phone') {
1564 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1565 if (isset($params[$phoneExtField])) {
1566 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1569 $values[$index] = $params[$detailName];
1573 $values[$index] = $params[$detailName];
1577 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1578 if ($params[$name]) {
1579 $values[$index] = '[ x ]';
1583 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
1585 SELECT html_type, data_type
1586 FROM civicrm_custom_field
1589 $dao = CRM_Core_DAO
::executeQuery($query);
1591 $htmlType = $dao->html_type
;
1593 if ($htmlType == 'File') {
1594 $values[$index] = $params[$index];
1597 if ($dao->data_type
== 'Int' ||
1598 $dao->data_type
== 'Boolean'
1600 $v = $params[$name];
1601 if (!CRM_Utils_System
::isNull($v)) {
1602 $customVal = (int)$v;
1605 elseif ($dao->data_type
== 'Float') {
1606 $customVal = (float )($params[$name]);
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
);
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
);
1623 $customVal = $params[$name];
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
;
1630 $displayValue = CRM_Core_BAO_CustomField
::getDisplayValue($customVal, $cfID, $options);
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);
1638 //use difference of arrays
1639 if (empty($customValue) ||
!$customValue) {
1640 $values[$index] = '';
1643 $values[$index] = $displayValue;
1647 elseif ($name == 'home_URL' &&
1648 !empty($params[$name])
1650 $url = CRM_Utils_System
::fixURL($params[$name]);
1651 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
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]));
1658 $values[$index] = $params[$name];
1662 $profileFields[$name] = $field;
1668 * Build the array for Additional participant's information array of priamry and additional Ids
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
1676 * @param bool $skipCancel
1678 * @return array $customProfile array of Additional participant's info OR array of Ids.
1680 static function buildCustomProfile($participantId,
1684 $isIdsArray = FALSE,
1688 $customProfile = $additionalIDs = array();
1689 if (!$participantId) {
1690 CRM_Core_Error
::fatal(ts('Cannot find participant ID'));
1693 //set Ids of Primary Participant also.
1694 if ($isIdsArray && $contactId) {
1695 $additionalIDs[$participantId] = $contactId;
1698 //hack to skip cancelled participants, CRM-4320
1699 $where = "participant.registered_by_id={$participantId}";
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}";
1707 SELECT participant.id, participant.contact_id
1708 FROM civicrm_participant participant
1711 $dao = CRM_Core_DAO
::executeQuery($query);
1712 while ($dao->fetch()) {
1713 $additionalIDs[$dao->id
] = $dao->contact_id
;
1716 //return if only array is required.
1717 if ($isIdsArray && $contactId) {
1718 return $additionalIDs;
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();
1728 $isCustomProfile = TRUE;
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());
1735 list($profilePre, $groupTitles) = self
::buildCustomDisplay($preProfileID,
1736 'additionalCustomPre',
1746 $profile = $profilePre;
1747 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1749 $title = $groupTitles;
1753 list($profilePost, $groupTitles) = self
::buildCustomDisplay($postProfileID,
1754 'additionalCustomPost',
1764 if (isset($profilePre)) {
1765 $profile = array_merge($profilePre, $profilePost);
1767 $title = array_merge($title, $groupTitles);
1771 $profile = $profilePost;
1773 $title = $groupTitles;
1777 $profiles[] = $profile;
1780 $customProfile['title'] = $title;
1781 $customProfile['profile'] = $profiles;
1785 return $customProfile;
1788 /* Function to retrieve all events those having location block set.
1790 * @return array $events array of all events.
1795 public static function getLocationEvents() {
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
1807 $dao = CRM_Core_DAO
::executeQuery($query);
1808 while ($dao->fetch()) {
1809 $events[$dao->loc_block_id
] = $dao->title
;
1816 * @param int $locBlockId
1818 * @return int|null|string
1820 public static function countEventsUsingLocBlockId($locBlockId) {
1825 $locBlockId = CRM_Utils_Type
::escape($locBlockId, 'Integer');
1828 SELECT count(*) FROM civicrm_event ce
1829 WHERE ce.loc_block_id = $locBlockId";
1831 return CRM_Core_DAO
::singleValueQuery($query);
1835 * Check if event registration is valid according to permissions AND Dates
1837 * @param array $values
1838 * @param integer $eventID
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'
1847 return $hasPermission && self
::validRegistrationDate($values);
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));
1862 if ($startDate && $startDate >= $now) {
1865 if ($endDate && $endDate < $now) {
1868 if ($eventEnd && $eventEnd < $now) {
1875 /* Function to Show - Hide the Registration Link.
1877 * @param array $values key/value event info
1878 * @return boolean true if allow registration otherwise false
1885 public static function showHideRegistrationLink($values) {
1887 $session = CRM_Core_Session
::singleton();
1888 $contactID = $session->get('userID');
1889 $alreadyRegistered = FALSE;
1892 $params = array('contact_id' => $contactID);
1894 if ($eventId = CRM_Utils_Array
::value('id', $values['event'])) {
1895 $params['event_id'] = $eventId;
1897 if ($roleId = CRM_Utils_Array
::value('default_role_id', $values['event'])) {
1898 $params['role_id'] = $roleId;
1900 $alreadyRegistered = self
::checkRegistration($params);
1903 if (!empty($values['event']['allow_same_participant_emails']) ||
1911 /* Function to check if given contact is already registered.
1913 * @param array $params key/value participant info
1914 * @return boolean $alreadyRegistered true/false
1917 * @param array $params
1921 public static function checkRegistration($params) {
1922 $alreadyRegistered = FALSE;
1923 if (empty($params['contact_id'])) {
1924 return $alreadyRegistered;
1927 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
1929 $participant = new CRM_Event_DAO_Participant();
1930 $participant->copyValues($params);
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;
1939 return $alreadyRegistered;
1943 * Make sure that the user has permission to access this event
1945 * @param int $eventId
1948 * @return string the permission that the user has (or null)
1951 public static function checkPermission($eventId = NULL, $type = CRM_Core_Permission
::VIEW
) {
1952 static $permissions = NULL;
1954 if (empty($permissions)) {
1955 $allEvents = CRM_Event_PseudoConstant
::event(NULL, TRUE);
1956 $createdEvents = array();
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}"));
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);
1969 $permissions[CRM_Core_Permission
::EDIT
] = &CRM_ACL_API
::group(CRM_Core_Permission
::EDIT
, NULL, 'civicrm_event', $allEvents, $createdEvents);
1972 if (CRM_Core_Permission
::check('edit all events')) {
1973 $permissions[CRM_Core_Permission
::VIEW
] = array_keys($allEvents);
1976 if (CRM_Core_Permission
::check('access CiviEvent') &&
1977 CRM_Core_Permission
::check('view event participants')
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);
1984 $permissions[CRM_Core_Permission
::VIEW
] = &CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_event', $allEvents, $createdEvents);
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
]
1999 return in_array($eventId, $permissions[$type]) ?
TRUE : FALSE;
2002 return $permissions;
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
2009 * @param int $eventId the id of the event
2011 * @return array an array of email ids
2014 public static function getFromEmailIds($eventId = NULL) {
2015 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email
::getFromEmail();
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();
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']}>";
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),
2031 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2035 return $fromEmailValues;
2039 * Calculate event total seats occupied.
2041 * @param int $eventId event id.
2042 * @param sting $extraWhereClause extra filter on participants.
2044 * @return int event total seats w/ given criteria.
2047 public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
2048 if (empty($eventId)) {
2052 $extraWhereClause = trim($extraWhereClause);
2053 if (!empty($extraWhereClause)) {
2054 $extraWhereClause = " AND ( {$extraWhereClause} )";
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.
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
2078 GROUP BY participant.event_id";
2080 return (int)CRM_Core_DAO
::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
2084 * Retrieve event template default values to be set
2085 * as default values for current new event.
2087 * @param int $templateId event template id.
2089 * @return array of custom data defaults.
2091 public static function getTemplateDefaultValues($templateId) {
2092 $defaults = array();
2097 $templateParams = array('id' => $templateId);
2098 CRM_Event_BAO_Event
::retrieve($templateParams, $defaults);
2099 $fieldsToExclude = array(
2102 'default_discount_fee_id',
2108 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2113 * @param int $event_id
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);
2124 * Update the Campaign Id of all the participants of the given event
2126 * @param int $eventID event id.
2127 * @param int $eventCampaignID campaign id of that event
2129 public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
2131 $params[1] = array($eventID, 'Integer');
2133 if(empty($eventCampaignID)) {
2134 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2137 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2138 $params[2] = array($eventCampaignID, 'Integer');
2140 CRM_Core_DAO
::executeQuery($query, $params);
2144 * Get options for a given field.
2145 * @see CRM_Core_DAO::buildOptions
2147 * @param String $fieldName
2148 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
2149 * @param Array $props: whatever is known about this dao object
2151 * @return array|bool
2153 public static function buildOptions($fieldName, $context = NULL, $props = 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();
2162 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);