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