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