3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 function __construct() {
41 parent
::__construct();
45 * Takes a bunch of params that are needed to match certain criteria and
46 * retrieves the relevant objects. Typically the valid params are only
47 * contact_id. We'll tweak this function to be more full featured over a period
48 * of time. This is the inverse function of create. It also stores all the retrieved
49 * values in the default array
51 * @param array $params (reference ) an assoc array of name/value pairs
52 * @param array $defaults (reference ) an assoc array to hold the flattened values
54 * @return object CRM_Event_BAO_ManageEvent object
58 static function retrieve(&$params, &$defaults) {
59 $event = new CRM_Event_DAO_Event();
60 $event->copyValues($params);
61 if ($event->find(TRUE)) {
62 CRM_Core_DAO
::storeValues($event, $defaults);
69 * update the is_active flag in the db
71 * @param int $id id of the database record
72 * @param boolean $is_active value we want to set the is_active field
74 * @return Object DAO object on sucess, null otherwise
77 static function setIsActive($id, $is_active) {
78 return CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
82 * function to add the event
84 * @param array $params reference array contains the values submitted by the form
91 static function add(&$params) {
92 CRM_Utils_System
::flushCache();
93 $financialTypeId = NULL;
94 if (!empty($params['id'])) {
95 CRM_Utils_Hook
::pre('edit', 'Event', $params['id'], $params);
96 if (empty($params['skipFinancialType'])) {
97 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $params['id'], 'financial_type_id');
101 CRM_Utils_Hook
::pre('create', 'Event', NULL, $params);
104 $event = new CRM_Event_DAO_Event();
106 $event->copyValues($params);
107 $result = $event->save();
109 if (!empty($params['id'])) {
110 CRM_Utils_Hook
::post('edit', 'Event', $event->id
, $event);
113 CRM_Utils_Hook
::post('create', 'Event', $event->id
, $event);
115 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
116 CRM_Price_BAO_PriceFieldValue
::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
122 * function to create the event
124 * @param array $params reference array contains the values submitted by the form
131 public static function create(&$params) {
132 $transaction = new CRM_Core_Transaction();
133 if (empty($params['is_template'])) {
134 $params['is_template'] = 0;
136 // check if new event, if so set the created_id (if not set)
137 // and always set created_date to now
138 if (empty($params['id'])) {
139 if (empty($params['created_id'])) {
140 $session = CRM_Core_Session
::singleton();
141 $params['created_id'] = $session->get('userID');
143 $params['created_date'] = date('YmdHis');
146 $event = self
::add($params);
148 if (is_a($event, 'CRM_Core_Error')) {
149 CRM_Core_DAO
::transaction('ROLLBACK');
153 $session = CRM_Core_Session
::singleton();
154 $contactId = $session->get('userID');
156 $contactId = CRM_Utils_Array
::value('contact_id', $params);
159 // Log the information on successful add/edit of Event
161 'entity_table' => 'civicrm_event',
162 'entity_id' => $event->id
,
163 'modified_id' => $contactId,
164 'modified_date' => date('Ymd'),
167 CRM_Core_BAO_Log
::add($logParams);
169 if (!empty($params['custom']) &&
170 is_array($params['custom'])
172 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_event', $event->id
);
175 $transaction->commit();
181 * Function to delete the event
183 * @param int $id event id
190 static function del($id) {
195 CRM_Utils_Hook
::pre('delete', 'Event', $id, CRM_Core_DAO
::$_nullArray);
197 $extends = array('event');
198 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
199 foreach ($groupTree as $values) {
200 $query = "DELETE FROM " . $values['table_name'] . " WHERE entity_id = " . $id;
202 $params = array(1 => array($values['table_name'], 'string'),
203 2 => array($id, 'integer'),
206 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
209 // price set cleanup, CRM-5527
210 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_event', $id);
212 $event = new CRM_Event_DAO_Event();
215 if ($event->find(TRUE)) {
216 $locBlockId = $event->loc_block_id
;
217 $result = $event->delete();
219 if (!is_null($locBlockId)) {
220 self
::deleteEventLocBlock($locBlockId, $id);
223 CRM_Utils_Hook
::post('delete', 'Event', $id, $event);
231 * Function to delete the location block associated with an event,
232 * if not being used by any other event.
235 * @param null $eventId
237 * @internal param int $loc_block_id location block id to be deleted
238 * @internal param int $eventid event id with which loc block is associated
243 static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
244 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
247 $query .= " AND ce.id != $eventId;";
250 $locCount = CRM_Core_DAO
::singleValueQuery($query);
252 if ($locCount == 0) {
253 CRM_Core_BAO_Location
::deleteLocBlock($locBlockId);
258 * Function to get current/future Events
260 * @param $all int 0 returns current and future events
261 * 1 if events all are required
262 * 2 returns events since 3 months ago
263 * @param bool|int $id int id of a specific event to return
264 * @param $isActive boolean true if you need only active events
265 * @param $checkPermission boolean true if you need to check permission else false
270 static function getEvents($all = 0,
273 $checkPermission = TRUE
276 SELECT `id`, `title`, `start_date`
278 WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
281 $query .= " AND `id` = {$id}";
284 // find only events ending in the future
285 $endDate = date('YmdHis');
287 AND ( `end_date` >= {$endDate} OR
289 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
294 // find only events starting in the last 3 months
295 $startDate = date('YmdHis', strtotime('3 months ago'));
296 $query .= " AND ( `start_date` >= {$startDate} OR start_date IS NULL )";
299 $query .= " AND civicrm_event.is_active = 1";
302 $query .= " ORDER BY title asc";
305 $dao = CRM_Core_DAO
::executeQuery($query);
306 while ($dao->fetch()) {
307 if ((!$checkPermission ||
308 CRM_Event_BAO_Event
::checkPermission($dao->id
)
312 $events[$dao->id
] = $dao->title
. ' - ' . CRM_Utils_Date
::customFormat($dao->start_date
);
320 * Function to get events Summary
324 * @return array Array of event summary values
326 static function getEventSummary() {
327 $eventSummary = $eventIds = array();
328 $config = CRM_Core_Config
::singleton();
330 // get permission and include them here
331 // does not scale, but rearranging code for now
332 // FIXME in a future release
333 $permissions = CRM_Event_BAO_Event
::checkPermission();
335 if (empty($permissions[CRM_Core_Permission
::VIEW
])) {
336 $eventSummary['total_events'] = 0;
337 return $eventSummary;
340 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission
::VIEW
])) . " ) ";
343 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
345 SELECT count(id) as total_events
347 WHERE civicrm_event.is_active = 1 AND
348 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
349 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
352 $dao = CRM_Core_DAO
::executeQuery($query);
355 $eventSummary['total_events'] = $dao->total_events
;
358 if (empty($eventSummary) ||
359 $dao->total_events
== 0
361 return $eventSummary;
364 //get the participant status type values.
365 $query = 'SELECT id, name, class FROM civicrm_participant_status_type';
366 $status = CRM_Core_DAO
::executeQuery($query);
367 $statusValues = array();
368 while ($status->fetch()) {
369 $statusValues[$status->id
]['id'] = $status->id
;
370 $statusValues[$status->id
]['name'] = $status->name
;
371 $statusValues[$status->id
]['class'] = $status->class;
374 // Get the Id of Option Group for Event Types
375 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
376 $optionGroupDAO->name
= 'event_type';
377 $optionGroupId = NULL;
378 if ($optionGroupDAO->find(TRUE)) {
379 $optionGroupId = $optionGroupDAO->id
;
383 SELECT civicrm_event.id as id, civicrm_event.title as event_title, civicrm_event.is_public as is_public,
384 civicrm_event.max_participants as max_participants, civicrm_event.start_date as start_date,
385 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,
386 civicrm_event.slot_label_id,
387 civicrm_event.summary as summary,
388 civicrm_pcp_block.id as is_pcp_enabled
390 LEFT JOIN civicrm_option_value ON (
391 civicrm_event.event_type_id = civicrm_option_value.value AND
392 civicrm_option_value.option_group_id = %1 )
393 LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_event.id AND civicrm_tell_friend.entity_table = 'civicrm_event' )
394 LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_event.id AND civicrm_pcp_block.entity_table = 'civicrm_event')
395 WHERE civicrm_event.is_active = 1 AND
396 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
397 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
399 GROUP BY civicrm_event.id
400 ORDER BY civicrm_event.start_date ASC
403 $eventParticipant = array();
407 'eventTitle' => 'event_title',
408 'isPublic' => 'is_public',
409 'maxParticipants' => 'max_participants',
410 'startDate' => 'start_date',
411 'endDate' => 'end_date',
412 'eventType' => 'event_type',
414 'participants' => 'participants',
415 'notCountedDueToRole' => 'notCountedDueToRole',
416 'notCountedDueToStatus' => 'notCountedDueToStatus',
417 'notCountedParticipants' => 'notCountedParticipants',
420 $params = array(1 => array($optionGroupId, 'Integer'));
421 $mappingID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', 'civicrm_event', 'id', 'entity_value');
422 $dao = CRM_Core_DAO
::executeQuery($query, $params);
423 while ($dao->fetch()) {
424 foreach ($properties as $property => $name) {
434 $eventSummary['events'][$dao->id
][$property] = $set;
438 if ($dao->$name && $config->mapAPIKey
) {
441 $params = array('entity_id' => $dao->id
, 'entity_table' => 'civicrm_event');
442 $values['location'] = CRM_Core_BAO_Location
::getValues($params, TRUE);
443 if (is_numeric(CRM_Utils_Array
::value('geo_code_1', $values['location']['address'][1])) ||
444 ($config->mapGeoCoding
&&
445 !empty($values['location']['address'][1]['city']) &&
446 !empty($values['location']['address'][1]['state_province_id'])
449 $set = CRM_Utils_System
::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
453 $eventSummary['events'][$dao->id
][$property] = $set;
454 if (in_array($dao->id
, $permissions[CRM_Core_Permission
::EDIT
])) {
455 $eventSummary['events'][$dao->id
]['configure'] = CRM_Utils_System
::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
461 $eventSummary['events'][$dao->id
][$property] = CRM_Utils_Date
::customFormat($dao->$name,
467 case 'notCountedDueToRole':
468 case 'notCountedDueToStatus':
469 case 'notCountedParticipants':
472 if ($name == 'participants') {
473 $propertyCnt = self
::getParticipantCount($dao->id
);
475 $set = CRM_Utils_System
::url('civicrm/event/search',
476 "reset=1&force=1&event=$dao->id&status=true&role=true"
480 elseif ($name == 'notCountedParticipants') {
481 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, TRUE, FALSE);
483 // FIXME : selector fail to search w/ OR operator.
484 // $set = CRM_Utils_System::url( 'civicrm/event/search',
485 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
488 elseif ($name == 'notCountedDueToStatus') {
489 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, FALSE, FALSE);
491 $set = CRM_Utils_System
::url('civicrm/event/search',
492 "reset=1&force=1&event=$dao->id&status=false"
497 $propertyCnt = self
::getParticipantCount($dao->id
, FALSE, FALSE, TRUE, FALSE);
499 $set = CRM_Utils_System
::url('civicrm/event/search',
500 "reset=1&force=1&event=$dao->id&role=false"
505 $eventSummary['events'][$dao->id
][$property] = $propertyCnt;
506 $eventSummary['events'][$dao->id
][$name . '_url'] = $set;
510 $eventSummary['events'][$dao->id
][$property] = $dao->$name;
515 // prepare the area for per-status participant counts
516 $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
517 $eventSummary['events'][$dao->id
]['statuses'] = array_fill_keys($statusClasses, array());
519 $eventSummary['events'][$dao->id
]['friend'] = $dao->is_friend_active
;
520 $eventSummary['events'][$dao->id
]['is_monetary'] = $dao->is_monetary
;
521 $eventSummary['events'][$dao->id
]['is_online_registration'] = $dao->is_online_registration
;
522 $eventSummary['events'][$dao->id
]['is_show_location'] = $dao->is_show_location
;
523 $eventSummary['events'][$dao->id
]['is_subevent'] = $dao->slot_label_id
;
524 $eventSummary['events'][$dao->id
]['is_pcp_enabled'] = $dao->is_pcp_enabled
;
525 $eventSummary['events'][$dao->id
]['reminder'] = CRM_Core_BAO_ActionSchedule
::isConfigured($dao->id
, $mappingID);
527 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
528 foreach ($statusValues as $statusId => $statusValue) {
529 if (!array_key_exists($statusId, $statusTypes)) {
532 $class = $statusValue['class'];
533 $statusCount = self
::eventTotalSeats($dao->id
, "( participant.status_id = {$statusId} )");
535 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
536 $statusInfo = array('url' => CRM_Utils_System
::url('civicrm/event/search', $urlString),
537 'name' => $statusValue['name'],
538 'count' => $statusCount,
540 $eventSummary['events'][$dao->id
]['statuses'][$class][] = $statusInfo;
545 $countedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
546 $nonCountedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
547 $countedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
548 $nonCountedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
550 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
551 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
553 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
554 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
555 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
556 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
558 return $eventSummary;
562 * Function to get participant count
565 * @param boolean $considerStatus consider status for participant count.
566 * @param boolean $status consider counted participant.
567 * @param boolean $considerRole consider role for participant count.
568 * @param boolean $role consider counted( is filter role) participant.
570 * @internal param array $eventIds consider participants from given events.
571 * @internal param bool $countWithStatus retrieve participant count w/ each participant status.
575 * @return array array with count of participants for each event based on status/role
577 public static function getParticipantCount($eventId,
578 $considerStatus = TRUE,
580 $considerRole = TRUE,
584 // consider both role and status for counted participants, CRM-4924.
586 // not counted participant.
587 if ($considerStatus && $considerRole && !$status && !$role) {
591 if ($considerStatus) {
592 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
593 $statusClause = 'NOT IN';
595 $statusClause = 'IN';
597 $status = implode(',', array_keys($statusTypes));
598 if (empty($status)) {
601 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
605 $roleTypes = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
606 $roleClause = 'NOT IN';
610 $roles = implode(',', array_keys($roleTypes));
614 $clause[] = "participant.role_id {$roleClause} ( $roles )";
618 if (!empty($clause)) {
619 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
622 return self
::eventTotalSeats($eventId, $sqlClause);
626 * function to get the information to map a event
630 * @internal param array $ids the list of ids for which we want map info
632 * @return null|string title of the event
636 static function &getMapInfo(&$id) {
640 civicrm_event.id AS event_id,
641 civicrm_event.title AS display_name,
642 civicrm_address.street_address AS street_address,
643 civicrm_address.city AS city,
644 civicrm_address.postal_code AS postal_code,
645 civicrm_address.postal_code_suffix AS postal_code_suffix,
646 civicrm_address.geo_code_1 AS latitude,
647 civicrm_address.geo_code_2 AS longitude,
648 civicrm_state_province.abbreviation AS state,
649 civicrm_country.name AS country,
650 civicrm_location_type.name AS location_type
653 LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )
654 LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )
655 LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )
656 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
657 LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )
658 WHERE civicrm_address.geo_code_1 IS NOT NULL
659 AND civicrm_address.geo_code_2 IS NOT NULL
660 AND civicrm_event.id = " . CRM_Utils_Type
::escape($id, 'Integer');
662 $dao = new CRM_Core_DAO();
665 $locations = array();
667 $config = CRM_Core_Config
::singleton();
669 while ($dao->fetch()) {
672 $location['displayName'] = addslashes($dao->display_name
);
673 $location['lat'] = $dao->latitude
;
674 $location['marker_class'] = 'Event';
675 $location['lng'] = $dao->longitude
;
677 $params = array('entity_id' => $id, 'entity_table' => 'civicrm_event');
678 $addressValues = CRM_Core_BAO_Location
::getValues($params, TRUE);
679 $location['address'] = str_replace(array("\r", "\n"), '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
681 $location['url'] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
);
682 $location['location_type'] = $dao->location_type
;
683 $eventImage = '<img src="' . $config->resourceBase
. 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
684 $location['image'] = $eventImage;
685 $location['displayAddress'] = str_replace('<br />', ', ', $location['address']);
686 $locations[] = $location;
692 * function to get the complete information for one or more events
694 * @param date $start get events with start date >= this date
695 * @param integer $type get events on the a specific event type (by event_type_id)
696 * @param integer $eventId return a single event - by event id
697 * @param date $end also get events with end date >= this date
698 * @param boolean $onlyPublic include public events only, default TRUE
700 * @return array $all array of all the events that are searched
704 static function &getCompleteInfo(
711 $publicCondition = NULL;
713 $publicCondition = " AND civicrm_event.is_public = 1";
717 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
719 // get events with start_date >= requested start
720 $startDate = CRM_Utils_Type
::escape($start, 'Date');
721 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
725 // also get events with end_date <= requested end
726 $endDate = CRM_Utils_Type
::escape($end, 'Date');
727 $dateCondition .= " AND ( civicrm_event.end_date <= '{$endDate}' ) ";
730 // CRM-9421 and CRM-8620 Default mode for ical/rss feeds. No start or end filter passed.
731 // Need to exclude old events with only start date
732 // and not exclude events in progress (start <= today and end >= today). DGG
733 if (empty($start) && empty($end)) {
734 // get events with end date >= today, not sure of this logic
735 // but keeping this for backward compatibility as per issue CRM-5133
736 $today = date("Y-m-d G:i:s");
737 $dateCondition .= " AND ( civicrm_event.end_date >= '{$today}' OR civicrm_event.start_date >= '{$today}' ) ";
741 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
744 // Get the Id of Option Group for Event Types
745 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
746 $optionGroupDAO->name
= 'event_type';
747 $optionGroupId = NULL;
748 if ($optionGroupDAO->find(TRUE)) {
749 $optionGroupId = $optionGroupDAO->id
;
754 civicrm_event.id as event_id,
755 civicrm_email.email as email,
756 civicrm_event.title as title,
757 civicrm_event.summary as summary,
758 civicrm_event.start_date as start,
759 civicrm_event.end_date as end,
760 civicrm_event.description as description,
761 civicrm_event.is_show_location as is_show_location,
762 civicrm_event.is_online_registration as is_online_registration,
763 civicrm_event.registration_link_text as registration_link_text,
764 civicrm_event.registration_start_date as registration_start_date,
765 civicrm_event.registration_end_date as registration_end_date,
766 civicrm_option_value.label as event_type,
767 civicrm_address.name as address_name,
768 civicrm_address.street_address as street_address,
769 civicrm_address.supplemental_address_1 as supplemental_address_1,
770 civicrm_address.supplemental_address_2 as supplemental_address_2,
771 civicrm_address.city as city,
772 civicrm_address.postal_code as postal_code,
773 civicrm_address.postal_code_suffix as postal_code_suffix,
774 civicrm_state_province.abbreviation as state,
775 civicrm_country.name AS country
777 LEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id
778 LEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id
779 LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
780 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
781 LEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id
782 LEFT JOIN civicrm_option_value ON (
783 civicrm_event.event_type_id = civicrm_option_value.value AND
784 civicrm_option_value.option_group_id = %1 )
785 WHERE civicrm_event.is_active = 1
786 AND (is_template = 0 OR is_template IS NULL)
790 if (isset($typeCondition)) {
791 $query .= $typeCondition;
794 if (isset($eventId)) {
795 $query .= " AND civicrm_event.id =$eventId ";
797 $query .= " ORDER BY civicrm_event.start_date ASC";
800 $params = array(1 => array($optionGroupId, 'Integer'));
801 $dao = CRM_Core_DAO
::executeQuery($query, $params);
803 $config = CRM_Core_Config
::singleton();
805 $baseURL = parse_url($config->userFrameworkBaseURL
);
806 $url = "@" . $baseURL['host'];
807 if (!empty($baseURL['path'])) {
808 $url .= substr($baseURL['path'], 0, -1);
811 // check 'view event info' permission
812 //@todo - per CRM-14626 we have resolved that 'view event info' means 'view ALL event info'
813 // and passing in the specific permission here will short-circuit the evaluation of permission to
814 // see specific events (doesn't seem relevant to this call
815 // however, since this function is accessed only by a convoluted call from a joomla block function
816 // it seems safer not to touch here. Suggestion is that CRM_Core_Permission::check(array or relevant permissions) would
817 // be clearer & safer here
818 $permissions = CRM_Core_Permission
::event(CRM_Core_Permission
::VIEW
);
820 // check if we're in shopping cart mode for events
821 $enable_cart = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::EVENT_PREFERENCES_NAME
,
825 while ($dao->fetch()) {
826 if (!empty($permissions) && in_array($dao->event_id
, $permissions)) {
828 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL
) . $url;
830 $info['title'] = $dao->title
;
831 $info['event_id'] = $dao->event_id
;
832 $info['summary'] = $dao->summary
;
833 $info['description'] = $dao->description
;
834 $info['start_date'] = $dao->start
;
835 $info['end_date'] = $dao->end
;
836 $info['contact_email'] = $dao->email
;
837 $info['event_type'] = $dao->event_type
;
838 $info['is_show_location'] = $dao->is_show_location
;
839 $info['is_online_registration'] = $dao->is_online_registration
;
840 $info['registration_link_text'] = $dao->registration_link_text
;
841 $info['registration_start_date'] = $dao->registration_start_date
;
842 $info['registration_end_date'] = $dao->registration_end_date
;
847 'address_name' => $dao->address_name
,
848 'street_address' => $dao->street_address
,
849 'supplemental_address_1' => $dao->supplemental_address_1
,
850 'supplemental_address_2' => $dao->supplemental_address_2
,
851 'city' => $dao->city
,
852 'state_province' => $dao->state
,
853 'postal_code' => $dao->postal_code
,
854 'postal_code_suffix' => $dao->postal_code_suffix
,
855 'country' => $dao->country
,
859 CRM_Utils_String
::append($address, ', ',
860 CRM_Utils_Address
::format($addrFields)
862 $info['location'] = $address;
863 $info['url'] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
866 $reg = CRM_Event_Cart_BAO_EventInCart
::get_registration_link($dao->event_id
);
867 $info['registration_link'] = CRM_Utils_System
::url($reg['path'], $reg['query'], TRUE);
868 $info['registration_link_text'] = $reg['label'];
879 * This function is to make a copy of a Event, including
880 * all the fields in the event Wizard
882 * @param int $id the event id to copy
883 * obj $newEvent object of CRM_Event_DAO_Event
884 * boolean $afterCreate call to copy after the create function
885 * @param null $newEvent
886 * @param bool $afterCreate
891 static function copy($id, $newEvent = NULL, $afterCreate = FALSE) {
893 $defaults = $eventValues = array();
895 //get the require event values.
896 $eventParams = array('id' => $id);
897 $returnProperties = array('loc_block_id', 'is_show_location', 'default_fee_id', 'default_discount_fee_id', 'is_template');
899 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
901 // since the location is sharable, lets use the same loc_block_id.
902 $locBlockId = CRM_Utils_Array
::value('loc_block_id', $eventValues);
904 $fieldsFix = ($afterCreate) ?
array( ) : array('prefix' => array('title' => ts('Copy of') . ' '));
905 if (empty($eventValues['is_show_location'])) {
906 $fieldsFix['prefix']['is_show_location'] = 0;
909 if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
910 $copyEvent = $newEvent;
913 if (!isset($copyEvent)) {
914 $copyEvent = &CRM_Core_DAO
::copyGeneric('CRM_Event_DAO_Event',
918 ($locBlockId) ?
$locBlockId : NULL,
923 CRM_Price_BAO_PriceSet
::copyPriceSet('civicrm_event', $id, $copyEvent->id
);
924 $copyUF = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_UFJoin',
927 'entity_table' => 'civicrm_event',
929 array('entity_id' => $copyEvent->id
)
932 $copyTellFriend = &CRM_Core_DAO
::copyGeneric('CRM_Friend_DAO_Friend',
935 'entity_table' => 'civicrm_event',
937 array('entity_id' => $copyEvent->id
)
940 $copyPCP = &CRM_Core_DAO
::copyGeneric('CRM_PCP_DAO_PCPBlock',
943 'entity_table' => 'civicrm_event',
945 array('entity_id' => $copyEvent->id
),
946 array('replace' => array('target_entity_id' => $copyEvent->id
))
949 if ($eventValues['is_template']) {
950 $field = 'event_template';
953 $field = 'civicrm_event';
955 $mappingId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
956 $oldData = array('entity_value' => $id, 'mapping_id' => $mappingId);
957 if ($copyEvent->is_template
== 1) {
958 $field = 'event_template';
961 $field = 'civicrm_event';
963 $copyMappingId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
964 $newData = array('entity_value' => $copyEvent->id
, 'mapping_id' => $copyMappingId);
965 $copyReminder = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_ActionSchedule',
972 $extends = array('event');
973 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
975 foreach ($groupTree as $groupID => $group) {
976 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
977 foreach ($group['fields'] as $fieldID => $field) {
978 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
982 foreach ($table as $tableName => $tableColumns) {
983 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
984 $tableColumns[0] = $copyEvent->id
;
985 $select = 'SELECT ' . implode(', ', $tableColumns);
986 $from = ' FROM ' . $tableName;
987 $where = " WHERE {$tableName}.entity_id = {$id}";
988 $query = $insert . $select . $from . $where;
989 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
995 CRM_Utils_System
::flushCache();
997 CRM_Utils_Hook
::copy('Event', $copyEvent);
1003 * This is sometimes called in a loop (during event search)
1004 * hence we cache the values to prevent repeated calls to the db
1006 static function isMonetary($id) {
1007 static $isMonetary = array();
1008 if (!array_key_exists($id, $isMonetary)) {
1009 $isMonetary[$id] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event',
1014 return $isMonetary[$id];
1018 * This is sometimes called in a loop (during event search)
1019 * hence we cache the values to prevent repeated calls to the db
1021 static function usesPriceSet($id) {
1022 static $usesPriceSet = array();
1023 if (!array_key_exists($id, $usesPriceSet)) {
1024 $usesPriceSet[$id] = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $id);
1026 return $usesPriceSet[$id];
1030 * Process that send e-mails
1034 * @param $participantId
1035 * @param bool $isTest
1036 * @param bool $returnMessageText
1041 static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
1043 $template = CRM_Core_Smarty
::singleton();
1045 'custom_pre_id' => $values['custom_pre_id'],
1046 'custom_post_id' => $values['custom_post_id'],
1049 //get the params submitted by participant.
1050 $participantParams = CRM_Utils_Array
::value($participantId, $values['params'], array());
1052 if (!$returnMessageText) {
1053 //send notification email if field values are set (CRM-1941)
1054 foreach ($gIds as $key => $gIdValues) {
1056 if (!is_array($gIdValues)) {
1057 $gIdValues = array( $gIdValues );
1060 foreach ($gIdValues as $gId) {
1061 $email = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1063 //get values of corresponding profile fields for notification
1064 list($profileValues) = self
::buildCustomDisplay($gId,
1073 list($profileValues) = $profileValues;
1076 'values' => $profileValues,
1079 CRM_Core_BAO_UFGroup
::commonSendMail($contactID, $val);
1086 if ($values['event']['is_email_confirm'] ||
$returnMessageText) {
1087 list($displayName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1089 //send email only when email is present
1090 if (isset($email) ||
$returnMessageText) {
1091 $preProfileID = CRM_Utils_Array
::value('custom_pre_id', $values);
1092 $postProfileID = CRM_Utils_Array
::value('custom_post_id', $values);
1094 if (!empty($values['params']['additionalParticipant'])) {
1095 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values, $preProfileID );
1096 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values, $postProfileID );
1099 self
::buildCustomDisplay($preProfileID,
1109 self
::buildCustomDisplay($postProfileID,
1119 $sessions = CRM_Event_Cart_BAO_Conference
::get_participant_sessions($participantId);
1121 $tplParams = array_merge($values, $participantParams, array(
1123 'confirm_email_text' => CRM_Utils_Array
::value('confirm_email_text', $values['event']),
1124 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $values['event']),
1125 'contributeMode' => NULL,
1126 'participantID' => $participantId,
1127 'conference_sessions' => $sessions,
1130 // CRM-13890 : NOTE wait list condition need to be given so that
1131 // wait list message is shown properly in email i.e. WRT online event registration template
1132 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
1133 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id');
1134 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($statusId, NULL, 'label');
1137 $sendTemplateParams = array(
1138 'groupName' => 'msg_tpl_workflow_event',
1139 'valueName' => 'event_online_receipt',
1140 'contactId' => $contactID,
1141 'isTest' => $isTest,
1142 'tplParams' => $tplParams,
1143 'PDFFilename' => ts('confirmation').'.pdf',
1146 // address required during receipt processing (pdf and email receipt)
1147 if ($displayAddress = CRM_Utils_Array
::value('address', $values)) {
1148 $sendTemplateParams['tplParams']['address'] = $displayAddress;
1149 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1152 // set lineItem details
1153 if ($lineItem = CRM_Utils_Array
::value('lineItem', $values)) {
1154 // check if additional prticipant, if so filter only to relevant ones
1156 if (!empty($values['params']['additionalParticipant'])) {
1157 $ownLineItems = array( );
1158 foreach ( $lineItem as $liKey => $liValue ) {
1159 $firstElement = array_pop( $liValue );
1160 if ( $firstElement['entity_id'] == $participantId ) {
1161 $ownLineItems[0] = $lineItem[$liKey];
1165 if ( ! empty( $ownLineItems ) ) {
1166 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1170 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1174 if ($returnMessageText) {
1175 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1177 'subject' => $subject,
1179 'to' => $displayName,
1184 $sendTemplateParams['from'] = CRM_Utils_Array
::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array
::value('confirm_from_email', $values['event']) . ">";
1185 $sendTemplateParams['toName'] = $displayName;
1186 $sendTemplateParams['toEmail'] = $email;
1187 $sendTemplateParams['autoSubmitted'] = TRUE;
1188 $sendTemplateParams['cc'] = CRM_Utils_Array
::value('cc_confirm',
1191 $sendTemplateParams['bcc'] = CRM_Utils_Array
::value('bcc_confirm',
1194 // append invoice pdf to email
1195 $template = CRM_Core_Smarty
::singleton( );
1196 $taxAmt = $template->get_template_vars('totalTaxAmount');
1197 $prefixValue = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1198 $invoicing = CRM_Utils_Array
::value('invoicing', $prefixValue);
1199 if ($taxAmt && (isset($invoicing) && isset($prefixValue['is_email_pdf'])) ) {
1200 $sendTemplateParams['isEmailPdf'] = True;
1201 $sendTemplateParams['contributionId'] = $values['contributionId'];
1203 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1210 * Function to add the custom fields OR array of participant's
1217 * @param $participantId
1219 * @param bool $isCustomProfile
1220 * @param array $participantParams
1225 static function buildCustomDisplay($id,
1231 $isCustomProfile = FALSE,
1232 $participantParams = array()
1235 return array(NULL, NULL);
1238 if (!is_array($id)) {
1239 $id = CRM_Utils_Type
::escape($id, 'Positive');
1240 $profileIds = array($id);
1246 foreach ($profileIds as $gid) {
1247 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $cid)) {
1249 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
,
1250 NULL, NULL, FALSE, NULL,
1251 FALSE, NULL, CRM_Core_Permission
::CREATE
,
1255 //this condition is added, since same contact can have multiple event registrations..
1256 $params = array(array('participant_id', '=', $participantId, 0, 0));
1258 //add participant id
1259 $fields['participant_id'] = array(
1260 'name' => 'participant_id',
1261 'title' => 'Participant Id',
1263 //check whether its a text drive
1265 $params[] = array('participant_test', '=', 1, 0, 0);
1268 //display campaign on thankyou page.
1269 if (array_key_exists('participant_campaign_id', $fields)) {
1270 if ($participantId) {
1271 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1275 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1276 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array
::value($campaignId,
1280 unset($fields['participant_campaign_id']);
1284 foreach ($fields as $k => $v) {
1286 $groupTitle = $v['groupTitle'];
1288 // suppress all file fields from display
1290 CRM_Utils_Array
::value('data_type', $v, '') == 'File' ||
1291 CRM_Utils_Array
::value('name', $v, '') == 'image_URL' ||
1292 CRM_Utils_Array
::value('field_type', $v) == 'Formatting'
1299 $groupTitles[] = $groupTitle;
1301 //display profile groups those are subscribed by participant.
1302 if (($groups = CRM_Utils_Array
::value('group', $participantParams)) &&
1306 foreach ($groups as $grpId => $isSelected) {
1311 if (!empty($grpIds)) {
1312 //get the group titles.
1313 $grpTitles = array();
1314 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1315 $grp = CRM_Core_DAO
::executeQuery($query);
1316 while ($grp->fetch()) {
1317 $grpTitles[] = $grp->title
;
1319 if (!empty($grpTitles) &&
1320 CRM_Utils_Array
::value('title', CRM_Utils_Array
::value('group', $fields))
1322 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1324 unset($fields['group']);
1328 CRM_Core_BAO_UFGroup
::getValues($cid, $fields, $values, FALSE, $params);
1330 if (isset($fields['participant_status_id']['title']) &&
1331 isset($values[$fields['participant_status_id']['title']]) &&
1332 is_numeric($values[$fields['participant_status_id']['title']])
1335 $status = CRM_Event_PseudoConstant
::participantStatus();
1336 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1339 if (isset($fields['participant_role_id']['title']) &&
1340 isset($values[$fields['participant_role_id']['title']]) &&
1341 is_numeric($values[$fields['participant_role_id']['title']])
1344 $roles = CRM_Event_PseudoConstant
::participantRole();
1345 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1348 if (isset($fields['participant_register_date']['title']) &&
1349 isset($values[$fields['participant_register_date']['title']])
1351 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date
::customFormat($values[$fields['participant_register_date']['title']]);
1354 //handle fee_level for price set
1355 if (isset($fields['participant_fee_level']['title']) &&
1356 isset($values[$fields['participant_fee_level']['title']])
1358 $feeLevel = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1359 $values[$fields['participant_fee_level']['title']]
1361 foreach ($feeLevel as $key => $value) {
1363 unset($feeLevel[$key]);
1366 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
1369 unset($values[$fields['participant_id']['title']]);
1376 $template->assign($name, $val);
1379 if (count($groupTitles)) {
1380 $template->assign($name . '_grouptitle', $groupTitles);
1383 //return if we only require array of participant's info.
1384 if ($isCustomProfile) {
1386 return array($val, $groupTitles);
1395 * Function to build the array for display the profile fields
1397 * @param array $params key value.
1398 * @param int $gid profile Id
1399 * @param array $groupTitle Profile Group Title.
1400 * @param array $values formatted array of key value
1402 * @param array $profileFields
1408 static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
1410 $config = CRM_Core_Config
::singleton();
1411 $session = CRM_Core_Session
::singleton();
1412 $contactID = $session->get('userID');
1414 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $contactID)) {
1415 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
);
1419 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::ADD
);
1422 foreach ($fields as $v) {
1423 if (!empty($v['groupTitle'])) {
1424 $groupTitle['groupTitle'] = $v['groupTitle'];
1429 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1430 //start of code to set the default values
1431 foreach ($fields as $name => $field) {
1433 // skip fields that should not be displayed separately
1434 if ($field['skipDisplay']) {
1438 $index = $field['title'];
1439 if ($name === 'organization_name') {
1440 $values[$index] = $params[$name];
1443 if ('state_province' == substr($name, 0, 14)) {
1444 if ($params[$name]) {
1445 $values[$index] = CRM_Core_PseudoConstant
::stateProvince($params[$name]);
1448 $values[$index] = '';
1451 elseif ('date' == substr($name, -4)) {
1452 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::processDate($params[$name]),
1453 $config->dateformatFull
);
1455 elseif ('country' == substr($name, 0, 7)) {
1456 if ($params[$name]) {
1457 $values[$index] = CRM_Core_PseudoConstant
::country($params[$name]);
1460 $values[$index] = '';
1463 elseif ('county' == substr($name, 0, 6)) {
1464 if ($params[$name]) {
1465 $values[$index] = CRM_Core_PseudoConstant
::county($params[$name]);
1468 $values[$index] = '';
1471 elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
1472 $values[$index] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
1474 elseif (in_array($name, array(
1475 'addressee', 'email_greeting', 'postal_greeting'))) {
1476 $filterCondition = array('greeting_type' => $name);
1477 $greeting = CRM_Core_PseudoConstant
::greeting($filterCondition);
1478 $values[$index] = $greeting[$params[$name]];
1480 elseif ($name === 'preferred_communication_method') {
1481 $communicationFields = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1483 $pref = $params[$name];
1484 if (is_array($pref)) {
1485 foreach ($pref as $k => $v) {
1487 $compref[] = $communicationFields[$k];
1491 $values[$index] = implode(',', $compref);
1493 elseif ($name == 'contact_sub_type') {
1494 $values[$index] = implode(', ', $params[$name]);
1496 elseif ($name == 'group') {
1497 $groups = CRM_Contact_BAO_GroupContact
::getGroupList();
1499 foreach ($params[$name] as $gId => $dontCare) {
1501 $title[] = $groups[$gId];
1504 $values[$index] = implode(', ', $title);
1506 elseif ($name == 'tag') {
1507 $entityTags = $params[$name];
1508 $allTags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
1510 if (is_array($entityTags)) {
1511 foreach ($entityTags as $tagId => $dontCare) {
1512 $title[] = $allTags[$tagId];
1515 $values[$index] = implode(', ', $title);
1517 elseif ('participant_role_id' == $name OR
1518 'participant_role' == $name
1520 $roles = CRM_Event_PseudoConstant
::participantRole();
1521 $values[$index] = $roles[$params[$name]];
1523 elseif ('participant_status_id' == $name OR
1524 'participant_status' == $name
1526 $status = CRM_Event_PseudoConstant
::participantStatus();
1527 $values[$index] = $status[$params[$name]];
1529 elseif (substr($name, -11) == 'campaign_id') {
1530 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($params[$name]);
1531 $values[$index] = CRM_Utils_Array
::value($params[$name], $campaigns);
1533 elseif (strpos($name, '-') !== FALSE) {
1534 list($fieldName, $id) = CRM_Utils_System
::explode('-', $name, 2);
1535 $detailName = str_replace(' ', '_', $name);
1536 if (in_array($fieldName, array(
1537 'state_province', 'country', 'county'))) {
1538 $values[$index] = $params[$detailName];
1539 $idx = $detailName . '_id';
1540 $values[$index] = $params[$idx];
1542 elseif ($fieldName == 'im') {
1543 $providerName = NULL;
1544 if ($providerId = $detailName . '-provider_id') {
1545 $providerName = CRM_Utils_Array
::value($params[$providerId], $imProviders);
1547 if ($providerName) {
1548 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1551 $values[$index] = $params[$detailName];
1554 elseif ($fieldName == 'phone') {
1555 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1556 if (isset($params[$phoneExtField])) {
1557 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1560 $values[$index] = $params[$detailName];
1564 $values[$index] = $params[$detailName];
1568 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1569 if ($params[$name]) {
1570 $values[$index] = '[ x ]';
1574 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
1576 SELECT html_type, data_type
1577 FROM civicrm_custom_field
1580 $dao = CRM_Core_DAO
::executeQuery($query);
1582 $htmlType = $dao->html_type
;
1584 if ($htmlType == 'File') {
1585 $values[$index] = $params[$index];
1588 if ($dao->data_type
== 'Int' ||
1589 $dao->data_type
== 'Boolean'
1591 $v = $params[$name];
1592 if (!CRM_Utils_System
::isNull($v)) {
1593 $customVal = (int)$v;
1596 elseif ($dao->data_type
== 'Float') {
1597 $customVal = (float )($params[$name]);
1599 elseif ($dao->data_type
== 'Date') {
1600 //@todo note the currently we are using default date time formatting. Since you can select/set
1601 // different date and time format specific to custom field we should consider fixing this
1602 // sometime in the future
1603 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1604 CRM_Utils_Date
::processDate($params[$name]), $config->dateformatFull
);
1606 if (!empty($params[$name . '_time'])) {
1607 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1608 CRM_Utils_Date
::processDate($params[$name], $params[$name . '_time']),
1609 $config->dateformatDatetime
);
1614 $customVal = $params[$name];
1616 //take the custom field options
1617 $returnProperties = array($name => 1);
1618 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
1619 $options = &$query->_options
;
1621 $displayValue = CRM_Core_BAO_CustomField
::getDisplayValue($customVal, $cfID, $options);
1623 //Hack since we dont have function to check empty.
1624 //FIXME in 2.3 using crmIsEmptyArray()
1625 $customValue = TRUE;
1626 if (is_array($customVal) && is_array($displayValue)) {
1627 $customValue = array_diff($customVal, $displayValue);
1629 //use difference of arrays
1630 if (empty($customValue) ||
!$customValue) {
1631 $values[$index] = '';
1634 $values[$index] = $displayValue;
1638 elseif ($name == 'home_URL' &&
1639 !empty($params[$name])
1641 $url = CRM_Utils_System
::fixURL($params[$name]);
1642 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1644 elseif (in_array($name, array(
1645 'birth_date', 'deceased_date', 'participant_register_date'))) {
1646 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::format($params[$name]));
1649 $values[$index] = $params[$name];
1653 $profileFields[$name] = $field;
1659 * Function to build the array for Additional participant's information array of priamry and additional Ids
1661 * @param int $participantId id of Primary participant
1662 * @param array $values key/value event info
1663 * @param int $contactId contact id of Primary participant
1664 * @param boolean $isTest whether test or live transaction
1665 * @param boolean $isIdsArray to return an array of Ids
1667 * @param bool $skipCancel
1669 * @return array $customProfile array of Additional participant's info OR array of Ids.
1672 static function buildCustomProfile($participantId,
1676 $isIdsArray = FALSE,
1680 $customProfile = $additionalIDs = array();
1681 if (!$participantId) {
1682 CRM_Core_Error
::fatal(ts('Cannot find participant ID'));
1685 //set Ids of Primary Participant also.
1686 if ($isIdsArray && $contactId) {
1687 $additionalIDs[$participantId] = $contactId;
1690 //hack to skip cancelled participants, CRM-4320
1691 $where = "participant.registered_by_id={$participantId}";
1693 $cancelStatusId = 0;
1694 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1695 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1696 $where .= " AND participant.status_id != {$cancelStatusId}";
1699 SELECT participant.id, participant.contact_id
1700 FROM civicrm_participant participant
1703 $dao = CRM_Core_DAO
::executeQuery($query);
1704 while ($dao->fetch()) {
1705 $additionalIDs[$dao->id
] = $dao->contact_id
;
1708 //return if only array is required.
1709 if ($isIdsArray && $contactId) {
1710 return $additionalIDs;
1713 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values);
1714 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values);
1715 //else build array of Additional participant's information.
1716 if (count($additionalIDs)) {
1717 if ($preProfileID ||
$postProfileID) {
1718 $template = CRM_Core_Smarty
::singleton();
1720 $isCustomProfile = TRUE;
1722 $title = $groupTitles = array();
1723 foreach ($additionalIDs as $pId => $cId) {
1724 //get the params submitted by participant.
1725 $participantParams = CRM_Utils_Array
::value($pId, $values['params'], array());
1727 list($profilePre, $groupTitles) = self
::buildCustomDisplay($preProfileID,
1728 'additionalCustomPre',
1738 $profile = $profilePre;
1739 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1741 $title = $groupTitles;
1745 list($profilePost, $groupTitles) = self
::buildCustomDisplay($postProfileID,
1746 'additionalCustomPost',
1756 if (isset($profilePre)) {
1757 $profile = array_merge($profilePre, $profilePost);
1759 $title = array_merge($title, $groupTitles);
1763 $profile = $profilePost;
1765 $title = $groupTitles;
1769 $profiles[] = $profile;
1772 $customProfile['title'] = $title;
1773 $customProfile['profile'] = $profiles;
1777 return $customProfile;
1780 /* Function to retrieve all events those having location block set.
1782 * @return array $events array of all events.
1784 static function getLocationEvents() {
1788 SELECT CONCAT_WS(' :: ' , ca.name, ca.street_address, ca.city, sp.name) title, ce.loc_block_id
1789 FROM civicrm_event ce
1790 INNER JOIN civicrm_loc_block lb ON ce.loc_block_id = lb.id
1791 INNER JOIN civicrm_address ca ON lb.address_id = ca.id
1792 LEFT JOIN civicrm_state_province sp ON ca.state_province_id = sp.id
1793 ORDER BY sp.name, ca.city, ca.street_address ASC
1796 $dao = CRM_Core_DAO
::executeQuery($query);
1797 while ($dao->fetch()) {
1798 $events[$dao->loc_block_id
] = $dao->title
;
1804 static function countEventsUsingLocBlockId($locBlockId) {
1809 $locBlockId = CRM_Utils_Type
::escape($locBlockId, 'Integer');
1812 SELECT count(*) FROM civicrm_event ce
1813 WHERE ce.loc_block_id = $locBlockId";
1815 return CRM_Core_DAO
::singleValueQuery($query);
1819 * Check if event registration is valid according to permissions AND Dates
1821 * @param array $values
1822 * @param integer $eventID
1825 static function validRegistrationRequest($values, $eventID) {
1826 // check that the user has permission to register for this event
1827 $hasPermission = CRM_Core_Permission
::event(CRM_Core_Permission
::EDIT
,
1828 $eventID, 'register for events'
1831 return $hasPermission && self
::validRegistrationDate($values);
1834 static function validRegistrationDate(&$values) {
1835 // make sure that we are between registration start date and registration end date
1836 $startDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_start_date', $values));
1837 $endDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_end_date', $values));
1838 $eventEnd = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('end_date', $values));
1841 if ($startDate && $startDate >= $now) {
1844 if ($endDate && $endDate < $now) {
1847 if ($eventEnd && $eventEnd < $now) {
1854 /* Function to Show - Hide the Registration Link.
1856 * @param array $values key/value event info
1857 * @return boolean true if allow registration otherwise false
1860 static function showHideRegistrationLink($values) {
1862 $session = CRM_Core_Session
::singleton();
1863 $contactID = $session->get('userID');
1864 $alreadyRegistered = FALSE;
1867 $params = array('contact_id' => $contactID);
1869 if ($eventId = CRM_Utils_Array
::value('id', $values['event'])) {
1870 $params['event_id'] = $eventId;
1872 if ($roleId = CRM_Utils_Array
::value('default_role_id', $values['event'])) {
1873 $params['role_id'] = $roleId;
1875 $alreadyRegistered = self
::checkRegistration($params);
1878 if (!empty($values['event']['allow_same_participant_emails']) ||
1886 /* Function to check if given contact is already registered.
1888 * @param array $params key/value participant info
1889 * @return boolean $alreadyRegistered true/false
1892 static function checkRegistration($params) {
1893 $alreadyRegistered = FALSE;
1894 if (empty($params['contact_id'])) {
1895 return $alreadyRegistered;
1898 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
1900 $participant = new CRM_Event_DAO_Participant();
1901 $participant->copyValues($params);
1903 $participant->is_test
= CRM_Utils_Array
::value('is_test', $params, 0);
1904 $participant->selectAdd();
1905 $participant->selectAdd('status_id');
1906 if ($participant->find(TRUE) && array_key_exists($participant->status_id
, $statusTypes)) {
1907 $alreadyRegistered = TRUE;
1910 return $alreadyRegistered;
1914 * make sure that the user has permission to access this event
1916 * @param null $eventId
1919 * @internal param int $id the id of the event
1920 * @internal param int $name the name or title of the event
1922 * @return string the permission that the user has (or null)
1926 static function checkPermission($eventId = NULL, $type = CRM_Core_Permission
::VIEW
) {
1927 static $permissions = NULL;
1929 if (empty($permissions)) {
1930 $allEvents = CRM_Event_PseudoConstant
::event(NULL, TRUE);
1931 $createdEvents = array();
1933 $session = CRM_Core_Session
::singleton();
1934 if ($userID = $session->get('userID')) {
1935 $createdEvents = array_keys(CRM_Event_PseudoConstant
::event(NULL, TRUE, "created_id={$userID}"));
1938 // Note: for a multisite setup, a user with edit all events, can edit all events
1939 // including those from other sites
1940 if (CRM_Core_Permission
::check('edit all events')) {
1941 $permissions[CRM_Core_Permission
::EDIT
] = array_keys($allEvents);
1944 $permissions[CRM_Core_Permission
::EDIT
] = &CRM_ACL_API
::group(CRM_Core_Permission
::EDIT
, NULL, 'civicrm_event', $allEvents, $createdEvents);
1947 if (CRM_Core_Permission
::check('edit all events')) {
1948 $permissions[CRM_Core_Permission
::VIEW
] = array_keys($allEvents);
1951 if (CRM_Core_Permission
::check('access CiviEvent') &&
1952 CRM_Core_Permission
::check('view event participants')
1954 // use case: allow "view all events" but NOT "edit all events"
1955 // so for a normal site allow users with these two permissions to view all events AND
1956 // at the same time also allow any hook to override if needed.
1957 $createdEvents = array_keys($allEvents);
1959 $permissions[CRM_Core_Permission
::VIEW
] = &CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_event', $allEvents, $createdEvents);
1962 $permissions[CRM_Core_Permission
::DELETE
] = array();
1963 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
1964 // Note: we want to restrict the scope of delete permission to
1965 // events that are editable/viewable (usecase multisite).
1966 // We can remove array_intersect once we have ACL support for delete functionality.
1967 $permissions[CRM_Core_Permission
::DELETE
] = array_intersect($permissions[CRM_Core_Permission
::EDIT
],
1968 $permissions[CRM_Core_Permission
::VIEW
]
1974 return in_array($eventId, $permissions[$type]) ?
TRUE : FALSE;
1977 return $permissions;
1981 * Build From Email as the combination of all the email ids of the logged in user,
1982 * the domain email id and the email id configured for the event
1984 * @param int $eventId the id of the event
1986 * @return array an array of email ids
1990 static function getFromEmailIds($eventId = NULL) {
1991 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email
::getFromEmail();
1994 // add the email id configured for the event
1995 $params = array('id' => $eventId);
1996 $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
1997 $eventEmail = array();
1999 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
2000 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
2001 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
2003 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
2004 $fromEmailId = array('cc' => CRM_Utils_Array
::value('cc_confirm', $eventEmail),
2005 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventEmail),
2007 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2011 return $fromEmailValues;
2015 * Function to calculate event total seats occupied.
2017 * @param int $eventId event id.
2018 * @param sting $extraWhereClause extra filter on participants.
2020 * @return int event total seats w/ given criteria.
2024 static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
2025 if (empty($eventId)) {
2029 $extraWhereClause = trim($extraWhereClause);
2030 if (!empty($extraWhereClause)) {
2031 $extraWhereClause = " AND ( {$extraWhereClause} )";
2034 //event seats calculation :
2035 //1. consider event seat as a single when participant does not have line item.
2036 //2. consider event seat as a single when participant has line items but does not
2037 // have count for corresponding price field value ( ie price field value does not carry any seat )
2038 //3. consider event seat as a sum of all seats from line items in case price field value carries count.
2041 SELECT IF ( SUM( value.count*lineItem.qty ),
2042 SUM( value.count*lineItem.qty ) +
2043 COUNT( DISTINCT participant.id ) -
2044 COUNT( DISTINCT IF ( value.count, participant.id, NULL ) ),
2045 COUNT( DISTINCT participant.id ) )
2046 FROM civicrm_participant participant
2047 INNER JOIN civicrm_contact contact ON ( contact.id = participant.contact_id AND contact.is_deleted = 0 )
2048 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
2049 LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id
2050 AND lineItem.entity_table = 'civicrm_participant' )
2051 LEFT JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id AND value.count )
2052 WHERE ( participant.event_id = %1 )
2053 AND participant.is_test = 0
2055 GROUP BY participant.event_id";
2057 return (int)CRM_Core_DAO
::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
2061 * Retrieve event template default values to be set
2062 * as default values for current new event.
2064 * @params int $templateId event template id.
2066 * @return $defaults an array of custom data defaults.
2068 static function getTemplateDefaultValues($templateId) {
2069 $defaults = array();
2074 $templateParams = array('id' => $templateId);
2075 CRM_Event_BAO_Event
::retrieve($templateParams, $defaults);
2076 $fieldsToExclude = array(
2079 'default_discount_fee_id',
2085 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2089 static function get_sub_events($event_id) {
2090 $params = array('parent_event_id' => $event_id);
2091 $defaults = array();
2092 return CRM_Event_BAO_Event
::retrieve($params, $defaults);
2096 * Update the Campaign Id of all the participants of the given event
2098 * @params int $eventID event id.
2099 * @params int $eventCampaignID campaign id of that event
2102 static function updateParticipantCampaignID($eventID, $eventCampaignID) {
2104 $params[1] = array($eventID, 'Integer');
2106 if(empty($eventCampaignID)) {
2107 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2110 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2111 $params[2] = array($eventCampaignID, 'Integer');
2113 CRM_Core_DAO
::executeQuery($query, $params);
2117 * Get options for a given field.
2118 * @see CRM_Core_DAO::buildOptions
2120 * @param String $fieldName
2121 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
2122 * @param Array $props: whatever is known about this dao object
2124 * @return array|bool
2126 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2128 // Special logic for fields whose options depend on context or properties
2129 switch ($fieldName) {
2130 case 'financial_type_id':
2131 // Fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
2132 return CRM_Financial_BAO_FinancialType
::getIncomeFinancialType();
2135 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);