3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
33 class CRM_Event_BAO_Event
extends CRM_Event_DAO_Event
{
38 public function __construct() {
39 parent
::__construct();
43 * Fetch object based on array of properties.
45 * @param array $params
46 * (reference ) an assoc array of name/value pairs.
47 * @param array $defaults
48 * (reference ) an assoc array to hold the flattened values.
50 * @return CRM_Event_DAO_Event
52 public static function retrieve(&$params, &$defaults) {
53 $event = new CRM_Event_DAO_Event();
54 $event->copyValues($params);
55 if ($event->find(TRUE)) {
56 CRM_Core_DAO
::storeValues($event, $defaults);
63 * Update the is_active flag in the db.
66 * Id of the database record.
67 * @param bool $is_active
68 * Value we want to set the is_active field.
71 * DAO object on success, null otherwise
73 public static function setIsActive($id, $is_active) {
74 return CRM_Core_DAO
::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
80 * @param array $params
81 * Reference array contains the values submitted by the form.
83 * @return CRM_Event_DAO_Event
85 public static function add(&$params) {
86 CRM_Utils_System
::flushCache();
87 $financialTypeId = NULL;
88 if (!empty($params['id'])) {
89 CRM_Utils_Hook
::pre('edit', 'Event', $params['id'], $params);
90 if (empty($params['skipFinancialType'])) {
91 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $params['id'], 'financial_type_id');
95 CRM_Utils_Hook
::pre('create', 'Event', NULL, $params);
98 $event = new CRM_Event_DAO_Event();
100 $event->copyValues($params);
101 $result = $event->save();
103 if (!empty($params['id'])) {
104 CRM_Utils_Hook
::post('edit', 'Event', $event->id
, $event);
107 CRM_Utils_Hook
::post('create', 'Event', $event->id
, $event);
109 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
110 CRM_Price_BAO_PriceFieldValue
::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
118 * @param array $params
119 * Reference array contains the values submitted by the form.
123 public static function create(&$params) {
124 $transaction = new CRM_Core_Transaction();
125 if (empty($params['is_template'])) {
126 $params['is_template'] = 0;
128 // check if new event, if so set the created_id (if not set)
129 // and always set created_date to now
130 if (empty($params['id'])) {
131 if (empty($params['created_id'])) {
132 $session = CRM_Core_Session
::singleton();
133 $params['created_id'] = $session->get('userID');
135 $params['created_date'] = date('YmdHis');
138 $event = self
::add($params);
139 CRM_Price_BAO_PriceSet
::setPriceSets($params, $event, 'event');
140 if (is_a($event, 'CRM_Core_Error')) {
141 CRM_Core_DAO
::transaction('ROLLBACK');
145 $session = CRM_Core_Session
::singleton();
146 $contactId = $session->get('userID');
148 $contactId = CRM_Utils_Array
::value('contact_id', $params);
151 // Log the information on successful add/edit of Event
153 'entity_table' => 'civicrm_event',
154 'entity_id' => $event->id
,
155 'modified_id' => $contactId,
156 'modified_date' => date('Ymd'),
159 CRM_Core_BAO_Log
::add($logParams);
161 if (!empty($params['custom']) &&
162 is_array($params['custom'])
164 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_event', $event->id
);
167 $transaction->commit();
180 public static function del($id) {
185 CRM_Utils_Hook
::pre('delete', 'Event', $id, CRM_Core_DAO
::$_nullArray);
187 $extends = array('event');
188 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
189 foreach ($groupTree as $values) {
190 $query = "DELETE FROM " . $values['table_name'] . " WHERE entity_id = " . $id;
193 1 => array($values['table_name'], 'string'),
194 2 => array($id, 'integer'),
197 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
200 // price set cleanup, CRM-5527
201 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_event', $id);
203 $event = new CRM_Event_DAO_Event();
206 if ($event->find(TRUE)) {
207 $locBlockId = $event->loc_block_id
;
208 $result = $event->delete();
210 if (!is_null($locBlockId)) {
211 self
::deleteEventLocBlock($locBlockId, $id);
214 CRM_Utils_Hook
::post('delete', 'Event', $id, $event);
222 * Delete the location block associated with an event.
224 * Function checks that it is not being used by any other event.
226 * @param int $locBlockId
227 * Location block id to be deleted.
228 * @param int $eventId
229 * Event with which loc block is associated.
231 public static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
232 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
235 $query .= " AND ce.id != $eventId;";
238 $locCount = CRM_Core_DAO
::singleValueQuery($query);
240 if ($locCount == 0) {
241 CRM_Core_BAO_Location
::deleteLocBlock($locBlockId);
246 * Get current/future Events.
249 * 0 returns current and future events.
250 * 1 if events all are required
251 * 2 returns events since 3 months ago
252 * @param int|array $id single int event id or array of multiple event ids to return
253 * @param bool $isActive
254 * true if you need only active events.
255 * @param bool $checkPermission
256 * true if you need to check permission else false.
257 * @param bool $titleOnly
258 * true if you need only title not appended with start date
262 public static function getEvents(
266 $checkPermission = TRUE,
270 SELECT `id`, `title`, `start_date`
272 WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
275 $op = is_array($id) ?
'IN' : '=';
276 $where = CRM_Contact_BAO_Query
::buildClause('id', $op, $id);
277 $query .= " AND {$where}";
280 // find only events ending in the future
281 $endDate = date('YmdHis');
283 AND ( `end_date` >= {$endDate} OR
285 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
290 // find only events starting in the last 3 months
291 $startDate = date('YmdHis', strtotime('3 months ago'));
292 $query .= " AND ( `start_date` >= {$startDate} OR start_date IS NULL )";
295 $query .= " AND civicrm_event.is_active = 1";
298 $query .= " ORDER BY title asc";
301 $dao = CRM_Core_DAO
::executeQuery($query);
302 while ($dao->fetch()) {
303 if ((!$checkPermission ||
304 CRM_Event_BAO_Event
::checkPermission($dao->id
)
308 $events[$dao->id
] = $dao->title
;
310 $events[$dao->id
] .= ' - ' . CRM_Utils_Date
::customFormat($dao->start_date
);
319 * Get events Summary.
322 * Array of event summary values
324 public static function getEventSummary() {
325 $eventSummary = $eventIds = array();
326 $config = CRM_Core_Config
::singleton();
328 // get permission and include them here
329 // does not scale, but rearranging code for now
330 // FIXME in a future release
331 $permissions = CRM_Event_BAO_Event
::checkPermission();
333 if (empty($permissions[CRM_Core_Permission
::VIEW
])) {
334 $eventSummary['total_events'] = 0;
335 return $eventSummary;
338 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission
::VIEW
])) . " ) ";
341 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
343 SELECT count(id) as total_events
345 WHERE civicrm_event.is_active = 1 AND
346 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
347 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
350 $dao = CRM_Core_DAO
::executeQuery($query);
353 $eventSummary['total_events'] = $dao->total_events
;
356 if (empty($eventSummary) ||
357 $dao->total_events
== 0
359 return $eventSummary;
362 //get the participant status type values.
363 $cpstObject = new CRM_Event_DAO_ParticipantStatusType();
364 $cpst = $cpstObject->getTableName();
365 $query = "SELECT id, name, label, class FROM $cpst";
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
]['label'] = $status->label
;
372 $statusValues[$status->id
]['class'] = $status->class;
375 // Get the Id of Option Group for Event Types
376 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
377 $optionGroupDAO->name
= 'event_type';
378 $optionGroupId = NULL;
379 if ($optionGroupDAO->find(TRUE)) {
380 $optionGroupId = $optionGroupDAO->id
;
382 // Get the event summary display preferences
383 $show_max_events = Civi
::settings()->get('show_events');
384 // show all events if show_events is set to a negative value
385 if ($show_max_events >= 0) {
386 $event_summary_limit = "LIMIT 0, $show_max_events";
389 $event_summary_limit = "";
393 SELECT civicrm_event.id as id, civicrm_event.title as event_title, civicrm_event.is_public as is_public,
394 civicrm_event.max_participants as max_participants, civicrm_event.start_date as start_date,
395 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,
396 civicrm_event.slot_label_id,
397 civicrm_event.summary as summary,
398 civicrm_pcp_block.id as is_pcp_enabled,
399 civicrm_recurring_entity.parent_id as is_repeating_event
401 LEFT JOIN civicrm_option_value ON (
402 civicrm_event.event_type_id = civicrm_option_value.value AND
403 civicrm_option_value.option_group_id = %1 )
404 LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_event.id AND civicrm_tell_friend.entity_table = 'civicrm_event' )
405 LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_event.id AND civicrm_pcp_block.entity_table = 'civicrm_event')
406 LEFT JOIN civicrm_recurring_entity ON ( civicrm_event.id = civicrm_recurring_entity.entity_id AND civicrm_recurring_entity.entity_table = 'civicrm_event' )
407 WHERE civicrm_event.is_active = 1 AND
408 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
409 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
411 GROUP BY civicrm_event.id
412 ORDER BY civicrm_event.start_date ASC
415 $eventParticipant = array();
419 'eventTitle' => 'event_title',
420 'isPublic' => 'is_public',
421 'maxParticipants' => 'max_participants',
422 'startDate' => 'start_date',
423 'endDate' => 'end_date',
424 'eventType' => 'event_type',
426 'participants' => 'participants',
427 'notCountedDueToRole' => 'notCountedDueToRole',
428 'notCountedDueToStatus' => 'notCountedDueToStatus',
429 'notCountedParticipants' => 'notCountedParticipants',
432 $params = array(1 => array($optionGroupId, 'Integer'));
433 $mapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings(array(
434 'id' => CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
,
436 $dao = CRM_Core_DAO
::executeQuery($query, $params);
437 while ($dao->fetch()) {
438 foreach ($properties as $property => $name) {
448 $eventSummary['events'][$dao->id
][$property] = $set;
452 if ($dao->$name && $config->mapAPIKey
) {
455 $params = array('entity_id' => $dao->id
, 'entity_table' => 'civicrm_event');
456 $values['location'] = CRM_Core_BAO_Location
::getValues($params, TRUE);
457 if (is_numeric(CRM_Utils_Array
::value('geo_code_1', $values['location']['address'][1])) ||
459 !empty($values['location']['address'][1]['city']) &&
460 !empty($values['location']['address'][1]['state_province_id'])
463 $set = CRM_Utils_System
::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
467 $eventSummary['events'][$dao->id
][$property] = $set;
468 if (is_array($permissions[CRM_Core_Permission
::EDIT
])
469 && in_array($dao->id
, $permissions[CRM_Core_Permission
::EDIT
])) {
470 $eventSummary['events'][$dao->id
]['configure'] = CRM_Utils_System
::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
476 $eventSummary['events'][$dao->id
][$property] = CRM_Utils_Date
::customFormat($dao->$name,
482 case 'notCountedDueToRole':
483 case 'notCountedDueToStatus':
484 case 'notCountedParticipants':
487 if ($name == 'participants') {
488 $propertyCnt = self
::getParticipantCount($dao->id
);
490 $set = CRM_Utils_System
::url('civicrm/event/search',
491 "reset=1&force=1&event=$dao->id&status=true&role=true"
495 elseif ($name == 'notCountedParticipants') {
496 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, TRUE, FALSE);
498 // FIXME : selector fail to search w/ OR operator.
499 // $set = CRM_Utils_System::url( 'civicrm/event/search',
500 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
503 elseif ($name == 'notCountedDueToStatus') {
504 $propertyCnt = self
::getParticipantCount($dao->id
, TRUE, FALSE, FALSE, FALSE);
506 $set = CRM_Utils_System
::url('civicrm/event/search',
507 "reset=1&force=1&event=$dao->id&status=false"
512 $propertyCnt = self
::getParticipantCount($dao->id
, FALSE, FALSE, TRUE, FALSE);
514 $set = CRM_Utils_System
::url('civicrm/event/search',
515 "reset=1&force=1&event=$dao->id&role=false"
520 $eventSummary['events'][$dao->id
][$property] = $propertyCnt;
521 $eventSummary['events'][$dao->id
][$name . '_url'] = $set;
525 $eventSummary['events'][$dao->id
][$property] = $dao->$name;
530 // prepare the area for per-status participant counts
531 $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
532 $eventSummary['events'][$dao->id
]['statuses'] = array_fill_keys($statusClasses, array());
534 $eventSummary['events'][$dao->id
]['friend'] = $dao->is_friend_active
;
535 $eventSummary['events'][$dao->id
]['is_monetary'] = $dao->is_monetary
;
536 $eventSummary['events'][$dao->id
]['is_online_registration'] = $dao->is_online_registration
;
537 $eventSummary['events'][$dao->id
]['is_show_location'] = $dao->is_show_location
;
538 $eventSummary['events'][$dao->id
]['is_subevent'] = $dao->slot_label_id
;
539 $eventSummary['events'][$dao->id
]['is_pcp_enabled'] = $dao->is_pcp_enabled
;
540 $eventSummary['events'][$dao->id
]['reminder'] = CRM_Core_BAO_ActionSchedule
::isConfigured($dao->id
, $mapping->getId());
541 $eventSummary['events'][$dao->id
]['is_repeating_event'] = $dao->is_repeating_event
;
543 $statusTypes = CRM_Event_PseudoConstant
::participantStatus();
544 foreach ($statusValues as $statusId => $statusValue) {
545 if (!array_key_exists($statusId, $statusTypes)) {
548 $class = $statusValue['class'];
549 $statusCount = self
::eventTotalSeats($dao->id
, "( participant.status_id = {$statusId} )");
551 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
553 'url' => CRM_Utils_System
::url('civicrm/event/search', $urlString),
554 'name' => $statusValue['name'],
555 'label' => $statusValue['label'],
556 'count' => $statusCount,
558 $eventSummary['events'][$dao->id
]['statuses'][$class][] = $statusInfo;
563 $countedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
564 $nonCountedRoles = CRM_Event_PseudoConstant
::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
565 $countedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
566 $nonCountedStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
568 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
569 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
571 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
572 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
573 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
574 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
576 return $eventSummary;
580 * Get participant count.
582 * @param int $eventId
583 * @param bool $considerStatus consider status for participant count.
584 * Consider status for participant count.
585 * @param bool $status counted participant.
586 * Consider counted participant.
587 * @param bool $considerRole consider role for participant count.
588 * Consider role for participant count.
589 * @param bool $role consider counted( is filter role) participant.
590 * Consider counted( is filter role) participant.
593 * array with count of participants for each event based on status/role
595 public static function getParticipantCount(
597 $considerStatus = TRUE,
599 $considerRole = TRUE,
603 // consider both role and status for counted participants, CRM-4924.
605 // not counted participant.
606 if ($considerStatus && $considerRole && !$status && !$role) {
610 if ($considerStatus) {
611 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
612 $statusClause = 'NOT IN';
614 $statusClause = 'IN';
616 $status = implode(',', array_keys($statusTypes));
617 if (empty($status)) {
620 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
624 $roleTypes = CRM_Event_PseudoConstant
::participantRole(NULL, 'filter = 1');
625 $roleClause = 'NOT IN';
630 if (!empty($roleTypes)) {
631 $escapedRoles = array();
632 foreach (array_keys($roleTypes) as $roleType) {
633 $escapedRoles[] = CRM_Utils_Type
::escape($roleType, 'String');
636 $clause[] = "participant.role_id {$roleClause} ( '" . implode("', '", $escapedRoles) . "' ) ";
641 if (!empty($clause)) {
642 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
645 return self
::eventTotalSeats($eventId, $sqlClause);
649 * Get the information to map a event.
652 * For which we want map info.
654 * @return null|string
657 public static function &getMapInfo(&$id) {
661 civicrm_event.id AS event_id,
662 civicrm_event.title AS display_name,
663 civicrm_address.street_address AS street_address,
664 civicrm_address.city AS city,
665 civicrm_address.postal_code AS postal_code,
666 civicrm_address.postal_code_suffix AS postal_code_suffix,
667 civicrm_address.geo_code_1 AS latitude,
668 civicrm_address.geo_code_2 AS longitude,
669 civicrm_state_province.abbreviation AS state,
670 civicrm_country.name AS country,
671 civicrm_location_type.name AS location_type
674 LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )
675 LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )
676 LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )
677 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
678 LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )
679 WHERE civicrm_address.geo_code_1 IS NOT NULL
680 AND civicrm_address.geo_code_2 IS NOT NULL
681 AND civicrm_event.id = " . CRM_Utils_Type
::escape($id, 'Integer');
683 $dao = new CRM_Core_DAO();
686 $locations = array();
688 $config = CRM_Core_Config
::singleton();
690 while ($dao->fetch()) {
693 $location['displayName'] = addslashes($dao->display_name
);
694 $location['lat'] = $dao->latitude
;
695 $location['marker_class'] = 'Event';
696 $location['lng'] = $dao->longitude
;
698 $params = array('entity_id' => $id, 'entity_table' => 'civicrm_event');
699 $addressValues = CRM_Core_BAO_Location
::getValues($params, TRUE);
700 $location['address'] = str_replace(array(
703 ), '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
705 $location['url'] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
);
706 $location['location_type'] = $dao->location_type
;
707 $eventImage = '<img src="' . $config->resourceBase
. 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
708 $location['image'] = $eventImage;
709 $location['displayAddress'] = str_replace('<br />', ', ', $location['address']);
710 $locations[] = $location;
716 * Get the complete information for one or more events.
719 * Get events with start date >= this date.
720 * @param int $type Get events on the a specific event type (by event_type_id).
721 * Get events on the a specific event type (by event_type_id).
722 * @param int $eventId Return a single event - by event id.
723 * Return a single event - by event id.
725 * Also get events with end date >= this date.
726 * @param bool $onlyPublic Include public events only, default TRUE.
727 * Include public events only, default TRUE.
730 * array of all the events that are searched
732 public static function &getCompleteInfo(
739 $publicCondition = NULL;
741 $publicCondition = " AND civicrm_event.is_public = 1";
745 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
747 // get events with start_date >= requested start
748 $startDate = CRM_Utils_Type
::escape($start, 'Date');
749 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
753 // also get events with end_date <= requested end
754 $endDate = CRM_Utils_Type
::escape($end, 'Date');
755 $dateCondition .= " AND ( civicrm_event.end_date <= '{$endDate}' ) ";
758 // CRM-9421 and CRM-8620 Default mode for ical/rss feeds. No start or end filter passed.
759 // Need to exclude old events with only start date
760 // and not exclude events in progress (start <= today and end >= today). DGG
761 if (empty($start) && empty($end)) {
762 // get events with end date >= today, not sure of this logic
763 // but keeping this for backward compatibility as per issue CRM-5133
764 $today = date("Y-m-d G:i:s");
765 $dateCondition .= " AND ( civicrm_event.end_date >= '{$today}' OR civicrm_event.start_date >= '{$today}' ) ";
769 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
772 // Get the Id of Option Group for Event Types
773 $optionGroupDAO = new CRM_Core_DAO_OptionGroup();
774 $optionGroupDAO->name
= 'event_type';
775 $optionGroupId = NULL;
776 if ($optionGroupDAO->find(TRUE)) {
777 $optionGroupId = $optionGroupDAO->id
;
782 civicrm_event.id as event_id,
783 civicrm_email.email as email,
784 civicrm_event.title as title,
785 civicrm_event.summary as summary,
786 civicrm_event.start_date as start,
787 civicrm_event.end_date as end,
788 civicrm_event.description as description,
789 civicrm_event.is_show_location as is_show_location,
790 civicrm_event.is_online_registration as is_online_registration,
791 civicrm_event.registration_link_text as registration_link_text,
792 civicrm_event.registration_start_date as registration_start_date,
793 civicrm_event.registration_end_date as registration_end_date,
794 civicrm_option_value.label as event_type,
795 civicrm_address.name as address_name,
796 civicrm_address.street_address as street_address,
797 civicrm_address.supplemental_address_1 as supplemental_address_1,
798 civicrm_address.supplemental_address_2 as supplemental_address_2,
799 civicrm_address.city as city,
800 civicrm_address.postal_code as postal_code,
801 civicrm_address.postal_code_suffix as postal_code_suffix,
802 civicrm_state_province.abbreviation as state,
803 civicrm_country.name AS country
805 LEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id
806 LEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id
807 LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
808 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
809 LEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id
810 LEFT JOIN civicrm_option_value ON (
811 civicrm_event.event_type_id = civicrm_option_value.value AND
812 civicrm_option_value.option_group_id = %1 )
813 WHERE civicrm_event.is_active = 1
814 AND (is_template = 0 OR is_template IS NULL)
818 if (isset($typeCondition)) {
819 $query .= $typeCondition;
822 if (isset($eventId)) {
823 $query .= " AND civicrm_event.id =$eventId ";
825 $query .= " ORDER BY civicrm_event.start_date ASC";
827 $params = array(1 => array($optionGroupId, 'Integer'));
828 $dao = CRM_Core_DAO
::executeQuery($query, $params);
830 $config = CRM_Core_Config
::singleton();
832 $baseURL = parse_url($config->userFrameworkBaseURL
);
833 $url = "@" . $baseURL['host'];
834 if (!empty($baseURL['path'])) {
835 $url .= substr($baseURL['path'], 0, -1);
838 // check 'view event info' permission
839 //@todo - per CRM-14626 we have resolved that 'view event info' means 'view ALL event info'
840 // and passing in the specific permission here will short-circuit the evaluation of permission to
841 // see specific events (doesn't seem relevant to this call
842 // however, since this function is accessed only by a convoluted call from a joomla block function
843 // it seems safer not to touch here. Suggestion is that CRM_Core_Permission::check(array or relevant permissions) would
844 // be clearer & safer here
845 $permissions = CRM_Core_Permission
::event(CRM_Core_Permission
::VIEW
);
847 // check if we're in shopping cart mode for events
848 $enable_cart = Civi
::settings()->get('enable_cart');
851 while ($dao->fetch()) {
852 if (!empty($permissions) && in_array($dao->event_id
, $permissions)) {
854 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL
) . $url;
856 $info['title'] = $dao->title
;
857 $info['event_id'] = $dao->event_id
;
858 $info['summary'] = $dao->summary
;
859 $info['description'] = $dao->description
;
860 $info['start_date'] = $dao->start
;
861 $info['end_date'] = $dao->end
;
862 $info['contact_email'] = $dao->email
;
863 $info['event_type'] = $dao->event_type
;
864 $info['is_show_location'] = $dao->is_show_location
;
865 $info['is_online_registration'] = $dao->is_online_registration
;
866 $info['registration_link_text'] = $dao->registration_link_text
;
867 $info['registration_start_date'] = $dao->registration_start_date
;
868 $info['registration_end_date'] = $dao->registration_end_date
;
873 'address_name' => $dao->address_name
,
874 'street_address' => $dao->street_address
,
875 'supplemental_address_1' => $dao->supplemental_address_1
,
876 'supplemental_address_2' => $dao->supplemental_address_2
,
877 'city' => $dao->city
,
878 'state_province' => $dao->state
,
879 'postal_code' => $dao->postal_code
,
880 'postal_code_suffix' => $dao->postal_code_suffix
,
881 'country' => $dao->country
,
885 CRM_Utils_String
::append($address, ', ',
886 CRM_Utils_Address
::format($addrFields)
888 $info['location'] = $address;
889 $info['url'] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
892 $reg = CRM_Event_Cart_BAO_EventInCart
::get_registration_link($dao->event_id
);
893 $info['registration_link'] = CRM_Utils_System
::url($reg['path'], $reg['query'], TRUE);
894 $info['registration_link_text'] = $reg['label'];
905 * Make a copy of a Event.
907 * Include all the fields in the event Wizard.
910 * The event id to copy.
911 * boolean $afterCreate call to copy after the create function
912 * @param null $newEvent
913 * @param bool $afterCreate
915 * @return CRM_Event_DAO_Event
917 public static function copy($id, $newEvent = NULL, $afterCreate = FALSE) {
919 $eventValues = array();
921 //get the require event values.
922 $eventParams = array('id' => $id);
923 $returnProperties = array(
927 'default_discount_fee_id',
931 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
933 // since the location is sharable, lets use the same loc_block_id.
934 $locBlockId = CRM_Utils_Array
::value('loc_block_id', $eventValues);
936 $fieldsFix = ($afterCreate) ?
array() : array('prefix' => array('title' => ts('Copy of') . ' '));
937 if (empty($eventValues['is_show_location'])) {
938 $fieldsFix['prefix']['is_show_location'] = 0;
941 if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
942 $copyEvent = $newEvent;
945 if (!isset($copyEvent)) {
946 $copyEvent = &CRM_Core_DAO
::copyGeneric('CRM_Event_DAO_Event',
950 ($locBlockId) ?
$locBlockId : NULL,
955 CRM_Price_BAO_PriceSet
::copyPriceSet('civicrm_event', $id, $copyEvent->id
);
956 $copyUF = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_UFJoin',
959 'entity_table' => 'civicrm_event',
961 array('entity_id' => $copyEvent->id
)
964 $copyTellFriend = &CRM_Core_DAO
::copyGeneric('CRM_Friend_DAO_Friend',
967 'entity_table' => 'civicrm_event',
969 array('entity_id' => $copyEvent->id
)
972 $copyPCP = &CRM_Core_DAO
::copyGeneric('CRM_PCP_DAO_PCPBlock',
975 'entity_table' => 'civicrm_event',
977 array('entity_id' => $copyEvent->id
),
978 array('replace' => array('target_entity_id' => $copyEvent->id
))
981 $oldMapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings(array(
982 'id' => ($eventValues['is_template'] ? CRM_Event_ActionMapping
::EVENT_TPL_MAPPING_ID
: CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
),
984 $copyMapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings(array(
985 'id' => ($copyEvent->is_template
== 1 ? CRM_Event_ActionMapping
::EVENT_TPL_MAPPING_ID
: CRM_Event_ActionMapping
::EVENT_NAME_MAPPING_ID
),
987 $copyReminder = &CRM_Core_DAO
::copyGeneric('CRM_Core_DAO_ActionSchedule',
988 array('entity_value' => $id, 'mapping_id' => $oldMapping->getId()),
989 array('entity_value' => $copyEvent->id
, 'mapping_id' => $copyMapping->getId())
994 $extends = array('event');
995 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
997 foreach ($groupTree as $groupID => $group) {
998 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
999 foreach ($group['fields'] as $fieldID => $field) {
1000 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1004 foreach ($table as $tableName => $tableColumns) {
1005 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
1006 $tableColumns[0] = $copyEvent->id
;
1007 $select = 'SELECT ' . implode(', ', $tableColumns);
1008 $from = ' FROM ' . $tableName;
1009 $where = " WHERE {$tableName}.entity_id = {$id}";
1010 $query = $insert . $select . $from . $where;
1011 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1017 CRM_Utils_System
::flushCache();
1018 if (!$afterCreate) {
1019 CRM_Utils_Hook
::copy('Event', $copyEvent);
1025 * This is sometimes called in a loop (during event search).
1027 * We cache the values to prevent repeated calls to the db.
1033 public static function isMonetary($id) {
1034 static $isMonetary = array();
1035 if (!array_key_exists($id, $isMonetary)) {
1036 $isMonetary[$id] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event',
1041 return $isMonetary[$id];
1045 * This is sometimes called in a loop (during event search).
1047 * We cache the values to prevent repeated calls to the db.
1053 public static function usesPriceSet($id) {
1054 static $usesPriceSet = array();
1055 if (!array_key_exists($id, $usesPriceSet)) {
1056 $usesPriceSet[$id] = CRM_Price_BAO_PriceSet
::getFor('civicrm_event', $id);
1058 return $usesPriceSet[$id];
1064 * @param int $contactID
1065 * @param array $values
1066 * @param int $participantId
1067 * @param bool $isTest
1068 * @param bool $returnMessageText
1070 public static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
1072 $template = CRM_Core_Smarty
::singleton();
1074 'custom_pre_id' => $values['custom_pre_id'],
1075 'custom_post_id' => $values['custom_post_id'],
1078 //get the params submitted by participant.
1079 $participantParams = CRM_Utils_Array
::value($participantId, $values['params'], array());
1081 if (!$returnMessageText) {
1082 //send notification email if field values are set (CRM-1941)
1083 foreach ($gIds as $key => $gIdValues) {
1085 if (!is_array($gIdValues)) {
1086 $gIdValues = array($gIdValues);
1089 foreach ($gIdValues as $gId) {
1090 $email = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1092 //get values of corresponding profile fields for notification
1093 list($profileValues) = self
::buildCustomDisplay($gId,
1102 list($profileValues) = $profileValues;
1105 'values' => $profileValues,
1108 CRM_Core_BAO_UFGroup
::commonSendMail($contactID, $val);
1115 if ($values['event']['is_email_confirm'] ||
$returnMessageText) {
1116 list($displayName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1118 //send email only when email is present
1119 if (isset($email) ||
$returnMessageText) {
1120 $preProfileID = CRM_Utils_Array
::value('custom_pre_id', $values);
1121 $postProfileID = CRM_Utils_Array
::value('custom_post_id', $values);
1123 if (!empty($values['params']['additionalParticipant'])) {
1124 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values, $preProfileID);
1125 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values, $postProfileID);
1128 self
::buildCustomDisplay($preProfileID,
1138 self
::buildCustomDisplay($postProfileID,
1148 $sessions = CRM_Event_Cart_BAO_Conference
::get_participant_sessions($participantId);
1150 $tplParams = array_merge($values, $participantParams, array(
1152 'confirm_email_text' => CRM_Utils_Array
::value('confirm_email_text', $values['event']),
1153 'isShowLocation' => CRM_Utils_Array
::value('is_show_location', $values['event']),
1154 // The concept of contributeMode is deprecated.
1155 'contributeMode' => CRM_Utils_Array
::value('contributeMode', $template->_tpl_vars
),
1156 'participantID' => $participantId,
1157 'conference_sessions' => $sessions,
1158 'credit_card_number' =>
1159 CRM_Utils_System
::mungeCreditCard(
1160 CRM_Utils_Array
::value('credit_card_number', $participantParams)),
1161 'credit_card_exp_date' =>
1162 CRM_Utils_Date
::mysqlToIso(
1163 CRM_Utils_Date
::format(
1164 CRM_Utils_Array
::value('credit_card_exp_date', $participantParams))),
1167 // CRM-13890 : NOTE wait list condition need to be given so that
1168 // wait list message is shown properly in email i.e. WRT online event registration template
1169 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
1170 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id', TRUE);
1171 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($statusId, NULL, 'label');
1173 //CRM-15754 - if participant_status contains status ID
1174 elseif (!empty($tplParams['participant_status']) && CRM_Utils_Rule
::integer($tplParams['participant_status'])) {
1175 $tplParams['participant_status'] = CRM_Event_PseudoConstant
::participantStatus($tplParams['participant_status'], NULL, 'label');
1178 $sendTemplateParams = array(
1179 'groupName' => 'msg_tpl_workflow_event',
1180 'valueName' => 'event_online_receipt',
1181 'contactId' => $contactID,
1182 'isTest' => $isTest,
1183 'tplParams' => $tplParams,
1184 'PDFFilename' => ts('confirmation') . '.pdf',
1187 // address required during receipt processing (pdf and email receipt)
1188 if ($displayAddress = CRM_Utils_Array
::value('address', $values)) {
1189 $sendTemplateParams['tplParams']['address'] = $displayAddress;
1190 // The concept of contributeMode is deprecated.
1191 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1194 // set lineItem details
1195 if ($lineItem = CRM_Utils_Array
::value('lineItem', $values)) {
1196 // check if additional participant, if so filter only to relevant ones
1198 if (!empty($values['params']['additionalParticipant'])) {
1199 $ownLineItems = array();
1200 foreach ($lineItem as $liKey => $liValue) {
1201 $firstElement = array_pop($liValue);
1202 if ($firstElement['entity_id'] == $participantId) {
1203 $ownLineItems[0] = $lineItem[$liKey];
1207 if (!empty($ownLineItems)) {
1208 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1212 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1216 if ($returnMessageText) {
1217 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1219 'subject' => $subject,
1221 'to' => $displayName,
1226 $sendTemplateParams['from'] = CRM_Utils_Array
::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array
::value('confirm_from_email', $values['event']) . ">";
1227 $sendTemplateParams['toName'] = $displayName;
1228 $sendTemplateParams['toEmail'] = $email;
1229 $sendTemplateParams['autoSubmitted'] = TRUE;
1230 $sendTemplateParams['cc'] = CRM_Utils_Array
::value('cc_confirm',
1233 $sendTemplateParams['bcc'] = CRM_Utils_Array
::value('bcc_confirm',
1236 // append invoice pdf to email
1237 $template = CRM_Core_Smarty
::singleton();
1238 $taxAmt = $template->get_template_vars('totalTaxAmount');
1239 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
1240 $invoicing = CRM_Utils_Array
::value('invoicing', $prefixValue);
1241 if (isset($invoicing) && isset($prefixValue['is_email_pdf']) && !empty($values['contributionId'])) {
1242 $sendTemplateParams['isEmailPdf'] = TRUE;
1243 $sendTemplateParams['contributionId'] = $values['contributionId'];
1245 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1252 * Add the custom fields OR array of participant's profile info.
1255 * @param string $name
1257 * @param string $template
1258 * @param int $participantId
1259 * @param bool $isTest
1260 * @param bool $isCustomProfile
1261 * @param array $participantParams
1263 * @return array|null
1265 public static function buildCustomDisplay(
1272 $isCustomProfile = FALSE,
1273 $participantParams = array()
1276 return array(NULL, NULL);
1279 if (!is_array($id)) {
1280 $id = CRM_Utils_Type
::escape($id, 'Positive');
1281 $profileIds = array($id);
1287 $val = $groupTitles = NULL;
1288 foreach ($profileIds as $gid) {
1289 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $cid)) {
1291 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
,
1292 NULL, NULL, FALSE, NULL,
1293 FALSE, NULL, CRM_Core_Permission
::CREATE
,
1297 //this condition is added, since same contact can have multiple event registrations..
1298 $params = array(array('participant_id', '=', $participantId, 0, 0));
1300 //add participant id
1301 $fields['participant_id'] = array(
1302 'name' => 'participant_id',
1303 'title' => ts('Participant ID'),
1305 //check whether its a text drive
1307 $params[] = array('participant_test', '=', 1, 0, 0);
1310 //display campaign on thankyou page.
1311 if (array_key_exists('participant_campaign_id', $fields)) {
1312 if ($participantId) {
1313 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1317 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1318 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array
::value($campaignId,
1322 unset($fields['participant_campaign_id']);
1326 foreach ($fields as $k => $v) {
1328 $groupTitle = $v['groupTitle'];
1330 // suppress all file fields from display
1332 CRM_Utils_Array
::value('data_type', $v, '') == 'File' ||
1333 CRM_Utils_Array
::value('name', $v, '') == 'image_URL' ||
1334 CRM_Utils_Array
::value('field_type', $v) == 'Formatting'
1341 $groupTitles[] = $groupTitle;
1343 //display profile groups those are subscribed by participant.
1344 if (($groups = CRM_Utils_Array
::value('group', $participantParams)) &&
1348 foreach ($groups as $grpId => $isSelected) {
1353 if (!empty($grpIds)) {
1354 //get the group titles.
1355 $grpTitles = array();
1356 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1357 $grp = CRM_Core_DAO
::executeQuery($query);
1358 while ($grp->fetch()) {
1359 $grpTitles[] = $grp->title
;
1361 if (!empty($grpTitles) &&
1362 CRM_Utils_Array
::value('title', CRM_Utils_Array
::value('group', $fields))
1364 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1366 unset($fields['group']);
1370 CRM_Core_BAO_UFGroup
::getValues($cid, $fields, $values, FALSE, $params);
1372 if (isset($fields['participant_status_id']['title']) &&
1373 isset($values[$fields['participant_status_id']['title']]) &&
1374 is_numeric($values[$fields['participant_status_id']['title']])
1377 $status = CRM_Event_PseudoConstant
::participantStatus();
1378 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1381 if (isset($fields['participant_role_id']['title']) &&
1382 isset($values[$fields['participant_role_id']['title']]) &&
1383 is_numeric($values[$fields['participant_role_id']['title']])
1386 $roles = CRM_Event_PseudoConstant
::participantRole();
1387 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1390 if (isset($fields['participant_register_date']['title']) &&
1391 isset($values[$fields['participant_register_date']['title']])
1393 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date
::customFormat($values[$fields['participant_register_date']['title']]);
1396 //handle fee_level for price set
1397 if (isset($fields['participant_fee_level']['title']) &&
1398 isset($values[$fields['participant_fee_level']['title']])
1400 $feeLevel = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1401 $values[$fields['participant_fee_level']['title']]
1403 foreach ($feeLevel as $key => $value) {
1405 unset($feeLevel[$key]);
1408 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
1411 unset($values[$fields['participant_id']['title']]);
1418 $template->assign($name, $val);
1421 if (count($groupTitles)) {
1422 $template->assign($name . '_grouptitle', $groupTitles);
1425 //return if we only require array of participant's info.
1426 if ($isCustomProfile) {
1428 return array($val, $groupTitles);
1437 * Build the array for display the profile fields.
1439 * @param array $params
1443 * @param array $groupTitle
1444 * Profile Group Title.
1445 * @param array $values
1446 * Formatted array of key value.
1448 * @param array $profileFields
1450 public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
1452 $config = CRM_Core_Config
::singleton();
1453 $session = CRM_Core_Session
::singleton();
1454 $contactID = $session->get('userID');
1456 if (CRM_Core_BAO_UFGroup
::filterUFGroups($gid, $contactID)) {
1457 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::VIEW
);
1461 $fields = CRM_Core_BAO_UFGroup
::getFields($gid, FALSE, CRM_Core_Action
::ADD
);
1464 foreach ($fields as $v) {
1465 if (!empty($v['groupTitle'])) {
1466 $groupTitle['groupTitle'] = $v['groupTitle'];
1471 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1472 //start of code to set the default values
1473 foreach ($fields as $name => $field) {
1475 // skip fields that should not be displayed separately
1476 if ($field['skipDisplay']) {
1480 $index = $field['title'];
1481 if ($name === 'organization_name') {
1482 $values[$index] = $params[$name];
1485 if ('state_province' == substr($name, 0, 14)) {
1486 if ($params[$name]) {
1487 $values[$index] = CRM_Core_PseudoConstant
::stateProvince($params[$name]);
1490 $values[$index] = '';
1493 elseif ('date' == substr($name, -4)) {
1494 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::processDate($params[$name]),
1495 $config->dateformatFull
);
1497 elseif ('country' == substr($name, 0, 7)) {
1498 if ($params[$name]) {
1499 $values[$index] = CRM_Core_PseudoConstant
::country($params[$name]);
1502 $values[$index] = '';
1505 elseif ('county' == substr($name, 0, 6)) {
1506 if ($params[$name]) {
1507 $values[$index] = CRM_Core_PseudoConstant
::county($params[$name]);
1510 $values[$index] = '';
1513 elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
1514 $values[$index] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
1516 elseif (in_array($name, array(
1521 $filterCondition = array('greeting_type' => $name);
1522 $greeting = CRM_Core_PseudoConstant
::greeting($filterCondition);
1523 $values[$index] = $greeting[$params[$name]];
1525 elseif ($name === 'preferred_communication_method') {
1526 $communicationFields = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1528 $pref = $params[$name];
1529 if (is_array($pref)) {
1530 foreach ($pref as $k => $v) {
1532 $compref[] = $communicationFields[$k];
1536 $values[$index] = implode(',', $compref);
1538 elseif ($name == 'contact_sub_type') {
1539 $values[$index] = implode(', ', $params[$name]);
1541 elseif ($name == 'group') {
1542 $groups = CRM_Contact_BAO_GroupContact
::getGroupList();
1544 foreach ($params[$name] as $gId => $dontCare) {
1546 $title[] = $groups[$gId];
1549 $values[$index] = implode(', ', $title);
1551 elseif ($name == 'tag') {
1552 $entityTags = $params[$name];
1553 $allTags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
1555 if (is_array($entityTags)) {
1556 foreach ($entityTags as $tagId => $dontCare) {
1557 $title[] = $allTags[$tagId];
1560 $values[$index] = implode(', ', $title);
1562 elseif ('participant_role_id' == $name OR
1563 'participant_role' == $name
1565 $roles = CRM_Event_PseudoConstant
::participantRole();
1566 $values[$index] = $roles[$params[$name]];
1568 elseif ('participant_status_id' == $name OR
1569 'participant_status' == $name
1571 $status = CRM_Event_PseudoConstant
::participantStatus();
1572 $values[$index] = $status[$params[$name]];
1574 elseif (substr($name, -11) == 'campaign_id') {
1575 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($params[$name]);
1576 $values[$index] = CRM_Utils_Array
::value($params[$name], $campaigns);
1578 elseif (strpos($name, '-') !== FALSE) {
1579 list($fieldName, $id) = CRM_Utils_System
::explode('-', $name, 2);
1580 $detailName = str_replace(' ', '_', $name);
1581 if (in_array($fieldName, array(
1586 $values[$index] = $params[$detailName];
1587 $idx = $detailName . '_id';
1588 $values[$index] = $params[$idx];
1590 elseif ($fieldName == 'im') {
1591 $providerName = NULL;
1592 if ($providerId = $detailName . '-provider_id') {
1593 $providerName = CRM_Utils_Array
::value($params[$providerId], $imProviders);
1595 if ($providerName) {
1596 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1599 $values[$index] = $params[$detailName];
1602 elseif ($fieldName == 'phone') {
1603 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1604 if (isset($params[$phoneExtField])) {
1605 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1608 $values[$index] = $params[$detailName];
1612 $values[$index] = $params[$detailName];
1616 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1617 if ($params[$name]) {
1618 $values[$index] = '[ x ]';
1622 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
1624 SELECT html_type, data_type
1625 FROM civicrm_custom_field
1628 $dao = CRM_Core_DAO
::executeQuery($query);
1630 $htmlType = $dao->html_type
;
1632 if ($htmlType == 'File') {
1633 $values[$index] = $params[$index];
1636 if ($dao->data_type
== 'Int' ||
1637 $dao->data_type
== 'Boolean'
1639 $v = $params[$name];
1640 if (!CRM_Utils_System
::isNull($v)) {
1641 $customVal = (int) $v;
1644 elseif ($dao->data_type
== 'Float') {
1645 $customVal = (float ) ($params[$name]);
1647 elseif ($dao->data_type
== 'Date') {
1648 //@todo note the currently we are using default date time formatting. Since you can select/set
1649 // different date and time format specific to custom field we should consider fixing this
1650 // sometime in the future
1651 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1652 CRM_Utils_Date
::processDate($params[$name]), $config->dateformatFull
);
1654 if (!empty($params[$name . '_time'])) {
1655 $customVal = $displayValue = CRM_Utils_Date
::customFormat(
1656 CRM_Utils_Date
::processDate($params[$name], $params[$name . '_time']),
1657 $config->dateformatDatetime
);
1662 $customVal = $params[$name];
1664 //take the custom field options
1665 $returnProperties = array($name => 1);
1666 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
1667 $options = &$query->_options
;
1669 $displayValue = CRM_Core_BAO_CustomField
::getDisplayValue($customVal, $cfID, $options);
1671 //Hack since we dont have function to check empty.
1672 //FIXME in 2.3 using crmIsEmptyArray()
1673 $customValue = TRUE;
1674 if (is_array($customVal) && is_array($displayValue)) {
1675 $customValue = array_diff($customVal, $displayValue);
1677 //use difference of arrays
1678 if (empty($customValue) ||
!$customValue) {
1679 $values[$index] = '';
1682 $values[$index] = $displayValue;
1686 elseif ($name == 'home_URL' &&
1687 !empty($params[$name])
1689 $url = CRM_Utils_System
::fixURL($params[$name]);
1690 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1692 elseif (in_array($name, array(
1695 'participant_register_date',
1697 $values[$index] = CRM_Utils_Date
::customFormat(CRM_Utils_Date
::format($params[$name]));
1700 $values[$index] = CRM_Utils_Array
::value($name, $params);
1704 $profileFields[$name] = $field;
1710 * Build the array for Additional participant's information array of primary and additional Ids.
1712 * @param int $participantId
1713 * Id of Primary participant.
1714 * @param array $values
1715 * Key/value event info.
1716 * @param int $contactId
1717 * Contact id of Primary participant.
1718 * @param bool $isTest
1719 * Whether test or live transaction.
1720 * @param bool $isIdsArray
1721 * To return an array of Ids.
1723 * @param bool $skipCancel
1726 * array of Additional participant's info OR array of Ids.
1728 public static function buildCustomProfile(
1733 $isIdsArray = FALSE,
1737 $customProfile = $additionalIDs = array();
1738 if (!$participantId) {
1739 CRM_Core_Error
::fatal(ts('Cannot find participant ID'));
1742 //set Ids of Primary Participant also.
1743 if ($isIdsArray && $contactId) {
1744 $additionalIDs[$participantId] = $contactId;
1747 //hack to skip cancelled participants, CRM-4320
1748 $where = "participant.registered_by_id={$participantId}";
1750 $cancelStatusId = 0;
1751 $negativeStatuses = CRM_Event_PseudoConstant
::participantStatus(NULL, "class = 'Negative'");
1752 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
1753 $where .= " AND participant.status_id != {$cancelStatusId}";
1756 SELECT participant.id, participant.contact_id
1757 FROM civicrm_participant participant
1760 $dao = CRM_Core_DAO
::executeQuery($query);
1761 while ($dao->fetch()) {
1762 $additionalIDs[$dao->id
] = $dao->contact_id
;
1765 //return if only array is required.
1766 if ($isIdsArray && $contactId) {
1767 return $additionalIDs;
1770 $preProfileID = CRM_Utils_Array
::value('additional_custom_pre_id', $values);
1771 $postProfileID = CRM_Utils_Array
::value('additional_custom_post_id', $values);
1772 //else build array of Additional participant's information.
1773 if (count($additionalIDs)) {
1774 if ($preProfileID ||
$postProfileID) {
1775 $template = CRM_Core_Smarty
::singleton();
1777 $isCustomProfile = TRUE;
1779 $title = $groupTitles = array();
1780 foreach ($additionalIDs as $pId => $cId) {
1781 //get the params submitted by participant.
1782 $participantParams = CRM_Utils_Array
::value($pId, $values['params'], array());
1784 list($profilePre, $groupTitles) = self
::buildCustomDisplay($preProfileID,
1785 'additionalCustomPre',
1795 $profile = $profilePre;
1796 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1798 $title = $groupTitles;
1802 list($profilePost, $groupTitles) = self
::buildCustomDisplay($postProfileID,
1803 'additionalCustomPost',
1813 if (isset($profilePre)) {
1814 $profile = array_merge($profilePre, $profilePost);
1816 $title = array_merge($title, $groupTitles);
1820 $profile = $profilePost;
1822 $title = $groupTitles;
1826 $profiles[] = $profile;
1829 $customProfile['title'] = $title;
1830 $customProfile['profile'] = $profiles;
1834 return $customProfile;
1837 /* Function to retrieve all events those having location block set.
1840 * array of all events.
1845 public static function getLocationEvents() {
1849 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
1850 FROM civicrm_event ce
1851 INNER JOIN civicrm_loc_block lb ON ce.loc_block_id = lb.id
1852 INNER JOIN civicrm_address ca ON lb.address_id = ca.id
1853 LEFT JOIN civicrm_state_province sp ON ca.state_province_id = sp.id
1854 ORDER BY sp.name, ca.city, ca.street_address ASC
1857 $dao = CRM_Core_DAO
::executeQuery($query);
1858 while ($dao->fetch()) {
1859 $events[$dao->loc_block_id
] = $dao->title
;
1866 * @param int $locBlockId
1868 * @return int|null|string
1870 public static function countEventsUsingLocBlockId($locBlockId) {
1875 $locBlockId = CRM_Utils_Type
::escape($locBlockId, 'Integer');
1878 SELECT count(*) FROM civicrm_event ce
1879 WHERE ce.loc_block_id = $locBlockId";
1881 return CRM_Core_DAO
::singleValueQuery($query);
1885 * Check if event registration is valid according to permissions AND Dates.
1887 * @param array $values
1888 * @param int $eventID
1891 public static function validRegistrationRequest($values, $eventID) {
1892 // check that the user has permission to register for this event
1893 $hasPermission = CRM_Core_Permission
::event(CRM_Core_Permission
::EDIT
,
1894 $eventID, 'register for events'
1897 return $hasPermission && self
::validRegistrationDate($values);
1905 public static function validRegistrationDate(&$values) {
1906 // make sure that we are between registration start date and registration end date
1907 $startDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_start_date', $values));
1908 $endDate = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('registration_end_date', $values));
1909 $eventEnd = CRM_Utils_Date
::unixTime(CRM_Utils_Array
::value('end_date', $values));
1912 if ($startDate && $startDate >= $now) {
1915 if ($endDate && $endDate < $now && $eventEnd && $eventEnd < $now) {
1922 /* Function to Show - Hide the Registration Link.
1924 * @param array $values
1925 * Key/value event info.
1927 * true if allow registration otherwise false
1934 public static function showHideRegistrationLink($values) {
1936 $session = CRM_Core_Session
::singleton();
1937 $contactID = $session->get('userID');
1938 $alreadyRegistered = FALSE;
1941 $params = array('contact_id' => $contactID);
1943 if ($eventId = CRM_Utils_Array
::value('id', $values['event'])) {
1944 $params['event_id'] = $eventId;
1946 if ($roleId = CRM_Utils_Array
::value('default_role_id', $values['event'])) {
1947 $params['role_id'] = $roleId;
1949 $alreadyRegistered = self
::checkRegistration($params);
1952 if (!empty($values['event']['allow_same_participant_emails']) ||
1960 /* Function to check if given contact is already registered.
1962 * @param array $params
1963 * Key/value participant info.
1967 * @param array $params
1971 public static function checkRegistration($params) {
1972 $alreadyRegistered = FALSE;
1973 if (empty($params['contact_id'])) {
1974 return $alreadyRegistered;
1977 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
1979 $participant = new CRM_Event_DAO_Participant();
1980 $participant->copyValues($params);
1982 $participant->is_test
= CRM_Utils_Array
::value('is_test', $params, 0);
1983 $participant->selectAdd();
1984 $participant->selectAdd('status_id');
1985 if ($participant->find(TRUE) && array_key_exists($participant->status_id
, $statusTypes)) {
1986 $alreadyRegistered = TRUE;
1989 return $alreadyRegistered;
1993 * Make sure that the user has permission to access this event.
1995 * @param int $eventId
1999 * the permission that the user has (or null)
2001 public static function checkPermission($eventId = NULL, $type = CRM_Core_Permission
::VIEW
) {
2002 static $permissions = NULL;
2004 if (empty($permissions)) {
2005 $allEvents = CRM_Event_PseudoConstant
::event(NULL, TRUE);
2006 $createdEvents = array();
2008 $session = CRM_Core_Session
::singleton();
2009 if ($userID = $session->get('userID')) {
2010 $createdEvents = array_keys(CRM_Event_PseudoConstant
::event(NULL, TRUE, "created_id={$userID}"));
2013 // Note: for a multisite setup, a user with edit all events, can edit all events
2014 // including those from other sites
2015 if (CRM_Core_Permission
::check('edit all events')) {
2016 $permissions[CRM_Core_Permission
::EDIT
] = array_keys($allEvents);
2019 $permissions[CRM_Core_Permission
::EDIT
] = CRM_ACL_API
::group(CRM_Core_Permission
::EDIT
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2022 if (CRM_Core_Permission
::check('edit all events')) {
2023 $permissions[CRM_Core_Permission
::VIEW
] = array_keys($allEvents);
2026 if (CRM_Core_Permission
::check('access CiviEvent') &&
2027 CRM_Core_Permission
::check('view event participants')
2029 // use case: allow "view all events" but NOT "edit all events"
2030 // so for a normal site allow users with these two permissions to view all events AND
2031 // at the same time also allow any hook to override if needed.
2032 $createdEvents = array_keys($allEvents);
2034 $permissions[CRM_Core_Permission
::VIEW
] = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_event', $allEvents, $createdEvents);
2037 $permissions[CRM_Core_Permission
::DELETE
] = array();
2038 if (CRM_Core_Permission
::check('delete in CiviEvent')) {
2039 // Note: we want to restrict the scope of delete permission to
2040 // events that are editable/viewable (usecase multisite).
2041 // We can remove array_intersect once we have ACL support for delete functionality.
2042 $permissions[CRM_Core_Permission
::DELETE
] = array_intersect($permissions[CRM_Core_Permission
::EDIT
],
2043 $permissions[CRM_Core_Permission
::VIEW
]
2049 return in_array($eventId, $permissions[$type]) ?
TRUE : FALSE;
2052 return $permissions;
2056 * Build From Email as the combination of all the email ids of the logged in user,
2057 * the domain email id and the email id configured for the event
2059 * @param int $eventId
2060 * The id of the event.
2063 * an array of email ids
2065 public static function getFromEmailIds($eventId = NULL) {
2066 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email
::getFromEmail();
2069 // add the email id configured for the event
2070 $params = array('id' => $eventId);
2071 $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
2072 $eventEmail = array();
2074 CRM_Core_DAO
::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
2075 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
2076 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
2078 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
2079 $fromEmailId = array(
2080 'cc' => CRM_Utils_Array
::value('cc_confirm', $eventEmail),
2081 'bcc' => CRM_Utils_Array
::value('bcc_confirm', $eventEmail),
2083 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2087 return $fromEmailValues;
2091 * Calculate event total seats occupied.
2093 * @param int $eventId
2095 * @param sting $extraWhereClause
2096 * Extra filter on participants.
2099 * event total seats w/ given criteria.
2101 public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
2102 if (empty($eventId)) {
2106 $extraWhereClause = trim($extraWhereClause);
2107 if (!empty($extraWhereClause)) {
2108 $extraWhereClause = " AND ( {$extraWhereClause} )";
2111 //event seats calculation :
2112 //1. consider event seat as a single when participant does not have line item.
2113 //2. consider event seat as a single when participant has line items but does not
2114 // have count for corresponding price field value ( ie price field value does not carry any seat )
2115 //3. consider event seat as a sum of all seats from line items in case price field value carries count.
2118 SELECT IF ( SUM( value.count*lineItem.qty ),
2119 SUM( value.count*lineItem.qty ) +
2120 COUNT( DISTINCT participant.id ) -
2121 COUNT( DISTINCT IF ( value.count, participant.id, NULL ) ),
2122 COUNT( DISTINCT participant.id ) )
2123 FROM civicrm_participant participant
2124 INNER JOIN civicrm_contact contact ON ( contact.id = participant.contact_id AND contact.is_deleted = 0 )
2125 INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
2126 LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id
2127 AND lineItem.entity_table = 'civicrm_participant' )
2128 LEFT JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id AND value.count )
2129 WHERE ( participant.event_id = %1 )
2130 AND participant.is_test = 0
2132 GROUP BY participant.event_id";
2134 return (int) CRM_Core_DAO
::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
2138 * Retrieve event template default values to be set.
2139 * as default values for current new event.
2141 * @param int $templateId
2142 * Event template id.
2145 * Array of custom data defaults.
2147 public static function getTemplateDefaultValues($templateId) {
2148 $defaults = array();
2153 $templateParams = array('id' => $templateId);
2154 CRM_Event_BAO_Event
::retrieve($templateParams, $defaults);
2155 $fieldsToExclude = array(
2158 'default_discount_fee_id',
2164 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2169 * @param int $event_id
2173 public static function get_sub_events($event_id) {
2174 $params = array('parent_event_id' => $event_id);
2175 $defaults = array();
2176 return CRM_Event_BAO_Event
::retrieve($params, $defaults);
2180 * Update the Campaign Id of all the participants of the given event.
2182 * @param int $eventID
2184 * @param int $eventCampaignID
2185 * Campaign id of that event.
2187 public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
2189 $params[1] = array($eventID, 'Integer');
2191 if (empty($eventCampaignID)) {
2192 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2195 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2196 $params[2] = array($eventCampaignID, 'Integer');
2198 CRM_Core_DAO
::executeQuery($query, $params);
2202 * Get options for a given field.
2203 * @see CRM_Core_DAO::buildOptions
2205 * @param string $fieldName
2206 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2207 * @param array $props : whatever is known about this dao object
2209 * @return array|bool
2211 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2213 // Special logic for fields whose options depend on context or properties
2214 switch ($fieldName) {
2215 case 'financial_type_id':
2216 // Fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
2217 return CRM_Financial_BAO_FinancialType
::getIncomeFinancialType();
2221 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);