3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
35 class CRM_Event_BAO_Event
extends CRM_Event_DAO_Event
{
40 function __construct() {
41 parent
::__construct();
45 * Takes a bunch of params that are needed to match certain criteria and
46 * retrieves the relevant objects. Typically the valid params are only
47 * contact_id. We'll tweak this function to be more full featured over a period
48 * of time. This is the inverse function of create. It also stores all the retrieved
49 * values in the default array
51 * @param array $params (reference ) an assoc array of name/value pairs
52 * @param array $defaults (reference ) an assoc array to hold the flattened values
54 * @return object CRM_Event_BAO_ManageEvent object
58 static function retrieve(&$params, &$defaults) {
59 $event = new CRM_Event_DAO_Event();
60 $event->copyValues($params);
61 if ($event->find(TRUE)) {
62 CRM_Core_DAO
::storeValues($event, $defaults);
69 * update the is_active flag in the db
71 * @param int $id id of the database record
72 * @param boolean $is_active value we want to set the is_active field
74 * @return Object DAO object on sucess, null otherwise
77 static function setIsActive($id, $is_active) {
78 return CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
82 * function to add the event
84 * @param array $params reference array contains the values submitted by the form
91 static function add(&$params) {
92 CRM_Utils_System
::flushCache();
93 $financialTypeId = NULL;
94 if (!empty($params['id'])) {
95 CRM_Utils_Hook
::pre('edit', 'Event', $params['id'], $params);
96 if (empty($params['skipFinancialType'])) {
97 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $params['id'], 'financial_type_id');
101 CRM_Utils_Hook
::pre('create', 'Event', NULL, $params);
104 $event = new CRM_Event_DAO_Event();
106 $event->copyValues($params);
107 $result = $event->save();
109 if (!empty($params['id'])) {
110 CRM_Utils_Hook
::post('edit', 'Event', $event->id
, $event);
113 CRM_Utils_Hook
::post('create', 'Event', $event->id
, $event);
115 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
116 CRM_Price_BAO_PriceFieldValue
::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
122 * function to create the event
124 * @param array $params reference array contains the values submitted by the form
130 public static function create(&$params) {
131 $transaction = new CRM_Core_Transaction();
132 if (empty($params['is_template'])) {
133 $params['is_template'] = 0;
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');
142 $params['created_date'] = date('YmdHis');
145 $event = self
::add($params);
147 if (is_a($event, 'CRM_Core_Error')) {
148 CRM_Core_DAO
::transaction('ROLLBACK');
152 $session = CRM_Core_Session
::singleton();
153 $contactId = $session->get('userID');
155 $contactId = CRM_Utils_Array
::value('contact_id', $params);
158 // Log the information on successful add/edit of Event
160 'entity_table' => 'civicrm_event',
161 'entity_id' => $event->id
,
162 'modified_id' => $contactId,
163 'modified_date' => date('Ymd'),
166 CRM_Core_BAO_Log
::add($logParams);
168 if (!empty($params['custom']) &&
169 is_array($params['custom'])
171 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_event', $event->id
);
174 $transaction->commit();
180 * Function to delete the event
182 * @param int $id event id
188 static function del($id) {
193 CRM_Utils_Hook
::pre('delete', 'Event', $id, CRM_Core_DAO
::$_nullArray);
195 $extends = array('event');
196 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
197 foreach ($groupTree as $values) {
198 $query = "DELETE FROM " . $values['table_name'] . " WHERE entity_id = " . $id;
200 $params = array(1 => array($values['table_name'], 'string'),
201 2 => array($id, 'integer'),
204 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
207 // price set cleanup, CRM-5527
208 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_event', $id);
210 $event = new CRM_Event_DAO_Event();
213 if ($event->find(TRUE)) {
214 $locBlockId = $event->loc_block_id
;
215 $result = $event->delete();
217 if (!is_null($locBlockId)) {
218 self
::deleteEventLocBlock($locBlockId, $id);
221 CRM_Utils_Hook
::post('delete', 'Event', $id, $event);
229 * Function to delete the location block associated with an event,
230 * if not being used by any other event.
232 * @param int $loc_block_id location block id to be deleted
233 * @param int $eventid event id with which loc block is associated
239 static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
240 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
243 $query .= " AND ce.id != $eventId;";
246 $locCount = CRM_Core_DAO
::singleValueQuery($query);
248 if ($locCount == 0) {
249 CRM_Core_BAO_Location
::deleteLocBlock($locBlockId);
254 * Function to get current/future Events
256 * @param $all int 0 returns current and future events
257 * 1 if events all are required
258 * 2 returns events since 3 months ago
259 * @param $id int id of a specific event to return
260 * @param $isActive boolean true if you need only active events
261 * @param $checkPermission boolean true if you need to check permission else false
265 static function getEvents($all = 0,
268 $checkPermission = TRUE
271 SELECT `id`, `title`, `start_date`
273 WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
276 $query .= " AND `id` = {$id}";
279 // find only events ending in the future
280 $endDate = date('YmdHis');
282 AND ( `end_date` >= {$endDate} OR
284 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
289 // find only events starting in the last 3 months
290 $startDate = date('YmdHis', strtotime('3 months ago'));
291 $query .= " AND ( `start_date` >= {$startDate} OR start_date IS NULL )";
294 $query .= " AND civicrm_event.is_active = 1";
297 $query .= " ORDER BY title asc";
300 $dao = CRM_Core_DAO
::executeQuery($query);
301 while ($dao->fetch()) {
302 if ((!$checkPermission ||
303 CRM_Event_BAO_Event
::checkPermission($dao->id
)
307 $events[$dao->id
] = $dao->title
. ' - ' . CRM_Utils_Date
::customFormat($dao->start_date
);
315 * Function to get events Summary
319 * @return array Array of event summary values
321 static function getEventSummary() {
322 $eventSummary = $eventIds = array();
323 $config = CRM_Core_Config
::singleton();
325 // get permission and include them here
326 // does not scale, but rearranging code for now
327 // FIXME in a future release
328 $permissions = CRM_Event_BAO_Event
::checkPermission();
330 if (empty($permissions[CRM_Core_Permission
::VIEW
])) {
331 $eventSummary['total_events'] = 0;
332 return $eventSummary;
335 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission
::VIEW
])) . " ) ";
338 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
340 SELECT count(id) as total_events
342 WHERE civicrm_event.is_active = 1 AND
343 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
344 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
347 $dao = CRM_Core_DAO
::executeQuery($query);
350 $eventSummary['total_events'] = $dao->total_events
;
353 if (empty($eventSummary) ||
354 $dao->total_events
== 0
356 return $eventSummary;
359 //get the participant status type values.
360 $query = 'SELECT id, name, class FROM civicrm_participant_status_type';
361 $status = CRM_Core_DAO
::executeQuery($query);
362 $statusValues = array();
363 while ($status->fetch()) {
364 $statusValues[$status->id
]['id'] = $status->id
;
365 $statusValues[$status->id
]['name'] = $status->name
;
366 $statusValues[$status->id
]['class'] = $status->class;
369 // Get the Id of Option Group for Event Types
370 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
371 $optionGroupDAO->name
= 'event_type';
372 $optionGroupId = NULL;
373 if ($optionGroupDAO->find(TRUE)) {
374 $optionGroupId = $optionGroupDAO->id
;
378 SELECT civicrm_event.id as id, civicrm_event.title as event_title, civicrm_event.is_public as is_public,
379 civicrm_event.max_participants as max_participants, civicrm_event.start_date as start_date,
380 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,
381 civicrm_event.slot_label_id,
382 civicrm_event.summary as summary,
383 civicrm_pcp_block.id as is_pcp_enabled
385 LEFT JOIN civicrm_option_value ON (
386 civicrm_event.event_type_id = civicrm_option_value.value AND
387 civicrm_option_value.option_group_id = %1 )
388 LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_event.id AND civicrm_tell_friend.entity_table = 'civicrm_event' )
389 LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_event.id AND civicrm_pcp_block.entity_table = 'civicrm_event')
390 WHERE civicrm_event.is_active = 1 AND
391 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
392 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
394 GROUP BY civicrm_event.id
395 ORDER BY civicrm_event.start_date ASC
398 $eventParticipant = array();
402 'eventTitle' => 'event_title',
403 'isPublic' => 'is_public',
404 'maxParticipants' => 'max_participants',
405 'startDate' => 'start_date',
406 'endDate' => 'end_date',
407 'eventType' => 'event_type',
409 'participants' => 'participants',
410 'notCountedDueToRole' => 'notCountedDueToRole',
411 'notCountedDueToStatus' => 'notCountedDueToStatus',
412 'notCountedParticipants' => 'notCountedParticipants',
415 $params = array(1 => array($optionGroupId, 'Integer'));
416 $mappingID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', 'civicrm_event', 'id', 'entity_value');
417 $dao = CRM_Core_DAO
::executeQuery($query, $params);
418 while ($dao->fetch()) {
419 foreach ($properties as $property => $name) {
429 $eventSummary['events'][$dao->id
][$property] = $set;
433 if ($dao->$name && $config->mapAPIKey
) {
436 $params = array('entity_id' => $dao->id
, 'entity_table' => 'civicrm_event');
437 $values['location'] = CRM_Core_BAO_Location
::getValues($params, TRUE);
438 if (is_numeric(CRM_Utils_Array
::value('geo_code_1', $values['location']['address'][1])) ||
439 ($config->mapGeoCoding
&&
440 !empty($values['location']['address'][1]['city']) &&
441 !empty($values['location']['address'][1]['state_province_id'])
444 $set = CRM_Utils_System
::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
448 $eventSummary['events'][$dao->id
][$property] = $set;
449 if (in_array($dao->id
, $permissions[CRM_Core_Permission
::EDIT
])) {
450 $eventSummary['events'][$dao->id
]['configure'] = CRM_Utils_System
::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
456 $eventSummary['events'][$dao->id
][$property] = CRM_Utils_Date
::customFormat($dao->$name,
462 case 'notCountedDueToRole':
463 case 'notCountedDueToStatus':
464 case 'notCountedParticipants':
467 if ($name == 'participants') {
468 $propertyCnt = self
::getParticipantCount($dao->id
);
470 $set = CRM_Utils_System
::url('civicrm/event/search',
471 "reset=1&force=1&event=$dao->id&status=true&role=true"
475 elseif ($name == 'notCountedParticipants') {
476 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, TRUE, FALSE);
478 // FIXME : selector fail to search w/ OR operator.
479 // $set = CRM_Utils_System::url( 'civicrm/event/search',
480 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
483 elseif ($name == 'notCountedDueToStatus') {
484 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, FALSE, FALSE);
486 $set = CRM_Utils_System
::url('civicrm/event/search',
487 "reset=1&force=1&event=$dao->id&status=false"
492 $propertyCnt = self
::getParticipantCount($dao->id
, FALSE, FALSE, TRUE, FALSE);
494 $set = CRM_Utils_System
::url('civicrm/event/search',
495 "reset=1&force=1&event=$dao->id&role=false"
500 $eventSummary['events'][$dao->id
][$property] = $propertyCnt;
501 $eventSummary['events'][$dao->id
][$name . '_url'] = $set;
505 $eventSummary['events'][$dao->id
][$property] = $dao->$name;
510 // prepare the area for per-status participant counts
511 $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
512 $eventSummary['events'][$dao->id
]['statuses'] = array_fill_keys($statusClasses, array());
514 $eventSummary['events'][$dao->id
]['friend'] = $dao->is_friend_active
;
515 $eventSummary['events'][$dao->id
]['is_monetary'] = $dao->is_monetary
;
516 $eventSummary['events'][$dao->id
]['is_online_registration'] = $dao->is_online_registration
;
517 $eventSummary['events'][$dao->id
]['is_show_location'] = $dao->is_show_location
;
518 $eventSummary['events'][$dao->id
]['is_subevent'] = $dao->slot_label_id
;
519 $eventSummary['events'][$dao->id
]['is_pcp_enabled'] = $dao->is_pcp_enabled
;
520 $eventSummary['events'][$dao->id
]['reminder'] = CRM_Core_BAO_ActionSchedule
::isConfigured($dao->id
, $mappingID);
522 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
523 foreach ($statusValues as $statusId => $statusValue) {
524 if (!array_key_exists($statusId, $statusTypes)) {
527 $class = $statusValue['class'];
528 $statusCount = self
::eventTotalSeats($dao->id
, "( participant.status_id = {$statusId} )");
530 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
531 $statusInfo = array('url' => CRM_Utils_System
::url('civicrm/event/search', $urlString),
532 'name' => $statusValue['name'],
533 'count' => $statusCount,
535 $eventSummary['events'][$dao->id
]['statuses'][$class][] = $statusInfo;
540 $countedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
541 $nonCountedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
542 $countedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
543 $nonCountedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
545 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
546 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
548 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
549 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
550 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
551 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
553 return $eventSummary;
557 * Function to get participant count
559 * @param boolean $considerStatus consider status for participant count.
560 * @param boolean $status consider counted participant.
561 * @param boolean $considerRole consider role for participant count.
562 * @param boolean $role consider counted( is filter role) participant.
563 * @param array $eventIds consider participants from given events.
564 * @param boolean $countWithStatus retrieve participant count w/ each participant status.
568 * @return array array with count of participants for each event based on status/role
570 public static function getParticipantCount($eventId,
571 $considerStatus = TRUE,
573 $considerRole = TRUE,
577 // consider both role and status for counted participants, CRM-4924.
579 // not counted participant.
580 if ($considerStatus && $considerRole && !$status && !$role) {
584 if ($considerStatus) {
585 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
586 $statusClause = 'NOT IN';
588 $statusClause = 'IN';
590 $status = implode(',', array_keys($statusTypes));
591 if (empty($status)) {
594 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
598 $roleTypes = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
599 $roleClause = 'NOT IN';
603 $roles = implode(',', array_keys($roleTypes));
607 $clause[] = "participant.role_id {$roleClause} ( $roles )";
611 if (!empty($clause)) {
612 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
615 return self
::eventTotalSeats($eventId, $sqlClause);
619 * function to get the information to map a event
621 * @param array $ids the list of ids for which we want map info
623 * @return null|string title of the event
627 static function &getMapInfo(&$id) {
631 civicrm_event.id AS event_id,
632 civicrm_event.title AS display_name,
633 civicrm_address.street_address AS street_address,
634 civicrm_address.city AS city,
635 civicrm_address.postal_code AS postal_code,
636 civicrm_address.postal_code_suffix AS postal_code_suffix,
637 civicrm_address.geo_code_1 AS latitude,
638 civicrm_address.geo_code_2 AS longitude,
639 civicrm_state_province.abbreviation AS state,
640 civicrm_country.name AS country,
641 civicrm_location_type.name AS location_type
644 LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )
645 LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )
646 LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )
647 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
648 LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )
649 WHERE civicrm_address.geo_code_1 IS NOT NULL
650 AND civicrm_address.geo_code_2 IS NOT NULL
651 AND civicrm_event.id = " . CRM_Utils_Type
::escape($id, 'Integer');
653 $dao = new CRM_Core_DAO();
656 $locations = array();
658 $config = CRM_Core_Config
::singleton();
660 while ($dao->fetch()) {
663 $location['displayName'] = addslashes($dao->display_name
);
664 $location['lat'] = $dao->latitude
;
665 $location['marker_class'] = 'Event';
666 $location['lng'] = $dao->longitude
;
668 $params = array('entity_id' => $id, 'entity_table' => 'civicrm_event');
669 $addressValues = CRM_Core_BAO_Location
::getValues($params, TRUE);
670 $location['address'] = str_replace(array("\r", "\n"), '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
672 $location['url'] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
);
673 $location['location_type'] = $dao->location_type
;
674 $eventImage = '<img src="' . $config->resourceBase
. 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
675 $location['image'] = $eventImage;
676 $location['displayAddress'] = str_replace('<br />', ', ', $location['address']);
677 $locations[] = $location;
683 * function to get the complete information for one or more events
685 * @param date $start get events with start date >= this date
686 * @param integer $type get events on the a specific event type (by event_type_id)
687 * @param integer $eventId return a single event - by event id
688 * @param date $end also get events with end date >= this date
689 * @param boolean $onlyPublic include public events only, default TRUE
691 * @return array $all array of all the events that are searched
695 static function &getCompleteInfo(
702 $publicCondition = NULL;
704 $publicCondition = " AND civicrm_event.is_public = 1";
708 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
710 // get events with start_date >= requested start
711 $startDate = CRM_Utils_Type
::escape($start, 'Date');
712 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
716 // also get events with end_date <= requested end
717 $endDate = CRM_Utils_Type
::escape($end, 'Date');
718 $dateCondition .= " AND ( civicrm_event.end_date <= '{$endDate}' ) ";
721 // CRM-9421 and CRM-8620 Default mode for ical/rss feeds. No start or end filter passed.
722 // Need to exclude old events with only start date
723 // and not exclude events in progress (start <= today and end >= today). DGG
724 if (empty($start) && empty($end)) {
725 // get events with end date >= today, not sure of this logic
726 // but keeping this for backward compatibility as per issue CRM-5133
727 $today = date("Y-m-d G:i:s");
728 $dateCondition .= " AND ( civicrm_event.end_date >= '{$today}' OR civicrm_event.start_date >= '{$today}' ) ";
732 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
735 // Get the Id of Option Group for Event Types
736 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
737 $optionGroupDAO->name
= 'event_type';
738 $optionGroupId = NULL;
739 if ($optionGroupDAO->find(TRUE)) {
740 $optionGroupId = $optionGroupDAO->id
;
745 civicrm_event.id as event_id,
746 civicrm_email.email as email,
747 civicrm_event.title as title,
748 civicrm_event.summary as summary,
749 civicrm_event.start_date as start,
750 civicrm_event.end_date as end,
751 civicrm_event.description as description,
752 civicrm_event.is_show_location as is_show_location,
753 civicrm_event.is_online_registration as is_online_registration,
754 civicrm_event.registration_link_text as registration_link_text,
755 civicrm_event.registration_start_date as registration_start_date,
756 civicrm_event.registration_end_date as registration_end_date,
757 civicrm_option_value.label as event_type,
758 civicrm_address.name as address_name,
759 civicrm_address.street_address as street_address,
760 civicrm_address.supplemental_address_1 as supplemental_address_1,
761 civicrm_address.supplemental_address_2 as supplemental_address_2,
762 civicrm_address.city as city,
763 civicrm_address.postal_code as postal_code,
764 civicrm_address.postal_code_suffix as postal_code_suffix,
765 civicrm_state_province.abbreviation as state,
766 civicrm_country.name AS country
768 LEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id
769 LEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id
770 LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
771 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
772 LEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id
773 LEFT JOIN civicrm_option_value ON (
774 civicrm_event.event_type_id = civicrm_option_value.value AND
775 civicrm_option_value.option_group_id = %1 )
776 WHERE civicrm_event.is_active = 1
777 AND (is_template = 0 OR is_template IS NULL)
781 if (isset($typeCondition)) {
782 $query .= $typeCondition;
785 if (isset($eventId)) {
786 $query .= " AND civicrm_event.id =$eventId ";
788 $query .= " ORDER BY civicrm_event.start_date ASC";
791 $params = array(1 => array($optionGroupId, 'Integer'));
792 $dao = CRM_Core_DAO
::executeQuery($query, $params);
794 $config = CRM_Core_Config
::singleton();
796 $baseURL = parse_url($config->userFrameworkBaseURL
);
797 $url = "@" . $baseURL['host'];
798 if (!empty($baseURL['path'])) {
799 $url .= substr($baseURL['path'], 0, -1);
802 // check 'view event info' permission
803 $permissions = CRM_Core_Permission
::event(CRM_Core_Permission
::VIEW
);
805 // check if we're in shopping cart mode for events
806 $enable_cart = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
,
810 while ($dao->fetch()) {
811 if (!empty($permissions) && in_array($dao->event_id
, $permissions)) {
813 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL
) . $url;
815 $info['title'] = $dao->title
;
816 $info['event_id'] = $dao->event_id
;
817 $info['summary'] = $dao->summary
;
818 $info['description'] = $dao->description
;
819 $info['start_date'] = $dao->start
;
820 $info['end_date'] = $dao->end
;
821 $info['contact_email'] = $dao->email
;
822 $info['event_type'] = $dao->event_type
;
823 $info['is_show_location'] = $dao->is_show_location
;
824 $info['is_online_registration'] = $dao->is_online_registration
;
825 $info['registration_link_text'] = $dao->registration_link_text
;
826 $info['registration_start_date'] = $dao->registration_start_date
;
827 $info['registration_end_date'] = $dao->registration_end_date
;
832 'address_name' => $dao->address_name
,
833 'street_address' => $dao->street_address
,
834 'supplemental_address_1' => $dao->supplemental_address_1
,
835 'supplemental_address_2' => $dao->supplemental_address_2
,
836 'city' => $dao->city
,
837 'state_province' => $dao->state
,
838 'postal_code' => $dao->postal_code
,
839 'postal_code_suffix' => $dao->postal_code_suffix
,
840 'country' => $dao->country
,
844 CRM_Utils_String
::append($address, ', ',
845 CRM_Utils_Address
::format($addrFields)
847 $info['location'] = $address;
848 $info['url'] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
851 $reg = CRM_Event_Cart_BAO_EventInCart
::get_registration_link($dao->event_id
);
852 $info['registration_link'] = CRM_Utils_System
::url($reg['path'], $reg['query'], TRUE);
853 $info['registration_link_text'] = $reg['label'];
864 * This function is to make a copy of a Event, including
865 * all the fields in the event Wizard
867 * @param int $id the event id to copy
868 * obj $newEvent object of CRM_Event_DAO_Event
869 * boolean $afterCreate call to copy after the create function
873 static function copy($id, $newEvent = NULL, $afterCreate = FALSE) {
875 $defaults = $eventValues = array();
877 //get the require event values.
878 $eventParams = array('id' => $id);
879 $returnProperties = array('loc_block_id', 'is_show_location', 'default_fee_id', 'default_discount_fee_id', 'is_template');
881 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
883 // since the location is sharable, lets use the same loc_block_id.
884 $locBlockId = CRM_Utils_Array
::value('loc_block_id', $eventValues);
886 $fieldsFix = ($afterCreate) ?
array( ) : array('prefix' => array('title' => ts('Copy of') . ' '));
887 if (empty($eventValues['is_show_location'])) {
888 $fieldsFix['prefix']['is_show_location'] = 0;
891 if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
892 $copyEvent = $newEvent;
895 if (!isset($copyEvent)) {
896 $copyEvent = &CRM_Core_DAO
::copyGeneric('CRM_Event_DAO_Event',
900 ($locBlockId) ?
$locBlockId : NULL,
905 CRM_Price_BAO_PriceSet
::copyPriceSet('civicrm_event', $id, $copyEvent->id
);
906 $copyUF = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_UFJoin',
909 'entity_table' => 'civicrm_event',
911 array('entity_id' => $copyEvent->id
)
914 $copyTellFriend = &CRM_Core_DAO
::copyGeneric('CRM_Friend_DAO_Friend',
917 'entity_table' => 'civicrm_event',
919 array('entity_id' => $copyEvent->id
)
922 $copyPCP = &CRM_Core_DAO
::copyGeneric('CRM_PCP_DAO_PCPBlock',
925 'entity_table' => 'civicrm_event',
927 array('entity_id' => $copyEvent->id
),
928 array('replace' => array('target_entity_id' => $copyEvent->id
))
931 if ($eventValues['is_template']) {
932 $field = 'event_template';
935 $field = 'civicrm_event';
937 $mappingId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
938 $oldData = array('entity_value' => $id, 'mapping_id' => $mappingId);
939 if ($copyEvent->is_template
== 1) {
940 $field = 'event_template';
943 $field = 'civicrm_event';
945 $copyMappingId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
946 $newData = array('entity_value' => $copyEvent->id
, 'mapping_id' => $copyMappingId);
947 $copyReminder = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_ActionSchedule',
954 $extends = array('event');
955 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
957 foreach ($groupTree as $groupID => $group) {
958 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
959 foreach ($group['fields'] as $fieldID => $field) {
960 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
964 foreach ($table as $tableName => $tableColumns) {
965 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
966 $tableColumns[0] = $copyEvent->id
;
967 $select = 'SELECT ' . implode(', ', $tableColumns);
968 $from = ' FROM ' . $tableName;
969 $where = " WHERE {$tableName}.entity_id = {$id}";
970 $query = $insert . $select . $from . $where;
971 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
977 CRM_Utils_System
::flushCache();
979 CRM_Utils_Hook
::copy('Event', $copyEvent);
985 * This is sometimes called in a loop (during event search)
986 * hence we cache the values to prevent repeated calls to the db
988 static function isMonetary($id) {
989 static $isMonetary = array();
990 if (!array_key_exists($id, $isMonetary)) {
991 $isMonetary[$id] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event',
996 return $isMonetary[$id];
1000 * This is sometimes called in a loop (during event search)
1001 * hence we cache the values to prevent repeated calls to the db
1003 static function usesPriceSet($id) {
1004 static $usesPriceSet = array();
1005 if (!array_key_exists($id, $usesPriceSet)) {
1006 $usesPriceSet[$id] = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $id);
1008 return $usesPriceSet[$id];
1012 * Process that send e-mails
1017 static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
1019 $template = CRM_Core_Smarty
::singleton();
1021 'custom_pre_id' => $values['custom_pre_id'],
1022 'custom_post_id' => $values['custom_post_id'],
1025 //get the params submitted by participant.
1026 $participantParams = CRM_Utils_Array
::value($participantId, $values['params'], array());
1028 if (!$returnMessageText) {
1029 //send notification email if field values are set (CRM-1941)
1030 foreach ($gIds as $key => $gIdValues) {
1032 if (!is_array($gIdValues)) {
1033 $gIdValues = array( $gIdValues );
1036 foreach ($gIdValues as $gId) {
1037 $email = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1039 //get values of corresponding profile fields for notification
1040 list($profileValues) = self
::buildCustomDisplay($gId,
1049 list($profileValues) = $profileValues;
1052 'values' => $profileValues,
1055 CRM_Core_BAO_UFGroup
::commonSendMail($contactID, $val);
1062 if ($values['event']['is_email_confirm'] ||
$returnMessageText) {
1063 list($displayName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1065 //send email only when email is present
1066 if (isset($email) ||
$returnMessageText) {
1067 $preProfileID = CRM_Utils_Array
::value('custom_pre_id', $values);
1068 $postProfileID = CRM_Utils_Array
::value('custom_post_id', $values);
1070 if (!empty($values['params']['additionalParticipant'])) {
1071 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values, $preProfileID );
1072 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values, $postProfileID );
1075 self
::buildCustomDisplay($preProfileID,
1085 self
::buildCustomDisplay($postProfileID,
1095 $sessions = CRM_Event_Cart_BAO_Conference
::get_participant_sessions($participantId);
1097 $tplParams = array_merge($values, $participantParams, array(
1099 'confirm_email_text' => CRM_Utils_Array
::value('confirm_email_text', $values['event']),
1100 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $values['event']),
1101 'contributeMode' => NULL,
1102 'participantID' => $participantId,
1103 'conference_sessions' => $sessions,
1106 // CRM-13890 : NOTE wait list condition need to be given so that
1107 // wait list message is shown properly in email i.e. WRT online event registration template
1108 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
1109 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id');
1110 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($statusId, NULL, 'label');
1113 $sendTemplateParams = array(
1114 'groupName' => 'msg_tpl_workflow_event',
1115 'valueName' => 'event_online_receipt',
1116 'contactId' => $contactID,
1117 'isTest' => $isTest,
1118 'tplParams' => $tplParams,
1119 'PDFFilename' => ts('confirmation').'.pdf',
1122 // address required during receipt processing (pdf and email receipt)
1123 if ($displayAddress = CRM_Utils_Array
::value('address', $values)) {
1124 $sendTemplateParams['tplParams']['address'] = $displayAddress;
1125 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1128 // set lineItem details
1129 if ($lineItem = CRM_Utils_Array
::value('lineItem', $values)) {
1130 // check if additional prticipant, if so filter only to relevant ones
1132 if (!empty($values['params']['additionalParticipant'])) {
1133 $ownLineItems = array( );
1134 foreach ( $lineItem as $liKey => $liValue ) {
1135 $firstElement = array_pop( $liValue );
1136 if ( $firstElement['entity_id'] == $participantId ) {
1137 $ownLineItems[0] = $lineItem[$liKey];
1141 if ( ! empty( $ownLineItems ) ) {
1142 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1146 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1150 if ($returnMessageText) {
1151 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1153 'subject' => $subject,
1155 'to' => $displayName,
1160 $sendTemplateParams['from'] = CRM_Utils_Array
::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array
::value('confirm_from_email', $values['event']) . ">";
1161 $sendTemplateParams['toName'] = $displayName;
1162 $sendTemplateParams['toEmail'] = $email;
1163 $sendTemplateParams['autoSubmitted'] = TRUE;
1164 $sendTemplateParams['cc'] = CRM_Utils_Array
::value('cc_confirm',
1167 $sendTemplateParams['bcc'] = CRM_Utils_Array
::value('bcc_confirm',
1170 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1177 * Function to add the custom fields OR array of participant's
1183 static function buildCustomDisplay($id,
1189 $isCustomProfile = FALSE,
1190 $participantParams = array()
1193 return array(NULL, NULL);
1196 if (!is_array($id)) {
1197 $id = CRM_Utils_Type
::escape($id, 'Positive');
1198 $profileIds = array($id);
1204 foreach ($profileIds as $gid) {
1205 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $cid)) {
1207 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
,
1208 NULL, NULL, FALSE, NULL,
1209 FALSE, NULL, CRM_Core_Permission
::CREATE
,
1213 //this condition is added, since same contact can have multiple event registrations..
1214 $params = array(array('participant_id', '=', $participantId, 0, 0));
1216 //add participant id
1217 $fields['participant_id'] = array(
1218 'name' => 'participant_id',
1219 'title' => 'Participant Id',
1221 //check whether its a text drive
1223 $params[] = array('participant_test', '=', 1, 0, 0);
1226 //display campaign on thankyou page.
1227 if (array_key_exists('participant_campaign_id', $fields)) {
1228 if ($participantId) {
1229 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1233 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1234 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array
::value($campaignId,
1238 unset($fields['participant_campaign_id']);
1242 foreach ($fields as $k => $v) {
1244 $groupTitle = $v['groupTitle'];
1246 // suppress all file fields from display
1248 CRM_Utils_Array
::value('data_type', $v, '') == 'File' ||
1249 CRM_Utils_Array
::value('name', $v, '') == 'image_URL' ||
1250 CRM_Utils_Array
::value('field_type', $v) == 'Formatting'
1257 $groupTitles[] = $groupTitle;
1259 //display profile groups those are subscribed by participant.
1260 if (($groups = CRM_Utils_Array
::value('group', $participantParams)) &&
1264 foreach ($groups as $grpId => $isSelected) {
1269 if (!empty($grpIds)) {
1270 //get the group titles.
1271 $grpTitles = array();
1272 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1273 $grp = CRM_Core_DAO
::executeQuery($query);
1274 while ($grp->fetch()) {
1275 $grpTitles[] = $grp->title
;
1277 if (!empty($grpTitles) &&
1278 CRM_Utils_Array
::value('title', CRM_Utils_Array
::value('group', $fields))
1280 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1282 unset($fields['group']);
1286 CRM_Core_BAO_UFGroup
::getValues($cid, $fields, $values, FALSE, $params);
1288 if (isset($fields['participant_status_id']['title']) &&
1289 isset($values[$fields['participant_status_id']['title']]) &&
1290 is_numeric($values[$fields['participant_status_id']['title']])
1293 $status = CRM_Event_PseudoConstant
::participantStatus();
1294 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1297 if (isset($fields['participant_role_id']['title']) &&
1298 isset($values[$fields['participant_role_id']['title']]) &&
1299 is_numeric($values[$fields['participant_role_id']['title']])
1302 $roles = CRM_Event_PseudoConstant
::participantRole();
1303 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1306 if (isset($fields['participant_register_date']['title']) &&
1307 isset($values[$fields['participant_register_date']['title']])
1309 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date
::customFormat($values[$fields['participant_register_date']['title']]);
1312 //handle fee_level for price set
1313 if (isset($fields['participant_fee_level']['title']) &&
1314 isset($values[$fields['participant_fee_level']['title']])
1316 $feeLevel = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1317 $values[$fields['participant_fee_level']['title']]
1319 foreach ($feeLevel as $key => $value) {
1321 unset($feeLevel[$key]);
1324 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
1327 unset($values[$fields['participant_id']['title']]);
1334 $template->assign($name, $val);
1337 if (count($groupTitles)) {
1338 $template->assign($name . '_grouptitle', $groupTitles);
1341 //return if we only require array of participant's info.
1342 if ($isCustomProfile) {
1344 return array($val, $groupTitles);
1353 * Function to build the array for display the profile fields
1355 * @param array $params key value.
1356 * @param int $gid profile Id
1357 * @param array $groupTitle Profile Group Title.
1358 * @param array $values formatted array of key value
1364 static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
1366 $config = CRM_Core_Config
::singleton();
1367 $session = CRM_Core_Session
::singleton();
1368 $contactID = $session->get('userID');
1370 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $contactID)) {
1371 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
);
1375 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::ADD
);
1378 foreach ($fields as $v) {
1379 if (!empty($v['groupTitle'])) {
1380 $groupTitle['groupTitle'] = $v['groupTitle'];
1385 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1386 //start of code to set the default values
1387 foreach ($fields as $name => $field) {
1389 // skip fields that should not be displayed separately
1390 if ($field['skipDisplay']) {
1394 $index = $field['title'];
1395 if ($name === 'organization_name') {
1396 $values[$index] = $params[$name];
1399 if ('state_province' == substr($name, 0, 14)) {
1400 if ($params[$name]) {
1401 $values[$index] = CRM_Core_PseudoConstant
::stateProvince($params[$name]);
1404 $values[$index] = '';
1407 elseif ('date' == substr($name, -4)) {
1408 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::processDate($params[$name]),
1409 $config->dateformatFull
);
1411 elseif ('country' == substr($name, 0, 7)) {
1412 if ($params[$name]) {
1413 $values[$index] = CRM_Core_PseudoConstant
::country($params[$name]);
1416 $values[$index] = '';
1419 elseif ('county' == substr($name, 0, 6)) {
1420 if ($params[$name]) {
1421 $values[$index] = CRM_Core_PseudoConstant
::county($params[$name]);
1424 $values[$index] = '';
1427 elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
1428 $values[$index] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
1430 elseif (in_array($name, array(
1431 'addressee', 'email_greeting', 'postal_greeting'))) {
1432 $filterCondition = array('greeting_type' => $name);
1433 $greeting = CRM_Core_PseudoConstant
::greeting($filterCondition);
1434 $values[$index] = $greeting[$params[$name]];
1436 elseif ($name === 'preferred_communication_method') {
1437 $communicationFields = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1439 $pref = $params[$name];
1440 if (is_array($pref)) {
1441 foreach ($pref as $k => $v) {
1443 $compref[] = $communicationFields[$k];
1447 $values[$index] = implode(',', $compref);
1449 elseif ($name == 'contact_sub_type') {
1450 $values[$index] = implode(', ', $params[$name]);
1452 elseif ($name == 'group') {
1453 $groups = CRM_Contact_BAO_GroupContact
::getGroupList();
1455 foreach ($params[$name] as $gId => $dontCare) {
1457 $title[] = $groups[$gId];
1460 $values[$index] = implode(', ', $title);
1462 elseif ($name == 'tag') {
1463 $entityTags = $params[$name];
1464 $allTags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
1466 if (is_array($entityTags)) {
1467 foreach ($entityTags as $tagId => $dontCare) {
1468 $title[] = $allTags[$tagId];
1471 $values[$index] = implode(', ', $title);
1473 elseif ('participant_role_id' == $name OR
1474 'participant_role' == $name
1476 $roles = CRM_Event_PseudoConstant
::participantRole();
1477 $values[$index] = $roles[$params[$name]];
1479 elseif ('participant_status_id' == $name OR
1480 'participant_status' == $name
1482 $status = CRM_Event_PseudoConstant
::participantStatus();
1483 $values[$index] = $status[$params[$name]];
1485 elseif (substr($name, -11) == 'campaign_id') {
1486 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($params[$name]);
1487 $values[$index] = CRM_Utils_Array
::value($params[$name], $campaigns);
1489 elseif (strpos($name, '-') !== FALSE) {
1490 list($fieldName, $id) = CRM_Utils_System
::explode('-', $name, 2);
1491 $detailName = str_replace(' ', '_', $name);
1492 if (in_array($fieldName, array(
1493 'state_province', 'country', 'county'))) {
1494 $values[$index] = $params[$detailName];
1495 $idx = $detailName . '_id';
1496 $values[$index] = $params[$idx];
1498 elseif ($fieldName == 'im') {
1499 $providerName = NULL;
1500 if ($providerId = $detailName . '-provider_id') {
1501 $providerName = CRM_Utils_Array
::value($params[$providerId], $imProviders);
1503 if ($providerName) {
1504 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1507 $values[$index] = $params[$detailName];
1510 elseif ($fieldName == 'phone') {
1511 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1512 if (isset($params[$phoneExtField])) {
1513 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1516 $values[$index] = $params[$detailName];
1520 $values[$index] = $params[$detailName];
1524 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1525 if ($params[$name]) {
1526 $values[$index] = '[ x ]';
1530 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
1532 SELECT html_type, data_type
1533 FROM civicrm_custom_field
1536 $dao = CRM_Core_DAO
::executeQuery($query);
1538 $htmlType = $dao->html_type
;
1540 if ($htmlType == 'File') {
1541 $values[$index] = $params[$index];
1544 if ($dao->data_type
== 'Int' ||
1545 $dao->data_type
== 'Boolean'
1547 $v = $params[$name];
1548 if (!CRM_Utils_System
::isNull($v)) {
1549 $customVal = (int)$v;
1552 elseif ($dao->data_type
== 'Float') {
1553 $customVal = (float )($params[$name]);
1555 elseif ($dao->data_type
== 'Date') {
1556 //@todo note the currently we are using default date time formatting. Since you can select/set
1557 // different date and time format specific to custom field we should consider fixing this
1558 // sometime in the future
1559 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1560 CRM_Utils_Date
::processDate($params[$name]), $config->dateformatFull
);
1562 if (!empty($params[$name . '_time'])) {
1563 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1564 CRM_Utils_Date
::processDate($params[$name], $params[$name . '_time']),
1565 $config->dateformatDatetime
);
1570 $customVal = $params[$name];
1572 //take the custom field options
1573 $returnProperties = array($name => 1);
1574 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
1575 $options = &$query->_options
;
1577 $displayValue = CRM_Core_BAO_CustomField
::getDisplayValue($customVal, $cfID, $options);
1579 //Hack since we dont have function to check empty.
1580 //FIXME in 2.3 using crmIsEmptyArray()
1581 $customValue = TRUE;
1582 if (is_array($customVal) && is_array($displayValue)) {
1583 $customValue = array_diff($customVal, $displayValue);
1585 //use difference of arrays
1586 if (empty($customValue) ||
!$customValue) {
1587 $values[$index] = '';
1590 $values[$index] = $displayValue;
1594 elseif ($name == 'home_URL' &&
1595 !empty($params[$name])
1597 $url = CRM_Utils_System
::fixURL($params[$name]);
1598 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1600 elseif (in_array($name, array(
1601 'birth_date', 'deceased_date', 'participant_register_date'))) {
1602 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::format($params[$name]));
1605 $values[$index] = $params[$name];
1609 $profileFields[$name] = $field;
1615 * Function to build the array for Additional participant's information array of priamry and additional Ids
1617 *@param int $participantId id of Primary participant
1618 *@param array $values key/value event info
1619 *@param int $contactId contact id of Primary participant
1620 *@param boolean $isTest whether test or live transaction
1621 *@param boolean $isIdsArray to return an array of Ids
1623 *@return array $customProfile array of Additional participant's info OR array of Ids.
1626 static function buildCustomProfile($participantId,
1630 $isIdsArray = FALSE,
1634 $customProfile = $additionalIDs = array();
1635 if (!$participantId) {
1636 CRM_Core_Error
::fatal(ts('Cannot find participant ID'));
1639 //set Ids of Primary Participant also.
1640 if ($isIdsArray && $contactId) {
1641 $additionalIDs[$participantId] = $contactId;
1644 //hack to skip cancelled participants, CRM-4320
1645 $where = "participant.registered_by_id={$participantId}";
1647 $cancelStatusId = 0;
1648 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1649 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1650 $where .= " AND participant.status_id != {$cancelStatusId}";
1653 SELECT participant.id, participant.contact_id
1654 FROM civicrm_participant participant
1657 $dao = CRM_Core_DAO
::executeQuery($query);
1658 while ($dao->fetch()) {
1659 $additionalIDs[$dao->id
] = $dao->contact_id
;
1662 //return if only array is required.
1663 if ($isIdsArray && $contactId) {
1664 return $additionalIDs;
1667 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values);
1668 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values);
1669 //else build array of Additional participant's information.
1670 if (count($additionalIDs)) {
1671 if ($preProfileID ||
$postProfileID) {
1672 $template = CRM_Core_Smarty
::singleton();
1674 $isCustomProfile = TRUE;
1676 $title = $groupTitles = array();
1677 foreach ($additionalIDs as $pId => $cId) {
1678 //get the params submitted by participant.
1679 $participantParams = CRM_Utils_Array
::value($pId, $values['params'], array());
1681 list($profilePre, $groupTitles) = self
::buildCustomDisplay($preProfileID,
1682 'additionalCustomPre',
1692 $profile = $profilePre;
1693 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1695 $title = $groupTitles;
1699 list($profilePost, $groupTitles) = self
::buildCustomDisplay($postProfileID,
1700 'additionalCustomPost',
1710 if (isset($profilePre)) {
1711 $profile = array_merge($profilePre, $profilePost);
1713 $title = array_merge($title, $groupTitles);
1717 $profile = $profilePost;
1719 $title = $groupTitles;
1723 $profiles[] = $profile;
1726 $customProfile['title'] = $title;
1727 $customProfile['profile'] = $profiles;
1731 return $customProfile;
1734 /* Function to retrieve all events those having location block set.
1736 * @return array $events array of all events.
1738 static function getLocationEvents() {
1742 SELECT CONCAT_WS(' :: ' , ca.name, ca.street_address, ca.city, sp.name) title, ce.loc_block_id
1743 FROM civicrm_event ce
1744 INNER JOIN civicrm_loc_block lb ON ce.loc_block_id = lb.id
1745 INNER JOIN civicrm_address ca ON lb.address_id = ca.id
1746 LEFT JOIN civicrm_state_province sp ON ca.state_province_id = sp.id
1747 ORDER BY sp.name, ca.city, ca.street_address ASC
1750 $dao = CRM_Core_DAO
::executeQuery($query);
1751 while ($dao->fetch()) {
1752 $events[$dao->loc_block_id
] = $dao->title
;
1758 static function countEventsUsingLocBlockId($locBlockId) {
1763 $locBlockId = CRM_Utils_Type
::escape($locBlockId, 'Integer');
1766 SELECT count(*) FROM civicrm_event ce
1767 WHERE ce.loc_block_id = $locBlockId";
1769 return CRM_Core_DAO
::singleValueQuery($query);
1772 static function validRegistrationRequest($values, $contactID) {
1773 // check that the user has permission to register for this event
1774 $hasPermission = CRM_Core_Permission
::event(CRM_Core_Permission
::EDIT
,
1778 return $hasPermission && self
::validRegistrationDate($values);
1781 static function validRegistrationDate(&$values) {
1782 // make sure that we are between registration start date and registration end date
1783 $startDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_start_date', $values));
1784 $endDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_end_date', $values));
1785 $eventEnd = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('end_date', $values));
1788 if ($startDate && $startDate >= $now) {
1791 if ($endDate && $endDate < $now) {
1794 if ($eventEnd && $eventEnd < $now) {
1801 /* Function to Show - Hide the Registration Link.
1803 * @param array $values key/value event info
1804 * @return boolean true if allow registration otherwise false
1807 static function showHideRegistrationLink($values) {
1809 $session = CRM_Core_Session
::singleton();
1810 $contactID = $session->get('userID');
1811 $alreadyRegistered = FALSE;
1814 $params = array('contact_id' => $contactID);
1816 if ($eventId = CRM_Utils_Array
::value('id', $values['event'])) {
1817 $params['event_id'] = $eventId;
1819 if ($roleId = CRM_Utils_Array
::value('default_role_id', $values['event'])) {
1820 $params['role_id'] = $roleId;
1822 $alreadyRegistered = self
::checkRegistration($params);
1825 if (!empty($values['event']['allow_same_participant_emails']) ||
1833 /* Function to check if given contact is already registered.
1835 * @param array $params key/value participant info
1836 * @return boolean $alreadyRegistered true/false
1839 static function checkRegistration($params) {
1840 $alreadyRegistered = FALSE;
1841 if (empty($params['contact_id'])) {
1842 return $alreadyRegistered;
1845 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
1847 $participant = new CRM_Event_DAO_Participant();
1848 $participant->copyValues($params);
1850 $participant->is_test
= CRM_Utils_Array
::value('is_test', $params, 0);
1851 $participant->selectAdd();
1852 $participant->selectAdd('status_id');
1853 if ($participant->find(TRUE) && array_key_exists($participant->status_id
, $statusTypes)) {
1854 $alreadyRegistered = TRUE;
1857 return $alreadyRegistered;
1861 * make sure that the user has permission to access this event
1863 * @param int $id the id of the event
1864 * @param int $name the name or title of the event
1866 * @return string the permission that the user has (or null)
1870 static function checkPermission($eventId = NULL, $type = CRM_Core_Permission
::VIEW
) {
1871 static $permissions = NULL;
1873 if (empty($permissions)) {
1874 $allEvents = CRM_Event_PseudoConstant
::event(NULL, TRUE);
1875 $createdEvents = array();
1877 $session = CRM_Core_Session
::singleton();
1878 if ($userID = $session->get('userID')) {
1879 $createdEvents = array_keys(CRM_Event_PseudoConstant
::event(NULL, TRUE, "created_id={$userID}"));
1882 // Note: for a multisite setup, a user with edit all events, can edit all events
1883 // including those from other sites
1884 if (CRM_Core_Permission
::check('edit all events')) {
1885 $permissions[CRM_Core_Permission
::EDIT
] = array_keys($allEvents);
1888 $permissions[CRM_Core_Permission
::EDIT
] = &CRM_ACL_API
::group(CRM_Core_Permission
::EDIT
, NULL, 'civicrm_event', $allEvents, $createdEvents);
1891 if (CRM_Core_Permission
::check('edit all events')) {
1892 $permissions[CRM_Core_Permission
::VIEW
] = array_keys($allEvents);
1895 if (CRM_Core_Permission
::check('access CiviEvent') &&
1896 CRM_Core_Permission
::check('view event participants')
1898 // use case: allow "view all events" but NOT "edit all events"
1899 // so for a normal site allow users with these two permissions to view all events AND
1900 // at the same time also allow any hook to override if needed.
1901 $createdEvents = array_keys($allEvents);
1903 $permissions[CRM_Core_Permission
::VIEW
] = &CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_event', $allEvents, $createdEvents);
1906 $permissions[CRM_Core_Permission
::DELETE
] = array();
1907 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
1908 // Note: we want to restrict the scope of delete permission to
1909 // events that are editable/viewable (usecase multisite).
1910 // We can remove array_intersect once we have ACL support for delete functionality.
1911 $permissions[CRM_Core_Permission
::DELETE
] = array_intersect($permissions[CRM_Core_Permission
::EDIT
],
1912 $permissions[CRM_Core_Permission
::VIEW
]
1918 return in_array($eventId, $permissions[$type]) ?
TRUE : FALSE;
1921 return $permissions;
1925 * Build From Email as the combination of all the email ids of the logged in user,
1926 * the domain email id and the email id configured for the event
1928 * @param int $eventId the id of the event
1930 * @return array an array of email ids
1934 static function getFromEmailIds($eventId = NULL) {
1935 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email
::getFromEmail();
1938 // add the email id configured for the event
1939 $params = array('id' => $eventId);
1940 $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
1941 $eventEmail = array();
1943 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
1944 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
1945 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
1947 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
1948 $fromEmailId = array('cc' => CRM_Utils_Array
::value('cc_confirm', $eventEmail),
1949 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventEmail),
1951 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
1955 return $fromEmailValues;
1959 * Function to calculate event total seats occupied.
1961 * @param int $eventId event id.
1962 * @param sting $extraWhereClause extra filter on participants.
1964 * @return int event total seats w/ given criteria.
1968 static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
1969 if (empty($eventId)) {
1973 $extraWhereClause = trim($extraWhereClause);
1974 if (!empty($extraWhereClause)) {
1975 $extraWhereClause = " AND ( {$extraWhereClause} )";
1978 //event seats calculation :
1979 //1. consider event seat as a single when participant does not have line item.
1980 //2. consider event seat as a single when participant has line items but does not
1981 // have count for corresponding price field value ( ie price field value does not carry any seat )
1982 //3. consider event seat as a sum of all seats from line items in case price field value carries count.
1985 SELECT IF ( SUM( value.count*lineItem.qty ),
1986 SUM( value.count*lineItem.qty ) +
1987 COUNT( DISTINCT participant.id ) -
1988 COUNT( DISTINCT IF ( value.count, participant.id, NULL ) ),
1989 COUNT( DISTINCT participant.id ) )
1990 FROM civicrm_participant participant
1991 INNER JOIN civicrm_contact contact ON ( contact.id = participant.contact_id AND contact.is_deleted = 0 )
1992 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
1993 LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id
1994 AND lineItem.entity_table = 'civicrm_participant' )
1995 LEFT JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id AND value.count )
1996 WHERE ( participant.event_id = %1 )
1997 AND participant.is_test = 0
1999 GROUP BY participant.event_id";
2001 return (int)CRM_Core_DAO
::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
2005 * Retrieve event template default values to be set
2006 * as default values for current new event.
2008 * @params int $templateId event template id.
2010 * @return $defaults an array of custom data defaults.
2012 public function getTemplateDefaultValues($templateId) {
2013 $defaults = array();
2018 $templateParams = array('id' => $templateId);
2019 CRM_Event_BAO_Event
::retrieve($templateParams, $defaults);
2020 $fieldsToExclude = array(
2023 'default_discount_fee_id',
2029 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2033 static function get_sub_events($event_id) {
2034 $params = array('parent_event_id' => $event_id);
2035 $defaults = array();
2036 return CRM_Event_BAO_Event
::retrieve($params, $defaults);
2040 * Update the Campaign Id of all the participants of the given event
2042 * @params int $eventID event id.
2043 * @params int $eventCampaignID campaign id of that event
2046 static function updateParticipantCampaignID($eventID, $eventCampaignID) {
2048 $params[1] = array($eventID, 'Integer');
2050 if(empty($eventCampaignID)) {
2051 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2054 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2055 $params[2] = array($eventCampaignID, 'Integer');
2057 CRM_Core_DAO
::executeQuery($query, $params);
2061 * Get options for a given field.
2062 * @see CRM_Core_DAO::buildOptions
2064 * @param String $fieldName
2065 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
2066 * @param Array $props: whatever is known about this dao object
2068 * @return array|bool
2070 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2072 // Special logic for fields whose options depend on context or properties
2073 switch ($fieldName) {
2074 case 'financial_type_id':
2075 // Fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
2076 return CRM_Financial_BAO_FinancialType
::getIncomeFinancialType();
2079 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);