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);
98 $event = new CRM_Event_DAO_Event();
100 $event->copyValues($params);
101 $result = $event->save();
103 if (!empty($params['id'])) {
104 CRM_Utils_Hook
::post('edit', 'Event', $event->id
, $event);
107 CRM_Utils_Hook
::post('create', 'Event', $event->id
, $event);
109 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
110 CRM_Price_BAO_PriceFieldValue
::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
118 * @param array $params
119 * Reference array contains the values submitted by the form.
123 public static function create(&$params) {
124 $transaction = new CRM_Core_Transaction();
125 if (empty($params['is_template'])) {
126 $params['is_template'] = 0;
128 // check if new event, if so set the created_id (if not set)
129 // and always set created_date to now
130 if (empty($params['id'])) {
131 if (empty($params['created_id'])) {
132 $session = CRM_Core_Session
::singleton();
133 $params['created_id'] = $session->get('userID');
135 $params['created_date'] = date('YmdHis');
138 $event = self
::add($params);
139 CRM_Price_BAO_PriceSet
::setPriceSets($params, $event, 'event');
140 if (is_a($event, 'CRM_Core_Error')) {
141 CRM_Core_DAO
::transaction('ROLLBACK');
145 $contactId = CRM_Core_Session
::getLoggedInContactID();
147 $contactId = CRM_Utils_Array
::value('contact_id', $params);
150 // Log the information on successful add/edit of Event
152 'entity_table' => 'civicrm_event',
153 'entity_id' => $event->id
,
154 'modified_id' => $contactId,
155 'modified_date' => date('Ymd'),
158 CRM_Core_BAO_Log
::add($logParams);
160 if (!empty($params['custom']) &&
161 is_array($params['custom'])
163 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_event', $event->id
);
166 $transaction->commit();
179 public static function del($id) {
184 CRM_Utils_Hook
::pre('delete', 'Event', $id, CRM_Core_DAO
::$_nullArray);
186 $extends = array('event');
187 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
188 foreach ($groupTree as $values) {
189 $query = "DELETE FROM %1 WHERE entity_id = %2";
190 CRM_Core_DAO
::executeQuery($query, array(
191 1 => array($values['table_name'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
192 2 => array($id, 'Integer'),
196 // Clean up references to profiles used by the event (CRM-20935)
197 $ufJoinParams = array(
198 'module' => 'CiviEvent',
199 'entity_table' => 'civicrm_event',
202 CRM_Core_BAO_UFJoin
::deleteAll($ufJoinParams);
203 $ufJoinParams = array(
204 'module' => 'CiviEvent_Additional',
205 'entity_table' => 'civicrm_event',
208 CRM_Core_BAO_UFJoin
::deleteAll($ufJoinParams);
210 // price set cleanup, CRM-5527
211 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_event', $id);
213 $event = new CRM_Event_DAO_Event();
216 if ($event->find(TRUE)) {
217 $locBlockId = $event->loc_block_id
;
218 $result = $event->delete();
220 if (!is_null($locBlockId)) {
221 self
::deleteEventLocBlock($locBlockId, $id);
224 CRM_Utils_Hook
::post('delete', 'Event', $id, $event);
232 * Delete the location block associated with an event.
234 * Function checks that it is not being used by any other event.
236 * @param int $locBlockId
237 * Location block id to be deleted.
238 * @param int $eventId
239 * Event with which loc block is associated.
241 public static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
242 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
245 $query .= " AND ce.id != $eventId;";
248 $locCount = CRM_Core_DAO
::singleValueQuery($query);
250 if ($locCount == 0) {
251 CRM_Core_BAO_Location
::deleteLocBlock($locBlockId);
256 * Get current/future Events.
259 * 0 returns current and future events.
260 * 1 if events all are required
261 * 2 returns events since 3 months ago
262 * @param int|array $id single int event id or array of multiple event ids to return
263 * @param bool $isActive
264 * true if you need only active events.
265 * @param bool $checkPermission
266 * true if you need to check permission else false.
267 * @param bool $titleOnly
268 * true if you need only title not appended with start date
272 public static function getEvents(
276 $checkPermission = TRUE,
280 SELECT `id`, `title`, `start_date`
282 WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
285 $op = is_array($id) ?
'IN' : '=';
286 $where = CRM_Contact_BAO_Query
::buildClause('id', $op, $id);
287 $query .= " AND {$where}";
290 // find only events ending in the future
291 $endDate = date('YmdHis');
293 AND ( `end_date` >= {$endDate} OR
295 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
300 // find only events starting in the last 3 months
301 $startDate = date('YmdHis', strtotime('3 months ago'));
302 $query .= " AND ( `start_date` >= {$startDate} OR start_date IS NULL )";
305 $query .= " AND civicrm_event.is_active = 1";
308 $query .= " ORDER BY title asc";
311 $dao = CRM_Core_DAO
::executeQuery($query);
312 while ($dao->fetch()) {
313 if ((!$checkPermission ||
314 CRM_Event_BAO_Event
::checkPermission($dao->id
)
318 $events[$dao->id
] = $dao->title
;
320 $events[$dao->id
] .= ' - ' . CRM_Utils_Date
::customFormat($dao->start_date
);
329 * Get events Summary.
332 * Array of event summary values
334 public static function getEventSummary() {
335 $eventSummary = $eventIds = array();
336 $config = CRM_Core_Config
::singleton();
338 // get permission and include them here
339 // does not scale, but rearranging code for now
340 // FIXME in a future release
341 $permissions = CRM_Event_BAO_Event
::checkPermission();
343 if (empty($permissions[CRM_Core_Permission
::VIEW
])) {
344 $eventSummary['total_events'] = 0;
345 return $eventSummary;
348 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission
::VIEW
])) . " ) ";
351 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
353 SELECT count(id) as total_events
355 WHERE civicrm_event.is_active = 1 AND
356 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
357 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
360 $dao = CRM_Core_DAO
::executeQuery($query);
363 $eventSummary['total_events'] = $dao->total_events
;
366 if (empty($eventSummary) ||
367 $dao->total_events
== 0
369 return $eventSummary;
372 //get the participant status type values.
373 $cpstObject = new CRM_Event_DAO_ParticipantStatusType();
374 $cpst = $cpstObject->getTableName();
375 $query = "SELECT id, name, label, class FROM $cpst";
376 $status = CRM_Core_DAO
::executeQuery($query);
377 $statusValues = array();
378 while ($status->fetch()) {
379 $statusValues[$status->id
]['id'] = $status->id
;
380 $statusValues[$status->id
]['name'] = $status->name
;
381 $statusValues[$status->id
]['label'] = $status->label
;
382 $statusValues[$status->id
]['class'] = $status->class;
385 // Get the Id of Option Group for Event Types
386 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
387 $optionGroupDAO->name
= 'event_type';
388 $optionGroupId = NULL;
389 if ($optionGroupDAO->find(TRUE)) {
390 $optionGroupId = $optionGroupDAO->id
;
392 // Get the event summary display preferences
393 $show_max_events = Civi
::settings()->get('show_events');
394 // show all events if show_events is set to a negative value
395 if (isset($show_max_events) && $show_max_events >= 0) {
396 $event_summary_limit = "LIMIT 0, $show_max_events";
399 $event_summary_limit = "";
403 SELECT civicrm_event.id as id, civicrm_event.title as event_title, civicrm_event.is_public as is_public,
404 civicrm_event.max_participants as max_participants, civicrm_event.start_date as start_date,
405 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,
406 civicrm_event.slot_label_id,
407 civicrm_event.summary as summary,
408 civicrm_pcp_block.id as is_pcp_enabled,
409 civicrm_recurring_entity.parent_id as is_repeating_event
411 LEFT JOIN civicrm_option_value ON (
412 civicrm_event.event_type_id = civicrm_option_value.value AND
413 civicrm_option_value.option_group_id = %1 )
414 LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_event.id AND civicrm_tell_friend.entity_table = 'civicrm_event' )
415 LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_event.id AND civicrm_pcp_block.entity_table = 'civicrm_event')
416 LEFT JOIN civicrm_recurring_entity ON ( civicrm_event.id = civicrm_recurring_entity.entity_id AND civicrm_recurring_entity.entity_table = 'civicrm_event' )
417 WHERE civicrm_event.is_active = 1 AND
418 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
419 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
421 ORDER BY civicrm_event.start_date ASC
424 $eventParticipant = array();
428 'eventTitle' => 'event_title',
429 'isPublic' => 'is_public',
430 'maxParticipants' => 'max_participants',
431 'startDate' => 'start_date',
432 'endDate' => 'end_date',
433 'eventType' => 'event_type',
435 'participants' => 'participants',
436 'notCountedDueToRole' => 'notCountedDueToRole',
437 'notCountedDueToStatus' => 'notCountedDueToStatus',
438 'notCountedParticipants' => 'notCountedParticipants',
441 $params = array(1 => array($optionGroupId, 'Integer'));
442 $mapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings(array(
443 'id' => CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
,
445 $dao = CRM_Core_DAO
::executeQuery($query, $params);
446 while ($dao->fetch()) {
447 foreach ($properties as $property => $name) {
457 $eventSummary['events'][$dao->id
][$property] = $set;
461 if ($dao->$name && $config->mapAPIKey
) {
464 $params = array('entity_id' => $dao->id
, 'entity_table' => 'civicrm_event');
465 $values['location'] = CRM_Core_BAO_Location
::getValues($params, TRUE);
466 if (is_numeric(CRM_Utils_Array
::value('geo_code_1', $values['location']['address'][1])) ||
468 !empty($values['location']['address'][1]['city']) &&
469 !empty($values['location']['address'][1]['state_province_id'])
472 $set = CRM_Utils_System
::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
476 $eventSummary['events'][$dao->id
][$property] = $set;
477 if (is_array($permissions[CRM_Core_Permission
::EDIT
])
478 && in_array($dao->id
, $permissions[CRM_Core_Permission
::EDIT
])) {
479 $eventSummary['events'][$dao->id
]['configure'] = CRM_Utils_System
::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
485 $eventSummary['events'][$dao->id
][$property] = CRM_Utils_Date
::customFormat($dao->$name,
491 case 'notCountedDueToRole':
492 case 'notCountedDueToStatus':
493 case 'notCountedParticipants':
496 if ($name == 'participants') {
497 $propertyCnt = self
::getParticipantCount($dao->id
);
499 $set = CRM_Utils_System
::url('civicrm/event/search',
500 "reset=1&force=1&event=$dao->id&status=true&role=true"
504 elseif ($name == 'notCountedParticipants') {
505 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, TRUE, FALSE);
507 // FIXME : selector fail to search w/ OR operator.
508 // $set = CRM_Utils_System::url( 'civicrm/event/search',
509 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
512 elseif ($name == 'notCountedDueToStatus') {
513 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, FALSE, FALSE);
515 $set = CRM_Utils_System
::url('civicrm/event/search',
516 "reset=1&force=1&event=$dao->id&status=false"
521 $propertyCnt = self
::getParticipantCount($dao->id
, FALSE, FALSE, TRUE, FALSE);
523 $set = CRM_Utils_System
::url('civicrm/event/search',
524 "reset=1&force=1&event=$dao->id&role=false"
529 $eventSummary['events'][$dao->id
][$property] = $propertyCnt;
530 $eventSummary['events'][$dao->id
][$name . '_url'] = $set;
534 $eventSummary['events'][$dao->id
][$property] = $dao->$name;
539 // prepare the area for per-status participant counts
540 $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
541 $eventSummary['events'][$dao->id
]['statuses'] = array_fill_keys($statusClasses, array());
543 $eventSummary['events'][$dao->id
]['friend'] = $dao->is_friend_active
;
544 $eventSummary['events'][$dao->id
]['is_monetary'] = $dao->is_monetary
;
545 $eventSummary['events'][$dao->id
]['is_online_registration'] = $dao->is_online_registration
;
546 $eventSummary['events'][$dao->id
]['is_show_location'] = $dao->is_show_location
;
547 $eventSummary['events'][$dao->id
]['is_subevent'] = $dao->slot_label_id
;
548 $eventSummary['events'][$dao->id
]['is_pcp_enabled'] = $dao->is_pcp_enabled
;
549 $eventSummary['events'][$dao->id
]['reminder'] = CRM_Core_BAO_ActionSchedule
::isConfigured($dao->id
, $mapping->getId());
550 $eventSummary['events'][$dao->id
]['is_repeating_event'] = $dao->is_repeating_event
;
552 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
553 foreach ($statusValues as $statusId => $statusValue) {
554 if (!array_key_exists($statusId, $statusTypes)) {
557 $class = $statusValue['class'];
558 $statusCount = self
::eventTotalSeats($dao->id
, "( participant.status_id = {$statusId} )");
560 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
562 'url' => CRM_Utils_System
::url('civicrm/event/search', $urlString),
563 'name' => $statusValue['name'],
564 'label' => $statusValue['label'],
565 'count' => $statusCount,
567 $eventSummary['events'][$dao->id
]['statuses'][$class][] = $statusInfo;
572 $countedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
573 $nonCountedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
574 $countedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
575 $nonCountedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
577 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
578 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
580 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
581 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
582 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
583 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
585 return $eventSummary;
589 * Get participant count.
591 * @param int $eventId
592 * @param bool $considerStatus consider status for participant count.
593 * Consider status for participant count.
594 * @param bool $status counted participant.
595 * Consider counted participant.
596 * @param bool $considerRole consider role for participant count.
597 * Consider role for participant count.
598 * @param bool $role consider counted( is filter role) participant.
599 * Consider counted( is filter role) participant.
602 * array with count of participants for each event based on status/role
604 public static function getParticipantCount(
606 $considerStatus = TRUE,
608 $considerRole = TRUE,
612 // consider both role and status for counted participants, CRM-4924.
614 // not counted participant.
615 if ($considerStatus && $considerRole && !$status && !$role) {
619 if ($considerStatus) {
620 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
621 $statusClause = 'NOT IN';
623 $statusClause = 'IN';
625 $status = implode(',', array_keys($statusTypes));
626 if (empty($status)) {
629 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
633 $roleTypes = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
634 $roleClause = 'NOT IN';
639 if (!empty($roleTypes)) {
640 $escapedRoles = array();
641 foreach (array_keys($roleTypes) as $roleType) {
642 $escapedRoles[] = CRM_Utils_Type
::escape($roleType, 'String');
645 $clause[] = "participant.role_id {$roleClause} ( '" . implode("', '", $escapedRoles) . "' ) ";
650 if (!empty($clause)) {
651 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
654 return self
::eventTotalSeats($eventId, $sqlClause);
658 * Get the information to map a event.
661 * For which we want map info.
663 * @return null|string
666 public static function &getMapInfo(&$id) {
670 civicrm_event.id AS event_id,
671 civicrm_event.title AS display_name,
672 civicrm_address.street_address AS street_address,
673 civicrm_address.city AS city,
674 civicrm_address.postal_code AS postal_code,
675 civicrm_address.postal_code_suffix AS postal_code_suffix,
676 civicrm_address.geo_code_1 AS latitude,
677 civicrm_address.geo_code_2 AS longitude,
678 civicrm_state_province.abbreviation AS state,
679 civicrm_country.name AS country,
680 civicrm_location_type.name AS location_type
683 LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )
684 LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )
685 LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )
686 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
687 LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )
688 WHERE civicrm_address.geo_code_1 IS NOT NULL
689 AND civicrm_address.geo_code_2 IS NOT NULL
690 AND civicrm_event.id = " . CRM_Utils_Type
::escape($id, 'Integer');
692 $dao = new CRM_Core_DAO();
695 $locations = array();
697 $config = CRM_Core_Config
::singleton();
699 while ($dao->fetch()) {
702 $location['displayName'] = addslashes($dao->display_name
);
703 $location['lat'] = $dao->latitude
;
704 $location['marker_class'] = 'Event';
705 $location['lng'] = $dao->longitude
;
707 $params = array('entity_id' => $id, 'entity_table' => 'civicrm_event');
708 $addressValues = CRM_Core_BAO_Location
::getValues($params, TRUE);
709 $location['address'] = str_replace(array(
712 ), '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
714 $location['url'] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
);
715 $location['location_type'] = $dao->location_type
;
716 $eventImage = '<img src="' . $config->resourceBase
. 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
717 $location['image'] = $eventImage;
718 $location['displayAddress'] = str_replace('<br />', ', ', $location['address']);
719 $locations[] = $location;
725 * Get the complete information for one or more events.
728 * Get events with start date >= this date.
729 * @param int $type Get events on the a specific event type (by event_type_id).
730 * Get events on the a specific event type (by event_type_id).
731 * @param int $eventId Return a single event - by event id.
732 * Return a single event - by event id.
734 * Also get events with end date >= this date.
735 * @param bool $onlyPublic Include public events only, default TRUE.
736 * Include public events only, default TRUE.
739 * array of all the events that are searched
741 public static function &getCompleteInfo(
748 $publicCondition = NULL;
750 $publicCondition = " AND civicrm_event.is_public = 1";
754 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
756 // get events with start_date >= requested start
757 $startDate = CRM_Utils_Type
::escape($start, 'Date');
758 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
762 // also get events with end_date <= requested end
763 $endDate = CRM_Utils_Type
::escape($end, 'Date');
764 $dateCondition .= " AND ( civicrm_event.end_date <= '{$endDate}' ) ";
767 // CRM-9421 and CRM-8620 Default mode for ical/rss feeds. No start or end filter passed.
768 // Need to exclude old events with only start date
769 // and not exclude events in progress (start <= today and end >= today). DGG
770 if (empty($start) && empty($end)) {
771 // get events with end date >= today, not sure of this logic
772 // but keeping this for backward compatibility as per issue CRM-5133
773 $today = date("Y-m-d G:i:s");
774 $dateCondition .= " AND ( civicrm_event.end_date >= '{$today}' OR civicrm_event.start_date >= '{$today}' ) ";
778 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
781 // Get the Id of Option Group for Event Types
782 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
783 $optionGroupDAO->name
= 'event_type';
784 $optionGroupId = NULL;
785 if ($optionGroupDAO->find(TRUE)) {
786 $optionGroupId = $optionGroupDAO->id
;
791 civicrm_event.id as event_id,
792 civicrm_email.email as email,
793 civicrm_event.title as title,
794 civicrm_event.summary as summary,
795 civicrm_event.start_date as start,
796 civicrm_event.end_date as end,
797 civicrm_event.description as description,
798 civicrm_event.is_show_location as is_show_location,
799 civicrm_event.is_online_registration as is_online_registration,
800 civicrm_event.registration_link_text as registration_link_text,
801 civicrm_event.registration_start_date as registration_start_date,
802 civicrm_event.registration_end_date as registration_end_date,
803 civicrm_option_value.label as event_type,
804 civicrm_address.name as address_name,
805 civicrm_address.street_address as street_address,
806 civicrm_address.supplemental_address_1 as supplemental_address_1,
807 civicrm_address.supplemental_address_2 as supplemental_address_2,
808 civicrm_address.supplemental_address_3 as supplemental_address_3,
809 civicrm_address.city as city,
810 civicrm_address.postal_code as postal_code,
811 civicrm_address.postal_code_suffix as postal_code_suffix,
812 civicrm_state_province.abbreviation as state,
813 civicrm_country.name AS country
815 LEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id
816 LEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id
817 LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
818 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
819 LEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id
820 LEFT JOIN civicrm_option_value ON (
821 civicrm_event.event_type_id = civicrm_option_value.value AND
822 civicrm_option_value.option_group_id = %1 )
823 WHERE civicrm_event.is_active = 1
824 AND (is_template = 0 OR is_template IS NULL)
828 if (isset($typeCondition)) {
829 $query .= $typeCondition;
832 if (isset($eventId)) {
833 $query .= " AND civicrm_event.id =$eventId ";
835 $query .= " ORDER BY civicrm_event.start_date ASC";
837 $params = array(1 => array($optionGroupId, 'Integer'));
838 $dao = CRM_Core_DAO
::executeQuery($query, $params);
840 $config = CRM_Core_Config
::singleton();
842 $baseURL = parse_url($config->userFrameworkBaseURL
);
843 $url = "@" . $baseURL['host'];
844 if (!empty($baseURL['path'])) {
845 $url .= substr($baseURL['path'], 0, -1);
848 // check 'view event info' permission
849 //@todo - per CRM-14626 we have resolved that 'view event info' means 'view ALL event info'
850 // and passing in the specific permission here will short-circuit the evaluation of permission to
851 // see specific events (doesn't seem relevant to this call
852 // however, since this function is accessed only by a convoluted call from a joomla block function
853 // it seems safer not to touch here. Suggestion is that CRM_Core_Permission::check(array or relevant permissions) would
854 // be clearer & safer here
855 $permissions = CRM_Core_Permission
::event(CRM_Core_Permission
::VIEW
);
857 // check if we're in shopping cart mode for events
858 $enable_cart = Civi
::settings()->get('enable_cart');
861 while ($dao->fetch()) {
862 if (!empty($permissions) && in_array($dao->event_id
, $permissions)) {
864 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL
) . $url;
866 $info['title'] = $dao->title
;
867 $info['event_id'] = $dao->event_id
;
868 $info['summary'] = $dao->summary
;
869 $info['description'] = $dao->description
;
870 $info['start_date'] = $dao->start
;
871 $info['end_date'] = $dao->end
;
872 $info['contact_email'] = $dao->email
;
873 $info['event_type'] = $dao->event_type
;
874 $info['is_show_location'] = $dao->is_show_location
;
875 $info['is_online_registration'] = $dao->is_online_registration
;
876 $info['registration_link_text'] = $dao->registration_link_text
;
877 $info['registration_start_date'] = $dao->registration_start_date
;
878 $info['registration_end_date'] = $dao->registration_end_date
;
883 'address_name' => $dao->address_name
,
884 'street_address' => $dao->street_address
,
885 'supplemental_address_1' => $dao->supplemental_address_1
,
886 'supplemental_address_2' => $dao->supplemental_address_2
,
887 'supplemental_address_3' => $dao->supplemental_address_3
,
888 'city' => $dao->city
,
889 'state_province' => $dao->state
,
890 'postal_code' => $dao->postal_code
,
891 'postal_code_suffix' => $dao->postal_code_suffix
,
892 'country' => $dao->country
,
896 CRM_Utils_String
::append($address, ', ',
897 CRM_Utils_Address
::format($addrFields)
899 $info['location'] = $address;
900 $info['url'] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
903 $reg = CRM_Event_Cart_BAO_EventInCart
::get_registration_link($dao->event_id
);
904 $info['registration_link'] = CRM_Utils_System
::url($reg['path'], $reg['query'], TRUE);
905 $info['registration_link_text'] = $reg['label'];
916 * Make a copy of a Event.
918 * Include all the fields in the event Wizard.
921 * The event id to copy.
922 * boolean $afterCreate call to copy after the create function
923 * @param null $newEvent
924 * @param bool $afterCreate
926 * @return CRM_Event_DAO_Event
928 public static function copy($id, $newEvent = NULL, $afterCreate = FALSE) {
930 $eventValues = array();
932 //get the require event values.
933 $eventParams = array('id' => $id);
934 $returnProperties = array(
938 'default_discount_fee_id',
942 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
944 // since the location is sharable, lets use the same loc_block_id.
945 $locBlockId = CRM_Utils_Array
::value('loc_block_id', $eventValues);
947 $fieldsFix = ($afterCreate) ?
array() : array('prefix' => array('title' => ts('Copy of') . ' '));
948 if (empty($eventValues['is_show_location'])) {
949 $fieldsFix['prefix']['is_show_location'] = 0;
952 if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
953 $copyEvent = $newEvent;
956 if (!isset($copyEvent)) {
957 $copyEvent = &CRM_Core_DAO
::copyGeneric('CRM_Event_DAO_Event',
961 ($locBlockId) ?
$locBlockId : NULL,
966 CRM_Price_BAO_PriceSet
::copyPriceSet('civicrm_event', $id, $copyEvent->id
);
967 $copyUF = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_UFJoin',
970 'entity_table' => 'civicrm_event',
972 array('entity_id' => $copyEvent->id
)
975 $copyTellFriend = &CRM_Core_DAO
::copyGeneric('CRM_Friend_DAO_Friend',
978 'entity_table' => 'civicrm_event',
980 array('entity_id' => $copyEvent->id
)
983 $copyPCP = &CRM_Core_DAO
::copyGeneric('CRM_PCP_DAO_PCPBlock',
986 'entity_table' => 'civicrm_event',
988 array('entity_id' => $copyEvent->id
),
989 array('replace' => array('target_entity_id' => $copyEvent->id
))
992 $oldMapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings(array(
993 'id' => ($eventValues['is_template'] ? CRM_Event_ActionMapping
::EVENT_TPL_MAPPING_ID
: CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
),
995 $copyMapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings(array(
996 'id' => ($copyEvent->is_template
== 1 ? CRM_Event_ActionMapping
::EVENT_TPL_MAPPING_ID
: CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
),
998 $copyReminder = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_ActionSchedule',
999 array('entity_value' => $id, 'mapping_id' => $oldMapping->getId()),
1000 array('entity_value' => $copyEvent->id
, 'mapping_id' => $copyMapping->getId())
1003 if (!$afterCreate) {
1005 self
::copyCustomFields($id, $copyEvent->id
);
1010 CRM_Utils_System
::flushCache();
1011 if (!$afterCreate) {
1012 CRM_Utils_Hook
::copy('Event', $copyEvent);
1018 * Method that copies custom fields values from an old event to a new one. Fixes bug CRM-19302,
1019 * where if a custom field of File type was present, left both events using the same file,
1020 * breaking download URL's for the old event.
1022 * @param int $oldEventID
1023 * @param int $newCopyID
1025 public static function copyCustomFields($oldEventID, $newCopyID) {
1026 // Obtain custom values for old event
1027 $customParams = $htmlType = array();
1028 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($oldEventID, 'Event');
1030 // If custom values present, we copy them
1031 if (!empty($customValues)) {
1032 // Get Field ID's and identify File type attributes, to handle file copying.
1033 $fieldIds = implode(', ', array_keys($customValues));
1034 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1035 $result = CRM_Core_DAO
::executeQuery($sql);
1037 // Build array of File type fields
1038 while ($result->fetch()) {
1039 $htmlType[] = $result->id
;
1042 // Build params array of custom values
1043 foreach ($customValues as $field => $value) {
1044 if ($value !== NULL) {
1045 // Handle File type attributes
1046 if (in_array($field, $htmlType)) {
1047 $fileValues = CRM_Core_BAO_File
::path($value, $oldEventID);
1048 $customParams["custom_{$field}_-1"] = array(
1049 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1050 'type' => $fileValues[1],
1053 // Handle other types
1055 $customParams["custom_{$field}_-1"] = $value;
1060 // Save Custom Fields for new Event
1061 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, 'civicrm_event', $newCopyID, 'Event');
1064 // copy activity attachments ( if any )
1065 CRM_Core_BAO_File
::copyEntityFile('civicrm_event', $oldEventID, 'civicrm_event', $newCopyID);
1069 * This is sometimes called in a loop (during event search).
1071 * We cache the values to prevent repeated calls to the db.
1077 public static function isMonetary($id) {
1078 static $isMonetary = array();
1079 if (!array_key_exists($id, $isMonetary)) {
1080 $isMonetary[$id] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event',
1085 return $isMonetary[$id];
1089 * This is sometimes called in a loop (during event search).
1091 * We cache the values to prevent repeated calls to the db.
1097 public static function usesPriceSet($id) {
1098 static $usesPriceSet = array();
1099 if (!array_key_exists($id, $usesPriceSet)) {
1100 $usesPriceSet[$id] = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $id);
1102 return $usesPriceSet[$id];
1108 * @param int $contactID
1109 * @param array $values
1110 * @param int $participantId
1111 * @param bool $isTest
1112 * @param bool $returnMessageText
1113 * @return array|null
1115 public static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
1117 $template = CRM_Core_Smarty
::singleton();
1119 'custom_pre_id' => $values['custom_pre_id'],
1120 'custom_post_id' => $values['custom_post_id'],
1123 //get the params submitted by participant.
1124 $participantParams = CRM_Utils_Array
::value($participantId, $values['params'], array());
1126 if (!$returnMessageText) {
1127 //send notification email if field values are set (CRM-1941)
1128 foreach ($gIds as $key => $gIdValues) {
1130 if (!is_array($gIdValues)) {
1131 $gIdValues = array($gIdValues);
1134 foreach ($gIdValues as $gId) {
1135 $email = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1137 //get values of corresponding profile fields for notification
1138 list($profileValues) = self
::buildCustomDisplay($gId,
1147 list($profileValues) = $profileValues;
1150 'values' => $profileValues,
1153 CRM_Core_BAO_UFGroup
::commonSendMail($contactID, $val);
1160 if ($values['event']['is_email_confirm'] ||
$returnMessageText) {
1161 list($displayName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1163 //send email only when email is present
1164 if (isset($email) ||
$returnMessageText) {
1165 $preProfileID = CRM_Utils_Array
::value('custom_pre_id', $values);
1166 $postProfileID = CRM_Utils_Array
::value('custom_post_id', $values);
1168 if (!empty($values['params']['additionalParticipant'])) {
1169 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values, $preProfileID);
1170 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values, $postProfileID);
1173 self
::buildCustomDisplay($preProfileID,
1183 self
::buildCustomDisplay($postProfileID,
1193 $sessions = CRM_Event_Cart_BAO_Conference
::get_participant_sessions($participantId);
1195 $tplParams = array_merge($values, $participantParams, array(
1197 'confirm_email_text' => CRM_Utils_Array
::value('confirm_email_text', $values['event']),
1198 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $values['event']),
1199 // The concept of contributeMode is deprecated.
1200 'contributeMode' => CRM_Utils_Array
::value('contributeMode', $template->_tpl_vars
),
1201 'participantID' => $participantId,
1202 'conference_sessions' => $sessions,
1203 'credit_card_number' =>
1204 CRM_Utils_System
::mungeCreditCard(
1205 CRM_Utils_Array
::value('credit_card_number', $participantParams)),
1206 'credit_card_exp_date' =>
1207 CRM_Utils_Date
::mysqlToIso(
1208 CRM_Utils_Date
::format(
1209 CRM_Utils_Array
::value('credit_card_exp_date', $participantParams))),
1212 // CRM-13890 : NOTE wait list condition need to be given so that
1213 // wait list message is shown properly in email i.e. WRT online event registration template
1214 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
1215 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id', TRUE);
1216 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($statusId, NULL, 'label');
1218 //CRM-15754 - if participant_status contains status ID
1219 elseif (!empty($tplParams['participant_status']) && CRM_Utils_Rule
::integer($tplParams['participant_status'])) {
1220 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($tplParams['participant_status'], NULL, 'label');
1223 $sendTemplateParams = array(
1224 'groupName' => 'msg_tpl_workflow_event',
1225 'valueName' => 'event_online_receipt',
1226 'contactId' => $contactID,
1227 'isTest' => $isTest,
1228 'tplParams' => $tplParams,
1229 'PDFFilename' => ts('confirmation') . '.pdf',
1232 // address required during receipt processing (pdf and email receipt)
1233 if ($displayAddress = CRM_Utils_Array
::value('address', $values)) {
1234 $sendTemplateParams['tplParams']['address'] = $displayAddress;
1235 // The concept of contributeMode is deprecated.
1236 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1239 // set lineItem details
1240 if ($lineItem = CRM_Utils_Array
::value('lineItem', $values)) {
1241 // check if additional participant, if so filter only to relevant ones
1243 if (!empty($values['params']['additionalParticipant'])) {
1244 $ownLineItems = array();
1245 foreach ($lineItem as $liKey => $liValue) {
1246 $firstElement = array_pop($liValue);
1247 if ($firstElement['entity_id'] == $participantId) {
1248 $ownLineItems[0] = $lineItem[$liKey];
1252 if (!empty($ownLineItems)) {
1253 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1257 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1261 if ($returnMessageText) {
1262 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1264 'subject' => $subject,
1266 'to' => $displayName,
1271 $sendTemplateParams['from'] = CRM_Utils_Array
::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array
::value('confirm_from_email', $values['event']) . ">";
1272 $sendTemplateParams['toName'] = $displayName;
1273 $sendTemplateParams['toEmail'] = $email;
1274 $sendTemplateParams['autoSubmitted'] = TRUE;
1275 $sendTemplateParams['cc'] = CRM_Utils_Array
::value('cc_confirm',
1278 $sendTemplateParams['bcc'] = CRM_Utils_Array
::value('bcc_confirm',
1281 // append invoice pdf to email
1282 $template = CRM_Core_Smarty
::singleton();
1283 $taxAmt = $template->get_template_vars('totalTaxAmount');
1284 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
1285 $invoicing = CRM_Utils_Array
::value('invoicing', $prefixValue);
1286 if (isset($invoicing) && isset($prefixValue['is_email_pdf']) && !empty($values['contributionId'])) {
1287 $sendTemplateParams['isEmailPdf'] = TRUE;
1288 $sendTemplateParams['contributionId'] = $values['contributionId'];
1290 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1297 * Add the custom fields OR array of participant's profile info.
1300 * @param string $name
1302 * @param string $template
1303 * @param int $participantId
1304 * @param bool $isTest
1305 * @param bool $isCustomProfile
1306 * @param array $participantParams
1308 * @return array|null
1310 public static function buildCustomDisplay(
1317 $isCustomProfile = FALSE,
1318 $participantParams = array()
1321 return array(NULL, NULL);
1324 if (!is_array($id)) {
1325 $id = CRM_Utils_Type
::escape($id, 'Positive');
1326 $profileIds = array($id);
1332 $val = $groupTitles = NULL;
1333 foreach ($profileIds as $gid) {
1334 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $cid)) {
1336 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
,
1337 NULL, NULL, FALSE, NULL,
1338 FALSE, NULL, CRM_Core_Permission
::CREATE
,
1342 //this condition is added, since same contact can have multiple event registrations..
1343 $params = array(array('participant_id', '=', $participantId, 0, 0));
1345 //add participant id
1346 $fields['participant_id'] = array(
1347 'name' => 'participant_id',
1348 'title' => ts('Participant ID'),
1350 //check whether its a text drive
1352 $params[] = array('participant_test', '=', 1, 0, 0);
1355 //display campaign on thankyou page.
1356 if (array_key_exists('participant_campaign_id', $fields)) {
1357 if ($participantId) {
1358 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1362 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1363 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array
::value($campaignId,
1367 unset($fields['participant_campaign_id']);
1371 foreach ($fields as $k => $v) {
1373 $groupTitle = $v['groupTitle'];
1375 // suppress all file fields from display
1377 CRM_Utils_Array
::value('data_type', $v, '') == 'File' ||
1378 CRM_Utils_Array
::value('name', $v, '') == 'image_URL' ||
1379 CRM_Utils_Array
::value('field_type', $v) == 'Formatting'
1386 $groupTitles[] = $groupTitle;
1388 //display profile groups those are subscribed by participant.
1389 if (($groups = CRM_Utils_Array
::value('group', $participantParams)) &&
1393 foreach ($groups as $grpId => $isSelected) {
1398 if (!empty($grpIds)) {
1399 //get the group titles.
1400 $grpTitles = array();
1401 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1402 $grp = CRM_Core_DAO
::executeQuery($query);
1403 while ($grp->fetch()) {
1404 $grpTitles[] = $grp->title
;
1406 if (!empty($grpTitles) &&
1407 CRM_Utils_Array
::value('title', CRM_Utils_Array
::value('group', $fields))
1409 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1411 unset($fields['group']);
1415 CRM_Core_BAO_UFGroup
::getValues($cid, $fields, $values, FALSE, $params);
1417 if (isset($fields['participant_status_id']['title']) &&
1418 isset($values[$fields['participant_status_id']['title']]) &&
1419 is_numeric($values[$fields['participant_status_id']['title']])
1422 $status = CRM_Event_PseudoConstant
::participantStatus();
1423 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1426 if (isset($fields['participant_role_id']['title']) &&
1427 isset($values[$fields['participant_role_id']['title']]) &&
1428 is_numeric($values[$fields['participant_role_id']['title']])
1431 $roles = CRM_Event_PseudoConstant
::participantRole();
1432 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1435 if (isset($fields['participant_register_date']['title']) &&
1436 isset($values[$fields['participant_register_date']['title']])
1438 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date
::customFormat($values[$fields['participant_register_date']['title']]);
1441 //handle fee_level for price set
1442 if (isset($fields['participant_fee_level']['title']) &&
1443 isset($values[$fields['participant_fee_level']['title']])
1445 $feeLevel = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1446 $values[$fields['participant_fee_level']['title']]
1448 foreach ($feeLevel as $key => $value) {
1450 unset($feeLevel[$key]);
1453 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
1456 unset($values[$fields['participant_id']['title']]);
1463 $template->assign($name, $val);
1466 if (count($groupTitles)) {
1467 $template->assign($name . '_grouptitle', $groupTitles);
1470 //return if we only require array of participant's info.
1471 if ($isCustomProfile) {
1473 return array($val, $groupTitles);
1482 * Build the array for display the profile fields.
1484 * @param array $params
1488 * @param array $groupTitle
1489 * Profile Group Title.
1490 * @param array $values
1491 * Formatted array of key value.
1493 * @param array $profileFields
1495 public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
1497 $config = CRM_Core_Config
::singleton();
1498 $session = CRM_Core_Session
::singleton();
1499 $contactID = $session->get('userID');
1501 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $contactID)) {
1502 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
);
1506 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::ADD
);
1509 foreach ($fields as $v) {
1510 if (!empty($v['groupTitle'])) {
1511 $groupTitle['groupTitle'] = $v['groupTitle'];
1516 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1517 //start of code to set the default values
1518 foreach ($fields as $name => $field) {
1521 // skip fields that should not be displayed separately
1522 if ($field['skipDisplay']) {
1526 $index = $field['title'];
1527 if ($name === 'organization_name') {
1528 $values[$index] = $params[$name];
1531 if ('state_province' == substr($name, 0, 14)) {
1532 if ($params[$name]) {
1533 $values[$index] = CRM_Core_PseudoConstant
::stateProvince($params[$name]);
1536 $values[$index] = '';
1539 elseif ('date' == substr($name, -4)) {
1540 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::processDate($params[$name]),
1541 $config->dateformatFull
);
1543 elseif ('country' == substr($name, 0, 7)) {
1544 if ($params[$name]) {
1545 $values[$index] = CRM_Core_PseudoConstant
::country($params[$name]);
1548 $values[$index] = '';
1551 elseif ('county' == substr($name, 0, 6)) {
1552 if ($params[$name]) {
1553 $values[$index] = CRM_Core_PseudoConstant
::county($params[$name]);
1556 $values[$index] = '';
1559 elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
1560 $values[$index] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
1562 elseif (in_array($name, array(
1567 $filterCondition = array('greeting_type' => $name);
1568 $greeting = CRM_Core_PseudoConstant
::greeting($filterCondition);
1569 $values[$index] = $greeting[$params[$name]];
1571 elseif ($name === 'preferred_communication_method') {
1572 $communicationFields = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1574 $pref = $params[$name];
1575 if (is_array($pref)) {
1576 foreach ($pref as $k => $v) {
1578 $compref[] = $communicationFields[$k];
1582 $values[$index] = implode(',', $compref);
1584 elseif ($name == 'contact_sub_type') {
1585 $values[$index] = implode(', ', $params[$name]);
1587 elseif ($name == 'group') {
1588 $groups = CRM_Contact_BAO_GroupContact
::getGroupList();
1590 foreach ($params[$name] as $gId => $dontCare) {
1592 $title[] = $groups[$gId];
1595 $values[$index] = implode(', ', $title);
1597 elseif ($name == 'tag') {
1598 $entityTags = $params[$name];
1599 $allTags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
1601 if (is_array($entityTags)) {
1602 foreach ($entityTags as $tagId => $dontCare) {
1603 $title[] = $allTags[$tagId];
1606 $values[$index] = implode(', ', $title);
1608 elseif ('participant_role_id' == $name OR
1609 'participant_role' == $name
1611 $roles = CRM_Event_PseudoConstant
::participantRole();
1612 $values[$index] = $roles[$params[$name]];
1614 elseif ('participant_status_id' == $name OR
1615 'participant_status' == $name
1617 $status = CRM_Event_PseudoConstant
::participantStatus();
1618 $values[$index] = $status[$params[$name]];
1620 elseif (substr($name, -11) == 'campaign_id') {
1621 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($params[$name]);
1622 $values[$index] = CRM_Utils_Array
::value($params[$name], $campaigns);
1624 elseif (strpos($name, '-') !== FALSE) {
1625 list($fieldName, $id) = CRM_Utils_System
::explode('-', $name, 2);
1626 $detailName = str_replace(' ', '_', $name);
1627 if (in_array($fieldName, array(
1632 $values[$index] = $params[$detailName];
1633 $idx = $detailName . '_id';
1634 $values[$index] = $params[$idx];
1636 elseif ($fieldName == 'im') {
1637 $providerName = NULL;
1638 if ($providerId = $detailName . '-provider_id') {
1639 $providerName = CRM_Utils_Array
::value($params[$providerId], $imProviders);
1641 if ($providerName) {
1642 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1645 $values[$index] = $params[$detailName];
1648 elseif ($fieldName == 'phone') {
1649 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1650 if (isset($params[$phoneExtField])) {
1651 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1654 $values[$index] = $params[$detailName];
1658 $values[$index] = $params[$detailName];
1662 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1663 if ($params[$name]) {
1664 $values[$index] = '[ x ]';
1668 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
1670 SELECT html_type, data_type
1671 FROM civicrm_custom_field
1674 $dao = CRM_Core_DAO
::executeQuery($query);
1676 $htmlType = $dao->html_type
;
1678 if ($htmlType == 'File') {
1679 $path = CRM_Utils_Array
::value('name', $params[$name]);
1680 $fileType = CRM_Utils_Array
::value('type', $params[$name]);
1681 $values[$index] = CRM_Utils_File
::getFileURL($path, $fileType);
1684 if ($dao->data_type
== 'Int' ||
1685 $dao->data_type
== 'Boolean'
1687 $v = $params[$name];
1688 if (!CRM_Utils_System
::isNull($v)) {
1689 $customVal = (int) $v;
1692 elseif ($dao->data_type
== 'Float') {
1693 $customVal = (float ) ($params[$name]);
1695 elseif ($dao->data_type
== 'Date') {
1696 //@todo note the currently we are using default date time formatting. Since you can select/set
1697 // different date and time format specific to custom field we should consider fixing this
1698 // sometime in the future
1699 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1700 CRM_Utils_Date
::processDate($params[$name]), $config->dateformatFull
);
1702 if (!empty($params[$name . '_time'])) {
1703 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1704 CRM_Utils_Date
::processDate($params[$name], $params[$name . '_time']),
1705 $config->dateformatDatetime
);
1710 $customVal = $params[$name];
1712 //take the custom field options
1713 $returnProperties = array($name => 1);
1714 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
1716 $displayValue = CRM_Core_BAO_CustomField
::displayValue($customVal, $cfID);
1718 //Hack since we dont have function to check empty.
1719 //FIXME in 2.3 using crmIsEmptyArray()
1720 $customValue = TRUE;
1721 if (is_array($customVal) && is_array($displayValue)) {
1722 $customValue = array_diff($customVal, $displayValue);
1724 //use difference of arrays
1725 if (empty($customValue) ||
!$customValue) {
1726 $values[$index] = '';
1729 $values[$index] = $displayValue;
1733 elseif ($name == 'home_URL' &&
1734 !empty($params[$name])
1736 $url = CRM_Utils_System
::fixURL($params[$name]);
1737 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1739 elseif (in_array($name, array(
1742 'participant_register_date',
1744 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::format($params[$name]));
1747 $values[$index] = CRM_Utils_Array
::value($name, $params);
1751 $profileFields[$name] = $field;
1757 * Build the array for Additional participant's information array of primary and additional Ids.
1759 * @param int $participantId
1760 * Id of Primary participant.
1761 * @param array $values
1762 * Key/value event info.
1763 * @param int $contactId
1764 * Contact id of Primary participant.
1765 * @param bool $isTest
1766 * Whether test or live transaction.
1767 * @param bool $isIdsArray
1768 * To return an array of Ids.
1770 * @param bool $skipCancel
1773 * array of Additional participant's info OR array of Ids.
1775 public static function buildCustomProfile(
1780 $isIdsArray = FALSE,
1784 $customProfile = $additionalIDs = array();
1785 if (!$participantId) {
1786 CRM_Core_Error
::fatal(ts('Cannot find participant ID'));
1789 //set Ids of Primary Participant also.
1790 if ($isIdsArray && $contactId) {
1791 $additionalIDs[$participantId] = $contactId;
1794 //hack to skip cancelled participants, CRM-4320
1795 $where = "participant.registered_by_id={$participantId}";
1797 $cancelStatusId = 0;
1798 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1799 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1800 $where .= " AND participant.status_id != {$cancelStatusId}";
1803 SELECT participant.id, participant.contact_id
1804 FROM civicrm_participant participant
1807 $dao = CRM_Core_DAO
::executeQuery($query);
1808 while ($dao->fetch()) {
1809 $additionalIDs[$dao->id
] = $dao->contact_id
;
1812 //return if only array is required.
1813 if ($isIdsArray && $contactId) {
1814 return $additionalIDs;
1817 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values);
1818 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values);
1819 //else build array of Additional participant's information.
1820 if (count($additionalIDs)) {
1821 if ($preProfileID ||
$postProfileID) {
1822 $template = CRM_Core_Smarty
::singleton();
1824 $isCustomProfile = TRUE;
1826 $title = $groupTitles = array();
1827 foreach ($additionalIDs as $pId => $cId) {
1828 //get the params submitted by participant.
1829 $participantParams = CRM_Utils_Array
::value($pId, $values['params'], array());
1831 list($profilePre, $groupTitles) = self
::buildCustomDisplay($preProfileID,
1832 'additionalCustomPre',
1842 $profile = $profilePre;
1843 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1845 $title = $groupTitles;
1849 list($profilePost, $groupTitles) = self
::buildCustomDisplay($postProfileID,
1850 'additionalCustomPost',
1860 if (isset($profilePre)) {
1861 $profile = array_merge($profilePre, $profilePost);
1863 $title = array_merge($title, $groupTitles);
1867 $profile = $profilePost;
1869 $title = $groupTitles;
1873 $profiles[] = $profile;
1876 $customProfile['title'] = $title;
1877 $customProfile['profile'] = $profiles;
1881 return $customProfile;
1885 * Retrieve all event addresses.
1889 public static function getLocationEvents() {
1893 'loc_block_id.address_id.name',
1894 'loc_block_id.address_id.street_address',
1895 'loc_block_id.address_id.supplemental_address_1',
1896 'loc_block_id.address_id.supplemental_address_2',
1897 'loc_block_id.address_id.supplemental_address_3',
1898 'loc_block_id.address_id.city',
1899 'loc_block_id.address_id.state_province_id.name',
1902 $result = civicrm_api3('Event', 'get', array(
1903 'check_permissions' => TRUE,
1905 'loc_block_id.address_id' => array('IS NOT NULL' => 1),
1911 foreach ($result['values'] as $event) {
1913 foreach ($ret as $field) {
1914 if ($field != 'loc_block_id' && !empty($event[$field])) {
1915 $address .= ($address ?
' :: ' : '') . $event[$field];
1919 $events[$event['loc_block_id']] = $address;
1923 return CRM_Utils_Array
::asort($events);
1927 * @param int $locBlockId
1929 * @return int|null|string
1931 public static function countEventsUsingLocBlockId($locBlockId) {
1936 $locBlockId = CRM_Utils_Type
::escape($locBlockId, 'Integer');
1939 SELECT count(*) FROM civicrm_event ce
1940 WHERE ce.loc_block_id = $locBlockId";
1942 return CRM_Core_DAO
::singleValueQuery($query);
1946 * Check if event registration is valid according to permissions AND Dates.
1948 * @param array $values
1949 * @param int $eventID
1952 public static function validRegistrationRequest($values, $eventID) {
1953 // check that the user has permission to register for this event
1954 $hasPermission = CRM_Core_Permission
::event(CRM_Core_Permission
::EDIT
,
1955 $eventID, 'register for events'
1958 return $hasPermission && self
::validRegistrationDate($values);
1966 public static function validRegistrationDate(&$values) {
1967 // make sure that we are between registration start date and end dates
1968 // and that if the event has ended, registration is still specifically open
1969 $startDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_start_date', $values));
1970 $endDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_end_date', $values));
1971 $eventEnd = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('end_date', $values));
1974 if ($startDate && $startDate >= $now) {
1977 elseif ($endDate && $endDate < $now) {
1980 elseif ($eventEnd && $eventEnd < $now && !$endDate) {
1987 /* Function to Show - Hide the Registration Link.
1989 * @param array $values
1990 * Key/value event info.
1992 * true if allow registration otherwise false
1999 public static function showHideRegistrationLink($values) {
2001 $session = CRM_Core_Session
::singleton();
2002 $contactID = $session->get('userID');
2003 $alreadyRegistered = FALSE;
2006 $params = array('contact_id' => $contactID);
2008 if ($eventId = CRM_Utils_Array
::value('id', $values['event'])) {
2009 $params['event_id'] = $eventId;
2011 if ($roleId = CRM_Utils_Array
::value('default_role_id', $values['event'])) {
2012 $params['role_id'] = $roleId;
2014 $alreadyRegistered = self
::checkRegistration($params);
2017 if (!empty($values['event']['allow_same_participant_emails']) ||
2025 /* Function to check if given contact is already registered.
2027 * @param array $params
2028 * Key/value participant info.
2032 * @param array $params
2036 public static function checkRegistration($params) {
2037 $alreadyRegistered = FALSE;
2038 if (empty($params['contact_id'])) {
2039 return $alreadyRegistered;
2042 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
2044 $participant = new CRM_Event_DAO_Participant();
2045 $participant->copyValues($params);
2047 $participant->is_test
= CRM_Utils_Array
::value('is_test', $params, 0);
2048 $participant->selectAdd();
2049 $participant->selectAdd('status_id');
2050 if ($participant->find(TRUE) && array_key_exists($participant->status_id
, $statusTypes)) {
2051 $alreadyRegistered = TRUE;
2054 return $alreadyRegistered;
2058 * Make sure that the user has permission to access this event.
2060 * @param int $eventId
2064 * the permission that the user has (or null)
2066 public static function checkPermission($eventId = NULL, $type = CRM_Core_Permission
::VIEW
) {
2067 static $permissions = NULL;
2069 if (empty($permissions)) {
2071 'check_permissions' => 1,
2072 'return' => 'title',
2079 $params['id'] = $eventId;
2082 $result = civicrm_api3('Event', 'get', $params);
2083 $allEvents = CRM_Utils_Array
::collect('title', $result['values']);
2085 // Search again, but only events created by the user.
2086 $params['created_id'] = 'user_contact_id';
2087 $result = civicrm_api3('Event', 'get', $params);
2088 $createdEvents = CRM_Utils_Array
::collect('title', $result['values']);
2090 // Note: for a multisite setup, a user with edit all events, can edit all events
2091 // including those from other sites
2092 if (CRM_Core_Permission
::check('edit all events')) {
2093 $permissions[CRM_Core_Permission
::EDIT
] = array_keys($allEvents);
2096 $permissions[CRM_Core_Permission
::EDIT
] = CRM_ACL_API
::group(CRM_Core_Permission
::EDIT
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2099 if (CRM_Core_Permission
::check('edit all events')) {
2100 $permissions[CRM_Core_Permission
::VIEW
] = array_keys($allEvents);
2103 if (CRM_Core_Permission
::check('access CiviEvent') &&
2104 CRM_Core_Permission
::check('view event participants')
2106 // use case: allow "view all events" but NOT "edit all events"
2107 // so for a normal site allow users with these two permissions to view all events AND
2108 // at the same time also allow any hook to override if needed.
2109 $createdEvents = array_keys($allEvents);
2111 $permissions[CRM_Core_Permission
::VIEW
] = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2114 $permissions[CRM_Core_Permission
::DELETE
] = array();
2115 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
2116 // Note: we want to restrict the scope of delete permission to
2117 // events that are editable/viewable (usecase multisite).
2118 // We can remove array_intersect once we have ACL support for delete functionality.
2119 $permissions[CRM_Core_Permission
::DELETE
] = array_intersect($permissions[CRM_Core_Permission
::EDIT
],
2120 $permissions[CRM_Core_Permission
::VIEW
]
2126 return in_array($eventId, $permissions[$type]) ?
TRUE : FALSE;
2129 return $permissions;
2133 * Build From Email as the combination of all the email ids of the logged in user,
2134 * the domain email id and the email id configured for the event
2136 * @param int $eventId
2137 * The id of the event.
2140 * an array of email ids
2142 public static function getFromEmailIds($eventId = NULL) {
2143 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email
::getFromEmail();
2146 // add the email id configured for the event
2147 $params = array('id' => $eventId);
2148 $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
2149 $eventEmail = array();
2151 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
2152 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
2153 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
2155 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
2156 $fromEmailId = array(
2157 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventEmail),
2158 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventEmail),
2160 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2164 return $fromEmailValues;
2168 * Calculate event total seats occupied.
2170 * @param int $eventId
2172 * @param sting $extraWhereClause
2173 * Extra filter on participants.
2176 * event total seats w/ given criteria.
2178 public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
2179 if (empty($eventId)) {
2183 $extraWhereClause = trim($extraWhereClause);
2184 if (!empty($extraWhereClause)) {
2185 $extraWhereClause = " AND ( {$extraWhereClause} )";
2188 //event seats calculation :
2189 //1. consider event seat as a single when participant does not have line item.
2190 //2. consider event seat as a single when participant has line items but does not
2191 // have count for corresponding price field value ( ie price field value does not carry any seat )
2192 //3. consider event seat as a sum of all seats from line items in case price field value carries count.
2195 SELECT IF ( SUM( value.count*lineItem.qty ),
2196 SUM( value.count*lineItem.qty ) +
2197 COUNT( DISTINCT participant.id ) -
2198 COUNT( DISTINCT IF ( value.count, participant.id, NULL ) ),
2199 COUNT( DISTINCT participant.id ) )
2200 FROM civicrm_participant participant
2201 INNER JOIN civicrm_contact contact ON ( contact.id = participant.contact_id AND contact.is_deleted = 0 )
2202 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
2203 LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id
2204 AND lineItem.entity_table = 'civicrm_participant' )
2205 LEFT JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id AND value.count )
2206 WHERE ( participant.event_id = %1 )
2207 AND participant.is_test = 0
2209 GROUP BY participant.event_id";
2211 return (int) CRM_Core_DAO
::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
2215 * Retrieve event template default values to be set.
2216 * as default values for current new event.
2218 * @param int $templateId
2219 * Event template id.
2222 * Array of custom data defaults.
2224 public static function getTemplateDefaultValues($templateId) {
2225 $defaults = array();
2230 $templateParams = array('id' => $templateId);
2231 CRM_Event_BAO_Event
::retrieve($templateParams, $defaults);
2232 $fieldsToExclude = array(
2235 'default_discount_fee_id',
2241 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2246 * @param int $event_id
2250 public static function get_sub_events($event_id) {
2251 $params = array('parent_event_id' => $event_id);
2252 $defaults = array();
2253 return CRM_Event_BAO_Event
::retrieve($params, $defaults);
2257 * Update the Campaign Id of all the participants of the given event.
2259 * @param int $eventID
2261 * @param int $eventCampaignID
2262 * Campaign id of that event.
2264 public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
2266 $params[1] = array($eventID, 'Integer');
2268 if (empty($eventCampaignID)) {
2269 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2272 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2273 $params[2] = array($eventCampaignID, 'Integer');
2275 CRM_Core_DAO
::executeQuery($query, $params);
2279 * Get options for a given field.
2280 * @see CRM_Core_DAO::buildOptions
2282 * @param string $fieldName
2283 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2284 * @param array $props : whatever is known about this dao object
2286 * @return array|bool
2288 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2290 // Special logic for fields whose options depend on context or properties
2291 switch ($fieldName) {
2292 case 'financial_type_id':
2293 // Fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
2294 return CRM_Financial_BAO_FinancialType
::getIncomeFinancialType();
2298 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);