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
55 public static function retrieve(&$params, &$defaults) {
56 $event = new CRM_Event_DAO_Event();
57 $event->copyValues($params);
58 if ($event->find(TRUE)) {
59 CRM_Core_DAO
::storeValues($event, $defaults);
66 * Update the is_active flag in the db
69 * Id of the database record.
70 * @param bool $is_active
71 * Value we want to set the is_active field.
74 * DAO object on sucess, null otherwise
77 public static function setIsActive($id, $is_active) {
78 return CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
84 * @param array $params
85 * Reference array contains the values submitted by the form.
91 public static function add(&$params) {
92 CRM_Utils_System
::flushCache();
93 $financialTypeId = NULL;
94 if (!empty($params['id'])) {
95 CRM_Utils_Hook
::pre('edit', 'Event', $params['id'], $params);
96 if (empty($params['skipFinancialType'])) {
97 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $params['id'], 'financial_type_id');
101 CRM_Utils_Hook
::pre('create', 'Event', NULL, $params);
104 $event = new CRM_Event_DAO_Event();
106 $event->copyValues($params);
107 $result = $event->save();
109 if (!empty($params['id'])) {
110 CRM_Utils_Hook
::post('edit', 'Event', $event->id
, $event);
113 CRM_Utils_Hook
::post('create', 'Event', $event->id
, $event);
115 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
116 CRM_Price_BAO_PriceFieldValue
::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
124 * @param array $params
125 * Reference array contains the values submitted by the form.
130 public static function create(&$params) {
131 $transaction = new CRM_Core_Transaction();
132 if (empty($params['is_template'])) {
133 $params['is_template'] = 0;
135 // check if new event, if so set the created_id (if not set)
136 // and always set created_date to now
137 if (empty($params['id'])) {
138 if (empty($params['created_id'])) {
139 $session = CRM_Core_Session
::singleton();
140 $params['created_id'] = $session->get('userID');
142 $params['created_date'] = date('YmdHis');
145 $event = self
::add($params);
146 CRM_Price_BAO_PriceSet
::setPriceSets($params, $event, 'event');
147 if (is_a($event, 'CRM_Core_Error')) {
148 CRM_Core_DAO
::transaction('ROLLBACK');
152 $session = CRM_Core_Session
::singleton();
153 $contactId = $session->get('userID');
155 $contactId = CRM_Utils_Array
::value('contact_id', $params);
158 // Log the information on successful add/edit of Event
160 'entity_table' => 'civicrm_event',
161 'entity_id' => $event->id
,
162 'modified_id' => $contactId,
163 'modified_date' => date('Ymd'),
166 CRM_Core_BAO_Log
::add($logParams);
168 if (!empty($params['custom']) &&
169 is_array($params['custom'])
171 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_event', $event->id
);
174 $transaction->commit();
188 public static function del($id) {
193 CRM_Utils_Hook
::pre('delete', 'Event', $id, CRM_Core_DAO
::$_nullArray);
195 $extends = array('event');
196 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
197 foreach ($groupTree as $values) {
198 $query = "DELETE FROM " . $values['table_name'] . " WHERE entity_id = " . $id;
201 1 => array($values['table_name'], 'string'),
202 2 => array($id, 'integer'),
205 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
208 // price set cleanup, CRM-5527
209 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_event', $id);
211 $event = new CRM_Event_DAO_Event();
214 if ($event->find(TRUE)) {
215 $locBlockId = $event->loc_block_id
;
216 $result = $event->delete();
218 if (!is_null($locBlockId)) {
219 self
::deleteEventLocBlock($locBlockId, $id);
222 CRM_Utils_Hook
::post('delete', 'Event', $id, $event);
230 * Delete the location block associated with an event,
231 * if not being used by any other event.
234 * Location block id to be deleted.
235 * @param int $eventId
236 * Event with which loc block is associated.
240 public static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
241 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
244 $query .= " AND ce.id != $eventId;";
247 $locCount = CRM_Core_DAO
::singleValueQuery($query);
249 if ($locCount == 0) {
250 CRM_Core_BAO_Location
::deleteLocBlock($locBlockId);
255 * Get current/future Events
258 * 0 returns current and future events.
259 * 1 if events all are required
260 * 2 returns events since 3 months ago
261 * @param bool|int $id int id of a specific event to return
262 * @param bool $isActive
263 * true if you need only active events.
264 * @param bool $checkPermission
265 * true if you need to check permission else false.
270 static function getEvents(
274 $checkPermission = TRUE
277 SELECT `id`, `title`, `start_date`
279 WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
282 $query .= " AND `id` = {$id}";
285 // find only events ending in the future
286 $endDate = date('YmdHis');
288 AND ( `end_date` >= {$endDate} OR
290 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
295 // find only events starting in the last 3 months
296 $startDate = date('YmdHis', strtotime('3 months ago'));
297 $query .= " AND ( `start_date` >= {$startDate} OR start_date IS NULL )";
300 $query .= " AND civicrm_event.is_active = 1";
303 $query .= " ORDER BY title asc";
306 $dao = CRM_Core_DAO
::executeQuery($query);
307 while ($dao->fetch()) {
308 if ((!$checkPermission ||
309 CRM_Event_BAO_Event
::checkPermission($dao->id
)
313 $events[$dao->id
] = $dao->title
. ' - ' . CRM_Utils_Date
::customFormat($dao->start_date
);
326 * Array of event summary values
328 public static function getEventSummary() {
329 $eventSummary = $eventIds = array();
330 $config = CRM_Core_Config
::singleton();
332 // get permission and include them here
333 // does not scale, but rearranging code for now
334 // FIXME in a future release
335 $permissions = CRM_Event_BAO_Event
::checkPermission();
337 if (empty($permissions[CRM_Core_Permission
::VIEW
])) {
338 $eventSummary['total_events'] = 0;
339 return $eventSummary;
342 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission
::VIEW
])) . " ) ";
345 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
347 SELECT count(id) as total_events
349 WHERE civicrm_event.is_active = 1 AND
350 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
351 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
354 $dao = CRM_Core_DAO
::executeQuery($query);
357 $eventSummary['total_events'] = $dao->total_events
;
360 if (empty($eventSummary) ||
361 $dao->total_events
== 0
363 return $eventSummary;
366 //get the participant status type values.
367 $cpstObject = new CRM_Event_DAO_ParticipantStatusType();
368 $cpst = $cpstObject->getTableName();
369 $query = "SELECT id, name, label, class FROM $cpst";
370 $status = CRM_Core_DAO
::executeQuery($query);
371 $statusValues = array();
372 while ($status->fetch()) {
373 $statusValues[$status->id
]['id'] = $status->id
;
374 $statusValues[$status->id
]['name'] = $status->name
;
375 $statusValues[$status->id
]['label'] = $status->label
;
376 $statusValues[$status->id
]['class'] = $status->class;
379 // Get the Id of Option Group for Event Types
380 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
381 $optionGroupDAO->name
= 'event_type';
382 $optionGroupId = NULL;
383 if ($optionGroupDAO->find(TRUE)) {
384 $optionGroupId = $optionGroupDAO->id
;
386 // Get the event summary display preferences
387 $show_max_events = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
,
390 // default to 10 if no option is set
391 if (is_null($show_max_events)) {
392 $show_max_events = 10;
394 // show all events if show_events is set to a negative value
395 if ($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 GROUP BY civicrm_event.id
422 ORDER BY civicrm_event.start_date ASC
425 $eventParticipant = array();
429 'eventTitle' => 'event_title',
430 'isPublic' => 'is_public',
431 'maxParticipants' => 'max_participants',
432 'startDate' => 'start_date',
433 'endDate' => 'end_date',
434 'eventType' => 'event_type',
436 'participants' => 'participants',
437 'notCountedDueToRole' => 'notCountedDueToRole',
438 'notCountedDueToStatus' => 'notCountedDueToStatus',
439 'notCountedParticipants' => 'notCountedParticipants',
442 $params = array(1 => array($optionGroupId, 'Integer'));
443 $mappingID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', 'civicrm_event', 'id', 'entity_value');
444 $dao = CRM_Core_DAO
::executeQuery($query, $params);
445 while ($dao->fetch()) {
446 foreach ($properties as $property => $name) {
456 $eventSummary['events'][$dao->id
][$property] = $set;
460 if ($dao->$name && $config->mapAPIKey
) {
463 $params = array('entity_id' => $dao->id
, 'entity_table' => 'civicrm_event');
464 $values['location'] = CRM_Core_BAO_Location
::getValues($params, TRUE);
465 if (is_numeric(CRM_Utils_Array
::value('geo_code_1', $values['location']['address'][1])) ||
466 ($config->mapGeoCoding
&&
467 !empty($values['location']['address'][1]['city']) &&
468 !empty($values['location']['address'][1]['state_province_id'])
471 $set = CRM_Utils_System
::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
475 $eventSummary['events'][$dao->id
][$property] = $set;
476 if (in_array($dao->id
, $permissions[CRM_Core_Permission
::EDIT
])) {
477 $eventSummary['events'][$dao->id
]['configure'] = CRM_Utils_System
::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
483 $eventSummary['events'][$dao->id
][$property] = CRM_Utils_Date
::customFormat($dao->$name,
489 case 'notCountedDueToRole':
490 case 'notCountedDueToStatus':
491 case 'notCountedParticipants':
494 if ($name == 'participants') {
495 $propertyCnt = self
::getParticipantCount($dao->id
);
497 $set = CRM_Utils_System
::url('civicrm/event/search',
498 "reset=1&force=1&event=$dao->id&status=true&role=true"
502 elseif ($name == 'notCountedParticipants') {
503 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, TRUE, FALSE);
505 // FIXME : selector fail to search w/ OR operator.
506 // $set = CRM_Utils_System::url( 'civicrm/event/search',
507 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
510 elseif ($name == 'notCountedDueToStatus') {
511 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, FALSE, FALSE);
513 $set = CRM_Utils_System
::url('civicrm/event/search',
514 "reset=1&force=1&event=$dao->id&status=false"
519 $propertyCnt = self
::getParticipantCount($dao->id
, FALSE, FALSE, TRUE, FALSE);
521 $set = CRM_Utils_System
::url('civicrm/event/search',
522 "reset=1&force=1&event=$dao->id&role=false"
527 $eventSummary['events'][$dao->id
][$property] = $propertyCnt;
528 $eventSummary['events'][$dao->id
][$name . '_url'] = $set;
532 $eventSummary['events'][$dao->id
][$property] = $dao->$name;
537 // prepare the area for per-status participant counts
538 $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
539 $eventSummary['events'][$dao->id
]['statuses'] = array_fill_keys($statusClasses, array());
541 $eventSummary['events'][$dao->id
]['friend'] = $dao->is_friend_active
;
542 $eventSummary['events'][$dao->id
]['is_monetary'] = $dao->is_monetary
;
543 $eventSummary['events'][$dao->id
]['is_online_registration'] = $dao->is_online_registration
;
544 $eventSummary['events'][$dao->id
]['is_show_location'] = $dao->is_show_location
;
545 $eventSummary['events'][$dao->id
]['is_subevent'] = $dao->slot_label_id
;
546 $eventSummary['events'][$dao->id
]['is_pcp_enabled'] = $dao->is_pcp_enabled
;
547 $eventSummary['events'][$dao->id
]['reminder'] = CRM_Core_BAO_ActionSchedule
::isConfigured($dao->id
, $mappingID);
548 $eventSummary['events'][$dao->id
]['is_repeating_event'] = $dao->is_repeating_event
;
550 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
551 foreach ($statusValues as $statusId => $statusValue) {
552 if (!array_key_exists($statusId, $statusTypes)) {
555 $class = $statusValue['class'];
556 $statusCount = self
::eventTotalSeats($dao->id
, "( participant.status_id = {$statusId} )");
558 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
560 'url' => CRM_Utils_System
::url('civicrm/event/search', $urlString),
561 'name' => $statusValue['name'],
562 'label' => $statusValue['label'],
563 'count' => $statusCount,
565 $eventSummary['events'][$dao->id
]['statuses'][$class][] = $statusInfo;
570 $countedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
571 $nonCountedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
572 $countedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
573 $nonCountedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
575 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
576 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
578 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
579 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
580 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
581 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
583 return $eventSummary;
587 * Get participant count
589 * @param int $eventId
590 * @param bool $considerStatusConsider status for participant count.
591 * Consider status for participant count.
592 * @param bool $statusConsider counted participant.
593 * Consider counted participant.
594 * @param bool $considerRoleConsider role for participant count.
595 * Consider role for participant count.
596 * @param bool $roleConsider counted( is filter role) participant.
597 * Consider counted( is filter role) participant.
601 * array with count of participants for each event based on status/role
603 public static function getParticipantCount(
605 $considerStatus = TRUE,
607 $considerRole = TRUE,
611 // consider both role and status for counted participants, CRM-4924.
613 // not counted participant.
614 if ($considerStatus && $considerRole && !$status && !$role) {
618 if ($considerStatus) {
619 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
620 $statusClause = 'NOT IN';
622 $statusClause = 'IN';
624 $status = implode(',', array_keys($statusTypes));
625 if (empty($status)) {
628 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
632 $roleTypes = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
633 $roleClause = 'NOT IN';
637 $roles = implode(',', array_keys($roleTypes));
641 $clause[] = "participant.role_id {$roleClause} ( $roles )";
645 if (!empty($clause)) {
646 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
649 return self
::eventTotalSeats($eventId, $sqlClause);
653 * Get the information to map a event
656 * For which we want map info.
658 * @return null|string
662 public static function &getMapInfo(&$id) {
666 civicrm_event.id AS event_id,
667 civicrm_event.title AS display_name,
668 civicrm_address.street_address AS street_address,
669 civicrm_address.city AS city,
670 civicrm_address.postal_code AS postal_code,
671 civicrm_address.postal_code_suffix AS postal_code_suffix,
672 civicrm_address.geo_code_1 AS latitude,
673 civicrm_address.geo_code_2 AS longitude,
674 civicrm_state_province.abbreviation AS state,
675 civicrm_country.name AS country,
676 civicrm_location_type.name AS location_type
679 LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )
680 LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )
681 LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )
682 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
683 LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )
684 WHERE civicrm_address.geo_code_1 IS NOT NULL
685 AND civicrm_address.geo_code_2 IS NOT NULL
686 AND civicrm_event.id = " . CRM_Utils_Type
::escape($id, 'Integer');
688 $dao = new CRM_Core_DAO();
691 $locations = array();
693 $config = CRM_Core_Config
::singleton();
695 while ($dao->fetch()) {
698 $location['displayName'] = addslashes($dao->display_name
);
699 $location['lat'] = $dao->latitude
;
700 $location['marker_class'] = 'Event';
701 $location['lng'] = $dao->longitude
;
703 $params = array('entity_id' => $id, 'entity_table' => 'civicrm_event');
704 $addressValues = CRM_Core_BAO_Location
::getValues($params, TRUE);
705 $location['address'] = str_replace(array(
708 ), '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
710 $location['url'] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
);
711 $location['location_type'] = $dao->location_type
;
712 $eventImage = '<img src="' . $config->resourceBase
. 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
713 $location['image'] = $eventImage;
714 $location['displayAddress'] = str_replace('<br />', ', ', $location['address']);
715 $locations[] = $location;
721 * Get the complete information for one or more events
724 * Get events with start date >= this date.
725 * @param int $typeGet events on the a specific event type (by event_type_id).
726 * Get events on the a specific event type (by event_type_id).
727 * @param int $eventIdReturn a single event - by event id.
728 * Return a single event - by event id.
730 * Also get events with end date >= this date.
731 * @param bool $onlyPublicInclude public events only, default TRUE.
732 * Include public events only, default TRUE.
735 * array of all the events that are searched
738 static function &getCompleteInfo(
745 $publicCondition = NULL;
747 $publicCondition = " AND civicrm_event.is_public = 1";
751 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
753 // get events with start_date >= requested start
754 $startDate = CRM_Utils_Type
::escape($start, 'Date');
755 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
759 // also get events with end_date <= requested end
760 $endDate = CRM_Utils_Type
::escape($end, 'Date');
761 $dateCondition .= " AND ( civicrm_event.end_date <= '{$endDate}' ) ";
764 // CRM-9421 and CRM-8620 Default mode for ical/rss feeds. No start or end filter passed.
765 // Need to exclude old events with only start date
766 // and not exclude events in progress (start <= today and end >= today). DGG
767 if (empty($start) && empty($end)) {
768 // get events with end date >= today, not sure of this logic
769 // but keeping this for backward compatibility as per issue CRM-5133
770 $today = date("Y-m-d G:i:s");
771 $dateCondition .= " AND ( civicrm_event.end_date >= '{$today}' OR civicrm_event.start_date >= '{$today}' ) ";
775 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
778 // Get the Id of Option Group for Event Types
779 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
780 $optionGroupDAO->name
= 'event_type';
781 $optionGroupId = NULL;
782 if ($optionGroupDAO->find(TRUE)) {
783 $optionGroupId = $optionGroupDAO->id
;
788 civicrm_event.id as event_id,
789 civicrm_email.email as email,
790 civicrm_event.title as title,
791 civicrm_event.summary as summary,
792 civicrm_event.start_date as start,
793 civicrm_event.end_date as end,
794 civicrm_event.description as description,
795 civicrm_event.is_show_location as is_show_location,
796 civicrm_event.is_online_registration as is_online_registration,
797 civicrm_event.registration_link_text as registration_link_text,
798 civicrm_event.registration_start_date as registration_start_date,
799 civicrm_event.registration_end_date as registration_end_date,
800 civicrm_option_value.label as event_type,
801 civicrm_address.name as address_name,
802 civicrm_address.street_address as street_address,
803 civicrm_address.supplemental_address_1 as supplemental_address_1,
804 civicrm_address.supplemental_address_2 as supplemental_address_2,
805 civicrm_address.city as city,
806 civicrm_address.postal_code as postal_code,
807 civicrm_address.postal_code_suffix as postal_code_suffix,
808 civicrm_state_province.abbreviation as state,
809 civicrm_country.name AS country
811 LEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id
812 LEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id
813 LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
814 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
815 LEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id
816 LEFT JOIN civicrm_option_value ON (
817 civicrm_event.event_type_id = civicrm_option_value.value AND
818 civicrm_option_value.option_group_id = %1 )
819 WHERE civicrm_event.is_active = 1
820 AND (is_template = 0 OR is_template IS NULL)
824 if (isset($typeCondition)) {
825 $query .= $typeCondition;
828 if (isset($eventId)) {
829 $query .= " AND civicrm_event.id =$eventId ";
831 $query .= " ORDER BY civicrm_event.start_date ASC";
833 $params = array(1 => array($optionGroupId, 'Integer'));
834 $dao = CRM_Core_DAO
::executeQuery($query, $params);
836 $config = CRM_Core_Config
::singleton();
838 $baseURL = parse_url($config->userFrameworkBaseURL
);
839 $url = "@" . $baseURL['host'];
840 if (!empty($baseURL['path'])) {
841 $url .= substr($baseURL['path'], 0, -1);
844 // check 'view event info' permission
845 //@todo - per CRM-14626 we have resolved that 'view event info' means 'view ALL event info'
846 // and passing in the specific permission here will short-circuit the evaluation of permission to
847 // see specific events (doesn't seem relevant to this call
848 // however, since this function is accessed only by a convoluted call from a joomla block function
849 // it seems safer not to touch here. Suggestion is that CRM_Core_Permission::check(array or relevant permissions) would
850 // be clearer & safer here
851 $permissions = CRM_Core_Permission
::event(CRM_Core_Permission
::VIEW
);
853 // check if we're in shopping cart mode for events
854 $enable_cart = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
,
859 while ($dao->fetch()) {
860 if (!empty($permissions) && in_array($dao->event_id
, $permissions)) {
862 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL
) . $url;
864 $info['title'] = $dao->title
;
865 $info['event_id'] = $dao->event_id
;
866 $info['summary'] = $dao->summary
;
867 $info['description'] = $dao->description
;
868 $info['start_date'] = $dao->start
;
869 $info['end_date'] = $dao->end
;
870 $info['contact_email'] = $dao->email
;
871 $info['event_type'] = $dao->event_type
;
872 $info['is_show_location'] = $dao->is_show_location
;
873 $info['is_online_registration'] = $dao->is_online_registration
;
874 $info['registration_link_text'] = $dao->registration_link_text
;
875 $info['registration_start_date'] = $dao->registration_start_date
;
876 $info['registration_end_date'] = $dao->registration_end_date
;
881 'address_name' => $dao->address_name
,
882 'street_address' => $dao->street_address
,
883 'supplemental_address_1' => $dao->supplemental_address_1
,
884 'supplemental_address_2' => $dao->supplemental_address_2
,
885 'city' => $dao->city
,
886 'state_province' => $dao->state
,
887 'postal_code' => $dao->postal_code
,
888 'postal_code_suffix' => $dao->postal_code_suffix
,
889 'country' => $dao->country
,
893 CRM_Utils_String
::append($address, ', ',
894 CRM_Utils_Address
::format($addrFields)
896 $info['location'] = $address;
897 $info['url'] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
900 $reg = CRM_Event_Cart_BAO_EventInCart
::get_registration_link($dao->event_id
);
901 $info['registration_link'] = CRM_Utils_System
::url($reg['path'], $reg['query'], TRUE);
902 $info['registration_link_text'] = $reg['label'];
913 * make a copy of a Event, including
914 * all the fields in the event Wizard
917 * The event id to copy.
918 * boolean $afterCreate call to copy after the create function
919 * @param null $newEvent
920 * @param bool $afterCreate
922 * @return CRM_Event_DAO_Event
924 public static function copy($id, $newEvent = NULL, $afterCreate = FALSE) {
926 $eventValues = array();
928 //get the require event values.
929 $eventParams = array('id' => $id);
930 $returnProperties = array(
934 'default_discount_fee_id',
938 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
940 // since the location is sharable, lets use the same loc_block_id.
941 $locBlockId = CRM_Utils_Array
::value('loc_block_id', $eventValues);
943 $fieldsFix = ($afterCreate) ?
array() : array('prefix' => array('title' => ts('Copy of') . ' '));
944 if (empty($eventValues['is_show_location'])) {
945 $fieldsFix['prefix']['is_show_location'] = 0;
948 if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
949 $copyEvent = $newEvent;
952 if (!isset($copyEvent)) {
953 $copyEvent = &CRM_Core_DAO
::copyGeneric('CRM_Event_DAO_Event',
957 ($locBlockId) ?
$locBlockId : NULL,
962 CRM_Price_BAO_PriceSet
::copyPriceSet('civicrm_event', $id, $copyEvent->id
);
963 $copyUF = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_UFJoin',
966 'entity_table' => 'civicrm_event',
968 array('entity_id' => $copyEvent->id
)
971 $copyTellFriend = &CRM_Core_DAO
::copyGeneric('CRM_Friend_DAO_Friend',
974 'entity_table' => 'civicrm_event',
976 array('entity_id' => $copyEvent->id
)
979 $copyPCP = &CRM_Core_DAO
::copyGeneric('CRM_PCP_DAO_PCPBlock',
982 'entity_table' => 'civicrm_event',
984 array('entity_id' => $copyEvent->id
),
985 array('replace' => array('target_entity_id' => $copyEvent->id
))
988 if ($eventValues['is_template']) {
989 $field = 'event_template';
992 $field = 'civicrm_event';
994 $mappingId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
995 $oldData = array('entity_value' => $id, 'mapping_id' => $mappingId);
996 if ($copyEvent->is_template
== 1) {
997 $field = 'event_template';
1000 $field = 'civicrm_event';
1002 $copyMappingId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
1003 $newData = array('entity_value' => $copyEvent->id
, 'mapping_id' => $copyMappingId);
1004 $copyReminder = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_ActionSchedule',
1009 if (!$afterCreate) {
1011 $extends = array('event');
1012 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
1014 foreach ($groupTree as $groupID => $group) {
1015 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
1016 foreach ($group['fields'] as $fieldID => $field) {
1017 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1021 foreach ($table as $tableName => $tableColumns) {
1022 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
1023 $tableColumns[0] = $copyEvent->id
;
1024 $select = 'SELECT ' . implode(', ', $tableColumns);
1025 $from = ' FROM ' . $tableName;
1026 $where = " WHERE {$tableName}.entity_id = {$id}";
1027 $query = $insert . $select . $from . $where;
1028 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1034 CRM_Utils_System
::flushCache();
1035 if (!$afterCreate) {
1036 CRM_Utils_Hook
::copy('Event', $copyEvent);
1042 * This is sometimes called in a loop (during event search)
1043 * hence we cache the values to prevent repeated calls to the db
1045 public static function isMonetary($id) {
1046 static $isMonetary = array();
1047 if (!array_key_exists($id, $isMonetary)) {
1048 $isMonetary[$id] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event',
1053 return $isMonetary[$id];
1057 * This is sometimes called in a loop (during event search)
1058 * hence we cache the values to prevent repeated calls to the db
1060 public static function usesPriceSet($id) {
1061 static $usesPriceSet = array();
1062 if (!array_key_exists($id, $usesPriceSet)) {
1063 $usesPriceSet[$id] = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $id);
1065 return $usesPriceSet[$id];
1069 * Process that send e-mails
1071 * @param int $contactID
1073 * @param int $participantId
1074 * @param bool $isTest
1075 * @param bool $returnMessageText
1079 public static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
1081 $template = CRM_Core_Smarty
::singleton();
1083 'custom_pre_id' => $values['custom_pre_id'],
1084 'custom_post_id' => $values['custom_post_id'],
1087 //get the params submitted by participant.
1088 $participantParams = CRM_Utils_Array
::value($participantId, $values['params'], array());
1090 if (!$returnMessageText) {
1091 //send notification email if field values are set (CRM-1941)
1092 foreach ($gIds as $key => $gIdValues) {
1094 if (!is_array($gIdValues)) {
1095 $gIdValues = array($gIdValues);
1098 foreach ($gIdValues as $gId) {
1099 $email = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1101 //get values of corresponding profile fields for notification
1102 list($profileValues) = self
::buildCustomDisplay($gId,
1111 list($profileValues) = $profileValues;
1114 'values' => $profileValues,
1117 CRM_Core_BAO_UFGroup
::commonSendMail($contactID, $val);
1124 if ($values['event']['is_email_confirm'] ||
$returnMessageText) {
1125 list($displayName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1127 //send email only when email is present
1128 if (isset($email) ||
$returnMessageText) {
1129 $preProfileID = CRM_Utils_Array
::value('custom_pre_id', $values);
1130 $postProfileID = CRM_Utils_Array
::value('custom_post_id', $values);
1132 if (!empty($values['params']['additionalParticipant'])) {
1133 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values, $preProfileID);
1134 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values, $postProfileID);
1137 self
::buildCustomDisplay($preProfileID,
1147 self
::buildCustomDisplay($postProfileID,
1157 $sessions = CRM_Event_Cart_BAO_Conference
::get_participant_sessions($participantId);
1159 $tplParams = array_merge($values, $participantParams, array(
1161 'confirm_email_text' => CRM_Utils_Array
::value('confirm_email_text', $values['event']),
1162 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $values['event']),
1163 'contributeMode' => CRM_Utils_Array
::value('contributeMode', $template->_tpl_vars
),
1164 'participantID' => $participantId,
1165 'conference_sessions' => $sessions,
1166 'credit_card_number' =>
1167 CRM_Utils_System
::mungeCreditCard(
1168 CRM_Utils_Array
::value('credit_card_number', $participantParams)),
1169 'credit_card_exp_date' =>
1170 CRM_Utils_Date
::mysqlToIso(
1171 CRM_Utils_Date
::format(
1172 CRM_Utils_Array
::value('credit_card_exp_date', $participantParams))),
1175 // CRM-13890 : NOTE wait list condition need to be given so that
1176 // wait list message is shown properly in email i.e. WRT online event registration template
1177 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
1178 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id');
1179 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($statusId, NULL, 'label');
1181 //CRM-15754 - if participant_status contains status ID
1182 elseif (CRM_Utils_Rule
::integer($tplParams['participant_status'])) {
1183 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($tplParams['participant_status'], NULL, 'label');
1186 $sendTemplateParams = array(
1187 'groupName' => 'msg_tpl_workflow_event',
1188 'valueName' => 'event_online_receipt',
1189 'contactId' => $contactID,
1190 'isTest' => $isTest,
1191 'tplParams' => $tplParams,
1192 'PDFFilename' => ts('confirmation') . '.pdf',
1195 // address required during receipt processing (pdf and email receipt)
1196 if ($displayAddress = CRM_Utils_Array
::value('address', $values)) {
1197 $sendTemplateParams['tplParams']['address'] = $displayAddress;
1198 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1201 // set lineItem details
1202 if ($lineItem = CRM_Utils_Array
::value('lineItem', $values)) {
1203 // check if additional prticipant, if so filter only to relevant ones
1205 if (!empty($values['params']['additionalParticipant'])) {
1206 $ownLineItems = array();
1207 foreach ($lineItem as $liKey => $liValue) {
1208 $firstElement = array_pop($liValue);
1209 if ($firstElement['entity_id'] == $participantId) {
1210 $ownLineItems[0] = $lineItem[$liKey];
1214 if (!empty($ownLineItems)) {
1215 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1219 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1223 if ($returnMessageText) {
1224 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1226 'subject' => $subject,
1228 'to' => $displayName,
1233 $sendTemplateParams['from'] = CRM_Utils_Array
::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array
::value('confirm_from_email', $values['event']) . ">";
1234 $sendTemplateParams['toName'] = $displayName;
1235 $sendTemplateParams['toEmail'] = $email;
1236 $sendTemplateParams['autoSubmitted'] = TRUE;
1237 $sendTemplateParams['cc'] = CRM_Utils_Array
::value('cc_confirm',
1240 $sendTemplateParams['bcc'] = CRM_Utils_Array
::value('bcc_confirm',
1243 // append invoice pdf to email
1244 $template = CRM_Core_Smarty
::singleton();
1245 $taxAmt = $template->get_template_vars('totalTaxAmount');
1246 $prefixValue = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1247 $invoicing = CRM_Utils_Array
::value('invoicing', $prefixValue);
1248 if ($taxAmt && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1249 $sendTemplateParams['isEmailPdf'] = TRUE;
1250 $sendTemplateParams['contributionId'] = $values['contributionId'];
1252 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1259 * Add the custom fields OR array of participant's
1263 * @param string $name
1266 * @param int $participantId
1268 * @param bool $isCustomProfile
1269 * @param array $participantParams
1273 static function buildCustomDisplay(
1280 $isCustomProfile = FALSE,
1281 $participantParams = array()
1284 return array(NULL, NULL);
1287 if (!is_array($id)) {
1288 $id = CRM_Utils_Type
::escape($id, 'Positive');
1289 $profileIds = array($id);
1295 foreach ($profileIds as $gid) {
1296 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $cid)) {
1298 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
,
1299 NULL, NULL, FALSE, NULL,
1300 FALSE, NULL, CRM_Core_Permission
::CREATE
,
1304 //this condition is added, since same contact can have multiple event registrations..
1305 $params = array(array('participant_id', '=', $participantId, 0, 0));
1307 //add participant id
1308 $fields['participant_id'] = array(
1309 'name' => 'participant_id',
1310 'title' => ts('Participant ID'),
1312 //check whether its a text drive
1314 $params[] = array('participant_test', '=', 1, 0, 0);
1317 //display campaign on thankyou page.
1318 if (array_key_exists('participant_campaign_id', $fields)) {
1319 if ($participantId) {
1320 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1324 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1325 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array
::value($campaignId,
1329 unset($fields['participant_campaign_id']);
1333 foreach ($fields as $k => $v) {
1335 $groupTitle = $v['groupTitle'];
1337 // suppress all file fields from display
1339 CRM_Utils_Array
::value('data_type', $v, '') == 'File' ||
1340 CRM_Utils_Array
::value('name', $v, '') == 'image_URL' ||
1341 CRM_Utils_Array
::value('field_type', $v) == 'Formatting'
1348 $groupTitles[] = $groupTitle;
1350 //display profile groups those are subscribed by participant.
1351 if (($groups = CRM_Utils_Array
::value('group', $participantParams)) &&
1355 foreach ($groups as $grpId => $isSelected) {
1360 if (!empty($grpIds)) {
1361 //get the group titles.
1362 $grpTitles = array();
1363 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1364 $grp = CRM_Core_DAO
::executeQuery($query);
1365 while ($grp->fetch()) {
1366 $grpTitles[] = $grp->title
;
1368 if (!empty($grpTitles) &&
1369 CRM_Utils_Array
::value('title', CRM_Utils_Array
::value('group', $fields))
1371 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1373 unset($fields['group']);
1377 CRM_Core_BAO_UFGroup
::getValues($cid, $fields, $values, FALSE, $params);
1379 if (isset($fields['participant_status_id']['title']) &&
1380 isset($values[$fields['participant_status_id']['title']]) &&
1381 is_numeric($values[$fields['participant_status_id']['title']])
1384 $status = CRM_Event_PseudoConstant
::participantStatus();
1385 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1388 if (isset($fields['participant_role_id']['title']) &&
1389 isset($values[$fields['participant_role_id']['title']]) &&
1390 is_numeric($values[$fields['participant_role_id']['title']])
1393 $roles = CRM_Event_PseudoConstant
::participantRole();
1394 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1397 if (isset($fields['participant_register_date']['title']) &&
1398 isset($values[$fields['participant_register_date']['title']])
1400 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date
::customFormat($values[$fields['participant_register_date']['title']]);
1403 //handle fee_level for price set
1404 if (isset($fields['participant_fee_level']['title']) &&
1405 isset($values[$fields['participant_fee_level']['title']])
1407 $feeLevel = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1408 $values[$fields['participant_fee_level']['title']]
1410 foreach ($feeLevel as $key => $value) {
1412 unset($feeLevel[$key]);
1415 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
1418 unset($values[$fields['participant_id']['title']]);
1425 $template->assign($name, $val);
1428 if (count($groupTitles)) {
1429 $template->assign($name . '_grouptitle', $groupTitles);
1432 //return if we only require array of participant's info.
1433 if ($isCustomProfile) {
1435 return array($val, $groupTitles);
1444 * Build the array for display the profile fields
1446 * @param array $params
1450 * @param array $groupTitle
1451 * Profile Group Title.
1452 * @param array $values
1453 * Formatted array of key value.
1455 * @param array $profileFields
1460 public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
1462 $config = CRM_Core_Config
::singleton();
1463 $session = CRM_Core_Session
::singleton();
1464 $contactID = $session->get('userID');
1466 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $contactID)) {
1467 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
);
1471 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::ADD
);
1474 foreach ($fields as $v) {
1475 if (!empty($v['groupTitle'])) {
1476 $groupTitle['groupTitle'] = $v['groupTitle'];
1481 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1482 //start of code to set the default values
1483 foreach ($fields as $name => $field) {
1485 // skip fields that should not be displayed separately
1486 if ($field['skipDisplay']) {
1490 $index = $field['title'];
1491 if ($name === 'organization_name') {
1492 $values[$index] = $params[$name];
1495 if ('state_province' == substr($name, 0, 14)) {
1496 if ($params[$name]) {
1497 $values[$index] = CRM_Core_PseudoConstant
::stateProvince($params[$name]);
1500 $values[$index] = '';
1503 elseif ('date' == substr($name, -4)) {
1504 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::processDate($params[$name]),
1505 $config->dateformatFull
);
1507 elseif ('country' == substr($name, 0, 7)) {
1508 if ($params[$name]) {
1509 $values[$index] = CRM_Core_PseudoConstant
::country($params[$name]);
1512 $values[$index] = '';
1515 elseif ('county' == substr($name, 0, 6)) {
1516 if ($params[$name]) {
1517 $values[$index] = CRM_Core_PseudoConstant
::county($params[$name]);
1520 $values[$index] = '';
1523 elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
1524 $values[$index] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
1526 elseif (in_array($name, array(
1531 $filterCondition = array('greeting_type' => $name);
1532 $greeting = CRM_Core_PseudoConstant
::greeting($filterCondition);
1533 $values[$index] = $greeting[$params[$name]];
1535 elseif ($name === 'preferred_communication_method') {
1536 $communicationFields = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1538 $pref = $params[$name];
1539 if (is_array($pref)) {
1540 foreach ($pref as $k => $v) {
1542 $compref[] = $communicationFields[$k];
1546 $values[$index] = implode(',', $compref);
1548 elseif ($name == 'contact_sub_type') {
1549 $values[$index] = implode(', ', $params[$name]);
1551 elseif ($name == 'group') {
1552 $groups = CRM_Contact_BAO_GroupContact
::getGroupList();
1554 foreach ($params[$name] as $gId => $dontCare) {
1556 $title[] = $groups[$gId];
1559 $values[$index] = implode(', ', $title);
1561 elseif ($name == 'tag') {
1562 $entityTags = $params[$name];
1563 $allTags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
1565 if (is_array($entityTags)) {
1566 foreach ($entityTags as $tagId => $dontCare) {
1567 $title[] = $allTags[$tagId];
1570 $values[$index] = implode(', ', $title);
1572 elseif ('participant_role_id' == $name OR
1573 'participant_role' == $name
1575 $roles = CRM_Event_PseudoConstant
::participantRole();
1576 $values[$index] = $roles[$params[$name]];
1578 elseif ('participant_status_id' == $name OR
1579 'participant_status' == $name
1581 $status = CRM_Event_PseudoConstant
::participantStatus();
1582 $values[$index] = $status[$params[$name]];
1584 elseif (substr($name, -11) == 'campaign_id') {
1585 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($params[$name]);
1586 $values[$index] = CRM_Utils_Array
::value($params[$name], $campaigns);
1588 elseif (strpos($name, '-') !== FALSE) {
1589 list($fieldName, $id) = CRM_Utils_System
::explode('-', $name, 2);
1590 $detailName = str_replace(' ', '_', $name);
1591 if (in_array($fieldName, array(
1596 $values[$index] = $params[$detailName];
1597 $idx = $detailName . '_id';
1598 $values[$index] = $params[$idx];
1600 elseif ($fieldName == 'im') {
1601 $providerName = NULL;
1602 if ($providerId = $detailName . '-provider_id') {
1603 $providerName = CRM_Utils_Array
::value($params[$providerId], $imProviders);
1605 if ($providerName) {
1606 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1609 $values[$index] = $params[$detailName];
1612 elseif ($fieldName == 'phone') {
1613 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1614 if (isset($params[$phoneExtField])) {
1615 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1618 $values[$index] = $params[$detailName];
1622 $values[$index] = $params[$detailName];
1626 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1627 if ($params[$name]) {
1628 $values[$index] = '[ x ]';
1632 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
1634 SELECT html_type, data_type
1635 FROM civicrm_custom_field
1638 $dao = CRM_Core_DAO
::executeQuery($query);
1640 $htmlType = $dao->html_type
;
1642 if ($htmlType == 'File') {
1643 $values[$index] = $params[$index];
1646 if ($dao->data_type
== 'Int' ||
1647 $dao->data_type
== 'Boolean'
1649 $v = $params[$name];
1650 if (!CRM_Utils_System
::isNull($v)) {
1651 $customVal = (int) $v;
1654 elseif ($dao->data_type
== 'Float') {
1655 $customVal = (float ) ($params[$name]);
1657 elseif ($dao->data_type
== 'Date') {
1658 //@todo note the currently we are using default date time formatting. Since you can select/set
1659 // different date and time format specific to custom field we should consider fixing this
1660 // sometime in the future
1661 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1662 CRM_Utils_Date
::processDate($params[$name]), $config->dateformatFull
);
1664 if (!empty($params[$name . '_time'])) {
1665 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1666 CRM_Utils_Date
::processDate($params[$name], $params[$name . '_time']),
1667 $config->dateformatDatetime
);
1672 $customVal = $params[$name];
1674 //take the custom field options
1675 $returnProperties = array($name => 1);
1676 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
1677 $options = &$query->_options
;
1679 $displayValue = CRM_Core_BAO_CustomField
::getDisplayValue($customVal, $cfID, $options);
1681 //Hack since we dont have function to check empty.
1682 //FIXME in 2.3 using crmIsEmptyArray()
1683 $customValue = TRUE;
1684 if (is_array($customVal) && is_array($displayValue)) {
1685 $customValue = array_diff($customVal, $displayValue);
1687 //use difference of arrays
1688 if (empty($customValue) ||
!$customValue) {
1689 $values[$index] = '';
1692 $values[$index] = $displayValue;
1696 elseif ($name == 'home_URL' &&
1697 !empty($params[$name])
1699 $url = CRM_Utils_System
::fixURL($params[$name]);
1700 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1702 elseif (in_array($name, array(
1705 'participant_register_date',
1707 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::format($params[$name]));
1710 $values[$index] = $params[$name];
1714 $profileFields[$name] = $field;
1720 * Build the array for Additional participant's information array of priamry and additional Ids
1722 * @param int $participantId
1723 * Id of Primary participant.
1724 * @param array $values
1725 * Key/value event info.
1726 * @param int $contactId
1727 * Contact id of Primary participant.
1728 * @param bool $isTest
1729 * Whether test or live transaction.
1730 * @param bool $isIdsArray
1731 * To return an array of Ids.
1733 * @param bool $skipCancel
1736 * array of Additional participant's info OR array of Ids.
1738 static function buildCustomProfile(
1743 $isIdsArray = FALSE,
1747 $customProfile = $additionalIDs = array();
1748 if (!$participantId) {
1749 CRM_Core_Error
::fatal(ts('Cannot find participant ID'));
1752 //set Ids of Primary Participant also.
1753 if ($isIdsArray && $contactId) {
1754 $additionalIDs[$participantId] = $contactId;
1757 //hack to skip cancelled participants, CRM-4320
1758 $where = "participant.registered_by_id={$participantId}";
1760 $cancelStatusId = 0;
1761 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1762 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1763 $where .= " AND participant.status_id != {$cancelStatusId}";
1766 SELECT participant.id, participant.contact_id
1767 FROM civicrm_participant participant
1770 $dao = CRM_Core_DAO
::executeQuery($query);
1771 while ($dao->fetch()) {
1772 $additionalIDs[$dao->id
] = $dao->contact_id
;
1775 //return if only array is required.
1776 if ($isIdsArray && $contactId) {
1777 return $additionalIDs;
1780 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values);
1781 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values);
1782 //else build array of Additional participant's information.
1783 if (count($additionalIDs)) {
1784 if ($preProfileID ||
$postProfileID) {
1785 $template = CRM_Core_Smarty
::singleton();
1787 $isCustomProfile = TRUE;
1789 $title = $groupTitles = array();
1790 foreach ($additionalIDs as $pId => $cId) {
1791 //get the params submitted by participant.
1792 $participantParams = CRM_Utils_Array
::value($pId, $values['params'], array());
1794 list($profilePre, $groupTitles) = self
::buildCustomDisplay($preProfileID,
1795 'additionalCustomPre',
1805 $profile = $profilePre;
1806 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1808 $title = $groupTitles;
1812 list($profilePost, $groupTitles) = self
::buildCustomDisplay($postProfileID,
1813 'additionalCustomPost',
1823 if (isset($profilePre)) {
1824 $profile = array_merge($profilePre, $profilePost);
1826 $title = array_merge($title, $groupTitles);
1830 $profile = $profilePost;
1832 $title = $groupTitles;
1836 $profiles[] = $profile;
1839 $customProfile['title'] = $title;
1840 $customProfile['profile'] = $profiles;
1844 return $customProfile;
1847 /* Function to retrieve all events those having location block set.
1850 * array of all events.
1855 public static function getLocationEvents() {
1859 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
1860 FROM civicrm_event ce
1861 INNER JOIN civicrm_loc_block lb ON ce.loc_block_id = lb.id
1862 INNER JOIN civicrm_address ca ON lb.address_id = ca.id
1863 LEFT JOIN civicrm_state_province sp ON ca.state_province_id = sp.id
1864 ORDER BY sp.name, ca.city, ca.street_address ASC
1867 $dao = CRM_Core_DAO
::executeQuery($query);
1868 while ($dao->fetch()) {
1869 $events[$dao->loc_block_id
] = $dao->title
;
1876 * @param int $locBlockId
1878 * @return int|null|string
1880 public static function countEventsUsingLocBlockId($locBlockId) {
1885 $locBlockId = CRM_Utils_Type
::escape($locBlockId, 'Integer');
1888 SELECT count(*) FROM civicrm_event ce
1889 WHERE ce.loc_block_id = $locBlockId";
1891 return CRM_Core_DAO
::singleValueQuery($query);
1895 * Check if event registration is valid according to permissions AND Dates
1897 * @param array $values
1898 * @param int $eventID
1901 public static function validRegistrationRequest($values, $eventID) {
1902 // check that the user has permission to register for this event
1903 $hasPermission = CRM_Core_Permission
::event(CRM_Core_Permission
::EDIT
,
1904 $eventID, 'register for events'
1907 return $hasPermission && self
::validRegistrationDate($values);
1915 public static function validRegistrationDate(&$values) {
1916 // make sure that we are between registration start date and registration end date
1917 $startDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_start_date', $values));
1918 $endDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_end_date', $values));
1919 $eventEnd = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('end_date', $values));
1922 if ($startDate && $startDate >= $now) {
1925 if ($endDate && $endDate < $now) {
1928 if ($eventEnd && $eventEnd < $now) {
1935 /* Function to Show - Hide the Registration Link.
1937 * @param array $values
1938 * Key/value event info.
1940 * true if allow registration otherwise false
1947 public static function showHideRegistrationLink($values) {
1949 $session = CRM_Core_Session
::singleton();
1950 $contactID = $session->get('userID');
1951 $alreadyRegistered = FALSE;
1954 $params = array('contact_id' => $contactID);
1956 if ($eventId = CRM_Utils_Array
::value('id', $values['event'])) {
1957 $params['event_id'] = $eventId;
1959 if ($roleId = CRM_Utils_Array
::value('default_role_id', $values['event'])) {
1960 $params['role_id'] = $roleId;
1962 $alreadyRegistered = self
::checkRegistration($params);
1965 if (!empty($values['event']['allow_same_participant_emails']) ||
1973 /* Function to check if given contact is already registered.
1975 * @param array $params
1976 * Key/value participant info.
1980 * @param array $params
1984 public static function checkRegistration($params) {
1985 $alreadyRegistered = FALSE;
1986 if (empty($params['contact_id'])) {
1987 return $alreadyRegistered;
1990 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
1992 $participant = new CRM_Event_DAO_Participant();
1993 $participant->copyValues($params);
1995 $participant->is_test
= CRM_Utils_Array
::value('is_test', $params, 0);
1996 $participant->selectAdd();
1997 $participant->selectAdd('status_id');
1998 if ($participant->find(TRUE) && array_key_exists($participant->status_id
, $statusTypes)) {
1999 $alreadyRegistered = TRUE;
2002 return $alreadyRegistered;
2006 * Make sure that the user has permission to access this event
2008 * @param int $eventId
2012 * the permission that the user has (or null)
2015 public static function checkPermission($eventId = NULL, $type = CRM_Core_Permission
::VIEW
) {
2016 static $permissions = NULL;
2018 if (empty($permissions)) {
2019 $allEvents = CRM_Event_PseudoConstant
::event(NULL, TRUE);
2020 $createdEvents = array();
2022 $session = CRM_Core_Session
::singleton();
2023 if ($userID = $session->get('userID')) {
2024 $createdEvents = array_keys(CRM_Event_PseudoConstant
::event(NULL, TRUE, "created_id={$userID}"));
2027 // Note: for a multisite setup, a user with edit all events, can edit all events
2028 // including those from other sites
2029 if (CRM_Core_Permission
::check('edit all events')) {
2030 $permissions[CRM_Core_Permission
::EDIT
] = array_keys($allEvents);
2033 $permissions[CRM_Core_Permission
::EDIT
] = &CRM_ACL_API
::group(CRM_Core_Permission
::EDIT
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2036 if (CRM_Core_Permission
::check('edit all events')) {
2037 $permissions[CRM_Core_Permission
::VIEW
] = array_keys($allEvents);
2040 if (CRM_Core_Permission
::check('access CiviEvent') &&
2041 CRM_Core_Permission
::check('view event participants')
2043 // use case: allow "view all events" but NOT "edit all events"
2044 // so for a normal site allow users with these two permissions to view all events AND
2045 // at the same time also allow any hook to override if needed.
2046 $createdEvents = array_keys($allEvents);
2048 $permissions[CRM_Core_Permission
::VIEW
] = &CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2051 $permissions[CRM_Core_Permission
::DELETE
] = array();
2052 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
2053 // Note: we want to restrict the scope of delete permission to
2054 // events that are editable/viewable (usecase multisite).
2055 // We can remove array_intersect once we have ACL support for delete functionality.
2056 $permissions[CRM_Core_Permission
::DELETE
] = array_intersect($permissions[CRM_Core_Permission
::EDIT
],
2057 $permissions[CRM_Core_Permission
::VIEW
]
2063 return in_array($eventId, $permissions[$type]) ?
TRUE : FALSE;
2066 return $permissions;
2070 * Build From Email as the combination of all the email ids of the logged in user,
2071 * the domain email id and the email id configured for the event
2073 * @param int $eventId
2074 * The id of the event.
2077 * an array of email ids
2080 public static function getFromEmailIds($eventId = NULL) {
2081 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email
::getFromEmail();
2084 // add the email id configured for the event
2085 $params = array('id' => $eventId);
2086 $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
2087 $eventEmail = array();
2089 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
2090 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
2091 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
2093 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
2094 $fromEmailId = array(
2095 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventEmail),
2096 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventEmail),
2098 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2102 return $fromEmailValues;
2106 * Calculate event total seats occupied.
2108 * @param int $eventId
2110 * @param sting $extraWhereClause
2111 * Extra filter on participants.
2114 * event total seats w/ given criteria.
2117 public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
2118 if (empty($eventId)) {
2122 $extraWhereClause = trim($extraWhereClause);
2123 if (!empty($extraWhereClause)) {
2124 $extraWhereClause = " AND ( {$extraWhereClause} )";
2127 //event seats calculation :
2128 //1. consider event seat as a single when participant does not have line item.
2129 //2. consider event seat as a single when participant has line items but does not
2130 // have count for corresponding price field value ( ie price field value does not carry any seat )
2131 //3. consider event seat as a sum of all seats from line items in case price field value carries count.
2134 SELECT IF ( SUM( value.count*lineItem.qty ),
2135 SUM( value.count*lineItem.qty ) +
2136 COUNT( DISTINCT participant.id ) -
2137 COUNT( DISTINCT IF ( value.count, participant.id, NULL ) ),
2138 COUNT( DISTINCT participant.id ) )
2139 FROM civicrm_participant participant
2140 INNER JOIN civicrm_contact contact ON ( contact.id = participant.contact_id AND contact.is_deleted = 0 )
2141 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
2142 LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id
2143 AND lineItem.entity_table = 'civicrm_participant' )
2144 LEFT JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id AND value.count )
2145 WHERE ( participant.event_id = %1 )
2146 AND participant.is_test = 0
2148 GROUP BY participant.event_id";
2150 return (int) CRM_Core_DAO
::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
2154 * Retrieve event template default values to be set
2155 * as default values for current new event.
2157 * @param int $templateId
2158 * Event template id.
2161 * Array of custom data defaults.
2163 public static function getTemplateDefaultValues($templateId) {
2164 $defaults = array();
2169 $templateParams = array('id' => $templateId);
2170 CRM_Event_BAO_Event
::retrieve($templateParams, $defaults);
2171 $fieldsToExclude = array(
2174 'default_discount_fee_id',
2180 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2185 * @param int $event_id
2189 public static function get_sub_events($event_id) {
2190 $params = array('parent_event_id' => $event_id);
2191 $defaults = array();
2192 return CRM_Event_BAO_Event
::retrieve($params, $defaults);
2196 * Update the Campaign Id of all the participants of the given event
2198 * @param int $eventID
2200 * @param int $eventCampaignID
2201 * Campaign id of that event.
2203 public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
2205 $params[1] = array($eventID, 'Integer');
2207 if (empty($eventCampaignID)) {
2208 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2211 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2212 $params[2] = array($eventCampaignID, 'Integer');
2214 CRM_Core_DAO
::executeQuery($query, $params);
2218 * Get options for a given field.
2219 * @see CRM_Core_DAO::buildOptions
2221 * @param string $fieldName
2222 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2223 * @param array $props : whatever is known about this dao object
2225 * @return array|bool
2227 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2229 // Special logic for fields whose options depend on context or properties
2230 switch ($fieldName) {
2231 case 'financial_type_id':
2232 // Fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
2233 return CRM_Financial_BAO_FinancialType
::getIncomeFinancialType();
2237 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);