Cleanup deprecated CRM_Core_BAO_Settings calls CRM-17507
[civicrm-core.git] / CRM / Event / BAO / Event.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
32 */
33class CRM_Event_BAO_Event extends CRM_Event_DAO_Event {
34
35 /**
66f9e52b 36 * Class constructor.
6a488035 37 */
00be9182 38 public function __construct() {
6a488035
TO
39 parent::__construct();
40 }
41
42 /**
66f9e52b 43 * Fetch object based on array of properties.
6a488035 44 *
d4dd1e85
TO
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.
6a488035 49 *
3d469574 50 * @return CRM_Event_DAO_Event
6a488035 51 */
00be9182 52 public static function retrieve(&$params, &$defaults) {
6a488035
TO
53 $event = new CRM_Event_DAO_Event();
54 $event->copyValues($params);
55 if ($event->find(TRUE)) {
56 CRM_Core_DAO::storeValues($event, $defaults);
57 return $event;
58 }
59 return NULL;
60 }
61
62 /**
fe482240 63 * Update the is_active flag in the db.
6a488035 64 *
d4dd1e85
TO
65 * @param int $id
66 * Id of the database record.
67 * @param bool $is_active
68 * Value we want to set the is_active field.
6a488035 69 *
a6c01b45 70 * @return Object
b44e3f84 71 * DAO object on success, null otherwise
6a488035 72 */
00be9182 73 public static function setIsActive($id, $is_active) {
6a488035
TO
74 return CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Event', $id, 'is_active', $is_active);
75 }
76
77 /**
66f9e52b 78 * Add the event.
6a488035 79 *
d4dd1e85
TO
80 * @param array $params
81 * Reference array contains the values submitted by the form.
6a488035 82 *
3d469574 83 * @return CRM_Event_DAO_Event
6a488035 84 */
00be9182 85 public static function add(&$params) {
6a488035 86 CRM_Utils_System::flushCache();
cc9b58f3 87 $financialTypeId = NULL;
a7488080 88 if (!empty($params['id'])) {
6a488035 89 CRM_Utils_Hook::pre('edit', 'Event', $params['id'], $params);
a7488080 90 if (empty($params['skipFinancialType'])) {
cc9b58f3
PN
91 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['id'], 'financial_type_id');
92 }
6a488035
TO
93 }
94 else {
95 CRM_Utils_Hook::pre('create', 'Event', NULL, $params);
96 }
97
98 $event = new CRM_Event_DAO_Event();
99
100 $event->copyValues($params);
101 $result = $event->save();
102
a7488080 103 if (!empty($params['id'])) {
6a488035
TO
104 CRM_Utils_Hook::post('edit', 'Event', $event->id, $event);
105 }
106 else {
107 CRM_Utils_Hook::post('create', 'Event', $event->id, $event);
108 }
8cc574cf 109 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
e1c77163 110 CRM_Price_BAO_PriceFieldValue::updateFinancialType($params['id'], 'civicrm_event', $params['financial_type_id']);
cc9b58f3 111 }
6a488035
TO
112 return $result;
113 }
114
115 /**
66f9e52b 116 * Create the event.
6a488035 117 *
d4dd1e85
TO
118 * @param array $params
119 * Reference array contains the values submitted by the form.
6a488035 120 *
9637d4be 121 * @return object
6a488035
TO
122 */
123 public static function create(&$params) {
124 $transaction = new CRM_Core_Transaction();
125 if (empty($params['is_template'])) {
126 $params['is_template'] = 0;
127 }
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');
134 }
135 $params['created_date'] = date('YmdHis');
136 }
137
138 $event = self::add($params);
b2cdd843 139 CRM_Price_BAO_PriceSet::setPriceSets($params, $event, 'event');
6a488035
TO
140 if (is_a($event, 'CRM_Core_Error')) {
141 CRM_Core_DAO::transaction('ROLLBACK');
142 return $event;
143 }
144
145 $session = CRM_Core_Session::singleton();
146 $contactId = $session->get('userID');
147 if (!$contactId) {
148 $contactId = CRM_Utils_Array::value('contact_id', $params);
149 }
150
151 // Log the information on successful add/edit of Event
152 $logParams = array(
153 'entity_table' => 'civicrm_event',
154 'entity_id' => $event->id,
155 'modified_id' => $contactId,
156 'modified_date' => date('Ymd'),
157 );
158
159 CRM_Core_BAO_Log::add($logParams);
160
a7488080 161 if (!empty($params['custom']) &&
6a488035
TO
162 is_array($params['custom'])
163 ) {
164 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_event', $event->id);
165 }
166
167 $transaction->commit();
168
169 return $event;
170 }
171
172 /**
66f9e52b 173 * Delete the event.
6a488035 174 *
d4dd1e85
TO
175 * @param int $id
176 * Event id.
6a488035 177 *
77b97be7 178 * @return mixed|null
6a488035 179 */
00be9182 180 public static function del($id) {
6a488035
TO
181 if (!$id) {
182 return NULL;
183 }
184
185 CRM_Utils_Hook::pre('delete', 'Event', $id, CRM_Core_DAO::$_nullArray);
186
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;
191
0479b4c8 192 $params = array(
ddca8f33 193 1 => array($values['table_name'], 'string'),
6a488035
TO
194 2 => array($id, 'integer'),
195 );
196
197 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
198 }
199
200 // price set cleanup, CRM-5527
9da8dc8c 201 CRM_Price_BAO_PriceSet::removeFrom('civicrm_event', $id);
6a488035
TO
202
203 $event = new CRM_Event_DAO_Event();
204 $event->id = $id;
205
206 if ($event->find(TRUE)) {
207 $locBlockId = $event->loc_block_id;
208 $result = $event->delete();
209
210 if (!is_null($locBlockId)) {
211 self::deleteEventLocBlock($locBlockId, $id);
212 }
213
214 CRM_Utils_Hook::post('delete', 'Event', $id, $event);
215 return $result;
216 }
217
218 return NULL;
219 }
220
221 /**
3bdf1f3a 222 * Delete the location block associated with an event.
223 *
224 * Function checks that it is not being used by any other event.
6a488035 225 *
3bdf1f3a 226 * @param int $locBlockId
d4dd1e85
TO
227 * Location block id to be deleted.
228 * @param int $eventId
229 * Event with which loc block is associated.
6a488035 230 */
00be9182 231 public static function deleteEventLocBlock($locBlockId, $eventId = NULL) {
6a488035
TO
232 $query = "SELECT count(ce.id) FROM civicrm_event ce WHERE ce.loc_block_id = $locBlockId";
233
234 if ($eventId) {
235 $query .= " AND ce.id != $eventId;";
236 }
237
238 $locCount = CRM_Core_DAO::singleValueQuery($query);
239
240 if ($locCount == 0) {
241 CRM_Core_BAO_Location::deleteLocBlock($locBlockId);
242 }
243 }
244
245 /**
3bdf1f3a 246 * Get current/future Events.
6a488035 247 *
5a4f6742
CW
248 * @param int $all
249 * 0 returns current and future events.
c2be40dc
AH
250 * 1 if events all are required
251 * 2 returns events since 3 months ago
97c1cf60 252 * @param int|array $id single int event id or array of multiple event ids to return
5a4f6742
CW
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.
97c1cf60 257 * @param bool $titleOnly
258 * true if you need only title not appended with start date
6a488035 259 *
77b97be7 260 * @return array
6a488035 261 */
5396af74 262 public static function getEvents(
ddca8f33 263 $all = 0,
97c1cf60 264 $id = NULL,
353ffa53 265 $isActive = TRUE,
97c1cf60 266 $checkPermission = TRUE,
267 $titleOnly = FALSE
6a488035
TO
268 ) {
269 $query = "
270SELECT `id`, `title`, `start_date`
271FROM `civicrm_event`
272WHERE ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )";
273
97c1cf60 274 if (!empty($id)) {
836f1f3f 275 $op = is_array($id) ? 'IN' : '=';
276 $where = CRM_Contact_BAO_Query::buildClause('id', $op, $id);
277 $query .= " AND {$where}";
6a488035 278 }
c2be40dc
AH
279 elseif ($all == 0) {
280 // find only events ending in the future
6a488035 281 $endDate = date('YmdHis');
b093546a
BS
282 $query .= "
283 AND ( `end_date` >= {$endDate} OR
284 (
285 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$endDate}
286 )
287 )";
6a488035 288 }
c2be40dc
AH
289 elseif ($all == 2) {
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 )";
293 }
6a488035
TO
294 if ($isActive) {
295 $query .= " AND civicrm_event.is_active = 1";
296 }
297
298 $query .= " ORDER BY title asc";
299 $events = array();
300
301 $dao = CRM_Core_DAO::executeQuery($query);
302 while ($dao->fetch()) {
303 if ((!$checkPermission ||
304 CRM_Event_BAO_Event::checkPermission($dao->id)
305 ) &&
306 $dao->title
307 ) {
97c1cf60 308 $events[$dao->id] = $dao->title;
309 if (!$titleOnly) {
310 $events[$dao->id] .= ' - ' . CRM_Utils_Date::customFormat($dao->start_date);
311 }
6a488035
TO
312 }
313 }
314
315 return $events;
316 }
317
318 /**
66f9e52b 319 * Get events Summary.
6a488035 320 *
a6c01b45
CW
321 * @return array
322 * Array of event summary values
6a488035 323 */
00be9182 324 public static function getEventSummary() {
6a488035
TO
325 $eventSummary = $eventIds = array();
326 $config = CRM_Core_Config::singleton();
327
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();
332 $validEventIDs = '';
333 if (empty($permissions[CRM_Core_Permission::VIEW])) {
334 $eventSummary['total_events'] = 0;
335 return $eventSummary;
336 }
337 else {
338 $validEventIDs = " AND civicrm_event.id IN ( " . implode(',', array_values($permissions[CRM_Core_Permission::VIEW])) . " ) ";
339 }
340
341 // We're fetching recent and upcoming events (where start date is 7 days ago OR later)
342 $query = "
343SELECT count(id) as total_events
344FROM civicrm_event
345WHERE 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 )
348 $validEventIDs";
349
350 $dao = CRM_Core_DAO::executeQuery($query);
351
352 if ($dao->fetch()) {
353 $eventSummary['total_events'] = $dao->total_events;
354 }
355
356 if (empty($eventSummary) ||
357 $dao->total_events == 0
358 ) {
359 return $eventSummary;
360 }
361
362 //get the participant status type values.
29b6b1dd 363 $cpstObject = new CRM_Event_DAO_ParticipantStatusType();
364 $cpst = $cpstObject->getTableName();
365 $query = "SELECT id, name, label, class FROM $cpst";
d7d7d5ab 366 $status = CRM_Core_DAO::executeQuery($query);
6a488035
TO
367 $statusValues = array();
368 while ($status->fetch()) {
369 $statusValues[$status->id]['id'] = $status->id;
370 $statusValues[$status->id]['name'] = $status->name;
afc3dfa7 371 $statusValues[$status->id]['label'] = $status->label;
6a488035
TO
372 $statusValues[$status->id]['class'] = $status->class;
373 }
374
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;
381 }
b8ce3328 382 // Get the event summary display preferences
aaffa79f 383 $show_max_events = Civi::settings()->get('show_events');
b8ce3328 384 // default to 10 if no option is set
385 if (is_null($show_max_events)) {
386 $show_max_events = 10;
387 }
388 // show all events if show_events is set to a negative value
389 if ($show_max_events >= 0) {
390 $event_summary_limit = "LIMIT 0, $show_max_events";
391 }
392 else {
393 $event_summary_limit = "";
394 }
6a488035
TO
395
396 $query = "
397SELECT civicrm_event.id as id, civicrm_event.title as event_title, civicrm_event.is_public as is_public,
398 civicrm_event.max_participants as max_participants, civicrm_event.start_date as start_date,
399 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,
400 civicrm_event.slot_label_id,
401 civicrm_event.summary as summary,
72c67af6 402 civicrm_pcp_block.id as is_pcp_enabled,
30051f5b 403 civicrm_recurring_entity.parent_id as is_repeating_event
6a488035
TO
404FROM civicrm_event
405LEFT JOIN civicrm_option_value ON (
406 civicrm_event.event_type_id = civicrm_option_value.value AND
407 civicrm_option_value.option_group_id = %1 )
408LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_event.id AND civicrm_tell_friend.entity_table = 'civicrm_event' )
409LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_event.id AND civicrm_pcp_block.entity_table = 'civicrm_event')
72c67af6 410LEFT JOIN civicrm_recurring_entity ON ( civicrm_event.id = civicrm_recurring_entity.entity_id AND civicrm_recurring_entity.entity_table = 'civicrm_event' )
6a488035
TO
411WHERE civicrm_event.is_active = 1 AND
412 ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0) AND
413 civicrm_event.start_date >= DATE_SUB( NOW(), INTERVAL 7 day )
414 $validEventIDs
415GROUP BY civicrm_event.id
416ORDER BY civicrm_event.start_date ASC
b8ce3328 417$event_summary_limit
6a488035
TO
418";
419 $eventParticipant = array();
420
421 $properties = array(
d7d7d5ab 422 'id' => 'id',
423 'eventTitle' => 'event_title',
424 'isPublic' => 'is_public',
425 'maxParticipants' => 'max_participants',
426 'startDate' => 'start_date',
427 'endDate' => 'end_date',
428 'eventType' => 'event_type',
429 'isMap' => 'is_map',
430 'participants' => 'participants',
6a488035
TO
431 'notCountedDueToRole' => 'notCountedDueToRole',
432 'notCountedDueToStatus' => 'notCountedDueToStatus',
433 'notCountedParticipants' => 'notCountedParticipants',
434 );
435
436 $params = array(1 => array($optionGroupId, 'Integer'));
50a23755 437 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
46f5566c 438 'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
50a23755 439 )));
6a488035
TO
440 $dao = CRM_Core_DAO::executeQuery($query, $params);
441 while ($dao->fetch()) {
442 foreach ($properties as $property => $name) {
443 $set = NULL;
444 switch ($name) {
445 case 'is_public':
446 if ($dao->$name) {
447 $set = 'Yes';
448 }
449 else {
450 $set = 'No';
451 }
452 $eventSummary['events'][$dao->id][$property] = $set;
453 break;
454
455 case 'is_map':
456 if ($dao->$name && $config->mapAPIKey) {
d7d7d5ab 457 $values = array();
458 $ids = array();
459 $params = array('entity_id' => $dao->id, 'entity_table' => 'civicrm_event');
6a488035
TO
460 $values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
461 if (is_numeric(CRM_Utils_Array::value('geo_code_1', $values['location']['address'][1])) ||
f425e142 462 (
6a488035
TO
463 !empty($values['location']['address'][1]['city']) &&
464 !empty($values['location']['address'][1]['state_province_id'])
465 )
466 ) {
467 $set = CRM_Utils_System::url('civicrm/contact/map/event', "reset=1&eid={$dao->id}");
468 }
469 }
470
471 $eventSummary['events'][$dao->id][$property] = $set;
c613b5fb
MW
472 if (is_array($permissions[CRM_Core_Permission::EDIT])
473 && in_array($dao->id, $permissions[CRM_Core_Permission::EDIT])) {
7431d9cc 474 $eventSummary['events'][$dao->id]['configure'] = CRM_Utils_System::url('civicrm/admin/event', "action=update&id=$dao->id&reset=1");
6a488035
TO
475 }
476 break;
477
478 case 'end_date':
479 case 'start_date':
480 $eventSummary['events'][$dao->id][$property] = CRM_Utils_Date::customFormat($dao->$name,
481 NULL, array('d')
482 );
483 break;
484
485 case 'participants':
486 case 'notCountedDueToRole':
487 case 'notCountedDueToStatus':
488 case 'notCountedParticipants':
489 $set = NULL;
490 $propertyCnt = 0;
491 if ($name == 'participants') {
492 $propertyCnt = self::getParticipantCount($dao->id);
493 if ($propertyCnt) {
494 $set = CRM_Utils_System::url('civicrm/event/search',
495 "reset=1&force=1&event=$dao->id&status=true&role=true"
496 );
497 }
498 }
499 elseif ($name == 'notCountedParticipants') {
500 $propertyCnt = self::getParticipantCount($dao->id, TRUE, FALSE, TRUE, FALSE);
501 if ($propertyCnt) {
502 // FIXME : selector fail to search w/ OR operator.
503 // $set = CRM_Utils_System::url( 'civicrm/event/search',
504 // "reset=1&force=1&event=$dao->id&status=false&role=false" );
505 }
506 }
507 elseif ($name == 'notCountedDueToStatus') {
508 $propertyCnt = self::getParticipantCount($dao->id, TRUE, FALSE, FALSE, FALSE);
509 if ($propertyCnt) {
510 $set = CRM_Utils_System::url('civicrm/event/search',
511 "reset=1&force=1&event=$dao->id&status=false"
512 );
513 }
514 }
515 else {
516 $propertyCnt = self::getParticipantCount($dao->id, FALSE, FALSE, TRUE, FALSE);
517 if ($propertyCnt) {
518 $set = CRM_Utils_System::url('civicrm/event/search',
519 "reset=1&force=1&event=$dao->id&role=false"
520 );
521 }
522 }
523
524 $eventSummary['events'][$dao->id][$property] = $propertyCnt;
525 $eventSummary['events'][$dao->id][$name . '_url'] = $set;
526 break;
527
528 default:
529 $eventSummary['events'][$dao->id][$property] = $dao->$name;
530 break;
531 }
532 }
533
534 // prepare the area for per-status participant counts
535 $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
536 $eventSummary['events'][$dao->id]['statuses'] = array_fill_keys($statusClasses, array());
537
538 $eventSummary['events'][$dao->id]['friend'] = $dao->is_friend_active;
539 $eventSummary['events'][$dao->id]['is_monetary'] = $dao->is_monetary;
540 $eventSummary['events'][$dao->id]['is_online_registration'] = $dao->is_online_registration;
541 $eventSummary['events'][$dao->id]['is_show_location'] = $dao->is_show_location;
542 $eventSummary['events'][$dao->id]['is_subevent'] = $dao->slot_label_id;
543 $eventSummary['events'][$dao->id]['is_pcp_enabled'] = $dao->is_pcp_enabled;
9e1bf145 544 $eventSummary['events'][$dao->id]['reminder'] = CRM_Core_BAO_ActionSchedule::isConfigured($dao->id, $mapping->getId());
72c67af6 545 $eventSummary['events'][$dao->id]['is_repeating_event'] = $dao->is_repeating_event;
eea16664 546
6a488035
TO
547 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
548 foreach ($statusValues as $statusId => $statusValue) {
549 if (!array_key_exists($statusId, $statusTypes)) {
550 continue;
551 }
552 $class = $statusValue['class'];
553 $statusCount = self::eventTotalSeats($dao->id, "( participant.status_id = {$statusId} )");
554 if ($statusCount) {
555 $urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
0479b4c8 556 $statusInfo = array(
ddca8f33 557 'url' => CRM_Utils_System::url('civicrm/event/search', $urlString),
6a488035 558 'name' => $statusValue['name'],
afc3dfa7 559 'label' => $statusValue['label'],
6a488035
TO
560 'count' => $statusCount,
561 );
562 $eventSummary['events'][$dao->id]['statuses'][$class][] = $statusInfo;
563 }
564 }
565 }
566
d7d7d5ab 567 $countedRoles = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
568 $nonCountedRoles = CRM_Event_PseudoConstant::participantRole(NULL, '( filter = 0 OR filter IS NULL )');
569 $countedStatus = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
6a488035
TO
570 $nonCountedStatus = CRM_Event_PseudoConstant::participantStatus(NULL, '( is_counted = 0 OR is_counted IS NULL )');
571
572 $countedStatusANDRoles = array_merge($countedStatus, $countedRoles);
573 $nonCountedStatusANDRoles = array_merge($nonCountedStatus, $nonCountedRoles);
574
575 $eventSummary['nonCountedRoles'] = implode('/', array_values($nonCountedRoles));
576 $eventSummary['nonCountedStatus'] = implode('/', array_values($nonCountedStatus));
577 $eventSummary['countedStatusANDRoles'] = implode('/', array_values($countedStatusANDRoles));
578 $eventSummary['nonCountedStatusANDRoles'] = implode('/', array_values($nonCountedStatusANDRoles));
579
580 return $eventSummary;
581 }
582
583 /**
66f9e52b 584 * Get participant count.
6a488035 585 *
100fef9d 586 * @param int $eventId
5396af74 587 * @param bool $considerStatus consider status for participant count.
d4dd1e85 588 * Consider status for participant count.
5396af74 589 * @param bool $status counted participant.
d4dd1e85 590 * Consider counted participant.
5396af74 591 * @param bool $considerRole consider role for participant count.
d4dd1e85 592 * Consider role for participant count.
5396af74 593 * @param bool $role consider counted( is filter role) participant.
d4dd1e85 594 * Consider counted( is filter role) participant.
77b97be7 595 *
a6c01b45
CW
596 * @return array
597 * array with count of participants for each event based on status/role
6a488035 598 */
ddca8f33
TO
599 public static function getParticipantCount(
600 $eventId,
353ffa53
TO
601 $considerStatus = TRUE,
602 $status = TRUE,
603 $considerRole = TRUE,
604 $role = TRUE
6a488035
TO
605 ) {
606
607 // consider both role and status for counted participants, CRM-4924.
608 $operator = " AND ";
609 // not counted participant.
610 if ($considerStatus && $considerRole && !$status && !$role) {
611 $operator = " OR ";
612 }
613 $clause = array();
614 if ($considerStatus) {
615 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
616 $statusClause = 'NOT IN';
617 if ($status) {
618 $statusClause = 'IN';
619 }
620 $status = implode(',', array_keys($statusTypes));
621 if (empty($status)) {
622 $status = 0;
623 }
624 $clause[] = "participant.status_id {$statusClause} ( {$status} ) ";
625 }
626
627 if ($considerRole) {
628 $roleTypes = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
629 $roleClause = 'NOT IN';
630 if ($role) {
631 $roleClause = 'IN';
632 }
633 $roles = implode(',', array_keys($roleTypes));
634 if (empty($roles)) {
635 $roles = 0;
636 }
637 $clause[] = "participant.role_id {$roleClause} ( $roles )";
638 }
639
640 $sqlClause = '';
641 if (!empty($clause)) {
642 $sqlClause = ' ( ' . implode($operator, $clause) . ' )';
643 }
644
645 return self::eventTotalSeats($eventId, $sqlClause);
646 }
647
648 /**
66f9e52b 649 * Get the information to map a event.
6a488035 650 *
d4dd1e85
TO
651 * @param int $id
652 * For which we want map info.
6a488035 653 *
72b3a70c
CW
654 * @return null|string
655 * title of the event
6a488035 656 */
00be9182 657 public static function &getMapInfo(&$id) {
6a488035
TO
658
659 $sql = "
660SELECT
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
672FROM
673 civicrm_event
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 )
679WHERE 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');
682
683 $dao = new CRM_Core_DAO();
684 $dao->query($sql);
685
686 $locations = array();
687
688 $config = CRM_Core_Config::singleton();
689
690 while ($dao->fetch()) {
691
692 $location = array();
693 $location['displayName'] = addslashes($dao->display_name);
694 $location['lat'] = $dao->latitude;
695 $location['marker_class'] = 'Event';
696 $location['lng'] = $dao->longitude;
697
698 $params = array('entity_id' => $id, 'entity_table' => 'civicrm_event');
699 $addressValues = CRM_Core_BAO_Location::getValues($params, TRUE);
ddca8f33 700 $location['address'] = str_replace(array(
353ffa53
TO
701 "\r",
702 "\n",
703 ), '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
6a488035
TO
704
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;
711 }
712 return $locations;
713 }
714
715 /**
66f9e52b 716 * Get the complete information for one or more events.
6a488035 717 *
d4dd1e85
TO
718 * @param date $start
719 * Get events with start date >= this date.
5396af74 720 * @param int $type Get events on the a specific event type (by event_type_id).
d4dd1e85 721 * Get events on the a specific event type (by event_type_id).
5396af74 722 * @param int $eventId Return a single event - by event id.
d4dd1e85
TO
723 * Return a single event - by event id.
724 * @param date $end
725 * Also get events with end date >= this date.
5396af74 726 * @param bool $onlyPublic Include public events only, default TRUE.
d4dd1e85 727 * Include public events only, default TRUE.
6a488035 728 *
a6c01b45
CW
729 * @return array
730 * array of all the events that are searched
6a488035 731 */
5396af74 732 public static function &getCompleteInfo(
0ae0bb0e
DL
733 $start = NULL,
734 $type = NULL,
735 $eventId = NULL,
736 $end = NULL,
737 $onlyPublic = TRUE
738 ) {
739 $publicCondition = NULL;
740 if ($onlyPublic) {
741 $publicCondition = " AND civicrm_event.is_public = 1";
742 }
743
6a488035
TO
744 $dateCondition = '';
745 // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133
746 if ($start) {
747 // get events with start_date >= requested start
748 $startDate = CRM_Utils_Type::escape($start, 'Date');
749 $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )";
750 }
751
752 if ($end) {
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}' ) ";
756 }
757
0ae0bb0e
DL
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
6a488035
TO
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}' ) ";
766 }
767
768 if ($type) {
769 $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type::escape($type, 'Integer');
770 }
771
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;
778 }
779
780 $query = "
781SELECT
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
804FROM civicrm_event
805LEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id
806LEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id
807LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
808LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
809LEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id
810LEFT JOIN civicrm_option_value ON (
811 civicrm_event.event_type_id = civicrm_option_value.value AND
812 civicrm_option_value.option_group_id = %1 )
813WHERE civicrm_event.is_active = 1
6a488035 814 AND (is_template = 0 OR is_template IS NULL)
0ae0bb0e 815 {$publicCondition}
6a488035
TO
816 {$dateCondition}";
817
818 if (isset($typeCondition)) {
819 $query .= $typeCondition;
820 }
821
822 if (isset($eventId)) {
823 $query .= " AND civicrm_event.id =$eventId ";
824 }
825 $query .= " ORDER BY civicrm_event.start_date ASC";
826
6a488035 827 $params = array(1 => array($optionGroupId, 'Integer'));
ddca8f33
TO
828 $dao = CRM_Core_DAO::executeQuery($query, $params);
829 $all = array();
6a488035
TO
830 $config = CRM_Core_Config::singleton();
831
832 $baseURL = parse_url($config->userFrameworkBaseURL);
833 $url = "@" . $baseURL['host'];
a7488080 834 if (!empty($baseURL['path'])) {
6a488035
TO
835 $url .= substr($baseURL['path'], 0, -1);
836 }
837
838 // check 'view event info' permission
e2d09ab4
EM
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
6a488035
TO
845 $permissions = CRM_Core_Permission::event(CRM_Core_Permission::VIEW);
846
847 // check if we're in shopping cart mode for events
aaffa79f 848 $enable_cart = Civi::settings()->get('enable_cart');
ddca8f33
TO
849 if ($enable_cart) {
850 }
6a488035 851 while ($dao->fetch()) {
9f0f552c 852 if (!empty($permissions) && in_array($dao->event_id, $permissions)) {
6a488035
TO
853 $info = array();
854 $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL) . $url;
855
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;
869
870 $address = '';
871
872 $addrFields = array(
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,
882 'county' => NULL,
883 );
884
885 CRM_Utils_String::append($address, ', ',
886 CRM_Utils_Address::format($addrFields)
887 );
888 $info['location'] = $address;
889 $info['url'] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
890
891 if ($enable_cart) {
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'];
895 }
896
897 $all[] = $info;
898 }
899 }
900
901 return $all;
902 }
903
904 /**
3bdf1f3a 905 * Make a copy of a Event.
906 *
907 * Include all the fields in the event Wizard.
6a488035 908 *
d4dd1e85
TO
909 * @param int $id
910 * The event id to copy.
6a488035 911 * boolean $afterCreate call to copy after the create function
2a6da8d7
EM
912 * @param null $newEvent
913 * @param bool $afterCreate
914 *
10525e44 915 * @return CRM_Event_DAO_Event
6a488035 916 */
00be9182 917 public static function copy($id, $newEvent = NULL, $afterCreate = FALSE) {
6a488035 918
10525e44 919 $eventValues = array();
6a488035
TO
920
921 //get the require event values.
922 $eventParams = array('id' => $id);
ddca8f33
TO
923 $returnProperties = array(
924 'loc_block_id',
925 'is_show_location',
926 'default_fee_id',
927 'default_discount_fee_id',
21dfd5f5 928 'is_template',
ddca8f33 929 );
6a488035
TO
930
931 CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
932
933 // since the location is sharable, lets use the same loc_block_id.
934 $locBlockId = CRM_Utils_Array::value('loc_block_id', $eventValues);
935
0479b4c8 936 $fieldsFix = ($afterCreate) ? array() : array('prefix' => array('title' => ts('Copy of') . ' '));
a7488080 937 if (empty($eventValues['is_show_location'])) {
6a488035
TO
938 $fieldsFix['prefix']['is_show_location'] = 0;
939 }
940
941 if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
942 $copyEvent = $newEvent;
943 }
944
945 if (!isset($copyEvent)) {
946 $copyEvent = &CRM_Core_DAO::copyGeneric('CRM_Event_DAO_Event',
947 array('id' => $id),
ddca8f33
TO
948 array(
949 'loc_block_id' =>
5396af74 950 ($locBlockId) ? $locBlockId : NULL,
ddca8f33
TO
951 ),
952 $fieldsFix
953 );
6a488035 954 }
9da8dc8c 955 CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_event', $id, $copyEvent->id);
6a488035
TO
956 $copyUF = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin',
957 array(
958 'entity_id' => $id,
959 'entity_table' => 'civicrm_event',
960 ),
961 array('entity_id' => $copyEvent->id)
962 );
963
964 $copyTellFriend = &CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend',
965 array(
966 'entity_id' => $id,
967 'entity_table' => 'civicrm_event',
968 ),
969 array('entity_id' => $copyEvent->id)
970 );
971
972 $copyPCP = &CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock',
973 array(
974 'entity_id' => $id,
975 'entity_table' => 'civicrm_event',
976 ),
977 array('entity_id' => $copyEvent->id),
978 array('replace' => array('target_entity_id' => $copyEvent->id))
979 );
980
50a23755 981 $oldMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
46f5566c 982 'id' => ($eventValues['is_template'] ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID),
50a23755
TO
983 )));
984 $copyMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
46f5566c 985 'id' => ($copyEvent->is_template == 1 ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID),
50a23755 986 )));
6a488035 987 $copyReminder = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_ActionSchedule',
9e1bf145
TO
988 array('entity_value' => $id, 'mapping_id' => $oldMapping->getId()),
989 array('entity_value' => $copyEvent->id, 'mapping_id' => $copyMapping->getId())
6a488035
TO
990 );
991
992 if (!$afterCreate) {
993 //copy custom data
994 $extends = array('event');
995 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
996 if ($groupTree) {
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'];
1001 }
1002 }
1003
1004 foreach ($table as $tableName => $tableColumns) {
ddca8f33 1005 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
6a488035 1006 $tableColumns[0] = $copyEvent->id;
ddca8f33
TO
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);
6a488035
TO
1012 }
1013 }
1014 }
1015 $copyEvent->save();
1016
1017 CRM_Utils_System::flushCache();
1018 if (!$afterCreate) {
1019 CRM_Utils_Hook::copy('Event', $copyEvent);
1020 }
1021 return $copyEvent;
1022 }
1023
1024 /**
3bdf1f3a 1025 * This is sometimes called in a loop (during event search).
1026 *
1027 * We cache the values to prevent repeated calls to the db.
ea3ddccf 1028 *
1029 * @param int $id
1030 *
3d469574 1031 * @return bool
6a488035 1032 */
00be9182 1033 public static function isMonetary($id) {
6a488035
TO
1034 static $isMonetary = array();
1035 if (!array_key_exists($id, $isMonetary)) {
1036 $isMonetary[$id] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
1037 $id,
1038 'is_monetary'
1039 );
1040 }
1041 return $isMonetary[$id];
1042 }
1043
1044 /**
3bdf1f3a 1045 * This is sometimes called in a loop (during event search).
1046 *
1047 * We cache the values to prevent repeated calls to the db.
54957108 1048 *
1049 * @param int $id
1050 *
1051 * @return bool
6a488035 1052 */
00be9182 1053 public static function usesPriceSet($id) {
6a488035
TO
1054 static $usesPriceSet = array();
1055 if (!array_key_exists($id, $usesPriceSet)) {
9da8dc8c 1056 $usesPriceSet[$id] = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $id);
6a488035
TO
1057 }
1058 return $usesPriceSet[$id];
1059 }
1060
1061 /**
3bdf1f3a 1062 * Send e-mails.
6a488035 1063 *
100fef9d 1064 * @param int $contactID
3bdf1f3a 1065 * @param array $values
100fef9d 1066 * @param int $participantId
dd244018
EM
1067 * @param bool $isTest
1068 * @param bool $returnMessageText
6a488035 1069 */
00be9182 1070 public static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
6a488035
TO
1071
1072 $template = CRM_Core_Smarty::singleton();
1073 $gIds = array(
1074 'custom_pre_id' => $values['custom_pre_id'],
1075 'custom_post_id' => $values['custom_post_id'],
1076 );
1077
1078 //get the params submitted by participant.
1079 $participantParams = CRM_Utils_Array::value($participantId, $values['params'], array());
1080
1081 if (!$returnMessageText) {
1082 //send notification email if field values are set (CRM-1941)
1083 foreach ($gIds as $key => $gIdValues) {
1084 if ($gIdValues) {
1085 if (!is_array($gIdValues)) {
ddca8f33 1086 $gIdValues = array($gIdValues);
6a488035
TO
1087 }
1088
1089 foreach ($gIdValues as $gId) {
0479b4c8
TO
1090 $email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
1091 if ($email) {
1092 //get values of corresponding profile fields for notification
1093 list($profileValues) = self::buildCustomDisplay($gId,
ddca8f33
TO
1094 NULL,
1095 $contactID,
1096 $template,
1097 $participantId,
1098 $isTest,
1099 TRUE,
1100 $participantParams
0479b4c8
TO
1101 );
1102 list($profileValues) = $profileValues;
1103 $val = array(
ddca8f33
TO
1104 'id' => $gId,
1105 'values' => $profileValues,
1106 'email' => $email,
0479b4c8
TO
1107 );
1108 CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val);
1109 }
6a488035
TO
1110 }
1111 }
1112 }
1113 }
6a488035
TO
1114
1115 if ($values['event']['is_email_confirm'] || $returnMessageText) {
1116 list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
1117
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);
1122
a7488080 1123 if (!empty($values['params']['additionalParticipant'])) {
ddca8f33
TO
1124 $preProfileID = CRM_Utils_Array::value('additional_custom_pre_id', $values, $preProfileID);
1125 $postProfileID = CRM_Utils_Array::value('additional_custom_post_id', $values, $postProfileID);
6a488035
TO
1126 }
1127
1128 self::buildCustomDisplay($preProfileID,
1129 'customPre',
1130 $contactID,
1131 $template,
1132 $participantId,
1133 $isTest,
1134 NULL,
1135 $participantParams
1136 );
1137
1138 self::buildCustomDisplay($postProfileID,
1139 'customPost',
1140 $contactID,
1141 $template,
1142 $participantId,
1143 $isTest,
1144 NULL,
1145 $participantParams
1146 );
1147
1148 $sessions = CRM_Event_Cart_BAO_Conference::get_participant_sessions($participantId);
1149
1150 $tplParams = array_merge($values, $participantParams, array(
ddca8f33
TO
1151 'email' => $email,
1152 'confirm_email_text' => CRM_Utils_Array::value('confirm_email_text', $values['event']),
1153 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $values['event']),
0f2b049e 1154 // The concept of contributeMode is deprecated.
ddca8f33
TO
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))),
1165 ));
6a488035 1166
9e58e6ff
PJ
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
10c7ceab 1169 if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
66df7769 1170 $statusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id', TRUE);
9e58e6ff
PJ
1171 $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($statusId, NULL, 'label');
1172 }
10c7ceab 1173 //CRM-15754 - if participant_status contains status ID
26fe6f4c 1174 elseif (!empty($tplParams['participant_status']) && CRM_Utils_Rule::integer($tplParams['participant_status'])) {
10c7ceab 1175 $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($tplParams['participant_status'], NULL, 'label');
1176 }
9e58e6ff 1177
6a488035
TO
1178 $sendTemplateParams = array(
1179 'groupName' => 'msg_tpl_workflow_event',
1180 'valueName' => 'event_online_receipt',
1181 'contactId' => $contactID,
1182 'isTest' => $isTest,
1183 'tplParams' => $tplParams,
ddca8f33 1184 'PDFFilename' => ts('confirmation') . '.pdf',
6a488035
TO
1185 );
1186
1187 // address required during receipt processing (pdf and email receipt)
1188 if ($displayAddress = CRM_Utils_Array::value('address', $values)) {
1189 $sendTemplateParams['tplParams']['address'] = $displayAddress;
0f2b049e 1190 // The concept of contributeMode is deprecated.
6a488035
TO
1191 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
1192 }
1193
1194 // set lineItem details
1195 if ($lineItem = CRM_Utils_Array::value('lineItem', $values)) {
0f2b049e 1196 // check if additional participant, if so filter only to relevant ones
6a488035 1197 // CRM-9902
a7488080 1198 if (!empty($values['params']['additionalParticipant'])) {
0479b4c8 1199 $ownLineItems = array();
ddca8f33
TO
1200 foreach ($lineItem as $liKey => $liValue) {
1201 $firstElement = array_pop($liValue);
1202 if ($firstElement['entity_id'] == $participantId) {
6a488035
TO
1203 $ownLineItems[0] = $lineItem[$liKey];
1204 break;
1205 }
1206 }
ddca8f33 1207 if (!empty($ownLineItems)) {
6a488035
TO
1208 $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
1209 }
1210 }
1211 else {
1212 $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
1213 }
1214 }
1215
1216 if ($returnMessageText) {
c6327d7d 1217 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
1218 return array(
1219 'subject' => $subject,
1220 'body' => $message,
1221 'to' => $displayName,
1222 'html' => $html,
1223 );
1224 }
1225 else {
e4933c3f 1226 $sendTemplateParams['from'] = CRM_Utils_Array::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array::value('confirm_from_email', $values['event']) . ">";
6a488035
TO
1227 $sendTemplateParams['toName'] = $displayName;
1228 $sendTemplateParams['toEmail'] = $email;
1229 $sendTemplateParams['autoSubmitted'] = TRUE;
1230 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm',
1231 $values['event']
1232 );
1233 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm',
1234 $values['event']
1235 );
9161952c 1236 // append invoice pdf to email
ddca8f33 1237 $template = CRM_Core_Smarty::singleton();
9161952c 1238 $taxAmt = $template->get_template_vars('totalTaxAmount');
aaffa79f 1239 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
9161952c 1240 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
ce933183 1241 if (isset($invoicing) && isset($prefixValue['is_email_pdf']) && !empty($values['contributionId'])) {
0479b4c8 1242 $sendTemplateParams['isEmailPdf'] = TRUE;
d75f2f47 1243 $sendTemplateParams['contributionId'] = $values['contributionId'];
9161952c 1244 }
c6327d7d 1245 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
1246 }
1247 }
1248 }
1249 }
1250
1251 /**
3d469574 1252 * Add the custom fields OR array of participant's profile info.
6a488035 1253 *
100fef9d
CW
1254 * @param int $id
1255 * @param string $name
1256 * @param int $cid
3d469574 1257 * @param string $template
100fef9d 1258 * @param int $participantId
3d469574 1259 * @param bool $isTest
dd244018
EM
1260 * @param bool $isCustomProfile
1261 * @param array $participantParams
3d469574 1262 *
1263 * @return array|null
6a488035 1264 */
5396af74 1265 public static function buildCustomDisplay(
ddca8f33 1266 $id,
6a488035
TO
1267 $name,
1268 $cid,
1269 &$template,
1270 $participantId,
1271 $isTest,
1272 $isCustomProfile = FALSE,
1273 $participantParams = array()
1274 ) {
1275 if (!$id) {
1276 return array(NULL, NULL);
1277 }
1278
1279 if (!is_array($id)) {
1280 $id = CRM_Utils_Type::escape($id, 'Positive');
1281 $profileIds = array($id);
1282 }
1283 else {
1284 $profileIds = $id;
1285 }
1286
5efc507e 1287 $val = $groupTitles = NULL;
6a488035
TO
1288 foreach ($profileIds as $gid) {
1289 if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $cid)) {
1290 $values = array();
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,
1294 'field_name', TRUE
1295 );
1296
1297 //this condition is added, since same contact can have multiple event registrations..
1298 $params = array(array('participant_id', '=', $participantId, 0, 0));
1299
1300 //add participant id
1301 $fields['participant_id'] = array(
1302 'name' => 'participant_id',
aa6228f8 1303 'title' => ts('Participant ID'),
6a488035
TO
1304 );
1305 //check whether its a text drive
1306 if ($isTest) {
1307 $params[] = array('participant_test', '=', 1, 0, 0);
1308 }
1309
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',
1314 $participantId,
1315 'campaign_id'
1316 );
1317 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
1318 $values[$fields['participant_campaign_id']['title']] = CRM_Utils_Array::value($campaignId,
1319 $campaigns
1320 );
1321 }
1322 unset($fields['participant_campaign_id']);
1323 }
1324
1325 $groupTitle = NULL;
1326 foreach ($fields as $k => $v) {
1327 if (!$groupTitle) {
7431d9cc 1328 $groupTitle = $v['groupTitle'];
6a488035
TO
1329 }
1330 // suppress all file fields from display
1331 if (
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'
1335 ) {
1336 unset($fields[$k]);
1337 }
1338 }
1339
1340 if ($groupTitle) {
1341 $groupTitles[] = $groupTitle;
1342 }
1343 //display profile groups those are subscribed by participant.
1344 if (($groups = CRM_Utils_Array::value('group', $participantParams)) &&
1345 is_array($groups)
1346 ) {
1347 $grpIds = array();
1348 foreach ($groups as $grpId => $isSelected) {
1349 if ($isSelected) {
1350 $grpIds[] = $grpId;
1351 }
1352 }
1353 if (!empty($grpIds)) {
1354 //get the group titles.
1355 $grpTitles = array();
ddca8f33
TO
1356 $query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
1357 $grp = CRM_Core_DAO::executeQuery($query);
6a488035
TO
1358 while ($grp->fetch()) {
1359 $grpTitles[] = $grp->title;
1360 }
1361 if (!empty($grpTitles) &&
1362 CRM_Utils_Array::value('title', CRM_Utils_Array::value('group', $fields))
1363 ) {
1364 $values[$fields['group']['title']] = implode(', ', $grpTitles);
1365 }
1366 unset($fields['group']);
1367 }
1368 }
1369
1370 CRM_Core_BAO_UFGroup::getValues($cid, $fields, $values, FALSE, $params);
1371
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']])
1375 ) {
1376 $status = array();
1377 $status = CRM_Event_PseudoConstant::participantStatus();
1378 $values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
1379 }
1380
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']])
1384 ) {
1385 $roles = array();
1386 $roles = CRM_Event_PseudoConstant::participantRole();
1387 $values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
1388 }
1389
1390 if (isset($fields['participant_register_date']['title']) &&
1391 isset($values[$fields['participant_register_date']['title']])
1392 ) {
1393 $values[$fields['participant_register_date']['title']] = CRM_Utils_Date::customFormat($values[$fields['participant_register_date']['title']]);
1394 }
1395
1396 //handle fee_level for price set
1397 if (isset($fields['participant_fee_level']['title']) &&
1398 isset($values[$fields['participant_fee_level']['title']])
1399 ) {
1400 $feeLevel = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1401 $values[$fields['participant_fee_level']['title']]
1402 );
1403 foreach ($feeLevel as $key => $value) {
1404 if (!$value) {
1405 unset($feeLevel[$key]);
1406 }
1407 }
7431d9cc 1408 $values[$fields['participant_fee_level']['title']] = implode(',', $feeLevel);
6a488035
TO
1409 }
1410
1411 unset($values[$fields['participant_id']['title']]);
1412
1413 $val[] = $values;
1414 }
1415 }
1416
1417 if (count($val)) {
1418 $template->assign($name, $val);
1419 }
1420
1421 if (count($groupTitles)) {
1422 $template->assign($name . '_grouptitle', $groupTitles);
1423 }
1424
1425 //return if we only require array of participant's info.
1426 if ($isCustomProfile) {
1427 if (count($val)) {
1428 return array($val, $groupTitles);
1429 }
1430 else {
1431 return NULL;
1432 }
1433 }
1434 }
1435
1436 /**
66f9e52b 1437 * Build the array for display the profile fields.
6a488035 1438 *
d4dd1e85
TO
1439 * @param array $params
1440 * Key value.
1441 * @param int $gid
1442 * Profile Id.
1443 * @param array $groupTitle
1444 * Profile Group Title.
1445 * @param array $values
1446 * Formatted array of key value.
6a488035 1447 *
77b97be7 1448 * @param array $profileFields
6a488035 1449 */
00be9182 1450 public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
6a488035 1451 if ($gid) {
f5f3f029 1452 $config = CRM_Core_Config::singleton();
6a488035
TO
1453 $session = CRM_Core_Session::singleton();
1454 $contactID = $session->get('userID');
1455 if ($contactID) {
1456 if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) {
1457 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW);
1458 }
1459 }
1460 else {
1461 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::ADD);
1462 }
1463
1464 foreach ($fields as $v) {
a7488080 1465 if (!empty($v['groupTitle'])) {
7431d9cc 1466 $groupTitle['groupTitle'] = $v['groupTitle'];
6a488035
TO
1467 break;
1468 }
1469 }
ddca8f33
TO
1470 $customVal = '';
1471 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
6a488035
TO
1472 //start of code to set the default values
1473 foreach ($fields as $name => $field) {
9e7eeb0f 1474 $skip = FALSE;
6a488035
TO
1475 // skip fields that should not be displayed separately
1476 if ($field['skipDisplay']) {
1477 continue;
1478 }
1479
1480 $index = $field['title'];
1481 if ($name === 'organization_name') {
1482 $values[$index] = $params[$name];
1483 }
1484
1485 if ('state_province' == substr($name, 0, 14)) {
1486 if ($params[$name]) {
1487 $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]);
1488 }
1489 else {
1490 $values[$index] = '';
1491 }
1492 }
1493 elseif ('date' == substr($name, -4)) {
f5f3f029
KJ
1494 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]),
1495 $config->dateformatFull);
6a488035
TO
1496 }
1497 elseif ('country' == substr($name, 0, 7)) {
1498 if ($params[$name]) {
1499 $values[$index] = CRM_Core_PseudoConstant::country($params[$name]);
1500 }
1501 else {
1502 $values[$index] = '';
1503 }
1504 }
1505 elseif ('county' == substr($name, 0, 6)) {
1506 if ($params[$name]) {
1507 $values[$index] = CRM_Core_PseudoConstant::county($params[$name]);
1508 }
1509 else {
1510 $values[$index] = '';
1511 }
1512 }
aa62b355 1513 elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
36c514a1 1514 $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
6a488035
TO
1515 }
1516 elseif (in_array($name, array(
ddca8f33
TO
1517 'addressee',
1518 'email_greeting',
21dfd5f5 1519 'postal_greeting',
ddca8f33 1520 ))) {
6a488035 1521 $filterCondition = array('greeting_type' => $name);
ddca8f33
TO
1522 $greeting = CRM_Core_PseudoConstant::greeting($filterCondition);
1523 $values[$index] = $greeting[$params[$name]];
6a488035
TO
1524 }
1525 elseif ($name === 'preferred_communication_method') {
e7e657f0 1526 $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
ddca8f33
TO
1527 $compref = array();
1528 $pref = $params[$name];
6a488035
TO
1529 if (is_array($pref)) {
1530 foreach ($pref as $k => $v) {
1531 if ($v) {
1532 $compref[] = $communicationFields[$k];
1533 }
1534 }
1535 }
1536 $values[$index] = implode(',', $compref);
1537 }
1538 elseif ($name == 'contact_sub_type') {
1539 $values[$index] = implode(', ', $params[$name]);
1540 }
1541 elseif ($name == 'group') {
1542 $groups = CRM_Contact_BAO_GroupContact::getGroupList();
1543 $title = array();
1544 foreach ($params[$name] as $gId => $dontCare) {
1545 if ($dontCare) {
1546 $title[] = $groups[$gId];
1547 }
1548 }
1549 $values[$index] = implode(', ', $title);
1550 }
1551 elseif ($name == 'tag') {
1552 $entityTags = $params[$name];
ddca8f33
TO
1553 $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
1554 $title = array();
6a488035
TO
1555 if (is_array($entityTags)) {
1556 foreach ($entityTags as $tagId => $dontCare) {
1557 $title[] = $allTags[$tagId];
1558 }
1559 }
1560 $values[$index] = implode(', ', $title);
1561 }
1562 elseif ('participant_role_id' == $name OR
1563 'participant_role' == $name
1564 ) {
1565 $roles = CRM_Event_PseudoConstant::participantRole();
1566 $values[$index] = $roles[$params[$name]];
1567 }
1568 elseif ('participant_status_id' == $name OR
1569 'participant_status' == $name
1570 ) {
1571 $status = CRM_Event_PseudoConstant::participantStatus();
1572 $values[$index] = $status[$params[$name]];
1573 }
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);
1577 }
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(
ddca8f33
TO
1582 'state_province',
1583 'country',
21dfd5f5 1584 'county',
ddca8f33 1585 ))) {
6a488035 1586 $values[$index] = $params[$detailName];
ddca8f33 1587 $idx = $detailName . '_id';
6a488035
TO
1588 $values[$index] = $params[$idx];
1589 }
1590 elseif ($fieldName == 'im') {
1591 $providerName = NULL;
1592 if ($providerId = $detailName . '-provider_id') {
1593 $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders);
1594 }
1595 if ($providerName) {
1596 $values[$index] = $params[$detailName] . " (" . $providerName . ")";
1597 }
1598 else {
1599 $values[$index] = $params[$detailName];
1600 }
1601 }
1602 elseif ($fieldName == 'phone') {
1603 $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
1604 if (isset($params[$phoneExtField])) {
1605 $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
1606 }
1607 else {
1608 $values[$index] = $params[$detailName];
1609 }
1610 }
1611 else {
1612 $values[$index] = $params[$detailName];
1613 }
1614 }
1615 else {
1616 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
1617 if ($params[$name]) {
1618 $values[$index] = '[ x ]';
1619 }
1620 }
1621 else {
1622 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
1623 $query = "
5f0aaea4 1624SELECT html_type, data_type
6a488035
TO
1625FROM civicrm_custom_field
1626WHERE id = $cfID
1627";
1628 $dao = CRM_Core_DAO::executeQuery($query);
1629 $dao->fetch();
1630 $htmlType = $dao->html_type;
6a488035
TO
1631
1632 if ($htmlType == 'File') {
6a488035
TO
1633 $values[$index] = $params[$index];
1634 }
1635 else {
1636 if ($dao->data_type == 'Int' ||
1637 $dao->data_type == 'Boolean'
1638 ) {
01e21c0a
PJ
1639 $v = $params[$name];
1640 if (!CRM_Utils_System::isNull($v)) {
0479b4c8 1641 $customVal = (int) $v;
01e21c0a 1642 }
6a488035
TO
1643 }
1644 elseif ($dao->data_type == 'Float') {
0479b4c8 1645 $customVal = (float ) ($params[$name]);
6a488035
TO
1646 }
1647 elseif ($dao->data_type == 'Date') {
5f0aaea4
KJ
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
f5f3f029
KJ
1651 $customVal = $displayValue = CRM_Utils_Date::customFormat(
1652 CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull);
1653
9e7eeb0f 1654 if (!empty($params[$name . '_time'])) {
f5f3f029
KJ
1655 $customVal = $displayValue = CRM_Utils_Date::customFormat(
1656 CRM_Utils_Date::processDate($params[$name], $params[$name . '_time']),
156d7175 1657 $config->dateformatDatetime);
6a488035 1658 }
9e7eeb0f 1659 $skip = TRUE;
6a488035
TO
1660 }
1661 else {
1662 $customVal = $params[$name];
1663 }
1664 //take the custom field options
1665 $returnProperties = array($name => 1);
ddca8f33
TO
1666 $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
1667 $options = &$query->_options;
9e7eeb0f 1668 if (!$skip) {
ddca8f33 1669 $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
9e7eeb0f 1670 }
6a488035
TO
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);
1676 }
1677 //use difference of arrays
1678 if (empty($customValue) || !$customValue) {
1679 $values[$index] = '';
1680 }
1681 else {
1682 $values[$index] = $displayValue;
1683 }
1684 }
1685 }
1686 elseif ($name == 'home_URL' &&
1687 !empty($params[$name])
1688 ) {
1689 $url = CRM_Utils_System::fixURL($params[$name]);
1690 $values[$index] = "<a href=\"$url\">{$params[$name]}</a>";
1691 }
1692 elseif (in_array($name, array(
ddca8f33
TO
1693 'birth_date',
1694 'deceased_date',
21dfd5f5 1695 'participant_register_date',
ddca8f33 1696 ))) {
6a488035
TO
1697 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name]));
1698 }
1699 else {
5efc507e 1700 $values[$index] = CRM_Utils_Array::value($name, $params);
6a488035
TO
1701 }
1702 }
1703 }
1704 $profileFields[$name] = $field;
1705 }
1706 }
1707 }
1708
1709 /**
3d469574 1710 * Build the array for Additional participant's information array of primary and additional Ids.
6a488035 1711 *
d4dd1e85
TO
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.
77b97be7
EM
1722 *
1723 * @param bool $skipCancel
6a488035 1724 *
a6c01b45
CW
1725 * @return array
1726 * array of Additional participant's info OR array of Ids.
6a488035 1727 */
5396af74 1728 public static function buildCustomProfile(
ddca8f33 1729 $participantId,
6a488035 1730 $values,
0479b4c8
TO
1731 $contactId = NULL,
1732 $isTest = FALSE,
6a488035
TO
1733 $isIdsArray = FALSE,
1734 $skipCancel = TRUE
1735 ) {
1736
1737 $customProfile = $additionalIDs = array();
1738 if (!$participantId) {
1739 CRM_Core_Error::fatal(ts('Cannot find participant ID'));
1740 }
1741
1742 //set Ids of Primary Participant also.
1743 if ($isIdsArray && $contactId) {
1744 $additionalIDs[$participantId] = $contactId;
1745 }
1746
1747 //hack to skip cancelled participants, CRM-4320
1748 $where = "participant.registered_by_id={$participantId}";
1749 if ($skipCancel) {
ddca8f33 1750 $cancelStatusId = 0;
6a488035 1751 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
ddca8f33 1752 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
6a488035
TO
1753 $where .= " AND participant.status_id != {$cancelStatusId}";
1754 }
1755 $query = "
1756 SELECT participant.id, participant.contact_id
1757 FROM civicrm_participant participant
1758 WHERE {$where}";
1759
1760 $dao = CRM_Core_DAO::executeQuery($query);
1761 while ($dao->fetch()) {
1762 $additionalIDs[$dao->id] = $dao->contact_id;
1763 }
1764
1765 //return if only array is required.
1766 if ($isIdsArray && $contactId) {
1767 return $additionalIDs;
1768 }
1769
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();
1776
1777 $isCustomProfile = TRUE;
ddca8f33
TO
1778 $i = 1;
1779 $title = $groupTitles = array();
6a488035
TO
1780 foreach ($additionalIDs as $pId => $cId) {
1781 //get the params submitted by participant.
1782 $participantParams = CRM_Utils_Array::value($pId, $values['params'], array());
1783
1784 list($profilePre, $groupTitles) = self::buildCustomDisplay($preProfileID,
1785 'additionalCustomPre',
1786 $cId,
1787 $template,
1788 $pId,
1789 $isTest,
1790 $isCustomProfile,
1791 $participantParams
1792 );
1793
1794 if ($profilePre) {
1795 $profile = $profilePre;
1796 // $customProfile[$i] = array_merge( $groupTitles, $customProfile[$i] );
1797 if ($i === 1) {
1798 $title = $groupTitles;
1799 }
1800 }
1801
1802 list($profilePost, $groupTitles) = self::buildCustomDisplay($postProfileID,
1803 'additionalCustomPost',
1804 $cId,
1805 $template,
1806 $pId,
1807 $isTest,
1808 $isCustomProfile,
1809 $participantParams
1810 );
1811
1812 if ($profilePost) {
1813 if (isset($profilePre)) {
1814 $profile = array_merge($profilePre, $profilePost);
1815 if ($i === 1) {
1816 $title = array_merge($title, $groupTitles);
1817 }
1818 }
1819 else {
1820 $profile = $profilePost;
1821 if ($i === 1) {
1822 $title = $groupTitles;
1823 }
1824 }
1825 }
1826 $profiles[] = $profile;
1827 $i++;
1828 }
1829 $customProfile['title'] = $title;
1830 $customProfile['profile'] = $profiles;
1831 }
1832 }
1833
1834 return $customProfile;
1835 }
1836
1837 /* Function to retrieve all events those having location block set.
1838 *
a6c01b45
CW
1839 * @return array
1840 * array of all events.
6a488035 1841 */
0cf587a7
EM
1842 /**
1843 * @return array
1844 */
00be9182 1845 public static function getLocationEvents() {
6a488035
TO
1846 $events = array();
1847
1848 $query = "
9fab06f3 1849SELECT CONCAT_WS(' :: ' , ca.name, ca.street_address, ca.city, sp.name, ca.supplemental_address_1, ca.supplemental_address_2) title, ce.loc_block_id
6a488035
TO
1850FROM civicrm_event ce
1851INNER JOIN civicrm_loc_block lb ON ce.loc_block_id = lb.id
1852INNER JOIN civicrm_address ca ON lb.address_id = ca.id
1853LEFT JOIN civicrm_state_province sp ON ca.state_province_id = sp.id
1854ORDER BY sp.name, ca.city, ca.street_address ASC
1855";
1856
1857 $dao = CRM_Core_DAO::executeQuery($query);
1858 while ($dao->fetch()) {
1859 $events[$dao->loc_block_id] = $dao->title;
1860 }
1861
1862 return $events;
1863 }
1864
0cf587a7 1865 /**
100fef9d 1866 * @param int $locBlockId
0cf587a7
EM
1867 *
1868 * @return int|null|string
1869 */
00be9182 1870 public static function countEventsUsingLocBlockId($locBlockId) {
6a488035
TO
1871 if (!$locBlockId) {
1872 return 0;
1873 }
1874
1875 $locBlockId = CRM_Utils_Type::escape($locBlockId, 'Integer');
1876
1877 $query = "
1878SELECT count(*) FROM civicrm_event ce
1879WHERE ce.loc_block_id = $locBlockId";
1880
1881 return CRM_Core_DAO::singleValueQuery($query);
1882 }
1883
e2d09ab4 1884 /**
66f9e52b 1885 * Check if event registration is valid according to permissions AND Dates.
e2d09ab4
EM
1886 *
1887 * @param array $values
d4dd1e85 1888 * @param int $eventID
5396af74 1889 * @return bool
e2d09ab4 1890 */
00be9182 1891 public static function validRegistrationRequest($values, $eventID) {
6a488035
TO
1892 // check that the user has permission to register for this event
1893 $hasPermission = CRM_Core_Permission::event(CRM_Core_Permission::EDIT,
e2d09ab4 1894 $eventID, 'register for events'
6a488035
TO
1895 );
1896
1897 return $hasPermission && self::validRegistrationDate($values);
1898 }
1899
0cf587a7
EM
1900 /**
1901 * @param $values
1902 *
1903 * @return bool
1904 */
00be9182 1905 public static function validRegistrationDate(&$values) {
6a488035
TO
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));
ddca8f33
TO
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));
1910 $now = time();
6a488035
TO
1911 $validDate = TRUE;
1912 if ($startDate && $startDate >= $now) {
1913 $validDate = FALSE;
1914 }
8065136a 1915 if ($endDate && $endDate < $now && $eventEnd && $eventEnd < $now) {
6a488035
TO
1916 $validDate = FALSE;
1917 }
1918
1919 return $validDate;
1920 }
1921
1922 /* Function to Show - Hide the Registration Link.
1923 *
d4dd1e85
TO
1924 * @param array $values
1925 * Key/value event info.
a6c01b45
CW
1926 * @return boolean
1927 * true if allow registration otherwise false
6a488035 1928 */
0cf587a7
EM
1929 /**
1930 * @param $values
1931 *
1932 * @return bool
1933 */
00be9182 1934 public static function showHideRegistrationLink($values) {
6a488035 1935
ddca8f33
TO
1936 $session = CRM_Core_Session::singleton();
1937 $contactID = $session->get('userID');
6a488035
TO
1938 $alreadyRegistered = FALSE;
1939
1940 if ($contactID) {
1941 $params = array('contact_id' => $contactID);
1942
1943 if ($eventId = CRM_Utils_Array::value('id', $values['event'])) {
1944 $params['event_id'] = $eventId;
1945 }
1946 if ($roleId = CRM_Utils_Array::value('default_role_id', $values['event'])) {
1947 $params['role_id'] = $roleId;
1948 }
1949 $alreadyRegistered = self::checkRegistration($params);
1950 }
1951
a7488080 1952 if (!empty($values['event']['allow_same_participant_emails']) ||
6a488035
TO
1953 !$alreadyRegistered
1954 ) {
1955 return TRUE;
1956 }
1957 return FALSE;
1958 }
1959
1960 /* Function to check if given contact is already registered.
1961 *
d4dd1e85
TO
1962 * @param array $params
1963 * Key/value participant info.
a6c01b45 1964 * @return boolean
6a488035 1965 */
0cf587a7 1966 /**
c490a46a 1967 * @param array $params
0cf587a7
EM
1968 *
1969 * @return bool
1970 */
00be9182 1971 public static function checkRegistration($params) {
6a488035 1972 $alreadyRegistered = FALSE;
a7488080 1973 if (empty($params['contact_id'])) {
6a488035
TO
1974 return $alreadyRegistered;
1975 }
1976
1977 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
1978
1979 $participant = new CRM_Event_DAO_Participant();
1980 $participant->copyValues($params);
1981
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;
1987 }
1988
1989 return $alreadyRegistered;
1990 }
1991
1992 /**
66f9e52b 1993 * Make sure that the user has permission to access this event.
6a488035 1994 *
c490a46a 1995 * @param int $eventId
77b97be7
EM
1996 * @param int $type
1997 *
a6c01b45
CW
1998 * @return string
1999 * the permission that the user has (or null)
6a488035 2000 */
00be9182 2001 public static function checkPermission($eventId = NULL, $type = CRM_Core_Permission::VIEW) {
6a488035
TO
2002 static $permissions = NULL;
2003
2004 if (empty($permissions)) {
2005 $allEvents = CRM_Event_PseudoConstant::event(NULL, TRUE);
2006 $createdEvents = array();
2007
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}"));
2011 }
2012
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);
2017 }
2018 else {
d596ca09 2019 $permissions[CRM_Core_Permission::EDIT] = CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_event', $allEvents, $createdEvents);
6a488035
TO
2020 }
2021
2022 if (CRM_Core_Permission::check('edit all events')) {
2023 $permissions[CRM_Core_Permission::VIEW] = array_keys($allEvents);
2024 }
2025 else {
2026 if (CRM_Core_Permission::check('access CiviEvent') &&
2027 CRM_Core_Permission::check('view event participants')
2028 ) {
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);
2033 }
d596ca09 2034 $permissions[CRM_Core_Permission::VIEW] = CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_event', $allEvents, $createdEvents);
6a488035
TO
2035 }
2036
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]
2044 );
2045 }
2046 }
2047
2048 if ($eventId) {
2049 return in_array($eventId, $permissions[$type]) ? TRUE : FALSE;
2050 }
2051
2052 return $permissions;
2053 }
2054
2055 /**
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
2058 *
d4dd1e85
TO
2059 * @param int $eventId
2060 * The id of the event.
6a488035 2061 *
a6c01b45
CW
2062 * @return array
2063 * an array of email ids
6a488035 2064 */
00be9182 2065 public static function getFromEmailIds($eventId = NULL) {
6a488035
TO
2066 $fromEmailValues['from_email_id'] = CRM_Core_BAO_Email::getFromEmail();
2067
2068 if ($eventId) {
2069 // add the email id configured for the event
ddca8f33 2070 $params = array('id' => $eventId);
6a488035 2071 $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
ddca8f33 2072 $eventEmail = array();
6a488035
TO
2073
2074 CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
8cc574cf 2075 if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
6a488035
TO
2076 $eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
2077
2078 $fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
0479b4c8 2079 $fromEmailId = array(
ddca8f33 2080 'cc' => CRM_Utils_Array::value('cc_confirm', $eventEmail),
6a488035
TO
2081 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventEmail),
2082 );
2083 $fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
2084 }
2085 }
2086
2087 return $fromEmailValues;
2088 }
2089
2090 /**
100fef9d 2091 * Calculate event total seats occupied.
6a488035 2092 *
d4dd1e85
TO
2093 * @param int $eventId
2094 * Event id.
2095 * @param sting $extraWhereClause
2096 * Extra filter on participants.
6a488035 2097 *
a6c01b45
CW
2098 * @return int
2099 * event total seats w/ given criteria.
6a488035 2100 */
00be9182 2101 public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
6a488035
TO
2102 if (empty($eventId)) {
2103 return 0;
2104 }
2105
2106 $extraWhereClause = trim($extraWhereClause);
2107 if (!empty($extraWhereClause)) {
2108 $extraWhereClause = " AND ( {$extraWhereClause} )";
2109 }
2110
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.
2116
2117 $query = "
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
2124INNER JOIN civicrm_contact contact ON ( contact.id = participant.contact_id AND contact.is_deleted = 0 )
2125INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
2126LEFT JOIN civicrm_line_item lineItem ON ( lineItem.entity_id = participant.id
2127 AND lineItem.entity_table = 'civicrm_participant' )
2128LEFT JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id AND value.count )
2129 WHERE ( participant.event_id = %1 )
4962bc92 2130 AND participant.is_test = 0
6a488035
TO
2131 {$extraWhereClause}
2132 GROUP BY participant.event_id";
2133
0479b4c8 2134 return (int) CRM_Core_DAO::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
6a488035
TO
2135 }
2136
c490a46a 2137 /**
66f9e52b 2138 * Retrieve event template default values to be set.
6a488035
TO
2139 * as default values for current new event.
2140 *
d4dd1e85
TO
2141 * @param int $templateId
2142 * Event template id.
6a488035 2143 *
a6c01b45 2144 * @return array
16b10e64 2145 * Array of custom data defaults.
0cf587a7 2146 */
00be9182 2147 public static function getTemplateDefaultValues($templateId) {
6a488035
TO
2148 $defaults = array();
2149 if (!$templateId) {
2150 return $defaults;
2151 }
2152
2153 $templateParams = array('id' => $templateId);
2154 CRM_Event_BAO_Event::retrieve($templateParams, $defaults);
2155 $fieldsToExclude = array(
2156 'id',
2157 'default_fee_id',
2158 'default_discount_fee_id',
2159 'created_date',
2160 'created_id',
2161 'is_template',
2162 'template_title',
2163 );
2164 $defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
2165 return $defaults;
2166 }
2167
0cf587a7 2168 /**
100fef9d 2169 * @param int $event_id
0cf587a7
EM
2170 *
2171 * @return object
2172 */
00be9182 2173 public static function get_sub_events($event_id) {
6a488035
TO
2174 $params = array('parent_event_id' => $event_id);
2175 $defaults = array();
2176 return CRM_Event_BAO_Event::retrieve($params, $defaults);
2177 }
49f68a22 2178
c490a46a 2179 /**
66f9e52b 2180 * Update the Campaign Id of all the participants of the given event.
49f68a22 2181 *
d4dd1e85
TO
2182 * @param int $eventID
2183 * Event id.
2184 * @param int $eventCampaignID
2185 * Campaign id of that event.
0cf587a7 2186 */
00be9182 2187 public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
49f68a22
DL
2188 $params = array();
2189 $params[1] = array($eventID, 'Integer');
2190
ddca8f33 2191 if (empty($eventCampaignID)) {
49f68a22
DL
2192 $query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
2193 }
2194 else {
2195 $query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
2196 $params[2] = array($eventCampaignID, 'Integer');
2197 }
2198 CRM_Core_DAO::executeQuery($query, $params);
2199 }
e1462487
CW
2200
2201 /**
2202 * Get options for a given field.
2203 * @see CRM_Core_DAO::buildOptions
2204 *
d4dd1e85 2205 * @param string $fieldName
ddca8f33
TO
2206 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2207 * @param array $props : whatever is known about this dao object
e1462487
CW
2208 *
2209 * @return array|bool
2210 */
2211 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2212 $params = 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();
0479b4c8 2218
5396af74 2219 break;
e1462487
CW
2220 }
2221 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
2222 }
d75f2f47
EM
2223
2224}