3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Event_BAO_Event
extends CRM_Event_DAO_Event
{
40 public function __construct() {
41 parent
::__construct();
45 * Fetch object based on array of properties.
47 * @param array $params
48 * (reference ) an assoc array of name/value pairs.
49 * @param array $defaults
50 * (reference ) an assoc array to hold the flattened values.
52 * @return CRM_Event_BAO_ManageEvent
54 public static function retrieve(&$params, &$defaults) {
55 $event = new CRM_Event_DAO_Event();
56 $event->copyValues($params);
57 if ($event->find(TRUE)) {
58 CRM_Core_DAO
::storeValues($event, $defaults);
65 * Update the is_active flag in the db.
68 * Id of the database record.
69 * @param bool $is_active
70 * Value we want to set the is_active field.
73 * DAO object on sucess, null otherwise
75 public static function setIsActive($id, $is_active) {
76 return CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
82 * @param array $params
83 * Reference array contains the values submitted by the form.
88 public static function add(&$params) {
89 CRM_Utils_System
::flushCache();
90 $financialTypeId = NULL;
91 if (!empty($params['id'])) {
92 CRM_Utils_Hook
::pre('edit', 'Event', $params['id'], $params);
93 if (empty($params['skipFinancialType'])) {
94 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $params['id'], 'financial_type_id');
98 CRM_Utils_Hook
::pre('create', 'Event', NULL, $params);
101 $event = new CRM_Event_DAO_Event();
103 $event->copyValues($params);
104 $result = $event->save();
106 if (!empty($params['id'])) {
107 CRM_Utils_Hook
::post('edit', 'Event', $event->id
, $event);
110 CRM_Utils_Hook
::post('create', 'Event', $event->id
, $event);
112 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
113 CRM_Price_BAO_PriceFieldValue
::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
121 * @param array $params
122 * Reference array contains the values submitted by the form.
126 public static function create(&$params) {
127 $transaction = new CRM_Core_Transaction();
128 if (empty($params['is_template'])) {
129 $params['is_template'] = 0;
131 // check if new event, if so set the created_id (if not set)
132 // and always set created_date to now
133 if (empty($params['id'])) {
134 if (empty($params['created_id'])) {
135 $session = CRM_Core_Session
::singleton();
136 $params['created_id'] = $session->get('userID');
138 $params['created_date'] = date('YmdHis');
141 $event = self
::add($params);
142 CRM_Price_BAO_PriceSet
::setPriceSets($params, $event, 'event');
143 if (is_a($event, 'CRM_Core_Error')) {
144 CRM_Core_DAO
::transaction('ROLLBACK');
148 $session = CRM_Core_Session
::singleton();
149 $contactId = $session->get('userID');
151 $contactId = CRM_Utils_Array
::value('contact_id', $params);
154 // Log the information on successful add/edit of Event
156 'entity_table' => 'civicrm_event',
157 'entity_id' => $event->id
,
158 'modified_id' => $contactId,
159 'modified_date' => date('Ymd'),
162 CRM_Core_BAO_Log
::add($logParams);
164 if (!empty($params['custom']) &&
165 is_array($params['custom'])
167 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_event', $event->id
);
170 $transaction->commit();
183 public static function del($id) {
188 CRM_Utils_Hook
::pre('delete', 'Event', $id, CRM_Core_DAO
::$_nullArray);
190 $extends = array('event');
191 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
192 foreach ($groupTree as $values) {
193 $query = "DELETE FROM " . $values['table_name'] . " WHERE entity_id = " . $id;
196 1 => array($values['table_name'], 'string'),
197 2 => array($id, 'integer'),
200 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
203 // price set cleanup, CRM-5527
204 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_event', $id);
206 $event = new CRM_Event_DAO_Event();
209 if ($event->find(TRUE)) {
210 $locBlockId = $event->loc_block_id
;
211 $result = $event->delete();
213 if (!is_null($locBlockId)) {
214 self
::deleteEventLocBlock($locBlockId, $id);
217 CRM_Utils_Hook
::post('delete', 'Event', $id, $event);
225 * Delete the location block associated with an event,
226 * if not being used by any other event.
229 * Location block id to be deleted.
230 * @param int $eventId
231 * Event with which loc block is associated.
234 public static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
235 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
238 $query .= " AND ce.id != $eventId;";
241 $locCount = CRM_Core_DAO
::singleValueQuery($query);
243 if ($locCount == 0) {
244 CRM_Core_BAO_Location
::deleteLocBlock($locBlockId);
249 * Get current/future Events
252 * 0 returns current and future events.
253 * 1 if events all are required
254 * 2 returns events since 3 months ago
255 * @param bool|int $id int id of a specific event to return
256 * @param bool $isActive
257 * true if you need only active events.
258 * @param bool $checkPermission
259 * true if you need to check permission else false.
263 public static function getEvents(
267 $checkPermission = TRUE
270 SELECT `id`, `title`, `start_date`
272 WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
275 $query .= " AND `id` = {$id}";
278 // find only events ending in the future
279 $endDate = date('YmdHis');
281 AND ( `end_date` >= {$endDate} OR
283 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
288 // find only events starting in the last 3 months
289 $startDate = date('YmdHis', strtotime('3 months ago'));
290 $query .= " AND ( `start_date` >= {$startDate} OR start_date IS NULL )";
293 $query .= " AND civicrm_event.is_active = 1";
296 $query .= " ORDER BY title asc";
299 $dao = CRM_Core_DAO
::executeQuery($query);
300 while ($dao->fetch()) {
301 if ((!$checkPermission ||
302 CRM_Event_BAO_Event
::checkPermission($dao->id
)
306 $events[$dao->id
] = $dao->title
. ' - ' . CRM_Utils_Date
::customFormat($dao->start_date
);
314 * Get events Summary.
318 * Array of event summary values
320 public static function getEventSummary() {
321 $eventSummary = $eventIds = array();
322 $config = CRM_Core_Config
::singleton();
324 // get permission and include them here
325 // does not scale, but rearranging code for now
326 // FIXME in a future release
327 $permissions = CRM_Event_BAO_Event
::checkPermission();
329 if (empty($permissions[CRM_Core_Permission
::VIEW
])) {
330 $eventSummary['total_events'] = 0;
331 return $eventSummary;
334 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission
::VIEW
])) . " ) ";
337 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
339 SELECT count(id) as total_events
341 WHERE civicrm_event.is_active = 1 AND
342 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
343 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
346 $dao = CRM_Core_DAO
::executeQuery($query);
349 $eventSummary['total_events'] = $dao->total_events
;
352 if (empty($eventSummary) ||
353 $dao->total_events
== 0
355 return $eventSummary;
358 //get the participant status type values.
359 $cpstObject = new CRM_Event_DAO_ParticipantStatusType();
360 $cpst = $cpstObject->getTableName();
361 $query = "SELECT id, name, label, class FROM $cpst";
362 $status = CRM_Core_DAO
::executeQuery($query);
363 $statusValues = array();
364 while ($status->fetch()) {
365 $statusValues[$status->id
]['id'] = $status->id
;
366 $statusValues[$status->id
]['name'] = $status->name
;
367 $statusValues[$status->id
]['label'] = $status->label
;
368 $statusValues[$status->id
]['class'] = $status->class;
371 // Get the Id of Option Group for Event Types
372 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
373 $optionGroupDAO->name
= 'event_type';
374 $optionGroupId = NULL;
375 if ($optionGroupDAO->find(TRUE)) {
376 $optionGroupId = $optionGroupDAO->id
;
378 // Get the event summary display preferences
379 $show_max_events = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
,
382 // default to 10 if no option is set
383 if (is_null($show_max_events)) {
384 $show_max_events = 10;
386 // show all events if show_events is set to a negative value
387 if ($show_max_events >= 0) {
388 $event_summary_limit = "LIMIT 0, $show_max_events";
391 $event_summary_limit = "";
395 SELECT civicrm_event.id as id, civicrm_event.title as event_title, civicrm_event.is_public as is_public,
396 civicrm_event.max_participants as max_participants, civicrm_event.start_date as start_date,
397 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,
398 civicrm_event.slot_label_id,
399 civicrm_event.summary as summary,
400 civicrm_pcp_block.id as is_pcp_enabled,
401 civicrm_recurring_entity.parent_id as is_repeating_event
403 LEFT JOIN civicrm_option_value ON (
404 civicrm_event.event_type_id = civicrm_option_value.value AND
405 civicrm_option_value.option_group_id = %1 )
406 LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_event.id AND civicrm_tell_friend.entity_table = 'civicrm_event' )
407 LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_event.id AND civicrm_pcp_block.entity_table = 'civicrm_event')
408 LEFT JOIN civicrm_recurring_entity ON ( civicrm_event.id = civicrm_recurring_entity.entity_id AND civicrm_recurring_entity.entity_table = 'civicrm_event' )
409 WHERE civicrm_event.is_active = 1 AND
410 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
411 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
413 GROUP BY civicrm_event.id
414 ORDER BY civicrm_event.start_date ASC
417 $eventParticipant = array();
421 'eventTitle' => 'event_title',
422 'isPublic' => 'is_public',
423 'maxParticipants' => 'max_participants',
424 'startDate' => 'start_date',
425 'endDate' => 'end_date',
426 'eventType' => 'event_type',
428 'participants' => 'participants',
429 'notCountedDueToRole' => 'notCountedDueToRole',
430 'notCountedDueToStatus' => 'notCountedDueToStatus',
431 'notCountedParticipants' => 'notCountedParticipants',
434 $params = array(1 => array($optionGroupId, 'Integer'));
435 $mappingID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', 'civicrm_event', 'id', 'entity_value');
436 $dao = CRM_Core_DAO
::executeQuery($query, $params);
437 while ($dao->fetch()) {
438 foreach ($properties as $property => $name) {
448 $eventSummary['events'][$dao->id
][$property] = $set;
452 if ($dao->$name && $config->mapAPIKey
) {
455 $params = array('entity_id' => $dao->id
, 'entity_table' => 'civicrm_event');
456 $values['location'] = CRM_Core_BAO_Location
::getValues($params, TRUE);
457 if (is_numeric(CRM_Utils_Array
::value('geo_code_1', $values['location']['address'][1])) ||
458 ($config->mapGeoCoding
&&
459 !empty($values['location']['address'][1]['city']) &&
460 !empty($values['location']['address'][1]['state_province_id'])
463 $set = CRM_Utils_System
::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
467 $eventSummary['events'][$dao->id
][$property] = $set;
468 if (in_array($dao->id
, $permissions[CRM_Core_Permission
::EDIT
])) {
469 $eventSummary['events'][$dao->id
]['configure'] = CRM_Utils_System
::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
475 $eventSummary['events'][$dao->id
][$property] = CRM_Utils_Date
::customFormat($dao->$name,
481 case 'notCountedDueToRole':
482 case 'notCountedDueToStatus':
483 case 'notCountedParticipants':
486 if ($name == 'participants') {
487 $propertyCnt = self
::getParticipantCount($dao->id
);
489 $set = CRM_Utils_System
::url('civicrm/event/search',
490 "reset=1&force=1&event=$dao->id&status=true&role=true"
494 elseif ($name == 'notCountedParticipants') {
495 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, TRUE, FALSE);
497 // FIXME : selector fail to search w/ OR operator.
498 // $set = CRM_Utils_System::url( 'civicrm/event/search',
499 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
502 elseif ($name == 'notCountedDueToStatus') {
503 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, FALSE, FALSE);
505 $set = CRM_Utils_System
::url('civicrm/event/search',
506 "reset=1&force=1&event=$dao->id&status=false"
511 $propertyCnt = self
::getParticipantCount($dao->id
, FALSE, FALSE, TRUE, FALSE);
513 $set = CRM_Utils_System
::url('civicrm/event/search',
514 "reset=1&force=1&event=$dao->id&role=false"
519 $eventSummary['events'][$dao->id
][$property] = $propertyCnt;
520 $eventSummary['events'][$dao->id
][$name . '_url'] = $set;
524 $eventSummary['events'][$dao->id
][$property] = $dao->$name;
529 // prepare the area for per-status participant counts
530 $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
531 $eventSummary['events'][$dao->id
]['statuses'] = array_fill_keys($statusClasses, array());
533 $eventSummary['events'][$dao->id
]['friend'] = $dao->is_friend_active
;
534 $eventSummary['events'][$dao->id
]['is_monetary'] = $dao->is_monetary
;
535 $eventSummary['events'][$dao->id
]['is_online_registration'] = $dao->is_online_registration
;
536 $eventSummary['events'][$dao->id
]['is_show_location'] = $dao->is_show_location
;
537 $eventSummary['events'][$dao->id
]['is_subevent'] = $dao->slot_label_id
;
538 $eventSummary['events'][$dao->id
]['is_pcp_enabled'] = $dao->is_pcp_enabled
;
539 $eventSummary['events'][$dao->id
]['reminder'] = CRM_Core_BAO_ActionSchedule
::isConfigured($dao->id
, $mappingID);
540 $eventSummary['events'][$dao->id
]['is_repeating_event'] = $dao->is_repeating_event
;
542 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
543 foreach ($statusValues as $statusId => $statusValue) {
544 if (!array_key_exists($statusId, $statusTypes)) {
547 $class = $statusValue['class'];
548 $statusCount = self
::eventTotalSeats($dao->id
, "( participant.status_id = {$statusId} )");
550 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
552 'url' => CRM_Utils_System
::url('civicrm/event/search', $urlString),
553 'name' => $statusValue['name'],
554 'label' => $statusValue['label'],
555 'count' => $statusCount,
557 $eventSummary['events'][$dao->id
]['statuses'][$class][] = $statusInfo;
562 $countedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
563 $nonCountedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
564 $countedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
565 $nonCountedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
567 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
568 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
570 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
571 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
572 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
573 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
575 return $eventSummary;
579 * Get participant count.
581 * @param int $eventId
582 * @param bool $considerStatus consider status for participant count.
583 * Consider status for participant count.
584 * @param bool $status counted participant.
585 * Consider counted participant.
586 * @param bool $considerRole consider role for participant count.
587 * Consider role for participant count.
588 * @param bool $role consider counted( is filter role) participant.
589 * Consider counted( is filter role) participant.
593 * array with count of participants for each event based on status/role
595 public static function getParticipantCount(
597 $considerStatus = TRUE,
599 $considerRole = TRUE,
603 // consider both role and status for counted participants, CRM-4924.
605 // not counted participant.
606 if ($considerStatus && $considerRole && !$status && !$role) {
610 if ($considerStatus) {
611 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
612 $statusClause = 'NOT IN';
614 $statusClause = 'IN';
616 $status = implode(',', array_keys($statusTypes));
617 if (empty($status)) {
620 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
624 $roleTypes = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
625 $roleClause = 'NOT IN';
629 $roles = implode(',', array_keys($roleTypes));
633 $clause[] = "participant.role_id {$roleClause} ( $roles )";
637 if (!empty($clause)) {
638 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
641 return self
::eventTotalSeats($eventId, $sqlClause);
645 * Get the information to map a event.
648 * For which we want map info.
650 * @return null|string
653 public static function &getMapInfo(&$id) {
657 civicrm_event.id AS event_id,
658 civicrm_event.title AS display_name,
659 civicrm_address.street_address AS street_address,
660 civicrm_address.city AS city,
661 civicrm_address.postal_code AS postal_code,
662 civicrm_address.postal_code_suffix AS postal_code_suffix,
663 civicrm_address.geo_code_1 AS latitude,
664 civicrm_address.geo_code_2 AS longitude,
665 civicrm_state_province.abbreviation AS state,
666 civicrm_country.name AS country,
667 civicrm_location_type.name AS location_type
670 LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )
671 LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )
672 LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )
673 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
674 LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )
675 WHERE civicrm_address.geo_code_1 IS NOT NULL
676 AND civicrm_address.geo_code_2 IS NOT NULL
677 AND civicrm_event.id = " . CRM_Utils_Type
::escape($id, 'Integer');
679 $dao = new CRM_Core_DAO();
682 $locations = array();
684 $config = CRM_Core_Config
::singleton();
686 while ($dao->fetch()) {
689 $location['displayName'] = addslashes($dao->display_name
);
690 $location['lat'] = $dao->latitude
;
691 $location['marker_class'] = 'Event';
692 $location['lng'] = $dao->longitude
;
694 $params = array('entity_id' => $id, 'entity_table' => 'civicrm_event');
695 $addressValues = CRM_Core_BAO_Location
::getValues($params, TRUE);
696 $location['address'] = str_replace(array(
699 ), '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
701 $location['url'] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
);
702 $location['location_type'] = $dao->location_type
;
703 $eventImage = '<img src="' . $config->resourceBase
. 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
704 $location['image'] = $eventImage;
705 $location['displayAddress'] = str_replace('<br />', ', ', $location['address']);
706 $locations[] = $location;
712 * Get the complete information for one or more events.
715 * Get events with start date >= this date.
716 * @param int $type Get events on the a specific event type (by event_type_id).
717 * Get events on the a specific event type (by event_type_id).
718 * @param int $eventId Return a single event - by event id.
719 * Return a single event - by event id.
721 * Also get events with end date >= this date.
722 * @param bool $onlyPublic Include public events only, default TRUE.
723 * Include public events only, default TRUE.
726 * array of all the events that are searched
728 public static function &getCompleteInfo(
735 $publicCondition = NULL;
737 $publicCondition = " AND civicrm_event.is_public = 1";
741 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
743 // get events with start_date >= requested start
744 $startDate = CRM_Utils_Type
::escape($start, 'Date');
745 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
749 // also get events with end_date <= requested end
750 $endDate = CRM_Utils_Type
::escape($end, 'Date');
751 $dateCondition .= " AND ( civicrm_event.end_date <= '{$endDate}' ) ";
754 // CRM-9421 and CRM-8620 Default mode for ical/rss feeds. No start or end filter passed.
755 // Need to exclude old events with only start date
756 // and not exclude events in progress (start <= today and end >= today). DGG
757 if (empty($start) && empty($end)) {
758 // get events with end date >= today, not sure of this logic
759 // but keeping this for backward compatibility as per issue CRM-5133
760 $today = date("Y-m-d G:i:s");
761 $dateCondition .= " AND ( civicrm_event.end_date >= '{$today}' OR civicrm_event.start_date >= '{$today}' ) ";
765 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
768 // Get the Id of Option Group for Event Types
769 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
770 $optionGroupDAO->name
= 'event_type';
771 $optionGroupId = NULL;
772 if ($optionGroupDAO->find(TRUE)) {
773 $optionGroupId = $optionGroupDAO->id
;
778 civicrm_event.id as event_id,
779 civicrm_email.email as email,
780 civicrm_event.title as title,
781 civicrm_event.summary as summary,
782 civicrm_event.start_date as start,
783 civicrm_event.end_date as end,
784 civicrm_event.description as description,
785 civicrm_event.is_show_location as is_show_location,
786 civicrm_event.is_online_registration as is_online_registration,
787 civicrm_event.registration_link_text as registration_link_text,
788 civicrm_event.registration_start_date as registration_start_date,
789 civicrm_event.registration_end_date as registration_end_date,
790 civicrm_option_value.label as event_type,
791 civicrm_address.name as address_name,
792 civicrm_address.street_address as street_address,
793 civicrm_address.supplemental_address_1 as supplemental_address_1,
794 civicrm_address.supplemental_address_2 as supplemental_address_2,
795 civicrm_address.city as city,
796 civicrm_address.postal_code as postal_code,
797 civicrm_address.postal_code_suffix as postal_code_suffix,
798 civicrm_state_province.abbreviation as state,
799 civicrm_country.name AS country
801 LEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id
802 LEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id
803 LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
804 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
805 LEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id
806 LEFT JOIN civicrm_option_value ON (
807 civicrm_event.event_type_id = civicrm_option_value.value AND
808 civicrm_option_value.option_group_id = %1 )
809 WHERE civicrm_event.is_active = 1
810 AND (is_template = 0 OR is_template IS NULL)
814 if (isset($typeCondition)) {
815 $query .= $typeCondition;
818 if (isset($eventId)) {
819 $query .= " AND civicrm_event.id =$eventId ";
821 $query .= " ORDER BY civicrm_event.start_date ASC";
823 $params = array(1 => array($optionGroupId, 'Integer'));
824 $dao = CRM_Core_DAO
::executeQuery($query, $params);
826 $config = CRM_Core_Config
::singleton();
828 $baseURL = parse_url($config->userFrameworkBaseURL
);
829 $url = "@" . $baseURL['host'];
830 if (!empty($baseURL['path'])) {
831 $url .= substr($baseURL['path'], 0, -1);
834 // check 'view event info' permission
835 //@todo - per CRM-14626 we have resolved that 'view event info' means 'view ALL event info'
836 // and passing in the specific permission here will short-circuit the evaluation of permission to
837 // see specific events (doesn't seem relevant to this call
838 // however, since this function is accessed only by a convoluted call from a joomla block function
839 // it seems safer not to touch here. Suggestion is that CRM_Core_Permission::check(array or relevant permissions) would
840 // be clearer & safer here
841 $permissions = CRM_Core_Permission
::event(CRM_Core_Permission
::VIEW
);
843 // check if we're in shopping cart mode for events
844 $enable_cart = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
,
849 while ($dao->fetch()) {
850 if (!empty($permissions) && in_array($dao->event_id
, $permissions)) {
852 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL
) . $url;
854 $info['title'] = $dao->title
;
855 $info['event_id'] = $dao->event_id
;
856 $info['summary'] = $dao->summary
;
857 $info['description'] = $dao->description
;
858 $info['start_date'] = $dao->start
;
859 $info['end_date'] = $dao->end
;
860 $info['contact_email'] = $dao->email
;
861 $info['event_type'] = $dao->event_type
;
862 $info['is_show_location'] = $dao->is_show_location
;
863 $info['is_online_registration'] = $dao->is_online_registration
;
864 $info['registration_link_text'] = $dao->registration_link_text
;
865 $info['registration_start_date'] = $dao->registration_start_date
;
866 $info['registration_end_date'] = $dao->registration_end_date
;
871 'address_name' => $dao->address_name
,
872 'street_address' => $dao->street_address
,
873 'supplemental_address_1' => $dao->supplemental_address_1
,
874 'supplemental_address_2' => $dao->supplemental_address_2
,
875 'city' => $dao->city
,
876 'state_province' => $dao->state
,
877 'postal_code' => $dao->postal_code
,
878 'postal_code_suffix' => $dao->postal_code_suffix
,
879 'country' => $dao->country
,
883 CRM_Utils_String
::append($address, ', ',
884 CRM_Utils_Address
::format($addrFields)
886 $info['location'] = $address;
887 $info['url'] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
890 $reg = CRM_Event_Cart_BAO_EventInCart
::get_registration_link($dao->event_id
);
891 $info['registration_link'] = CRM_Utils_System
::url($reg['path'], $reg['query'], TRUE);
892 $info['registration_link_text'] = $reg['label'];
903 * make a copy of a Event, including
904 * all the fields in the event Wizard
907 * The event id to copy.
908 * boolean $afterCreate call to copy after the create function
909 * @param null $newEvent
910 * @param bool $afterCreate
912 * @return CRM_Event_DAO_Event
914 public static function copy($id, $newEvent = NULL, $afterCreate = FALSE) {
916 $eventValues = array();
918 //get the require event values.
919 $eventParams = array('id' => $id);
920 $returnProperties = array(
924 'default_discount_fee_id',
928 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
930 // since the location is sharable, lets use the same loc_block_id.
931 $locBlockId = CRM_Utils_Array
::value('loc_block_id', $eventValues);
933 $fieldsFix = ($afterCreate) ?
array() : array('prefix' => array('title' => ts('Copy of') . ' '));
934 if (empty($eventValues['is_show_location'])) {
935 $fieldsFix['prefix']['is_show_location'] = 0;
938 if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
939 $copyEvent = $newEvent;
942 if (!isset($copyEvent)) {
943 $copyEvent = &CRM_Core_DAO
::copyGeneric('CRM_Event_DAO_Event',
947 ($locBlockId) ?
$locBlockId : NULL,
952 CRM_Price_BAO_PriceSet
::copyPriceSet('civicrm_event', $id, $copyEvent->id
);
953 $copyUF = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_UFJoin',
956 'entity_table' => 'civicrm_event',
958 array('entity_id' => $copyEvent->id
)
961 $copyTellFriend = &CRM_Core_DAO
::copyGeneric('CRM_Friend_DAO_Friend',
964 'entity_table' => 'civicrm_event',
966 array('entity_id' => $copyEvent->id
)
969 $copyPCP = &CRM_Core_DAO
::copyGeneric('CRM_PCP_DAO_PCPBlock',
972 'entity_table' => 'civicrm_event',
974 array('entity_id' => $copyEvent->id
),
975 array('replace' => array('target_entity_id' => $copyEvent->id
))
978 if ($eventValues['is_template']) {
979 $field = 'event_template';
982 $field = 'civicrm_event';
984 $mappingId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
985 $oldData = array('entity_value' => $id, 'mapping_id' => $mappingId);
986 if ($copyEvent->is_template
== 1) {
987 $field = 'event_template';
990 $field = 'civicrm_event';
992 $copyMappingId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
993 $newData = array('entity_value' => $copyEvent->id
, 'mapping_id' => $copyMappingId);
994 $copyReminder = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_ActionSchedule',
1001 $extends = array('event');
1002 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
1004 foreach ($groupTree as $groupID => $group) {
1005 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
1006 foreach ($group['fields'] as $fieldID => $field) {
1007 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1011 foreach ($table as $tableName => $tableColumns) {
1012 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
1013 $tableColumns[0] = $copyEvent->id
;
1014 $select = 'SELECT ' . implode(', ', $tableColumns);
1015 $from = ' FROM ' . $tableName;
1016 $where = " WHERE {$tableName}.entity_id = {$id}";
1017 $query = $insert . $select . $from . $where;
1018 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1024 CRM_Utils_System
::flushCache();
1025 if (!$afterCreate) {
1026 CRM_Utils_Hook
::copy('Event', $copyEvent);
1032 * This is sometimes called in a loop (during event search)
1033 * hence we cache the values to prevent repeated calls to the db
1035 public static function isMonetary($id) {
1036 static $isMonetary = array();
1037 if (!array_key_exists($id, $isMonetary)) {
1038 $isMonetary[$id] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event',
1043 return $isMonetary[$id];
1047 * This is sometimes called in a loop (during event search)
1048 * hence we cache the values to prevent repeated calls to the db
1050 public static function usesPriceSet($id) {
1051 static $usesPriceSet = array();
1052 if (!array_key_exists($id, $usesPriceSet)) {
1053 $usesPriceSet[$id] = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $id);
1055 return $usesPriceSet[$id];
1059 * Process that send e-mails
1061 * @param int $contactID
1063 * @param int $participantId
1064 * @param bool $isTest
1065 * @param bool $returnMessageText
1069 public static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
1071 $template = CRM_Core_Smarty
::singleton();
1073 'custom_pre_id' => $values['custom_pre_id'],
1074 'custom_post_id' => $values['custom_post_id'],
1077 //get the params submitted by participant.
1078 $participantParams = CRM_Utils_Array
::value($participantId, $values['params'], array());
1080 if (!$returnMessageText) {
1081 //send notification email if field values are set (CRM-1941)
1082 foreach ($gIds as $key => $gIdValues) {
1084 if (!is_array($gIdValues)) {
1085 $gIdValues = array($gIdValues);
1088 foreach ($gIdValues as $gId) {
1089 $email = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1091 //get values of corresponding profile fields for notification
1092 list($profileValues) = self
::buildCustomDisplay($gId,
1101 list($profileValues) = $profileValues;
1104 'values' => $profileValues,
1107 CRM_Core_BAO_UFGroup
::commonSendMail($contactID, $val);
1114 if ($values['event']['is_email_confirm'] ||
$returnMessageText) {
1115 list($displayName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1117 //send email only when email is present
1118 if (isset($email) ||
$returnMessageText) {
1119 $preProfileID = CRM_Utils_Array
::value('custom_pre_id', $values);
1120 $postProfileID = CRM_Utils_Array
::value('custom_post_id', $values);
1122 if (!empty($values['params']['additionalParticipant'])) {
1123 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values, $preProfileID);
1124 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values, $postProfileID);
1127 self
::buildCustomDisplay($preProfileID,
1137 self
::buildCustomDisplay($postProfileID,
1147 $sessions = CRM_Event_Cart_BAO_Conference
::get_participant_sessions($participantId);
1149 $tplParams = array_merge($values, $participantParams, array(
1151 'confirm_email_text' => CRM_Utils_Array
::value('confirm_email_text', $values['event']),
1152 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $values['event']),
1153 'contributeMode' => CRM_Utils_Array
::value('contributeMode', $template->_tpl_vars
),
1154 'participantID' => $participantId,
1155 'conference_sessions' => $sessions,
1156 'credit_card_number' =>
1157 CRM_Utils_System
::mungeCreditCard(
1158 CRM_Utils_Array
::value('credit_card_number', $participantParams)),
1159 'credit_card_exp_date' =>
1160 CRM_Utils_Date
::mysqlToIso(
1161 CRM_Utils_Date
::format(
1162 CRM_Utils_Array
::value('credit_card_exp_date', $participantParams))),
1165 // CRM-13890 : NOTE wait list condition need to be given so that
1166 // wait list message is shown properly in email i.e. WRT online event registration template
1167 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
1168 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id');
1169 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($statusId, NULL, 'label');
1171 //CRM-15754 - if participant_status contains status ID
1172 elseif (!empty($tplParams['participant_status']) && CRM_Utils_Rule
::integer($tplParams['participant_status'])) {
1173 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($tplParams['participant_status'], NULL, 'label');
1176 $sendTemplateParams = array(
1177 'groupName' => 'msg_tpl_workflow_event',
1178 'valueName' => 'event_online_receipt',
1179 'contactId' => $contactID,
1180 'isTest' => $isTest,
1181 'tplParams' => $tplParams,
1182 'PDFFilename' => ts('confirmation') . '.pdf',
1185 // address required during receipt processing (pdf and email receipt)
1186 if ($displayAddress = CRM_Utils_Array
::value('address', $values)) {
1187 $sendTemplateParams['tplParams']['address'] = $displayAddress;
1188 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1191 // set lineItem details
1192 if ($lineItem = CRM_Utils_Array
::value('lineItem', $values)) {
1193 // check if additional prticipant, if so filter only to relevant ones
1195 if (!empty($values['params']['additionalParticipant'])) {
1196 $ownLineItems = array();
1197 foreach ($lineItem as $liKey => $liValue) {
1198 $firstElement = array_pop($liValue);
1199 if ($firstElement['entity_id'] == $participantId) {
1200 $ownLineItems[0] = $lineItem[$liKey];
1204 if (!empty($ownLineItems)) {
1205 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1209 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1213 if ($returnMessageText) {
1214 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1216 'subject' => $subject,
1218 'to' => $displayName,
1223 $sendTemplateParams['from'] = CRM_Utils_Array
::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array
::value('confirm_from_email', $values['event']) . ">";
1224 $sendTemplateParams['toName'] = $displayName;
1225 $sendTemplateParams['toEmail'] = $email;
1226 $sendTemplateParams['autoSubmitted'] = TRUE;
1227 $sendTemplateParams['cc'] = CRM_Utils_Array
::value('cc_confirm',
1230 $sendTemplateParams['bcc'] = CRM_Utils_Array
::value('bcc_confirm',
1233 // append invoice pdf to email
1234 $template = CRM_Core_Smarty
::singleton();
1235 $taxAmt = $template->get_template_vars('totalTaxAmount');
1236 $prefixValue = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1237 $invoicing = CRM_Utils_Array
::value('invoicing', $prefixValue);
1238 if ($taxAmt && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1239 $sendTemplateParams['isEmailPdf'] = TRUE;
1240 $sendTemplateParams['contributionId'] = $values['contributionId'];
1242 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1249 * Add the custom fields OR array of participant's
1253 * @param string $name
1256 * @param int $participantId
1258 * @param bool $isCustomProfile
1259 * @param array $participantParams
1263 public static function buildCustomDisplay(
1270 $isCustomProfile = FALSE,
1271 $participantParams = array()
1274 return array(NULL, NULL);
1277 if (!is_array($id)) {
1278 $id = CRM_Utils_Type
::escape($id, 'Positive');
1279 $profileIds = array($id);
1285 foreach ($profileIds as $gid) {
1286 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $cid)) {
1288 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
,
1289 NULL, NULL, FALSE, NULL,
1290 FALSE, NULL, CRM_Core_Permission
::CREATE
,
1294 //this condition is added, since same contact can have multiple event registrations..
1295 $params = array(array('participant_id', '=', $participantId, 0, 0));
1297 //add participant id
1298 $fields['participant_id'] = array(
1299 'name' => 'participant_id',
1300 'title' => ts('Participant ID'),
1302 //check whether its a text drive
1304 $params[] = array('participant_test', '=', 1, 0, 0);
1307 //display campaign on thankyou page.
1308 if (array_key_exists('participant_campaign_id', $fields)) {
1309 if ($participantId) {
1310 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1314 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1315 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array
::value($campaignId,
1319 unset($fields['participant_campaign_id']);
1323 foreach ($fields as $k => $v) {
1325 $groupTitle = $v['groupTitle'];
1327 // suppress all file fields from display
1329 CRM_Utils_Array
::value('data_type', $v, '') == 'File' ||
1330 CRM_Utils_Array
::value('name', $v, '') == 'image_URL' ||
1331 CRM_Utils_Array
::value('field_type', $v) == 'Formatting'
1338 $groupTitles[] = $groupTitle;
1340 //display profile groups those are subscribed by participant.
1341 if (($groups = CRM_Utils_Array
::value('group', $participantParams)) &&
1345 foreach ($groups as $grpId => $isSelected) {
1350 if (!empty($grpIds)) {
1351 //get the group titles.
1352 $grpTitles = array();
1353 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1354 $grp = CRM_Core_DAO
::executeQuery($query);
1355 while ($grp->fetch()) {
1356 $grpTitles[] = $grp->title
;
1358 if (!empty($grpTitles) &&
1359 CRM_Utils_Array
::value('title', CRM_Utils_Array
::value('group', $fields))
1361 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1363 unset($fields['group']);
1367 CRM_Core_BAO_UFGroup
::getValues($cid, $fields, $values, FALSE, $params);
1369 if (isset($fields['participant_status_id']['title']) &&
1370 isset($values[$fields['participant_status_id']['title']]) &&
1371 is_numeric($values[$fields['participant_status_id']['title']])
1374 $status = CRM_Event_PseudoConstant
::participantStatus();
1375 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1378 if (isset($fields['participant_role_id']['title']) &&
1379 isset($values[$fields['participant_role_id']['title']]) &&
1380 is_numeric($values[$fields['participant_role_id']['title']])
1383 $roles = CRM_Event_PseudoConstant
::participantRole();
1384 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1387 if (isset($fields['participant_register_date']['title']) &&
1388 isset($values[$fields['participant_register_date']['title']])
1390 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date
::customFormat($values[$fields['participant_register_date']['title']]);
1393 //handle fee_level for price set
1394 if (isset($fields['participant_fee_level']['title']) &&
1395 isset($values[$fields['participant_fee_level']['title']])
1397 $feeLevel = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1398 $values[$fields['participant_fee_level']['title']]
1400 foreach ($feeLevel as $key => $value) {
1402 unset($feeLevel[$key]);
1405 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
1408 unset($values[$fields['participant_id']['title']]);
1415 $template->assign($name, $val);
1418 if (count($groupTitles)) {
1419 $template->assign($name . '_grouptitle', $groupTitles);
1422 //return if we only require array of participant's info.
1423 if ($isCustomProfile) {
1425 return array($val, $groupTitles);
1434 * Build the array for display the profile fields.
1436 * @param array $params
1440 * @param array $groupTitle
1441 * Profile Group Title.
1442 * @param array $values
1443 * Formatted array of key value.
1445 * @param array $profileFields
1449 public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
1451 $config = CRM_Core_Config
::singleton();
1452 $session = CRM_Core_Session
::singleton();
1453 $contactID = $session->get('userID');
1455 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $contactID)) {
1456 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
);
1460 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::ADD
);
1463 foreach ($fields as $v) {
1464 if (!empty($v['groupTitle'])) {
1465 $groupTitle['groupTitle'] = $v['groupTitle'];
1470 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1471 //start of code to set the default values
1472 foreach ($fields as $name => $field) {
1474 // skip fields that should not be displayed separately
1475 if ($field['skipDisplay']) {
1479 $index = $field['title'];
1480 if ($name === 'organization_name') {
1481 $values[$index] = $params[$name];
1484 if ('state_province' == substr($name, 0, 14)) {
1485 if ($params[$name]) {
1486 $values[$index] = CRM_Core_PseudoConstant
::stateProvince($params[$name]);
1489 $values[$index] = '';
1492 elseif ('date' == substr($name, -4)) {
1493 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::processDate($params[$name]),
1494 $config->dateformatFull
);
1496 elseif ('country' == substr($name, 0, 7)) {
1497 if ($params[$name]) {
1498 $values[$index] = CRM_Core_PseudoConstant
::country($params[$name]);
1501 $values[$index] = '';
1504 elseif ('county' == substr($name, 0, 6)) {
1505 if ($params[$name]) {
1506 $values[$index] = CRM_Core_PseudoConstant
::county($params[$name]);
1509 $values[$index] = '';
1512 elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
1513 $values[$index] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
1515 elseif (in_array($name, array(
1520 $filterCondition = array('greeting_type' => $name);
1521 $greeting = CRM_Core_PseudoConstant
::greeting($filterCondition);
1522 $values[$index] = $greeting[$params[$name]];
1524 elseif ($name === 'preferred_communication_method') {
1525 $communicationFields = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1527 $pref = $params[$name];
1528 if (is_array($pref)) {
1529 foreach ($pref as $k => $v) {
1531 $compref[] = $communicationFields[$k];
1535 $values[$index] = implode(',', $compref);
1537 elseif ($name == 'contact_sub_type') {
1538 $values[$index] = implode(', ', $params[$name]);
1540 elseif ($name == 'group') {
1541 $groups = CRM_Contact_BAO_GroupContact
::getGroupList();
1543 foreach ($params[$name] as $gId => $dontCare) {
1545 $title[] = $groups[$gId];
1548 $values[$index] = implode(', ', $title);
1550 elseif ($name == 'tag') {
1551 $entityTags = $params[$name];
1552 $allTags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
1554 if (is_array($entityTags)) {
1555 foreach ($entityTags as $tagId => $dontCare) {
1556 $title[] = $allTags[$tagId];
1559 $values[$index] = implode(', ', $title);
1561 elseif ('participant_role_id' == $name OR
1562 'participant_role' == $name
1564 $roles = CRM_Event_PseudoConstant
::participantRole();
1565 $values[$index] = $roles[$params[$name]];
1567 elseif ('participant_status_id' == $name OR
1568 'participant_status' == $name
1570 $status = CRM_Event_PseudoConstant
::participantStatus();
1571 $values[$index] = $status[$params[$name]];
1573 elseif (substr($name, -11) == 'campaign_id') {
1574 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($params[$name]);
1575 $values[$index] = CRM_Utils_Array
::value($params[$name], $campaigns);
1577 elseif (strpos($name, '-') !== FALSE) {
1578 list($fieldName, $id) = CRM_Utils_System
::explode('-', $name, 2);
1579 $detailName = str_replace(' ', '_', $name);
1580 if (in_array($fieldName, array(
1585 $values[$index] = $params[$detailName];
1586 $idx = $detailName . '_id';
1587 $values[$index] = $params[$idx];
1589 elseif ($fieldName == 'im') {
1590 $providerName = NULL;
1591 if ($providerId = $detailName . '-provider_id') {
1592 $providerName = CRM_Utils_Array
::value($params[$providerId], $imProviders);
1594 if ($providerName) {
1595 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1598 $values[$index] = $params[$detailName];
1601 elseif ($fieldName == 'phone') {
1602 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1603 if (isset($params[$phoneExtField])) {
1604 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1607 $values[$index] = $params[$detailName];
1611 $values[$index] = $params[$detailName];
1615 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1616 if ($params[$name]) {
1617 $values[$index] = '[ x ]';
1621 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
1623 SELECT html_type, data_type
1624 FROM civicrm_custom_field
1627 $dao = CRM_Core_DAO
::executeQuery($query);
1629 $htmlType = $dao->html_type
;
1631 if ($htmlType == 'File') {
1632 $values[$index] = $params[$index];
1635 if ($dao->data_type
== 'Int' ||
1636 $dao->data_type
== 'Boolean'
1638 $v = $params[$name];
1639 if (!CRM_Utils_System
::isNull($v)) {
1640 $customVal = (int) $v;
1643 elseif ($dao->data_type
== 'Float') {
1644 $customVal = (float ) ($params[$name]);
1646 elseif ($dao->data_type
== 'Date') {
1647 //@todo note the currently we are using default date time formatting. Since you can select/set
1648 // different date and time format specific to custom field we should consider fixing this
1649 // sometime in the future
1650 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1651 CRM_Utils_Date
::processDate($params[$name]), $config->dateformatFull
);
1653 if (!empty($params[$name . '_time'])) {
1654 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1655 CRM_Utils_Date
::processDate($params[$name], $params[$name . '_time']),
1656 $config->dateformatDatetime
);
1661 $customVal = $params[$name];
1663 //take the custom field options
1664 $returnProperties = array($name => 1);
1665 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
1666 $options = &$query->_options
;
1668 $displayValue = CRM_Core_BAO_CustomField
::getDisplayValue($customVal, $cfID, $options);
1670 //Hack since we dont have function to check empty.
1671 //FIXME in 2.3 using crmIsEmptyArray()
1672 $customValue = TRUE;
1673 if (is_array($customVal) && is_array($displayValue)) {
1674 $customValue = array_diff($customVal, $displayValue);
1676 //use difference of arrays
1677 if (empty($customValue) ||
!$customValue) {
1678 $values[$index] = '';
1681 $values[$index] = $displayValue;
1685 elseif ($name == 'home_URL' &&
1686 !empty($params[$name])
1688 $url = CRM_Utils_System
::fixURL($params[$name]);
1689 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1691 elseif (in_array($name, array(
1694 'participant_register_date',
1696 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::format($params[$name]));
1699 $values[$index] = $params[$name];
1703 $profileFields[$name] = $field;
1709 * Build the array for Additional participant's information array of priamry and additional Ids
1711 * @param int $participantId
1712 * Id of Primary participant.
1713 * @param array $values
1714 * Key/value event info.
1715 * @param int $contactId
1716 * Contact id of Primary participant.
1717 * @param bool $isTest
1718 * Whether test or live transaction.
1719 * @param bool $isIdsArray
1720 * To return an array of Ids.
1722 * @param bool $skipCancel
1725 * array of Additional participant's info OR array of Ids.
1727 public static function buildCustomProfile(
1732 $isIdsArray = FALSE,
1736 $customProfile = $additionalIDs = array();
1737 if (!$participantId) {
1738 CRM_Core_Error
::fatal(ts('Cannot find participant ID'));
1741 //set Ids of Primary Participant also.
1742 if ($isIdsArray && $contactId) {
1743 $additionalIDs[$participantId] = $contactId;
1746 //hack to skip cancelled participants, CRM-4320
1747 $where = "participant.registered_by_id={$participantId}";
1749 $cancelStatusId = 0;
1750 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1751 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1752 $where .= " AND participant.status_id != {$cancelStatusId}";
1755 SELECT participant.id, participant.contact_id
1756 FROM civicrm_participant participant
1759 $dao = CRM_Core_DAO
::executeQuery($query);
1760 while ($dao->fetch()) {
1761 $additionalIDs[$dao->id
] = $dao->contact_id
;
1764 //return if only array is required.
1765 if ($isIdsArray && $contactId) {
1766 return $additionalIDs;
1769 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values);
1770 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values);
1771 //else build array of Additional participant's information.
1772 if (count($additionalIDs)) {
1773 if ($preProfileID ||
$postProfileID) {
1774 $template = CRM_Core_Smarty
::singleton();
1776 $isCustomProfile = TRUE;
1778 $title = $groupTitles = array();
1779 foreach ($additionalIDs as $pId => $cId) {
1780 //get the params submitted by participant.
1781 $participantParams = CRM_Utils_Array
::value($pId, $values['params'], array());
1783 list($profilePre, $groupTitles) = self
::buildCustomDisplay($preProfileID,
1784 'additionalCustomPre',
1794 $profile = $profilePre;
1795 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1797 $title = $groupTitles;
1801 list($profilePost, $groupTitles) = self
::buildCustomDisplay($postProfileID,
1802 'additionalCustomPost',
1812 if (isset($profilePre)) {
1813 $profile = array_merge($profilePre, $profilePost);
1815 $title = array_merge($title, $groupTitles);
1819 $profile = $profilePost;
1821 $title = $groupTitles;
1825 $profiles[] = $profile;
1828 $customProfile['title'] = $title;
1829 $customProfile['profile'] = $profiles;
1833 return $customProfile;
1836 /* Function to retrieve all events those having location block set.
1839 * array of all events.
1844 public static function getLocationEvents() {
1848 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
1849 FROM civicrm_event ce
1850 INNER JOIN civicrm_loc_block lb ON ce.loc_block_id = lb.id
1851 INNER JOIN civicrm_address ca ON lb.address_id = ca.id
1852 LEFT JOIN civicrm_state_province sp ON ca.state_province_id = sp.id
1853 ORDER BY sp.name, ca.city, ca.street_address ASC
1856 $dao = CRM_Core_DAO
::executeQuery($query);
1857 while ($dao->fetch()) {
1858 $events[$dao->loc_block_id
] = $dao->title
;
1865 * @param int $locBlockId
1867 * @return int|null|string
1869 public static function countEventsUsingLocBlockId($locBlockId) {
1874 $locBlockId = CRM_Utils_Type
::escape($locBlockId, 'Integer');
1877 SELECT count(*) FROM civicrm_event ce
1878 WHERE ce.loc_block_id = $locBlockId";
1880 return CRM_Core_DAO
::singleValueQuery($query);
1884 * Check if event registration is valid according to permissions AND Dates.
1886 * @param array $values
1887 * @param int $eventID
1890 public static function validRegistrationRequest($values, $eventID) {
1891 // check that the user has permission to register for this event
1892 $hasPermission = CRM_Core_Permission
::event(CRM_Core_Permission
::EDIT
,
1893 $eventID, 'register for events'
1896 return $hasPermission && self
::validRegistrationDate($values);
1904 public static function validRegistrationDate(&$values) {
1905 // make sure that we are between registration start date and registration end date
1906 $startDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_start_date', $values));
1907 $endDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_end_date', $values));
1908 $eventEnd = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('end_date', $values));
1911 if ($startDate && $startDate >= $now) {
1914 if ($endDate && $endDate < $now) {
1917 if ($eventEnd && $eventEnd < $now) {
1924 /* Function to Show - Hide the Registration Link.
1926 * @param array $values
1927 * Key/value event info.
1929 * true if allow registration otherwise false
1936 public static function showHideRegistrationLink($values) {
1938 $session = CRM_Core_Session
::singleton();
1939 $contactID = $session->get('userID');
1940 $alreadyRegistered = FALSE;
1943 $params = array('contact_id' => $contactID);
1945 if ($eventId = CRM_Utils_Array
::value('id', $values['event'])) {
1946 $params['event_id'] = $eventId;
1948 if ($roleId = CRM_Utils_Array
::value('default_role_id', $values['event'])) {
1949 $params['role_id'] = $roleId;
1951 $alreadyRegistered = self
::checkRegistration($params);
1954 if (!empty($values['event']['allow_same_participant_emails']) ||
1962 /* Function to check if given contact is already registered.
1964 * @param array $params
1965 * Key/value participant info.
1969 * @param array $params
1973 public static function checkRegistration($params) {
1974 $alreadyRegistered = FALSE;
1975 if (empty($params['contact_id'])) {
1976 return $alreadyRegistered;
1979 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
1981 $participant = new CRM_Event_DAO_Participant();
1982 $participant->copyValues($params);
1984 $participant->is_test
= CRM_Utils_Array
::value('is_test', $params, 0);
1985 $participant->selectAdd();
1986 $participant->selectAdd('status_id');
1987 if ($participant->find(TRUE) && array_key_exists($participant->status_id
, $statusTypes)) {
1988 $alreadyRegistered = TRUE;
1991 return $alreadyRegistered;
1995 * Make sure that the user has permission to access this event.
1997 * @param int $eventId
2001 * the permission that the user has (or null)
2003 public static function checkPermission($eventId = NULL, $type = CRM_Core_Permission
::VIEW
) {
2004 static $permissions = NULL;
2006 if (empty($permissions)) {
2007 $allEvents = CRM_Event_PseudoConstant
::event(NULL, TRUE);
2008 $createdEvents = array();
2010 $session = CRM_Core_Session
::singleton();
2011 if ($userID = $session->get('userID')) {
2012 $createdEvents = array_keys(CRM_Event_PseudoConstant
::event(NULL, TRUE, "created_id={$userID}"));
2015 // Note: for a multisite setup, a user with edit all events, can edit all events
2016 // including those from other sites
2017 if (CRM_Core_Permission
::check('edit all events')) {
2018 $permissions[CRM_Core_Permission
::EDIT
] = array_keys($allEvents);
2021 $permissions[CRM_Core_Permission
::EDIT
] = &CRM_ACL_API
::group(CRM_Core_Permission
::EDIT
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2024 if (CRM_Core_Permission
::check('edit all events')) {
2025 $permissions[CRM_Core_Permission
::VIEW
] = array_keys($allEvents);
2028 if (CRM_Core_Permission
::check('access CiviEvent') &&
2029 CRM_Core_Permission
::check('view event participants')
2031 // use case: allow "view all events" but NOT "edit all events"
2032 // so for a normal site allow users with these two permissions to view all events AND
2033 // at the same time also allow any hook to override if needed.
2034 $createdEvents = array_keys($allEvents);
2036 $permissions[CRM_Core_Permission
::VIEW
] = &CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2039 $permissions[CRM_Core_Permission
::DELETE
] = array();
2040 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
2041 // Note: we want to restrict the scope of delete permission to
2042 // events that are editable/viewable (usecase multisite).
2043 // We can remove array_intersect once we have ACL support for delete functionality.
2044 $permissions[CRM_Core_Permission
::DELETE
] = array_intersect($permissions[CRM_Core_Permission
::EDIT
],
2045 $permissions[CRM_Core_Permission
::VIEW
]
2051 return in_array($eventId, $permissions[$type]) ?
TRUE : FALSE;
2054 return $permissions;
2058 * Build From Email as the combination of all the email ids of the logged in user,
2059 * the domain email id and the email id configured for the event
2061 * @param int $eventId
2062 * The id of the event.
2065 * an array of email ids
2067 public static function getFromEmailIds($eventId = NULL) {
2068 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email
::getFromEmail();
2071 // add the email id configured for the event
2072 $params = array('id' => $eventId);
2073 $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
2074 $eventEmail = array();
2076 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
2077 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
2078 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
2080 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
2081 $fromEmailId = array(
2082 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventEmail),
2083 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventEmail),
2085 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2089 return $fromEmailValues;
2093 * Calculate event total seats occupied.
2095 * @param int $eventId
2097 * @param sting $extraWhereClause
2098 * Extra filter on participants.
2101 * event total seats w/ given criteria.
2103 public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
2104 if (empty($eventId)) {
2108 $extraWhereClause = trim($extraWhereClause);
2109 if (!empty($extraWhereClause)) {
2110 $extraWhereClause = " AND ( {$extraWhereClause} )";
2113 //event seats calculation :
2114 //1. consider event seat as a single when participant does not have line item.
2115 //2. consider event seat as a single when participant has line items but does not
2116 // have count for corresponding price field value ( ie price field value does not carry any seat )
2117 //3. consider event seat as a sum of all seats from line items in case price field value carries count.
2120 SELECT IF ( SUM( value.count*lineItem.qty ),
2121 SUM( value.count*lineItem.qty ) +
2122 COUNT( DISTINCT participant.id ) -
2123 COUNT( DISTINCT IF ( value.count, participant.id, NULL ) ),
2124 COUNT( DISTINCT participant.id ) )
2125 FROM civicrm_participant participant
2126 INNER JOIN civicrm_contact contact ON ( contact.id = participant.contact_id AND contact.is_deleted = 0 )
2127 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
2128 LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id
2129 AND lineItem.entity_table = 'civicrm_participant' )
2130 LEFT JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id AND value.count )
2131 WHERE ( participant.event_id = %1 )
2132 AND participant.is_test = 0
2134 GROUP BY participant.event_id";
2136 return (int) CRM_Core_DAO
::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
2140 * Retrieve event template default values to be set.
2141 * as default values for current new event.
2143 * @param int $templateId
2144 * Event template id.
2147 * Array of custom data defaults.
2149 public static function getTemplateDefaultValues($templateId) {
2150 $defaults = array();
2155 $templateParams = array('id' => $templateId);
2156 CRM_Event_BAO_Event
::retrieve($templateParams, $defaults);
2157 $fieldsToExclude = array(
2160 'default_discount_fee_id',
2166 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2171 * @param int $event_id
2175 public static function get_sub_events($event_id) {
2176 $params = array('parent_event_id' => $event_id);
2177 $defaults = array();
2178 return CRM_Event_BAO_Event
::retrieve($params, $defaults);
2182 * Update the Campaign Id of all the participants of the given event.
2184 * @param int $eventID
2186 * @param int $eventCampaignID
2187 * Campaign id of that event.
2189 public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
2191 $params[1] = array($eventID, 'Integer');
2193 if (empty($eventCampaignID)) {
2194 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2197 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2198 $params[2] = array($eventCampaignID, 'Integer');
2200 CRM_Core_DAO
::executeQuery($query, $params);
2204 * Get options for a given field.
2205 * @see CRM_Core_DAO::buildOptions
2207 * @param string $fieldName
2208 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2209 * @param array $props : whatever is known about this dao object
2211 * @return array|bool
2213 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2215 // Special logic for fields whose options depend on context or properties
2216 switch ($fieldName) {
2217 case 'financial_type_id':
2218 // Fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
2219 return CRM_Financial_BAO_FinancialType
::getIncomeFinancialType();
2223 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);