3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
33 class CRM_Event_BAO_Event
extends CRM_Event_DAO_Event
{
38 public function __construct() {
39 parent
::__construct();
43 * Fetch object based on array of properties.
45 * @param array $params
46 * (reference ) an assoc array of name/value pairs.
47 * @param array $defaults
48 * (reference ) an assoc array to hold the flattened values.
50 * @return CRM_Event_DAO_Event
52 public static function retrieve(&$params, &$defaults) {
53 $event = new CRM_Event_DAO_Event();
54 $event->copyValues($params);
55 if ($event->find(TRUE)) {
56 CRM_Core_DAO
::storeValues($event, $defaults);
63 * Update the is_active flag in the db.
66 * Id of the database record.
67 * @param bool $is_active
68 * Value we want to set the is_active field.
71 * DAO object on success, null otherwise
73 public static function setIsActive($id, $is_active) {
74 return CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
80 * @param array $params
81 * Reference array contains the values submitted by the form.
83 * @return CRM_Event_DAO_Event
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);
99 if (!empty($params['financial_type_id'])) {
100 CRM_Financial_BAO_FinancialAccount
::validateFinancialType($params['financial_type_id']);
103 $event = new CRM_Event_DAO_Event();
105 $event->copyValues($params);
106 $result = $event->save();
108 if (!empty($params['id'])) {
109 CRM_Utils_Hook
::post('edit', 'Event', $event->id
, $event);
112 CRM_Utils_Hook
::post('create', 'Event', $event->id
, $event);
114 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
115 CRM_Price_BAO_PriceFieldValue
::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
123 * @param array $params
124 * Reference array contains the values submitted by the form.
128 public static function create(&$params) {
129 $transaction = new CRM_Core_Transaction();
130 if (empty($params['is_template'])) {
131 $params['is_template'] = 0;
133 // check if new event, if so set the created_id (if not set)
134 // and always set created_date to now
135 if (empty($params['id'])) {
136 if (empty($params['created_id'])) {
137 $session = CRM_Core_Session
::singleton();
138 $params['created_id'] = $session->get('userID');
140 $params['created_date'] = date('YmdHis');
143 $event = self
::add($params);
144 CRM_Price_BAO_PriceSet
::setPriceSets($params, $event, 'event');
145 if (is_a($event, 'CRM_Core_Error')) {
146 CRM_Core_DAO
::transaction('ROLLBACK');
150 $contactId = CRM_Core_Session
::getLoggedInContactID();
152 $contactId = CRM_Utils_Array
::value('contact_id', $params);
155 // Log the information on successful add/edit of Event
157 'entity_table' => 'civicrm_event',
158 'entity_id' => $event->id
,
159 'modified_id' => $contactId,
160 'modified_date' => date('Ymd'),
163 CRM_Core_BAO_Log
::add($logParams);
165 if (!empty($params['custom']) &&
166 is_array($params['custom'])
168 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_event', $event->id
);
171 $transaction->commit();
184 public static function del($id) {
189 CRM_Utils_Hook
::pre('delete', 'Event', $id, CRM_Core_DAO
::$_nullArray);
191 $extends = array('event');
192 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
193 foreach ($groupTree as $values) {
194 $query = "DELETE FROM " . $values['table_name'] . " WHERE entity_id = " . $id;
197 1 => array($values['table_name'], 'string'),
198 2 => array($id, 'integer'),
201 CRM_Core_DAO
::executeQuery($query);
204 // price set cleanup, CRM-5527
205 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_event', $id);
207 $event = new CRM_Event_DAO_Event();
210 if ($event->find(TRUE)) {
211 $locBlockId = $event->loc_block_id
;
212 $result = $event->delete();
214 if (!is_null($locBlockId)) {
215 self
::deleteEventLocBlock($locBlockId, $id);
218 CRM_Utils_Hook
::post('delete', 'Event', $id, $event);
226 * Delete the location block associated with an event.
228 * Function checks that it is not being used by any other event.
230 * @param int $locBlockId
231 * Location block id to be deleted.
232 * @param int $eventId
233 * Event with which loc block is associated.
235 public static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
236 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
239 $query .= " AND ce.id != $eventId;";
242 $locCount = CRM_Core_DAO
::singleValueQuery($query);
244 if ($locCount == 0) {
245 CRM_Core_BAO_Location
::deleteLocBlock($locBlockId);
250 * Get current/future Events.
253 * 0 returns current and future events.
254 * 1 if events all are required
255 * 2 returns events since 3 months ago
256 * @param int|array $id single int event id or array of multiple event ids to return
257 * @param bool $isActive
258 * true if you need only active events.
259 * @param bool $checkPermission
260 * true if you need to check permission else false.
261 * @param bool $titleOnly
262 * true if you need only title not appended with start date
266 public static function getEvents(
270 $checkPermission = TRUE,
274 SELECT `id`, `title`, `start_date`
276 WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
279 $op = is_array($id) ?
'IN' : '=';
280 $where = CRM_Contact_BAO_Query
::buildClause('id', $op, $id);
281 $query .= " AND {$where}";
284 // find only events ending in the future
285 $endDate = date('YmdHis');
287 AND ( `end_date` >= {$endDate} OR
289 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
294 // find only events starting in the last 3 months
295 $startDate = date('YmdHis', strtotime('3 months ago'));
296 $query .= " AND ( `start_date` >= {$startDate} OR start_date IS NULL )";
299 $query .= " AND civicrm_event.is_active = 1";
302 $query .= " ORDER BY title asc";
305 $dao = CRM_Core_DAO
::executeQuery($query);
306 while ($dao->fetch()) {
307 if ((!$checkPermission ||
308 CRM_Event_BAO_Event
::checkPermission($dao->id
)
312 $events[$dao->id
] = $dao->title
;
314 $events[$dao->id
] .= ' - ' . CRM_Utils_Date
::customFormat($dao->start_date
);
323 * Get events Summary.
326 * Array of event summary values
328 public static function getEventSummary() {
329 $eventSummary = $eventIds = array();
330 $config = CRM_Core_Config
::singleton();
332 // get permission and include them here
333 // does not scale, but rearranging code for now
334 // FIXME in a future release
335 $permissions = CRM_Event_BAO_Event
::checkPermission();
337 if (empty($permissions[CRM_Core_Permission
::VIEW
])) {
338 $eventSummary['total_events'] = 0;
339 return $eventSummary;
342 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission
::VIEW
])) . " ) ";
345 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
347 SELECT count(id) as total_events
349 WHERE civicrm_event.is_active = 1 AND
350 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
351 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
354 $dao = CRM_Core_DAO
::executeQuery($query);
357 $eventSummary['total_events'] = $dao->total_events
;
360 if (empty($eventSummary) ||
361 $dao->total_events
== 0
363 return $eventSummary;
366 //get the participant status type values.
367 $cpstObject = new CRM_Event_DAO_ParticipantStatusType();
368 $cpst = $cpstObject->getTableName();
369 $query = "SELECT id, name, label, class FROM $cpst";
370 $status = CRM_Core_DAO
::executeQuery($query);
371 $statusValues = array();
372 while ($status->fetch()) {
373 $statusValues[$status->id
]['id'] = $status->id
;
374 $statusValues[$status->id
]['name'] = $status->name
;
375 $statusValues[$status->id
]['label'] = $status->label
;
376 $statusValues[$status->id
]['class'] = $status->class;
379 // Get the Id of Option Group for Event Types
380 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
381 $optionGroupDAO->name
= 'event_type';
382 $optionGroupId = NULL;
383 if ($optionGroupDAO->find(TRUE)) {
384 $optionGroupId = $optionGroupDAO->id
;
386 // Get the event summary display preferences
387 $show_max_events = Civi
::settings()->get('show_events');
388 // show all events if show_events is set to a negative value
389 if (isset($show_max_events) && $show_max_events >= 0) {
390 $event_summary_limit = "LIMIT 0, $show_max_events";
393 $event_summary_limit = "";
397 SELECT civicrm_event.id as id, civicrm_event.title as event_title, civicrm_event.is_public as is_public,
398 civicrm_event.max_participants as max_participants, civicrm_event.start_date as start_date,
399 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,
400 civicrm_event.slot_label_id,
401 civicrm_event.summary as summary,
402 civicrm_pcp_block.id as is_pcp_enabled,
403 civicrm_recurring_entity.parent_id as is_repeating_event
405 LEFT JOIN civicrm_option_value ON (
406 civicrm_event.event_type_id = civicrm_option_value.value AND
407 civicrm_option_value.option_group_id = %1 )
408 LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_event.id AND civicrm_tell_friend.entity_table = 'civicrm_event' )
409 LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_event.id AND civicrm_pcp_block.entity_table = 'civicrm_event')
410 LEFT JOIN civicrm_recurring_entity ON ( civicrm_event.id = civicrm_recurring_entity.entity_id AND civicrm_recurring_entity.entity_table = 'civicrm_event' )
411 WHERE civicrm_event.is_active = 1 AND
412 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
413 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
415 ORDER BY civicrm_event.start_date ASC
418 $eventParticipant = array();
422 'eventTitle' => 'event_title',
423 'isPublic' => 'is_public',
424 'maxParticipants' => 'max_participants',
425 'startDate' => 'start_date',
426 'endDate' => 'end_date',
427 'eventType' => 'event_type',
429 'participants' => 'participants',
430 'notCountedDueToRole' => 'notCountedDueToRole',
431 'notCountedDueToStatus' => 'notCountedDueToStatus',
432 'notCountedParticipants' => 'notCountedParticipants',
435 $params = array(1 => array($optionGroupId, 'Integer'));
436 $mapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings(array(
437 'id' => CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
,
439 $dao = CRM_Core_DAO
::executeQuery($query, $params);
440 while ($dao->fetch()) {
441 foreach ($properties as $property => $name) {
451 $eventSummary['events'][$dao->id
][$property] = $set;
455 if ($dao->$name && $config->mapAPIKey
) {
458 $params = array('entity_id' => $dao->id
, 'entity_table' => 'civicrm_event');
459 $values['location'] = CRM_Core_BAO_Location
::getValues($params, TRUE);
460 if (is_numeric(CRM_Utils_Array
::value('geo_code_1', $values['location']['address'][1])) ||
462 !empty($values['location']['address'][1]['city']) &&
463 !empty($values['location']['address'][1]['state_province_id'])
466 $set = CRM_Utils_System
::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
470 $eventSummary['events'][$dao->id
][$property] = $set;
471 if (is_array($permissions[CRM_Core_Permission
::EDIT
])
472 && in_array($dao->id
, $permissions[CRM_Core_Permission
::EDIT
])) {
473 $eventSummary['events'][$dao->id
]['configure'] = CRM_Utils_System
::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
479 $eventSummary['events'][$dao->id
][$property] = CRM_Utils_Date
::customFormat($dao->$name,
485 case 'notCountedDueToRole':
486 case 'notCountedDueToStatus':
487 case 'notCountedParticipants':
490 if ($name == 'participants') {
491 $propertyCnt = self
::getParticipantCount($dao->id
);
493 $set = CRM_Utils_System
::url('civicrm/event/search',
494 "reset=1&force=1&event=$dao->id&status=true&role=true"
498 elseif ($name == 'notCountedParticipants') {
499 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, TRUE, FALSE);
501 // FIXME : selector fail to search w/ OR operator.
502 // $set = CRM_Utils_System::url( 'civicrm/event/search',
503 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
506 elseif ($name == 'notCountedDueToStatus') {
507 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, FALSE, FALSE);
509 $set = CRM_Utils_System
::url('civicrm/event/search',
510 "reset=1&force=1&event=$dao->id&status=false"
515 $propertyCnt = self
::getParticipantCount($dao->id
, FALSE, FALSE, TRUE, FALSE);
517 $set = CRM_Utils_System
::url('civicrm/event/search',
518 "reset=1&force=1&event=$dao->id&role=false"
523 $eventSummary['events'][$dao->id
][$property] = $propertyCnt;
524 $eventSummary['events'][$dao->id
][$name . '_url'] = $set;
528 $eventSummary['events'][$dao->id
][$property] = $dao->$name;
533 // prepare the area for per-status participant counts
534 $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
535 $eventSummary['events'][$dao->id
]['statuses'] = array_fill_keys($statusClasses, array());
537 $eventSummary['events'][$dao->id
]['friend'] = $dao->is_friend_active
;
538 $eventSummary['events'][$dao->id
]['is_monetary'] = $dao->is_monetary
;
539 $eventSummary['events'][$dao->id
]['is_online_registration'] = $dao->is_online_registration
;
540 $eventSummary['events'][$dao->id
]['is_show_location'] = $dao->is_show_location
;
541 $eventSummary['events'][$dao->id
]['is_subevent'] = $dao->slot_label_id
;
542 $eventSummary['events'][$dao->id
]['is_pcp_enabled'] = $dao->is_pcp_enabled
;
543 $eventSummary['events'][$dao->id
]['reminder'] = CRM_Core_BAO_ActionSchedule
::isConfigured($dao->id
, $mapping->getId());
544 $eventSummary['events'][$dao->id
]['is_repeating_event'] = $dao->is_repeating_event
;
546 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
547 foreach ($statusValues as $statusId => $statusValue) {
548 if (!array_key_exists($statusId, $statusTypes)) {
551 $class = $statusValue['class'];
552 $statusCount = self
::eventTotalSeats($dao->id
, "( participant.status_id = {$statusId} )");
554 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
556 'url' => CRM_Utils_System
::url('civicrm/event/search', $urlString),
557 'name' => $statusValue['name'],
558 'label' => $statusValue['label'],
559 'count' => $statusCount,
561 $eventSummary['events'][$dao->id
]['statuses'][$class][] = $statusInfo;
566 $countedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
567 $nonCountedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
568 $countedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
569 $nonCountedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
571 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
572 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
574 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
575 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
576 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
577 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
579 return $eventSummary;
583 * Get participant count.
585 * @param int $eventId
586 * @param bool $considerStatus consider status for participant count.
587 * Consider status for participant count.
588 * @param bool $status counted participant.
589 * Consider counted participant.
590 * @param bool $considerRole consider role for participant count.
591 * Consider role for participant count.
592 * @param bool $role consider counted( is filter role) participant.
593 * Consider counted( is filter role) participant.
596 * array with count of participants for each event based on status/role
598 public static function getParticipantCount(
600 $considerStatus = TRUE,
602 $considerRole = TRUE,
606 // consider both role and status for counted participants, CRM-4924.
608 // not counted participant.
609 if ($considerStatus && $considerRole && !$status && !$role) {
613 if ($considerStatus) {
614 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
615 $statusClause = 'NOT IN';
617 $statusClause = 'IN';
619 $status = implode(',', array_keys($statusTypes));
620 if (empty($status)) {
623 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
627 $roleTypes = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
628 $roleClause = 'NOT IN';
633 if (!empty($roleTypes)) {
634 $escapedRoles = array();
635 foreach (array_keys($roleTypes) as $roleType) {
636 $escapedRoles[] = CRM_Utils_Type
::escape($roleType, 'String');
639 $clause[] = "participant.role_id {$roleClause} ( '" . implode("', '", $escapedRoles) . "' ) ";
644 if (!empty($clause)) {
645 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
648 return self
::eventTotalSeats($eventId, $sqlClause);
652 * Get the information to map a event.
655 * For which we want map info.
657 * @return null|string
660 public static function &getMapInfo(&$id) {
664 civicrm_event.id AS event_id,
665 civicrm_event.title AS display_name,
666 civicrm_address.street_address AS street_address,
667 civicrm_address.city AS city,
668 civicrm_address.postal_code AS postal_code,
669 civicrm_address.postal_code_suffix AS postal_code_suffix,
670 civicrm_address.geo_code_1 AS latitude,
671 civicrm_address.geo_code_2 AS longitude,
672 civicrm_state_province.abbreviation AS state,
673 civicrm_country.name AS country,
674 civicrm_location_type.name AS location_type
677 LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )
678 LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )
679 LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )
680 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
681 LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )
682 WHERE civicrm_address.geo_code_1 IS NOT NULL
683 AND civicrm_address.geo_code_2 IS NOT NULL
684 AND civicrm_event.id = " . CRM_Utils_Type
::escape($id, 'Integer');
686 $dao = new CRM_Core_DAO();
689 $locations = array();
691 $config = CRM_Core_Config
::singleton();
693 while ($dao->fetch()) {
696 $location['displayName'] = addslashes($dao->display_name
);
697 $location['lat'] = $dao->latitude
;
698 $location['marker_class'] = 'Event';
699 $location['lng'] = $dao->longitude
;
701 $params = array('entity_id' => $id, 'entity_table' => 'civicrm_event');
702 $addressValues = CRM_Core_BAO_Location
::getValues($params, TRUE);
703 $location['address'] = str_replace(array(
706 ), '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
708 $location['url'] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
);
709 $location['location_type'] = $dao->location_type
;
710 $eventImage = '<img src="' . $config->resourceBase
. 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
711 $location['image'] = $eventImage;
712 $location['displayAddress'] = str_replace('<br />', ', ', $location['address']);
713 $locations[] = $location;
719 * Get the complete information for one or more events.
722 * Get events with start date >= this date.
723 * @param int $type Get events on the a specific event type (by event_type_id).
724 * Get events on the a specific event type (by event_type_id).
725 * @param int $eventId Return a single event - by event id.
726 * Return a single event - by event id.
728 * Also get events with end date >= this date.
729 * @param bool $onlyPublic Include public events only, default TRUE.
730 * Include public events only, default TRUE.
733 * array of all the events that are searched
735 public static function &getCompleteInfo(
742 $publicCondition = NULL;
744 $publicCondition = " AND civicrm_event.is_public = 1";
748 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
750 // get events with start_date >= requested start
751 $startDate = CRM_Utils_Type
::escape($start, 'Date');
752 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
756 // also get events with end_date <= requested end
757 $endDate = CRM_Utils_Type
::escape($end, 'Date');
758 $dateCondition .= " AND ( civicrm_event.end_date <= '{$endDate}' ) ";
761 // CRM-9421 and CRM-8620 Default mode for ical/rss feeds. No start or end filter passed.
762 // Need to exclude old events with only start date
763 // and not exclude events in progress (start <= today and end >= today). DGG
764 if (empty($start) && empty($end)) {
765 // get events with end date >= today, not sure of this logic
766 // but keeping this for backward compatibility as per issue CRM-5133
767 $today = date("Y-m-d G:i:s");
768 $dateCondition .= " AND ( civicrm_event.end_date >= '{$today}' OR civicrm_event.start_date >= '{$today}' ) ";
772 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
775 // Get the Id of Option Group for Event Types
776 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
777 $optionGroupDAO->name
= 'event_type';
778 $optionGroupId = NULL;
779 if ($optionGroupDAO->find(TRUE)) {
780 $optionGroupId = $optionGroupDAO->id
;
785 civicrm_event.id as event_id,
786 civicrm_email.email as email,
787 civicrm_event.title as title,
788 civicrm_event.summary as summary,
789 civicrm_event.start_date as start,
790 civicrm_event.end_date as end,
791 civicrm_event.description as description,
792 civicrm_event.is_show_location as is_show_location,
793 civicrm_event.is_online_registration as is_online_registration,
794 civicrm_event.registration_link_text as registration_link_text,
795 civicrm_event.registration_start_date as registration_start_date,
796 civicrm_event.registration_end_date as registration_end_date,
797 civicrm_option_value.label as event_type,
798 civicrm_address.name as address_name,
799 civicrm_address.street_address as street_address,
800 civicrm_address.supplemental_address_1 as supplemental_address_1,
801 civicrm_address.supplemental_address_2 as supplemental_address_2,
802 civicrm_address.city as city,
803 civicrm_address.postal_code as postal_code,
804 civicrm_address.postal_code_suffix as postal_code_suffix,
805 civicrm_state_province.abbreviation as state,
806 civicrm_country.name AS country
808 LEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id
809 LEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id
810 LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
811 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
812 LEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id
813 LEFT JOIN civicrm_option_value ON (
814 civicrm_event.event_type_id = civicrm_option_value.value AND
815 civicrm_option_value.option_group_id = %1 )
816 WHERE civicrm_event.is_active = 1
817 AND (is_template = 0 OR is_template IS NULL)
821 if (isset($typeCondition)) {
822 $query .= $typeCondition;
825 if (isset($eventId)) {
826 $query .= " AND civicrm_event.id =$eventId ";
828 $query .= " ORDER BY civicrm_event.start_date ASC";
830 $params = array(1 => array($optionGroupId, 'Integer'));
831 $dao = CRM_Core_DAO
::executeQuery($query, $params);
833 $config = CRM_Core_Config
::singleton();
835 $baseURL = parse_url($config->userFrameworkBaseURL
);
836 $url = "@" . $baseURL['host'];
837 if (!empty($baseURL['path'])) {
838 $url .= substr($baseURL['path'], 0, -1);
841 // check 'view event info' permission
842 //@todo - per CRM-14626 we have resolved that 'view event info' means 'view ALL event info'
843 // and passing in the specific permission here will short-circuit the evaluation of permission to
844 // see specific events (doesn't seem relevant to this call
845 // however, since this function is accessed only by a convoluted call from a joomla block function
846 // it seems safer not to touch here. Suggestion is that CRM_Core_Permission::check(array or relevant permissions) would
847 // be clearer & safer here
848 $permissions = CRM_Core_Permission
::event(CRM_Core_Permission
::VIEW
);
850 // check if we're in shopping cart mode for events
851 $enable_cart = Civi
::settings()->get('enable_cart');
854 while ($dao->fetch()) {
855 if (!empty($permissions) && in_array($dao->event_id
, $permissions)) {
857 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL
) . $url;
859 $info['title'] = $dao->title
;
860 $info['event_id'] = $dao->event_id
;
861 $info['summary'] = $dao->summary
;
862 $info['description'] = $dao->description
;
863 $info['start_date'] = $dao->start
;
864 $info['end_date'] = $dao->end
;
865 $info['contact_email'] = $dao->email
;
866 $info['event_type'] = $dao->event_type
;
867 $info['is_show_location'] = $dao->is_show_location
;
868 $info['is_online_registration'] = $dao->is_online_registration
;
869 $info['registration_link_text'] = $dao->registration_link_text
;
870 $info['registration_start_date'] = $dao->registration_start_date
;
871 $info['registration_end_date'] = $dao->registration_end_date
;
876 'address_name' => $dao->address_name
,
877 'street_address' => $dao->street_address
,
878 'supplemental_address_1' => $dao->supplemental_address_1
,
879 'supplemental_address_2' => $dao->supplemental_address_2
,
880 'city' => $dao->city
,
881 'state_province' => $dao->state
,
882 'postal_code' => $dao->postal_code
,
883 'postal_code_suffix' => $dao->postal_code_suffix
,
884 'country' => $dao->country
,
888 CRM_Utils_String
::append($address, ', ',
889 CRM_Utils_Address
::format($addrFields)
891 $info['location'] = $address;
892 $info['url'] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
895 $reg = CRM_Event_Cart_BAO_EventInCart
::get_registration_link($dao->event_id
);
896 $info['registration_link'] = CRM_Utils_System
::url($reg['path'], $reg['query'], TRUE);
897 $info['registration_link_text'] = $reg['label'];
908 * Make a copy of a Event.
910 * Include all the fields in the event Wizard.
913 * The event id to copy.
914 * boolean $afterCreate call to copy after the create function
915 * @param null $newEvent
916 * @param bool $afterCreate
918 * @return CRM_Event_DAO_Event
920 public static function copy($id, $newEvent = NULL, $afterCreate = FALSE) {
922 $eventValues = array();
924 //get the require event values.
925 $eventParams = array('id' => $id);
926 $returnProperties = array(
930 'default_discount_fee_id',
934 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
936 // since the location is sharable, lets use the same loc_block_id.
937 $locBlockId = CRM_Utils_Array
::value('loc_block_id', $eventValues);
939 $fieldsFix = ($afterCreate) ?
array() : array('prefix' => array('title' => ts('Copy of') . ' '));
940 if (empty($eventValues['is_show_location'])) {
941 $fieldsFix['prefix']['is_show_location'] = 0;
944 if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
945 $copyEvent = $newEvent;
948 if (!isset($copyEvent)) {
949 $copyEvent = &CRM_Core_DAO
::copyGeneric('CRM_Event_DAO_Event',
953 ($locBlockId) ?
$locBlockId : NULL,
958 CRM_Price_BAO_PriceSet
::copyPriceSet('civicrm_event', $id, $copyEvent->id
);
959 $copyUF = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_UFJoin',
962 'entity_table' => 'civicrm_event',
964 array('entity_id' => $copyEvent->id
)
967 $copyTellFriend = &CRM_Core_DAO
::copyGeneric('CRM_Friend_DAO_Friend',
970 'entity_table' => 'civicrm_event',
972 array('entity_id' => $copyEvent->id
)
975 $copyPCP = &CRM_Core_DAO
::copyGeneric('CRM_PCP_DAO_PCPBlock',
978 'entity_table' => 'civicrm_event',
980 array('entity_id' => $copyEvent->id
),
981 array('replace' => array('target_entity_id' => $copyEvent->id
))
984 $oldMapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings(array(
985 'id' => ($eventValues['is_template'] ? CRM_Event_ActionMapping
::EVENT_TPL_MAPPING_ID
: CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
),
987 $copyMapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings(array(
988 'id' => ($copyEvent->is_template
== 1 ? CRM_Event_ActionMapping
::EVENT_TPL_MAPPING_ID
: CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
),
990 $copyReminder = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_ActionSchedule',
991 array('entity_value' => $id, 'mapping_id' => $oldMapping->getId()),
992 array('entity_value' => $copyEvent->id
, 'mapping_id' => $copyMapping->getId())
997 self
::copyCustomFields($id, $copyEvent->id
);
1002 CRM_Utils_System
::flushCache();
1003 if (!$afterCreate) {
1004 CRM_Utils_Hook
::copy('Event', $copyEvent);
1010 * Method that copies custom fields values from an old event to a new one. Fixes bug CRM-19302,
1011 * where if a custom field of File type was present, left both events using the same file,
1012 * breaking download URL's for the old event.
1014 * @param int $oldEventID
1015 * @param int $newCopyID
1017 public static function copyCustomFields($oldEventID, $newCopyID) {
1018 // Obtain custom values for old event
1019 $customParams = $htmlType = array();
1020 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($oldEventID, 'Event');
1022 // If custom values present, we copy them
1023 if (!empty($customValues)) {
1024 // Get Field ID's and identify File type attributes, to handle file copying.
1025 $fieldIds = implode(', ', array_keys($customValues));
1026 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1027 $result = CRM_Core_DAO
::executeQuery($sql);
1029 // Build array of File type fields
1030 while ($result->fetch()) {
1031 $htmlType[] = $result->id
;
1034 // Build params array of custom values
1035 foreach ($customValues as $field => $value) {
1036 if ($value !== NULL) {
1037 // Handle File type attributes
1038 if (in_array($field, $htmlType)) {
1039 $fileValues = CRM_Core_BAO_File
::path($value, $oldEventID);
1040 $customParams["custom_{$field}_-1"] = array(
1041 'name' => $fileValues[0],
1042 'type' => $fileValues[1],
1045 // Handle other types
1047 $customParams["custom_{$field}_-1"] = $value;
1052 // Save Custom Fields for new Event
1053 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, 'civicrm_event', $newCopyID, 'Event');
1056 // copy activity attachments ( if any )
1057 CRM_Core_BAO_File
::copyEntityFile('civicrm_event', $oldEventID, 'civicrm_event', $newCopyID);
1061 * This is sometimes called in a loop (during event search).
1063 * We cache the values to prevent repeated calls to the db.
1069 public static function isMonetary($id) {
1070 static $isMonetary = array();
1071 if (!array_key_exists($id, $isMonetary)) {
1072 $isMonetary[$id] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event',
1077 return $isMonetary[$id];
1081 * This is sometimes called in a loop (during event search).
1083 * We cache the values to prevent repeated calls to the db.
1089 public static function usesPriceSet($id) {
1090 static $usesPriceSet = array();
1091 if (!array_key_exists($id, $usesPriceSet)) {
1092 $usesPriceSet[$id] = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $id);
1094 return $usesPriceSet[$id];
1100 * @param int $contactID
1101 * @param array $values
1102 * @param int $participantId
1103 * @param bool $isTest
1104 * @param bool $returnMessageText
1106 public static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
1108 $template = CRM_Core_Smarty
::singleton();
1110 'custom_pre_id' => $values['custom_pre_id'],
1111 'custom_post_id' => $values['custom_post_id'],
1114 //get the params submitted by participant.
1115 $participantParams = CRM_Utils_Array
::value($participantId, $values['params'], array());
1117 if (!$returnMessageText) {
1118 //send notification email if field values are set (CRM-1941)
1119 foreach ($gIds as $key => $gIdValues) {
1121 if (!is_array($gIdValues)) {
1122 $gIdValues = array($gIdValues);
1125 foreach ($gIdValues as $gId) {
1126 $email = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1128 //get values of corresponding profile fields for notification
1129 list($profileValues) = self
::buildCustomDisplay($gId,
1138 list($profileValues) = $profileValues;
1141 'values' => $profileValues,
1144 CRM_Core_BAO_UFGroup
::commonSendMail($contactID, $val);
1151 if ($values['event']['is_email_confirm'] ||
$returnMessageText) {
1152 list($displayName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1154 //send email only when email is present
1155 if (isset($email) ||
$returnMessageText) {
1156 $preProfileID = CRM_Utils_Array
::value('custom_pre_id', $values);
1157 $postProfileID = CRM_Utils_Array
::value('custom_post_id', $values);
1159 if (!empty($values['params']['additionalParticipant'])) {
1160 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values, $preProfileID);
1161 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values, $postProfileID);
1164 self
::buildCustomDisplay($preProfileID,
1174 self
::buildCustomDisplay($postProfileID,
1184 $sessions = CRM_Event_Cart_BAO_Conference
::get_participant_sessions($participantId);
1186 $tplParams = array_merge($values, $participantParams, array(
1188 'confirm_email_text' => CRM_Utils_Array
::value('confirm_email_text', $values['event']),
1189 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $values['event']),
1190 // The concept of contributeMode is deprecated.
1191 'contributeMode' => CRM_Utils_Array
::value('contributeMode', $template->_tpl_vars
),
1192 'participantID' => $participantId,
1193 'conference_sessions' => $sessions,
1194 'credit_card_number' =>
1195 CRM_Utils_System
::mungeCreditCard(
1196 CRM_Utils_Array
::value('credit_card_number', $participantParams)),
1197 'credit_card_exp_date' =>
1198 CRM_Utils_Date
::mysqlToIso(
1199 CRM_Utils_Date
::format(
1200 CRM_Utils_Array
::value('credit_card_exp_date', $participantParams))),
1203 // CRM-13890 : NOTE wait list condition need to be given so that
1204 // wait list message is shown properly in email i.e. WRT online event registration template
1205 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
1206 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id', TRUE);
1207 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($statusId, NULL, 'label');
1209 //CRM-15754 - if participant_status contains status ID
1210 elseif (!empty($tplParams['participant_status']) && CRM_Utils_Rule
::integer($tplParams['participant_status'])) {
1211 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($tplParams['participant_status'], NULL, 'label');
1214 $sendTemplateParams = array(
1215 'groupName' => 'msg_tpl_workflow_event',
1216 'valueName' => 'event_online_receipt',
1217 'contactId' => $contactID,
1218 'isTest' => $isTest,
1219 'tplParams' => $tplParams,
1220 'PDFFilename' => ts('confirmation') . '.pdf',
1223 // address required during receipt processing (pdf and email receipt)
1224 if ($displayAddress = CRM_Utils_Array
::value('address', $values)) {
1225 $sendTemplateParams['tplParams']['address'] = $displayAddress;
1226 // The concept of contributeMode is deprecated.
1227 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1230 // set lineItem details
1231 if ($lineItem = CRM_Utils_Array
::value('lineItem', $values)) {
1232 // check if additional participant, if so filter only to relevant ones
1234 if (!empty($values['params']['additionalParticipant'])) {
1235 $ownLineItems = array();
1236 foreach ($lineItem as $liKey => $liValue) {
1237 $firstElement = array_pop($liValue);
1238 if ($firstElement['entity_id'] == $participantId) {
1239 $ownLineItems[0] = $lineItem[$liKey];
1243 if (!empty($ownLineItems)) {
1244 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1248 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1252 if ($returnMessageText) {
1253 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1255 'subject' => $subject,
1257 'to' => $displayName,
1262 $sendTemplateParams['from'] = CRM_Utils_Array
::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array
::value('confirm_from_email', $values['event']) . ">";
1263 $sendTemplateParams['toName'] = $displayName;
1264 $sendTemplateParams['toEmail'] = $email;
1265 $sendTemplateParams['autoSubmitted'] = TRUE;
1266 $sendTemplateParams['cc'] = CRM_Utils_Array
::value('cc_confirm',
1269 $sendTemplateParams['bcc'] = CRM_Utils_Array
::value('bcc_confirm',
1272 // append invoice pdf to email
1273 $template = CRM_Core_Smarty
::singleton();
1274 $taxAmt = $template->get_template_vars('totalTaxAmount');
1275 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
1276 $invoicing = CRM_Utils_Array
::value('invoicing', $prefixValue);
1277 if (isset($invoicing) && isset($prefixValue['is_email_pdf']) && !empty($values['contributionId'])) {
1278 $sendTemplateParams['isEmailPdf'] = TRUE;
1279 $sendTemplateParams['contributionId'] = $values['contributionId'];
1281 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1288 * Add the custom fields OR array of participant's profile info.
1291 * @param string $name
1293 * @param string $template
1294 * @param int $participantId
1295 * @param bool $isTest
1296 * @param bool $isCustomProfile
1297 * @param array $participantParams
1299 * @return array|null
1301 public static function buildCustomDisplay(
1308 $isCustomProfile = FALSE,
1309 $participantParams = array()
1312 return array(NULL, NULL);
1315 if (!is_array($id)) {
1316 $id = CRM_Utils_Type
::escape($id, 'Positive');
1317 $profileIds = array($id);
1323 $val = $groupTitles = NULL;
1324 foreach ($profileIds as $gid) {
1325 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $cid)) {
1327 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
,
1328 NULL, NULL, FALSE, NULL,
1329 FALSE, NULL, CRM_Core_Permission
::CREATE
,
1333 //this condition is added, since same contact can have multiple event registrations..
1334 $params = array(array('participant_id', '=', $participantId, 0, 0));
1336 //add participant id
1337 $fields['participant_id'] = array(
1338 'name' => 'participant_id',
1339 'title' => ts('Participant ID'),
1341 //check whether its a text drive
1343 $params[] = array('participant_test', '=', 1, 0, 0);
1346 //display campaign on thankyou page.
1347 if (array_key_exists('participant_campaign_id', $fields)) {
1348 if ($participantId) {
1349 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1353 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1354 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array
::value($campaignId,
1358 unset($fields['participant_campaign_id']);
1362 foreach ($fields as $k => $v) {
1364 $groupTitle = $v['groupTitle'];
1366 // suppress all file fields from display
1368 CRM_Utils_Array
::value('data_type', $v, '') == 'File' ||
1369 CRM_Utils_Array
::value('name', $v, '') == 'image_URL' ||
1370 CRM_Utils_Array
::value('field_type', $v) == 'Formatting'
1377 $groupTitles[] = $groupTitle;
1379 //display profile groups those are subscribed by participant.
1380 if (($groups = CRM_Utils_Array
::value('group', $participantParams)) &&
1384 foreach ($groups as $grpId => $isSelected) {
1389 if (!empty($grpIds)) {
1390 //get the group titles.
1391 $grpTitles = array();
1392 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1393 $grp = CRM_Core_DAO
::executeQuery($query);
1394 while ($grp->fetch()) {
1395 $grpTitles[] = $grp->title
;
1397 if (!empty($grpTitles) &&
1398 CRM_Utils_Array
::value('title', CRM_Utils_Array
::value('group', $fields))
1400 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1402 unset($fields['group']);
1406 CRM_Core_BAO_UFGroup
::getValues($cid, $fields, $values, FALSE, $params);
1408 if (isset($fields['participant_status_id']['title']) &&
1409 isset($values[$fields['participant_status_id']['title']]) &&
1410 is_numeric($values[$fields['participant_status_id']['title']])
1413 $status = CRM_Event_PseudoConstant
::participantStatus();
1414 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1417 if (isset($fields['participant_role_id']['title']) &&
1418 isset($values[$fields['participant_role_id']['title']]) &&
1419 is_numeric($values[$fields['participant_role_id']['title']])
1422 $roles = CRM_Event_PseudoConstant
::participantRole();
1423 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1426 if (isset($fields['participant_register_date']['title']) &&
1427 isset($values[$fields['participant_register_date']['title']])
1429 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date
::customFormat($values[$fields['participant_register_date']['title']]);
1432 //handle fee_level for price set
1433 if (isset($fields['participant_fee_level']['title']) &&
1434 isset($values[$fields['participant_fee_level']['title']])
1436 $feeLevel = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1437 $values[$fields['participant_fee_level']['title']]
1439 foreach ($feeLevel as $key => $value) {
1441 unset($feeLevel[$key]);
1444 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
1447 unset($values[$fields['participant_id']['title']]);
1454 $template->assign($name, $val);
1457 if (count($groupTitles)) {
1458 $template->assign($name . '_grouptitle', $groupTitles);
1461 //return if we only require array of participant's info.
1462 if ($isCustomProfile) {
1464 return array($val, $groupTitles);
1473 * Build the array for display the profile fields.
1475 * @param array $params
1479 * @param array $groupTitle
1480 * Profile Group Title.
1481 * @param array $values
1482 * Formatted array of key value.
1484 * @param array $profileFields
1486 public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
1488 $config = CRM_Core_Config
::singleton();
1489 $session = CRM_Core_Session
::singleton();
1490 $contactID = $session->get('userID');
1492 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $contactID)) {
1493 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
);
1497 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::ADD
);
1500 foreach ($fields as $v) {
1501 if (!empty($v['groupTitle'])) {
1502 $groupTitle['groupTitle'] = $v['groupTitle'];
1507 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1508 //start of code to set the default values
1509 foreach ($fields as $name => $field) {
1512 // skip fields that should not be displayed separately
1513 if ($field['skipDisplay']) {
1517 $index = $field['title'];
1518 if ($name === 'organization_name') {
1519 $values[$index] = $params[$name];
1522 if ('state_province' == substr($name, 0, 14)) {
1523 if ($params[$name]) {
1524 $values[$index] = CRM_Core_PseudoConstant
::stateProvince($params[$name]);
1527 $values[$index] = '';
1530 elseif ('date' == substr($name, -4)) {
1531 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::processDate($params[$name]),
1532 $config->dateformatFull
);
1534 elseif ('country' == substr($name, 0, 7)) {
1535 if ($params[$name]) {
1536 $values[$index] = CRM_Core_PseudoConstant
::country($params[$name]);
1539 $values[$index] = '';
1542 elseif ('county' == substr($name, 0, 6)) {
1543 if ($params[$name]) {
1544 $values[$index] = CRM_Core_PseudoConstant
::county($params[$name]);
1547 $values[$index] = '';
1550 elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
1551 $values[$index] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
1553 elseif (in_array($name, array(
1558 $filterCondition = array('greeting_type' => $name);
1559 $greeting = CRM_Core_PseudoConstant
::greeting($filterCondition);
1560 $values[$index] = $greeting[$params[$name]];
1562 elseif ($name === 'preferred_communication_method') {
1563 $communicationFields = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1565 $pref = $params[$name];
1566 if (is_array($pref)) {
1567 foreach ($pref as $k => $v) {
1569 $compref[] = $communicationFields[$k];
1573 $values[$index] = implode(',', $compref);
1575 elseif ($name == 'contact_sub_type') {
1576 $values[$index] = implode(', ', $params[$name]);
1578 elseif ($name == 'group') {
1579 $groups = CRM_Contact_BAO_GroupContact
::getGroupList();
1581 foreach ($params[$name] as $gId => $dontCare) {
1583 $title[] = $groups[$gId];
1586 $values[$index] = implode(', ', $title);
1588 elseif ($name == 'tag') {
1589 $entityTags = $params[$name];
1590 $allTags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
1592 if (is_array($entityTags)) {
1593 foreach ($entityTags as $tagId => $dontCare) {
1594 $title[] = $allTags[$tagId];
1597 $values[$index] = implode(', ', $title);
1599 elseif ('participant_role_id' == $name OR
1600 'participant_role' == $name
1602 $roles = CRM_Event_PseudoConstant
::participantRole();
1603 $values[$index] = $roles[$params[$name]];
1605 elseif ('participant_status_id' == $name OR
1606 'participant_status' == $name
1608 $status = CRM_Event_PseudoConstant
::participantStatus();
1609 $values[$index] = $status[$params[$name]];
1611 elseif (substr($name, -11) == 'campaign_id') {
1612 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($params[$name]);
1613 $values[$index] = CRM_Utils_Array
::value($params[$name], $campaigns);
1615 elseif (strpos($name, '-') !== FALSE) {
1616 list($fieldName, $id) = CRM_Utils_System
::explode('-', $name, 2);
1617 $detailName = str_replace(' ', '_', $name);
1618 if (in_array($fieldName, array(
1623 $values[$index] = $params[$detailName];
1624 $idx = $detailName . '_id';
1625 $values[$index] = $params[$idx];
1627 elseif ($fieldName == 'im') {
1628 $providerName = NULL;
1629 if ($providerId = $detailName . '-provider_id') {
1630 $providerName = CRM_Utils_Array
::value($params[$providerId], $imProviders);
1632 if ($providerName) {
1633 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1636 $values[$index] = $params[$detailName];
1639 elseif ($fieldName == 'phone') {
1640 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1641 if (isset($params[$phoneExtField])) {
1642 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1645 $values[$index] = $params[$detailName];
1649 $values[$index] = $params[$detailName];
1653 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1654 if ($params[$name]) {
1655 $values[$index] = '[ x ]';
1659 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
1661 SELECT html_type, data_type
1662 FROM civicrm_custom_field
1665 $dao = CRM_Core_DAO
::executeQuery($query);
1667 $htmlType = $dao->html_type
;
1669 if ($htmlType == 'File') {
1670 $values[$index] = $params[$index];
1673 if ($dao->data_type
== 'Int' ||
1674 $dao->data_type
== 'Boolean'
1676 $v = $params[$name];
1677 if (!CRM_Utils_System
::isNull($v)) {
1678 $customVal = (int) $v;
1681 elseif ($dao->data_type
== 'Float') {
1682 $customVal = (float ) ($params[$name]);
1684 elseif ($dao->data_type
== 'Date') {
1685 //@todo note the currently we are using default date time formatting. Since you can select/set
1686 // different date and time format specific to custom field we should consider fixing this
1687 // sometime in the future
1688 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1689 CRM_Utils_Date
::processDate($params[$name]), $config->dateformatFull
);
1691 if (!empty($params[$name . '_time'])) {
1692 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1693 CRM_Utils_Date
::processDate($params[$name], $params[$name . '_time']),
1694 $config->dateformatDatetime
);
1699 $customVal = $params[$name];
1701 //take the custom field options
1702 $returnProperties = array($name => 1);
1703 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
1705 $displayValue = CRM_Core_BAO_CustomField
::displayValue($customVal, $cfID);
1707 //Hack since we dont have function to check empty.
1708 //FIXME in 2.3 using crmIsEmptyArray()
1709 $customValue = TRUE;
1710 if (is_array($customVal) && is_array($displayValue)) {
1711 $customValue = array_diff($customVal, $displayValue);
1713 //use difference of arrays
1714 if (empty($customValue) ||
!$customValue) {
1715 $values[$index] = '';
1718 $values[$index] = $displayValue;
1722 elseif ($name == 'home_URL' &&
1723 !empty($params[$name])
1725 $url = CRM_Utils_System
::fixURL($params[$name]);
1726 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1728 elseif (in_array($name, array(
1731 'participant_register_date',
1733 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::format($params[$name]));
1736 $values[$index] = CRM_Utils_Array
::value($name, $params);
1740 $profileFields[$name] = $field;
1746 * Build the array for Additional participant's information array of primary and additional Ids.
1748 * @param int $participantId
1749 * Id of Primary participant.
1750 * @param array $values
1751 * Key/value event info.
1752 * @param int $contactId
1753 * Contact id of Primary participant.
1754 * @param bool $isTest
1755 * Whether test or live transaction.
1756 * @param bool $isIdsArray
1757 * To return an array of Ids.
1759 * @param bool $skipCancel
1762 * array of Additional participant's info OR array of Ids.
1764 public static function buildCustomProfile(
1769 $isIdsArray = FALSE,
1773 $customProfile = $additionalIDs = array();
1774 if (!$participantId) {
1775 CRM_Core_Error
::fatal(ts('Cannot find participant ID'));
1778 //set Ids of Primary Participant also.
1779 if ($isIdsArray && $contactId) {
1780 $additionalIDs[$participantId] = $contactId;
1783 //hack to skip cancelled participants, CRM-4320
1784 $where = "participant.registered_by_id={$participantId}";
1786 $cancelStatusId = 0;
1787 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1788 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1789 $where .= " AND participant.status_id != {$cancelStatusId}";
1792 SELECT participant.id, participant.contact_id
1793 FROM civicrm_participant participant
1796 $dao = CRM_Core_DAO
::executeQuery($query);
1797 while ($dao->fetch()) {
1798 $additionalIDs[$dao->id
] = $dao->contact_id
;
1801 //return if only array is required.
1802 if ($isIdsArray && $contactId) {
1803 return $additionalIDs;
1806 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values);
1807 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values);
1808 //else build array of Additional participant's information.
1809 if (count($additionalIDs)) {
1810 if ($preProfileID ||
$postProfileID) {
1811 $template = CRM_Core_Smarty
::singleton();
1813 $isCustomProfile = TRUE;
1815 $title = $groupTitles = array();
1816 foreach ($additionalIDs as $pId => $cId) {
1817 //get the params submitted by participant.
1818 $participantParams = CRM_Utils_Array
::value($pId, $values['params'], array());
1820 list($profilePre, $groupTitles) = self
::buildCustomDisplay($preProfileID,
1821 'additionalCustomPre',
1831 $profile = $profilePre;
1832 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1834 $title = $groupTitles;
1838 list($profilePost, $groupTitles) = self
::buildCustomDisplay($postProfileID,
1839 'additionalCustomPost',
1849 if (isset($profilePre)) {
1850 $profile = array_merge($profilePre, $profilePost);
1852 $title = array_merge($title, $groupTitles);
1856 $profile = $profilePost;
1858 $title = $groupTitles;
1862 $profiles[] = $profile;
1865 $customProfile['title'] = $title;
1866 $customProfile['profile'] = $profiles;
1870 return $customProfile;
1873 /* Function to retrieve all events those having location block set.
1876 * array of all events.
1881 public static function getLocationEvents() {
1885 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
1886 FROM civicrm_event ce
1887 INNER JOIN civicrm_loc_block lb ON ce.loc_block_id = lb.id
1888 INNER JOIN civicrm_address ca ON lb.address_id = ca.id
1889 LEFT JOIN civicrm_state_province sp ON ca.state_province_id = sp.id
1890 ORDER BY sp.name, ca.city, ca.street_address ASC
1893 $dao = CRM_Core_DAO
::executeQuery($query);
1894 while ($dao->fetch()) {
1895 $events[$dao->loc_block_id
] = $dao->title
;
1902 * @param int $locBlockId
1904 * @return int|null|string
1906 public static function countEventsUsingLocBlockId($locBlockId) {
1911 $locBlockId = CRM_Utils_Type
::escape($locBlockId, 'Integer');
1914 SELECT count(*) FROM civicrm_event ce
1915 WHERE ce.loc_block_id = $locBlockId";
1917 return CRM_Core_DAO
::singleValueQuery($query);
1921 * Check if event registration is valid according to permissions AND Dates.
1923 * @param array $values
1924 * @param int $eventID
1927 public static function validRegistrationRequest($values, $eventID) {
1928 // check that the user has permission to register for this event
1929 $hasPermission = CRM_Core_Permission
::event(CRM_Core_Permission
::EDIT
,
1930 $eventID, 'register for events'
1933 return $hasPermission && self
::validRegistrationDate($values);
1941 public static function validRegistrationDate(&$values) {
1942 // make sure that we are between registration start date and end dates
1943 // and that if the event has ended, registration is still specifically open
1944 $startDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_start_date', $values));
1945 $endDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_end_date', $values));
1946 $eventEnd = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('end_date', $values));
1949 if ($startDate && $startDate >= $now) {
1952 elseif ($endDate && $endDate < $now) {
1955 elseif ($eventEnd && $eventEnd < $now && !$endDate) {
1962 /* Function to Show - Hide the Registration Link.
1964 * @param array $values
1965 * Key/value event info.
1967 * true if allow registration otherwise false
1974 public static function showHideRegistrationLink($values) {
1976 $session = CRM_Core_Session
::singleton();
1977 $contactID = $session->get('userID');
1978 $alreadyRegistered = FALSE;
1981 $params = array('contact_id' => $contactID);
1983 if ($eventId = CRM_Utils_Array
::value('id', $values['event'])) {
1984 $params['event_id'] = $eventId;
1986 if ($roleId = CRM_Utils_Array
::value('default_role_id', $values['event'])) {
1987 $params['role_id'] = $roleId;
1989 $alreadyRegistered = self
::checkRegistration($params);
1992 if (!empty($values['event']['allow_same_participant_emails']) ||
2000 /* Function to check if given contact is already registered.
2002 * @param array $params
2003 * Key/value participant info.
2007 * @param array $params
2011 public static function checkRegistration($params) {
2012 $alreadyRegistered = FALSE;
2013 if (empty($params['contact_id'])) {
2014 return $alreadyRegistered;
2017 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
2019 $participant = new CRM_Event_DAO_Participant();
2020 $participant->copyValues($params);
2022 $participant->is_test
= CRM_Utils_Array
::value('is_test', $params, 0);
2023 $participant->selectAdd();
2024 $participant->selectAdd('status_id');
2025 if ($participant->find(TRUE) && array_key_exists($participant->status_id
, $statusTypes)) {
2026 $alreadyRegistered = TRUE;
2029 return $alreadyRegistered;
2033 * Make sure that the user has permission to access this event.
2035 * @param int $eventId
2039 * the permission that the user has (or null)
2041 public static function checkPermission($eventId = NULL, $type = CRM_Core_Permission
::VIEW
) {
2042 static $permissions = NULL;
2044 if (empty($permissions)) {
2045 $allEvents = CRM_Event_PseudoConstant
::event(NULL, TRUE);
2046 $createdEvents = array();
2048 $session = CRM_Core_Session
::singleton();
2049 if ($userID = $session->get('userID')) {
2050 $createdEvents = array_keys(CRM_Event_PseudoConstant
::event(NULL, TRUE, "created_id={$userID}"));
2053 // Note: for a multisite setup, a user with edit all events, can edit all events
2054 // including those from other sites
2055 if (CRM_Core_Permission
::check('edit all events')) {
2056 $permissions[CRM_Core_Permission
::EDIT
] = array_keys($allEvents);
2059 $permissions[CRM_Core_Permission
::EDIT
] = CRM_ACL_API
::group(CRM_Core_Permission
::EDIT
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2062 if (CRM_Core_Permission
::check('edit all events')) {
2063 $permissions[CRM_Core_Permission
::VIEW
] = array_keys($allEvents);
2066 if (CRM_Core_Permission
::check('access CiviEvent') &&
2067 CRM_Core_Permission
::check('view event participants')
2069 // use case: allow "view all events" but NOT "edit all events"
2070 // so for a normal site allow users with these two permissions to view all events AND
2071 // at the same time also allow any hook to override if needed.
2072 $createdEvents = array_keys($allEvents);
2074 $permissions[CRM_Core_Permission
::VIEW
] = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2077 $permissions[CRM_Core_Permission
::DELETE
] = array();
2078 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
2079 // Note: we want to restrict the scope of delete permission to
2080 // events that are editable/viewable (usecase multisite).
2081 // We can remove array_intersect once we have ACL support for delete functionality.
2082 $permissions[CRM_Core_Permission
::DELETE
] = array_intersect($permissions[CRM_Core_Permission
::EDIT
],
2083 $permissions[CRM_Core_Permission
::VIEW
]
2089 return in_array($eventId, $permissions[$type]) ?
TRUE : FALSE;
2092 return $permissions;
2096 * Build From Email as the combination of all the email ids of the logged in user,
2097 * the domain email id and the email id configured for the event
2099 * @param int $eventId
2100 * The id of the event.
2103 * an array of email ids
2105 public static function getFromEmailIds($eventId = NULL) {
2106 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email
::getFromEmail();
2109 // add the email id configured for the event
2110 $params = array('id' => $eventId);
2111 $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
2112 $eventEmail = array();
2114 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
2115 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
2116 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
2118 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
2119 $fromEmailId = array(
2120 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventEmail),
2121 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventEmail),
2123 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2127 return $fromEmailValues;
2131 * Calculate event total seats occupied.
2133 * @param int $eventId
2135 * @param sting $extraWhereClause
2136 * Extra filter on participants.
2139 * event total seats w/ given criteria.
2141 public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
2142 if (empty($eventId)) {
2146 $extraWhereClause = trim($extraWhereClause);
2147 if (!empty($extraWhereClause)) {
2148 $extraWhereClause = " AND ( {$extraWhereClause} )";
2151 //event seats calculation :
2152 //1. consider event seat as a single when participant does not have line item.
2153 //2. consider event seat as a single when participant has line items but does not
2154 // have count for corresponding price field value ( ie price field value does not carry any seat )
2155 //3. consider event seat as a sum of all seats from line items in case price field value carries count.
2158 SELECT IF ( SUM( value.count*lineItem.qty ),
2159 SUM( value.count*lineItem.qty ) +
2160 COUNT( DISTINCT participant.id ) -
2161 COUNT( DISTINCT IF ( value.count, participant.id, NULL ) ),
2162 COUNT( DISTINCT participant.id ) )
2163 FROM civicrm_participant participant
2164 INNER JOIN civicrm_contact contact ON ( contact.id = participant.contact_id AND contact.is_deleted = 0 )
2165 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
2166 LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id
2167 AND lineItem.entity_table = 'civicrm_participant' )
2168 LEFT JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id AND value.count )
2169 WHERE ( participant.event_id = %1 )
2170 AND participant.is_test = 0
2172 GROUP BY participant.event_id";
2174 return (int) CRM_Core_DAO
::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
2178 * Retrieve event template default values to be set.
2179 * as default values for current new event.
2181 * @param int $templateId
2182 * Event template id.
2185 * Array of custom data defaults.
2187 public static function getTemplateDefaultValues($templateId) {
2188 $defaults = array();
2193 $templateParams = array('id' => $templateId);
2194 CRM_Event_BAO_Event
::retrieve($templateParams, $defaults);
2195 $fieldsToExclude = array(
2198 'default_discount_fee_id',
2204 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2209 * @param int $event_id
2213 public static function get_sub_events($event_id) {
2214 $params = array('parent_event_id' => $event_id);
2215 $defaults = array();
2216 return CRM_Event_BAO_Event
::retrieve($params, $defaults);
2220 * Update the Campaign Id of all the participants of the given event.
2222 * @param int $eventID
2224 * @param int $eventCampaignID
2225 * Campaign id of that event.
2227 public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
2229 $params[1] = array($eventID, 'Integer');
2231 if (empty($eventCampaignID)) {
2232 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2235 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2236 $params[2] = array($eventCampaignID, 'Integer');
2238 CRM_Core_DAO
::executeQuery($query, $params);
2242 * Get options for a given field.
2243 * @see CRM_Core_DAO::buildOptions
2245 * @param string $fieldName
2246 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2247 * @param array $props : whatever is known about this dao object
2249 * @return array|bool
2251 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2253 // Special logic for fields whose options depend on context or properties
2254 switch ($fieldName) {
2255 case 'financial_type_id':
2256 // Fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
2257 return CRM_Financial_BAO_FinancialType
::getIncomeFinancialType();
2261 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);