Set version to 5.3.alpha1
[civicrm-core.git] / CRM / Event / BAO / Participant.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
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
e70a7fc0 27 */
6a488035
TO
28
29/**
6a488035 30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 */
33class CRM_Event_BAO_Participant extends CRM_Event_DAO_Participant {
34
35 /**
66f9e52b 36 * Static field for all the participant information that we can potentially import.
6a488035
TO
37 *
38 * @var array
6a488035
TO
39 */
40 static $_importableFields = NULL;
41
42 /**
66f9e52b 43 * Static field for all the participant information that we can potentially export.
6a488035
TO
44 *
45 * @var array
6a488035
TO
46 */
47 static $_exportableFields = NULL;
48
49 /**
66f9e52b 50 * Static array for valid status transitions rules.
6a488035
TO
51 *
52 * @var array
6a488035
TO
53 */
54 static $_statusTransitionsRules = array(
55 'Pending from pay later' => array('Registered', 'Cancelled'),
56 'Pending from incomplete transaction' => array('Registered', 'Cancelled'),
57 'On waitlist' => array('Cancelled', 'Pending from waitlist'),
58 'Pending from waitlist' => array('Registered', 'Cancelled'),
59 'Awaiting approval' => array('Cancelled', 'Pending from approval'),
60 'Pending from approval' => array('Registered', 'Cancelled'),
61 );
0cf587a7
EM
62
63 /**
0cf587a7 64 */
00be9182 65 public function __construct() {
6a488035
TO
66 parent::__construct();
67 }
68
69 /**
66f9e52b 70 * Takes an associative array and creates a participant object.
6a488035
TO
71 *
72 * the function extract all the params it needs to initialize the create a
73 * participant object. the params array could contain additional unused name/value
74 * pairs
75 *
d4dd1e85
TO
76 * @param array $params
77 * (reference ) an assoc array of name/value pairs.
77035e4b 78 *
16b10e64 79 * @return CRM_Event_BAO_Participant
6a488035 80 */
00be9182 81 public static function &add(&$params) {
6a488035 82
a7488080 83 if (!empty($params['id'])) {
6a488035
TO
84 CRM_Utils_Hook::pre('edit', 'Participant', $params['id'], $params);
85 }
86 else {
87 CRM_Utils_Hook::pre('create', 'Participant', NULL, $params);
88 }
89
90 // converting dates to mysql format
a7488080 91 if (!empty($params['register_date'])) {
6a488035
TO
92 $params['register_date'] = CRM_Utils_Date::isoToMysql($params['register_date']);
93 }
94
a7488080 95 if (!empty($params['participant_fee_amount'])) {
6a488035
TO
96 $params['participant_fee_amount'] = CRM_Utils_Rule::cleanMoney($params['participant_fee_amount']);
97 }
98
a7488080 99 if (!empty($params['fee_amount'])) {
6a488035
TO
100 $params['fee_amount'] = CRM_Utils_Rule::cleanMoney($params['fee_amount']);
101 }
102
7577274a 103 // ensure that role ids are encoded as a string
3cef9954 104 if (isset($params['role_id']) && is_array($params['role_id'])) {
653cbe46 105 if (in_array(key($params['role_id']), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
e51b7372 106 $op = key($params['role_id']);
107 $params['role_id'] = $params['role_id'][$op];
108 }
774e09ad 109 else {
110 $params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
111 }
7577274a
KJ
112 }
113
2177d15c 114 $participantBAO = new CRM_Event_BAO_Participant();
a7488080 115 if (!empty($params['id'])) {
6a488035
TO
116 $participantBAO->id = CRM_Utils_Array::value('id', $params);
117 $participantBAO->find(TRUE);
118 $participantBAO->register_date = CRM_Utils_Date::isoToMysql($participantBAO->register_date);
119 }
120
121 $participantBAO->copyValues($params);
122
123 //CRM-6910
124 //1. If currency present, it should be valid one.
125 //2. We should have currency when amount is not null.
126 $currency = $participantBAO->fee_currency;
127 if ($currency ||
128 !CRM_Utils_System::isNull($participantBAO->fee_amount)
129 ) {
130 if (!CRM_Utils_Rule::currencyCode($currency)) {
131 $config = CRM_Core_Config::singleton();
132 $currency = $config->defaultCurrency;
133 }
134 }
135 $participantBAO->fee_currency = $currency;
136
137 $participantBAO->save();
138
139 $session = CRM_Core_Session::singleton();
140
2b68a50c 141 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
6a488035 142
a7488080 143 if (!empty($params['id'])) {
6a488035
TO
144 CRM_Utils_Hook::post('edit', 'Participant', $participantBAO->id, $participantBAO);
145 }
146 else {
147 CRM_Utils_Hook::post('create', 'Participant', $participantBAO->id, $participantBAO);
148 }
149
150 return $participantBAO;
151 }
152
153 /**
154 * Given the list of params in the params array, fetch the object
155 * and store the values in the values array
156 *
d4dd1e85
TO
157 * @param array $params
158 * Input parameters to find object.
159 * @param array $values
160 * Output values of the object.
6a488035 161 *
77035e4b
EM
162 * @param $ids
163 *
6a488035 164 * @return CRM_Event_BAO_Participant|null the found object or null
6a488035 165 */
00be9182 166 public static function getValues(&$params, &$values, &$ids) {
6a488035
TO
167 if (empty($params)) {
168 return NULL;
169 }
170 $participant = new CRM_Event_BAO_Participant();
171 $participant->copyValues($params);
172 $participant->find();
173 $participants = array();
174 while ($participant->fetch()) {
175 $ids['participant'] = $participant->id;
176 CRM_Core_DAO::storeValues($participant, $values[$participant->id]);
177 $participants[$participant->id] = $participant;
178 }
179 return $participants;
180 }
181
182 /**
66f9e52b 183 * Takes an associative array and creates a participant object.
6a488035 184 *
d4dd1e85
TO
185 * @param array $params
186 * (reference ) an assoc array of name/value pairs.
77035e4b 187 *
16b10e64 188 * @return CRM_Event_BAO_Participant
6a488035 189 */
00be9182 190 public static function create(&$params) {
6a488035
TO
191
192 $transaction = new CRM_Core_Transaction();
193 $status = NULL;
194
a7488080 195 if (!empty($params['id'])) {
6a488035
TO
196 $status = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
197 }
198
199 $participant = self::add($params);
200
201 if (is_a($participant, 'CRM_Core_Error')) {
202 $transaction->rollback();
203 return $participant;
204 }
205
206 if ((!CRM_Utils_Array::value('id', $params)) ||
9af2925b 207 (isset($params['status_id']) && $params['status_id'] != $status)
6a488035
TO
208 ) {
209 CRM_Activity_BAO_Activity::addActivity($participant);
210 }
211
212 //CRM-5403
213 //for update mode
214 if (self::isPrimaryParticipant($participant->id) && $status) {
215 self::updateParticipantStatus($participant->id, $status, $participant->status_id);
216 }
217
218 $session = CRM_Core_Session::singleton();
219 $id = $session->get('userID');
220 if (!$id) {
edf1b210 221 $id = CRM_Utils_Array::value('contact_id', $params);
6a488035
TO
222 }
223
224 // add custom field values
a7488080 225 if (!empty($params['custom']) &&
6a488035
TO
226 is_array($params['custom'])
227 ) {
228 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_participant', $participant->id);
229 }
230
231 //process note, CRM-7634
232 $noteId = NULL;
a7488080 233 if (!empty($params['id'])) {
6a488035
TO
234 $note = CRM_Core_BAO_Note::getNote($params['id'], 'civicrm_participant');
235 $noteId = key($note);
236 }
237 $noteValue = NULL;
238 $hasNoteField = FALSE;
239 foreach (array(
ddca8f33 240 'note',
21dfd5f5 241 'participant_note',
ddca8f33 242 ) as $noteFld) {
6a488035
TO
243 if (array_key_exists($noteFld, $params)) {
244 $noteValue = $params[$noteFld];
245 $hasNoteField = TRUE;
246 break;
247 }
248 }
249 if ($noteId || $noteValue) {
250 if ($noteValue) {
251 $noteParams = array(
252 'entity_table' => 'civicrm_participant',
253 'note' => $noteValue,
254 'entity_id' => $participant->id,
255 'contact_id' => $id,
256 'modified_date' => date('Ymd'),
257 );
258 $noteIDs = array();
259 if ($noteId) {
260 $noteIDs['id'] = $noteId;
261 }
262 CRM_Core_BAO_Note::add($noteParams, $noteIDs);
263 }
264 elseif ($noteId && $hasNoteField) {
265 CRM_Core_BAO_Note::del($noteId, FALSE);
266 }
267 }
268
269 // Log the information on successful add/edit of Participant data.
270 $logParams = array(
271 'entity_table' => 'civicrm_participant',
272 'entity_id' => $participant->id,
273 'data' => CRM_Event_PseudoConstant::participantStatus($participant->status_id),
274 'modified_id' => $id,
275 'modified_date' => date('Ymd'),
276 );
277
278 CRM_Core_BAO_Log::add($logParams);
279
280 $params['participant_id'] = $participant->id;
281
282 $transaction->commit();
283
284 // do not add to recent items for import, CRM-4399
a7488080 285 if (empty($params['skipRecentView'])) {
6a488035
TO
286
287 $url = CRM_Utils_System::url('civicrm/contact/view/participant',
288 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
289 );
290
291 $recentOther = array();
292 if (CRM_Core_Permission::check('edit event participants')) {
293 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
294 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
295 );
296 }
297 if (CRM_Core_Permission::check('delete in CiviEvent')) {
298 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
299 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
300 );
301 }
302
303 $participantRoles = CRM_Event_PseudoConstant::participantRole();
304
305 if ($participant->role_id) {
306 $role = explode(CRM_Core_DAO::VALUE_SEPARATOR, $participant->role_id);
307
308 foreach ($role as & $roleValue) {
309 if (isset($roleValue)) {
310 $roleValue = $participantRoles[$roleValue];
311 }
312 }
313 $roles = implode(', ', $role);
314 }
315
316 $roleString = empty($roles) ? '' : $roles;
317 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $participant->event_id, 'title');
318 $title = CRM_Contact_BAO_Contact::displayName($participant->contact_id) . ' (' . $roleString . ' - ' . $eventTitle . ')';
319
320 // add the recently created Participant
321 CRM_Utils_Recent::add($title,
322 $url,
323 $participant->id,
324 'Participant',
325 $participant->contact_id,
326 NULL,
327 $recentOther
328 );
329 }
330
331 return $participant;
332 }
333
334 /**
66f9e52b 335 * Check whether the event is full for participation and return as.
6a488035
TO
336 * per requirements.
337 *
d4dd1e85
TO
338 * @param int $eventId
339 * Event id.
340 * @param bool $returnEmptySeats
341 * Are we require number if empty seats.
342 * @param bool $includeWaitingList
343 * Consider waiting list in event full.
6a488035
TO
344 * calculation or not. (it is for cron job purpose)
345 *
77035e4b
EM
346 * @param bool $returnWaitingCount
347 * @param bool $considerTestParticipant
6a488035 348 *
72b3a70c
CW
349 * @return bool|int|null|string
350 * 1. false => If event having some empty spaces.
6a488035 351 */
2da40d21 352 public static function eventFull(
6a488035
TO
353 $eventId,
354 $returnEmptySeats = FALSE,
355 $includeWaitingList = TRUE,
356 $returnWaitingCount = FALSE,
357 $considerTestParticipant = FALSE
358 ) {
359 $result = NULL;
360 if (!$eventId) {
361 return $result;
362 }
363
364 // consider event is full when.
365 // 1. (count(is_counted) >= event_size) or
366 // 2. (count(participants-with-status-on-waitlist) > 0)
367 // It might be case there are some empty spaces and still event
368 // is full, as waitlist might represent group require spaces > empty.
369
ddca8f33
TO
370 $participantRoles = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
371 $countedStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
372 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
6a488035
TO
373 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
374
375 //when we do require only waiting count don't consider counted.
376 if (!$returnWaitingCount && !empty($countedStatuses)) {
377 $allStatusIds = array_keys($countedStatuses);
378 }
379
380 $where = array(' event.id = %1 ');
381 if (!$considerTestParticipant) {
382 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
383 }
384 if (!empty($participantRoles)) {
0906de17
MM
385 $escapedRoles = array();
386 foreach (array_keys($participantRoles) as $participantRole) {
387 $escapedRoles[] = CRM_Utils_Type::escape($participantRole, 'String');
388 }
389
aba574d4 390 $where[] = " participant.role_id IN ( '" . implode("', '", $escapedRoles) . "' ) ";
6a488035
TO
391 }
392
393 $eventParams = array(1 => array($eventId, 'Positive'));
394
395 //in case any waiting, straight forward event is full.
396 if ($includeWaitingList && $onWaitlistStatusId) {
397
398 //build the where clause.
ddca8f33
TO
399 $whereClause = ' WHERE ' . implode(' AND ', $where);
400 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
6a488035
TO
401 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
402
403 $query = "
404 SELECT participant.id id,
405 event.event_full_text as event_full_text
406 FROM civicrm_participant participant
407INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
408 {$whereClause}";
409
92d6c5f5 410 $eventFullText = ts('This event is full.');
6a488035
TO
411 $participants = CRM_Core_DAO::executeQuery($query, $eventParams);
412 while ($participants->fetch()) {
413 //oops here event is full and we don't want waiting count.
414 if ($returnWaitingCount) {
415 return CRM_Event_BAO_Event::eventTotalSeats($eventId, $eventSeatsWhere);
416 }
417 else {
418 return ($participants->event_full_text) ? $participants->event_full_text : $eventFullText;
419 }
420 }
421 }
422
423 //consider only counted participants.
ddca8f33
TO
424 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
425 $whereClause = ' WHERE ' . implode(' AND ', $where);
6a488035
TO
426 $eventSeatsWhere = implode(' AND ', $where);
427
428 $query = "
429 SELECT participant.id id,
430 event.event_full_text as event_full_text,
431 event.max_participants as max_participants
432 FROM civicrm_participant participant
433INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
434 {$whereClause}";
435
436 $eventMaxSeats = NULL;
92d6c5f5 437 $eventFullText = ts('This event is full.');
ddca8f33 438 $participants = CRM_Core_DAO::executeQuery($query, $eventParams);
6a488035
TO
439 while ($participants->fetch()) {
440 if ($participants->event_full_text) {
441 $eventFullText = $participants->event_full_text;
442 }
443 $eventMaxSeats = $participants->max_participants;
444 //don't have limit for event seats.
445 if ($participants->max_participants == NULL) {
446 return $result;
447 }
448 }
449
450 //get the total event seats occupied by these participants.
451 $eventRegisteredSeats = CRM_Event_BAO_Event::eventTotalSeats($eventId, $eventSeatsWhere);
452
453 if ($eventRegisteredSeats) {
454 if ($eventRegisteredSeats >= $eventMaxSeats) {
455 $result = $eventFullText;
456 }
457 elseif ($returnEmptySeats) {
458 $result = $eventMaxSeats - $eventRegisteredSeats;
459 }
460 return $result;
461 }
462 else {
463 $query = '
464SELECT event.event_full_text,
465 event.max_participants
466 FROM civicrm_event event
467 WHERE event.id = %1';
468 $event = CRM_Core_DAO::executeQuery($query, $eventParams);
469 while ($event->fetch()) {
470 $eventFullText = $event->event_full_text;
471 $eventMaxSeats = $event->max_participants;
472 }
473 }
474
475 // no limit for registration.
476 if ($eventMaxSeats == NULL) {
477 return $result;
478 }
479 if ($eventMaxSeats) {
480 return ($returnEmptySeats) ? (int) $eventMaxSeats : FALSE;
481 }
482
31312bdc 483 return $eventFullText;
6a488035
TO
484 }
485
486 /**
487 * Return the array of all price set field options,
488 * with total participant count that field going to carry.
489 *
d4dd1e85
TO
490 * @param int $eventId
491 * Event id.
492 * @param array $skipParticipantIds
493 * An array of participant ids those we should skip.
77035e4b
EM
494 * @param bool $considerCounted
495 * @param bool $considerWaiting
496 * @param bool $considerTestParticipants
497 *
a6c01b45
CW
498 * @return array
499 * an array of each option id and total count
6a488035 500 */
2da40d21 501 public static function priceSetOptionsCount(
6a488035
TO
502 $eventId,
503 $skipParticipantIds = array(),
504 $considerCounted = TRUE,
505 $considerWaiting = TRUE,
506 $considerTestParticipants = FALSE
507 ) {
508 $optionsCount = array();
509 if (!$eventId) {
510 return $optionsCount;
511 }
512
513 $allStatusIds = array();
514 if ($considerCounted) {
515 $countedStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
516 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
517 }
518 if ($considerWaiting) {
519 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
520 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
521 }
522 $statusIdClause = NULL;
523 if (!empty($allStatusIds)) {
524 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
525 }
526
527 $isTestClause = NULL;
528 if (!$considerTestParticipants) {
529 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
530 }
531
532 $skipParticipantClause = NULL;
533 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
534 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
535 }
536
537 $sql = "
538 SELECT line.id as lineId,
539 line.entity_id as entity_id,
540 line.qty,
541 value.id as valueId,
542 value.count,
543 field.html_type
544 FROM civicrm_line_item line
545INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
546 AND participant.id = line.entity_id )
547INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
548INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
549 WHERE participant.event_id = %1
0d9c7c6d 550 AND line.qty > 0
6a488035
TO
551 {$statusIdClause}
552 {$isTestClause}
553 {$skipParticipantClause}";
554
555 $lineItem = CRM_Core_DAO::executeQuery($sql, array(1 => array($eventId, 'Positive')));
556 while ($lineItem->fetch()) {
557 $count = $lineItem->count;
558 if (!$count) {
559 $count = 1;
560 }
561 if ($lineItem->html_type == 'Text') {
562 $count *= $lineItem->qty;
563 }
564 $optionsCount[$lineItem->valueId] = $count + CRM_Utils_Array::value($lineItem->valueId, $optionsCount, 0);
565 }
566
567 return $optionsCount;
568 }
569
570 /**
571 * Get the empty spaces for event those we can allocate
572 * to pending participant to become confirm.
573 *
d4dd1e85
TO
574 * @param int $eventId
575 * Event id.
6a488035 576 *
a6c01b45
CW
577 * @return int
578 * $spaces Number of Empty Seats/null.
6a488035 579 */
00be9182 580 public static function pendingToConfirmSpaces($eventId) {
6a488035
TO
581 $emptySeats = 0;
582 if (!$eventId) {
583 return $emptySeats;
584 }
585
586 $positiveStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Positive'");
587 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
588
589 $query = "
590 SELECT count(participant.id) as registered,
591 civicrm_event.max_participants
592 FROM civicrm_participant participant, civicrm_event
593 WHERE participant.event_id = {$eventId}
594 AND civicrm_event.id = participant.event_id
595 AND participant.status_id IN {$statusIds}
596GROUP BY participant.event_id
597";
598 $dao = CRM_Core_DAO::executeQuery($query);
599 if ($dao->fetch()) {
600
601 //unlimited space.
602 if ($dao->max_participants == NULL || $dao->max_participants <= 0) {
603 return NULL;
604 }
605
606 //no space.
607 if ($dao->registered >= $dao->max_participants) {
608 return $emptySeats;
609 }
610
611 //difference.
612 return $dao->max_participants - $dao->registered;
613 }
614
615 //space in case no registeration yet.
616 return CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
617 }
618
619 /**
66f9e52b 620 * Combine all the importable fields from the lower levels object.
6a488035 621 *
77035e4b
EM
622 * @param string $contactType
623 * @param bool $status
624 * @param bool $onlyParticipant
e9ff5391 625 * @param bool $checkPermission
626 * Is this a permissioned retrieval?
77035e4b 627 *
a6c01b45
CW
628 * @return array
629 * array of importable Fields
6a488035 630 */
e9ff5391 631 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE) {
6a488035
TO
632 if (!self::$_importableFields) {
633 if (!$onlyParticipant) {
634 if (!$status) {
635 $fields = array('' => array('title' => ts('- do not import -')));
636 }
637 else {
638 $fields = array('' => array('title' => ts('- Participant Fields -')));
639 }
640 }
641 else {
642 $fields = array();
643 }
644
645 $tmpFields = CRM_Event_DAO_Participant::import();
646
647 $note = array(
648 'participant_note' => array(
3cb8f9b2 649 'title' => ts('Participant Note'),
6a488035
TO
650 'name' => 'participant_note',
651 'headerPattern' => '/(participant.)?note$/i',
672b875d 652 'data_type' => CRM_Utils_Type::T_TEXT,
21dfd5f5 653 ),
ddca8f33 654 );
6a488035 655
3cb8f9b2
CW
656 // Split status and status id into 2 fields
657 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
6a488035
TO
658 $participantStatus = array(
659 'participant_status' => array(
3cb8f9b2 660 'title' => ts('Participant Status'),
6a488035
TO
661 'name' => 'participant_status',
662 'data_type' => CRM_Utils_Type::T_STRING,
21dfd5f5 663 ),
ddca8f33 664 );
3cb8f9b2 665 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
6a488035 666
3cb8f9b2
CW
667 // Split role and role id into 2 fields
668 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
6a488035
TO
669 $participantRole = array(
670 'participant_role' => array(
3cb8f9b2 671 'title' => ts('Participant Role'),
6a488035
TO
672 'name' => 'participant_role',
673 'data_type' => CRM_Utils_Type::T_STRING,
21dfd5f5 674 ),
ddca8f33 675 );
3cb8f9b2 676 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
6a488035
TO
677
678 $eventType = array(
679 'event_type' => array(
3cb8f9b2 680 'title' => ts('Event Type'),
6a488035
TO
681 'name' => 'event_type',
682 'data_type' => CRM_Utils_Type::T_STRING,
21dfd5f5 683 ),
ddca8f33 684 );
6a488035
TO
685
686 $tmpContactField = $contactFields = array();
0479b4c8 687 $contactFields = array();
6a488035
TO
688 if (!$onlyParticipant) {
689 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
690
691 // Using new Dedupe rule.
692 $ruleParams = array(
693 'contact_type' => $contactType,
ddca8f33 694 'used' => 'Unsupervised',
6a488035
TO
695 );
696 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
697
698 if (is_array($fieldsArray)) {
699 foreach ($fieldsArray as $value) {
700 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
701 $value,
702 'id',
703 'column_name'
704 );
705 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
706 $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
707 if (!$status) {
708 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
709 }
710 else {
711 $title = $tmpContactField[trim($value)]['title'];
712 }
713
714 $tmpContactField[trim($value)]['title'] = $title;
715 }
716 }
717 }
718 $extIdentifier = CRM_Utils_Array::value('external_identifier', $contactFields);
719 if ($extIdentifier) {
720 $tmpContactField['external_identifier'] = $extIdentifier;
6c552737 721 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array::value('title', $extIdentifier) . ' (match to contact)';
6a488035 722 }
6c552737 723 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
6a488035 724
6a488035
TO
725 $fields = array_merge($fields, $tmpContactField);
726 $fields = array_merge($fields, $tmpFields);
727 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
e9ff5391 728 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
6a488035
TO
729
730 self::$_importableFields = $fields;
731 }
732
733 return self::$_importableFields;
734 }
735
736 /**
e9ff5391 737 * Combine all the exportable fields from the lower level objects.
738 *
739 * @param bool $checkPermission
6a488035 740 *
a6c01b45
CW
741 * @return array
742 * array of exportable Fields
6a488035 743 */
e9ff5391 744 public static function &exportableFields($checkPermission = TRUE) {
6a488035
TO
745 if (!self::$_exportableFields) {
746 if (!self::$_exportableFields) {
747 self::$_exportableFields = array();
748 }
749
6a488035 750 $participantFields = CRM_Event_DAO_Participant::export();
e51b7372 751 $eventFields = CRM_Event_DAO_Event::export();
6a488035 752 $noteField = array(
0479b4c8 753 'participant_note' => array(
e300cf31 754 'title' => ts('Participant Note'),
6a488035 755 'name' => 'participant_note',
e51b7372 756 'type' => CRM_Utils_Type::T_STRING,
a1a2a83d
TO
757 ),
758 );
6a488035 759
a1a2a83d 760 $participantStatus = array(
0479b4c8 761 'participant_status' => array(
e300cf31 762 'title' => ts('Participant Status (label)'),
6a488035 763 'name' => 'participant_status',
e51b7372 764 'type' => CRM_Utils_Type::T_STRING,
a1a2a83d
TO
765 ),
766 );
6a488035 767
a1a2a83d 768 $participantRole = array(
0479b4c8 769 'participant_role' => array(
e300cf31 770 'title' => ts('Participant Role (label)'),
6a488035 771 'name' => 'participant_role',
e51b7372 772 'type' => CRM_Utils_Type::T_STRING,
a1a2a83d
TO
773 ),
774 );
8b8fa582 775
1fbc48b0
CW
776 $participantFields['participant_status_id']['title'] .= ' (ID)';
777 $participantFields['participant_role_id']['title'] .= ' (ID)';
778
a1a2a83d 779 $discountFields = CRM_Core_DAO_Discount::export();
6a488035 780
a1a2a83d 781 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
6a488035 782
a1a2a83d 783 // add custom data
e9ff5391 784 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
a1a2a83d 785 self::$_exportableFields = $fields;
6a488035
TO
786 }
787
788 return self::$_exportableFields;
789 }
790
791 /**
100fef9d 792 * Get the event name/sort name for a particular participation / participant
6a488035 793 *
d4dd1e85
TO
794 * @param int $participantId
795 * Id of the participant.
6a488035 796 *
a6c01b45
CW
797 * @return array
798 * associated array with sort_name and event title
6a488035 799 */
00be9182 800 public static function participantDetails($participantId) {
6a488035
TO
801 $query = "
802SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
803FROM civicrm_participant
804 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
805 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
806WHERE civicrm_participant.id = {$participantId}
807";
33621c4f 808 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
809
810 $details = array();
811 while ($dao->fetch()) {
ddca8f33 812 $details['name'] = $dao->name;
6a488035 813 $details['title'] = $dao->title;
ddca8f33 814 $details['cid'] = $dao->cid;
6a488035
TO
815 }
816
817 return $details;
818 }
819
820 /**
821 * Get the values for pseudoconstants for name->value and reverse.
822 *
d4dd1e85
TO
823 * @param array $defaults
824 * (reference) the default values, some of which need to be resolved.
825 * @param bool $reverse
826 * True if we want to resolve the values in the reverse direction (value -> name).
6a488035 827 */
00be9182 828 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
6a488035
TO
829 self::lookupValue($defaults, 'event', CRM_Event_PseudoConstant::event(), $reverse);
830 self::lookupValue($defaults, 'status', CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'), $reverse);
831 self::lookupValue($defaults, 'role', CRM_Event_PseudoConstant::participantRole(), $reverse);
832 }
833
834 /**
3bdf1f3a 835 * Convert associative array names to values and vice-versa.
6a488035
TO
836 *
837 * This function is used by both the web form layer and the api. Note that
838 * the api needs the name => value conversion, also the view layer typically
839 * requires value => name conversion
ad37ac8e 840 *
841 * @param array $defaults
842 * @param string $property
843 * @param string $lookup
844 * @param bool $reverse
845 *
846 * @return bool
6a488035 847 */
00be9182 848 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
6a488035
TO
849 $id = $property . '_id';
850
851 $src = $reverse ? $property : $id;
852 $dst = $reverse ? $id : $property;
853
854 if (!array_key_exists($src, $defaults)) {
855 return FALSE;
856 }
857
858 $look = $reverse ? array_flip($lookup) : $lookup;
859
860 if (is_array($look)) {
861 if (!array_key_exists($defaults[$src], $look)) {
862 return FALSE;
863 }
864 }
865 $defaults[$dst] = $look[$defaults[$src]];
866 return TRUE;
867 }
868
869 /**
3bdf1f3a 870 * Delete the records that are associated with this participation.
6a488035 871 *
d4dd1e85
TO
872 * @param int $id
873 * Id of the participation to delete.
6a488035 874 *
3bdf1f3a 875 * @return \CRM_Event_DAO_Participant
6a488035 876 */
00be9182 877 public static function deleteParticipant($id) {
a60c0bc8
SL
878 $participant = new CRM_Event_DAO_Participant();
879 $participant->id = $id;
880 if (!$participant->find()) {
881 return FALSE;
882 }
6a488035
TO
883 CRM_Utils_Hook::pre('delete', 'Participant', $id, CRM_Core_DAO::$_nullArray);
884
885 $transaction = new CRM_Core_Transaction();
886
887 //delete activity record
888 $params = array(
889 'source_record_id' => $id,
890 // activity type id for event registration
891 'activity_type_id' => 5,
892 );
893
894 CRM_Activity_BAO_Activity::deleteActivity($params);
895
896 // delete the participant payment record
897 // we need to do this since the cascaded constraints
898 // dont work with join tables
899 $p = array('participant_id' => $id);
900 CRM_Event_BAO_ParticipantPayment::deleteParticipantPayment($p);
901
902 // cleanup line items.
ddca8f33
TO
903 $participantsId = array();
904 $participantsId = self::getAdditionalParticipantIds($id);
6a488035
TO
905 $participantsId[] = $id;
906 CRM_Price_BAO_LineItem::deleteLineItems($participantsId, 'civicrm_participant');
907
908 //delete note when participant deleted.
909 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_participant');
910 $noteId = key($note);
911 if ($noteId) {
912 CRM_Core_BAO_Note::del($noteId, FALSE);
913 }
914
6a488035
TO
915 $participant->delete();
916
917 $transaction->commit();
918
919 CRM_Utils_Hook::post('delete', 'Participant', $participant->id, $participant);
920
921 // delete the recently created Participant
922 $participantRecent = array(
923 'id' => $id,
924 'type' => 'Participant',
925 );
926
927 CRM_Utils_Recent::del($participantRecent);
928
929 return $participant;
930 }
931
932 /**
66f9e52b 933 * Checks duplicate participants.
6a488035 934 *
d4dd1e85
TO
935 * @param array $input
936 * An assosiative array of name /value pairs.
16b10e64 937 * from other function
a1a2a83d
TO
938 * @param array $duplicates
939 * (reference ) an assoc array of name/value pairs.
6a488035 940 *
16b10e64 941 * @return CRM_Contribute_BAO_Contribution
6a488035 942 */
00be9182 943 public static function checkDuplicate($input, &$duplicates) {
6a488035
TO
944 $eventId = CRM_Utils_Array::value('event_id', $input);
945 $contactId = CRM_Utils_Array::value('contact_id', $input);
946
947 $clause = array();
948 $input = array();
949
950 if ($eventId) {
951 $clause[] = "event_id = %1";
952 $input[1] = array($eventId, 'Integer');
953 }
954
955 if ($contactId) {
956 $clause[] = "contact_id = %2";
957 $input[2] = array($contactId, 'Integer');
958 }
959
960 if (empty($clause)) {
961 return FALSE;
962 }
963
964 $clause = implode(' AND ', $clause);
965
ddca8f33
TO
966 $query = "SELECT id FROM civicrm_participant WHERE $clause";
967 $dao = CRM_Core_DAO::executeQuery($query, $input);
6a488035
TO
968 $result = FALSE;
969 while ($dao->fetch()) {
970 $duplicates[] = $dao->id;
971 $result = TRUE;
972 }
973 return $result;
974 }
975
976 /**
66f9e52b 977 * Fix the event level.
6a488035
TO
978 *
979 * When price sets are used as event fee, fee_level is set as ^A
77035e4b 980 * separated string. We need to change that string to comma
6a488035
TO
981 * separated string before using fee_level in view mode.
982 *
d4dd1e85 983 * @param string $eventLevel
3bdf1f3a 984 * Event_level string from db.
6a488035 985 */
00be9182 986 public static function fixEventLevel(&$eventLevel) {
6a488035
TO
987 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR) &&
988 (substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)
989 ) {
9747cc7e 990 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($eventLevel, 1, -1)));
0cca0bf4
J
991 $pos = strrpos($eventLevel, '(multiple participants)', 0);
992 if ($pos) {
6a488035
TO
993 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
994 }
995 }
996 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
997 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
ddca8f33
TO
998 substr($eventLevel, 0, 1)
999 ));
6a488035
TO
1000 }
1001 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
1002 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
ddca8f33
TO
1003 substr($eventLevel, 0, -1)
1004 ));
6a488035
TO
1005 }
1006 }
1007
1008 /**
100fef9d 1009 * Get the additional participant ids.
6a488035 1010 *
d4dd1e85
TO
1011 * @param int $primaryParticipantId
1012 * Primary partycipant Id.
1013 * @param bool $excludeCancel
1014 * Do not include participant those are cancelled.
654ca41c 1015 *
100fef9d 1016 * @param int $oldStatusId
6a488035 1017 *
a6c01b45 1018 * @return array
6a488035 1019 */
00be9182 1020 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
6a488035
TO
1021 $additionalParticipantIds = array();
1022 if (!$primaryParticipantId) {
1023 return $additionalParticipantIds;
1024 }
1025
1026 $where = "participant.registered_by_id={$primaryParticipantId}";
1027 if ($excludeCancel) {
ddca8f33 1028 $cancelStatusId = 0;
6a488035 1029 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
ddca8f33 1030 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
6a488035
TO
1031 $where .= " AND participant.status_id != {$cancelStatusId}";
1032 }
1033
1034 if ($oldStatusId) {
1035 $where .= " AND participant.status_id = {$oldStatusId}";
1036 }
1037
1038 $query = "
1039 SELECT participant.id
1040 FROM civicrm_participant participant
1041 WHERE {$where}";
1042
1043 $dao = CRM_Core_DAO::executeQuery($query);
1044 while ($dao->fetch()) {
1045 $additionalParticipantIds[$dao->id] = $dao->id;
1046 }
1047 return $additionalParticipantIds;
1048 }
1049
362bd1b7 1050 /**
1051 * Get the amount for the undiscounted version of the field.
1052 *
1053 * Note this function is part of the refactoring process rather than the best approach.
1054 *
1055 * @param int $eventID
1056 * @param int $discountedPriceFieldOptionID
1057 * @param string $feeLevel (deprecated)
1058 *
1059 * @return null|string
1060 */
1061 public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
1062 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID, NULL);
1063 $params = array(
1064 1 => array($priceSetId, 'Integer'),
1065 );
1066 if ($discountedPriceFieldOptionID) {
1067 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1068LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1069WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
1070 $params[2] = array($discountedPriceFieldOptionID, 'Integer');
1071 }
1072 else {
1073 $feeLevel = current($feeLevel);
1074 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1075LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1076WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1077 $params[2] = array($feeLevel, 'String');
1078 }
1079 return CRM_Core_DAO::singleValueQuery($query, $params);
1080 }
1081
6a488035
TO
1082 /**
1083 * Get the event fee info for given participant ids
1084 * either from line item table / participant table.
1085 *
d4dd1e85
TO
1086 * @param array $participantIds
1087 * Participant ids.
1088 * @param bool $hasLineItems
1089 * Do fetch from line items.
6a488035 1090 *
a6c01b45 1091 * @return array
6a488035 1092 */
00be9182 1093 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
6a488035
TO
1094 $feeDetails = array();
1095 if (!is_array($participantIds) || empty($participantIds)) {
1096 return $feeDetails;
1097 }
1098
1099 $select = '
1100SELECT participant.id as id,
1101 participant.fee_level as fee_level,
1102 participant.fee_amount as fee_amount';
1103 $from = 'FROM civicrm_participant participant';
1104 if ($hasLineItems) {
1105 $select .= ' ,
1106lineItem.id as lineId,
1107lineItem.label as label,
1108lineItem.qty as qty,
1109lineItem.unit_price as unit_price,
1110lineItem.line_total as line_total,
1111field.label as field_title,
1112field.html_type as html_type,
1113field.id as price_field_id,
1114value.id as price_field_value_id,
1115value.description as description,
1116IF( value.count, value.count, 0 ) as participant_count';
1117 $from .= "
1118INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1119 AND lineItem.entity_id = participant.id )
1120INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1121INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1122";
1123 }
1124 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1125 $query = "$select $from $where";
1126
ddca8f33
TO
1127 $feeInfo = CRM_Core_DAO::executeQuery($query);
1128 $feeProperties = array('fee_level', 'fee_amount');
6a488035 1129 $lineProperties = array(
ddca8f33
TO
1130 'lineId',
1131 'label',
1132 'qty',
1133 'unit_price',
1134 'line_total',
1135 'field_title',
1136 'html_type',
1137 'price_field_id',
1138 'participant_count',
1139 'price_field_value_id',
1140 'description',
6a488035
TO
1141 );
1142 while ($feeInfo->fetch()) {
1143 if ($hasLineItems) {
1144 foreach ($lineProperties as $property) {
1145 $feeDetails[$feeInfo->id][$feeInfo->lineId][$property] = $feeInfo->$property;
1146 }
1147 }
1148 else {
ddca8f33
TO
1149 foreach ($feeProperties as $property) {
1150 $feeDetails[$feeInfo->id][$property] = $feeInfo->$property;
0479b4c8 1151 }
6a488035
TO
1152 }
1153 }
1154
1155 return $feeDetails;
1156 }
1157
1158 /**
1159 * Retrieve additional participants display-names and URL to view their participant records.
1160 * (excludes cancelled participants automatically)
1161 *
d4dd1e85
TO
1162 * @param int $primaryParticipantID
1163 * Id of primary participant record.
6a488035 1164 *
a6c01b45
CW
1165 * @return array
1166 * $displayName => $viewUrl
6a488035 1167 */
00be9182 1168 public static function getAdditionalParticipants($primaryParticipantID) {
6a488035
TO
1169 $additionalParticipantIDs = array();
1170 $additionalParticipantIDs = self::getAdditionalParticipantIds($primaryParticipantID);
1171 if (!empty($additionalParticipantIDs)) {
1172 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1173 $additionalContactID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1174 $additionalParticipantID,
1175 'contact_id', 'id'
1176 );
1177 $additionalContactName = CRM_Contact_BAO_Contact::displayName($additionalContactID);
1178 $pViewURL = CRM_Utils_System::url('civicrm/contact/view/participant',
1179 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1180 );
1181
1182 $additionalParticipants[$additionalContactName] = $pViewURL;
1183 }
1184 }
1185 return $additionalParticipants;
1186 }
1187
1188 /**
66f9e52b 1189 * Function for update primary and additional participant status.
6a488035 1190 *
d4dd1e85
TO
1191 * @param int $participantID
1192 * Primary participant's id.
100fef9d
CW
1193 * @param int $oldStatusID
1194 * @param int $newStatusID
654ca41c
EM
1195 * @param bool $updatePrimaryStatus
1196 *
a1a2a83d 1197 * @return bool|NULL
6a488035 1198 */
00be9182 1199 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
6a488035 1200 if (!$participantID || !$oldStatusID) {
a1a2a83d 1201 return NULL;
6a488035
TO
1202 }
1203
1204 if (!$newStatusID) {
1205 $newStatusID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1206 }
1207 elseif ($updatePrimaryStatus) {
1208 CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1209 }
1210
1211 $cascadeAdditionalIds = self::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1212
1213 if (!empty($cascadeAdditionalIds)) {
f7f14b5c
JP
1214 try {
1215 foreach ($cascadeAdditionalIds as $id) {
1216 $participantParams = array(
1217 'id' => $id,
1218 'status_id' => $newStatusID,
1219 );
1220 civicrm_api3('Participant', 'create', $participantParams);
1221 }
1222 return TRUE;
1223 }
1224 catch (CiviCRM_API3_Exception $e) {
1225 throw new CRM_Core_Exception('Failed to update additional participant status in database');
29a59599 1226 }
6a488035
TO
1227 }
1228 return FALSE;
1229 }
1230
1231 /**
66f9e52b 1232 * Function for update status for given participant ids.
6a488035 1233 *
d4dd1e85
TO
1234 * @param int $participantIds
1235 * Array of participant ids.
1236 * @param int $statusId
1237 * Status id for participant.
654ca41c 1238 * @param bool $updateRegisterDate
6a488035 1239 */
00be9182 1240 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
6a488035
TO
1241 if (!is_array($participantIds) || empty($participantIds) || !$statusId) {
1242 return;
1243 }
1244
1245 //lets update register date as we update status to keep track
1246 //when we did update status, useful for moving participant
1247 //from pending to expired.
1248 $setClause = "status_id = {$statusId}";
1249 if ($updateRegisterDate) {
1250 $setClause .= ", register_date = NOW()";
1251 }
1252
1253 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1254
1255 $query = "
1256UPDATE civicrm_participant
1257 SET {$setClause}
1258 WHERE id IN {$participantIdClause}";
1259
1260 $dao = CRM_Core_DAO::executeQuery($query);
1261 }
1262
654ca41c 1263 /**
6a488035
TO
1264 * Function takes participant ids and statuses
1265 * update status from $fromStatusId to $toStatusId
1266 * and send mail + create activities.
1267 *
d4dd1e85
TO
1268 * @param array $participantIds
1269 * Participant ids.
1270 * @param int $toStatusId
1271 * Update status id.
1272 * @param int $fromStatusId
1273 * From status id.
654ca41c
EM
1274 * @param bool $returnResult
1275 * @param bool $skipCascadeRule
1276 *
a1a2a83d 1277 * @return array|NULL
6a488035 1278 */
2da40d21 1279 public static function transitionParticipants(
ddca8f33 1280 $participantIds, $toStatusId,
6a488035
TO
1281 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1282 ) {
1283 if (!is_array($participantIds) || empty($participantIds) || !$toStatusId) {
a1a2a83d 1284 return NULL;
6a488035
TO
1285 }
1286
1287 //thumb rule is if we triggering primary participant need to triggered additional
1288 $allParticipantIds = $primaryANDAdditonalIds = array();
1289 foreach ($participantIds as $id) {
1290 $allParticipantIds[] = $id;
1291 if (self::isPrimaryParticipant($id)) {
1292 //filter additional as per status transition rules, CRM-5403
1293 if ($skipCascadeRule) {
1294 $additionalIds = self::getAdditionalParticipantIds($id);
1295 }
1296 else {
1297 $additionalIds = self::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1298 }
1299 if (!empty($additionalIds)) {
1300 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1301 $primaryANDAdditonalIds[$id] = $additionalIds;
1302 }
1303 }
1304 }
1305
1306 //get the unique participant ids,
1307 $allParticipantIds = array_unique($allParticipantIds);
1308
1309 //pull required participants, contacts, events data, if not in hand
1310 static $eventDetails = array();
1311 static $domainValues = array();
1312 static $contactDetails = array();
1313
1314 $contactIds = $eventIds = $participantDetails = array();
1315
ddca8f33 1316 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
6a488035 1317 $participantRoles = CRM_Event_PseudoConstant::participantRole();
ddca8f33 1318 $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL,
6a488035
TO
1319 "class = 'Pending'"
1320 );
1321
1322 //first thing is pull all necessory data from db.
1323 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1324
1325 //get all participants data.
1326 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1327 $dao = CRM_Core_DAO::executeQuery($query);
1328 while ($dao->fetch()) {
1329 $participantDetails[$dao->id] = array(
1330 'id' => $dao->id,
1331 'role' => $participantRoles[$dao->role_id],
1332 'is_test' => $dao->is_test,
1333 'event_id' => $dao->event_id,
1334 'status_id' => $dao->status_id,
1335 'fee_amount' => $dao->fee_amount,
1336 'contact_id' => $dao->contact_id,
1337 'register_date' => $dao->register_date,
1338 'registered_by_id' => $dao->registered_by_id,
1339 );
1340 if (!array_key_exists($dao->contact_id, $contactDetails)) {
1341 $contactIds[$dao->contact_id] = $dao->contact_id;
1342 }
1343
1344 if (!array_key_exists($dao->event_id, $eventDetails)) {
1345 $eventIds[$dao->event_id] = $dao->event_id;
1346 }
1347 }
1348
1349 //get the domain values.
1350 if (empty($domainValues)) {
1351 // making all tokens available to templates.
1352 $domain = CRM_Core_BAO_Domain::getDomain();
0479b4c8 1353 $tokens = array(
ddca8f33 1354 'domain' => array('name', 'phone', 'address', 'email'),
6a488035
TO
1355 'contact' => CRM_Core_SelectValues::contactTokens(),
1356 );
1357
1358 foreach ($tokens['domain'] as $token) {
1359 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
1360 }
1361 }
1362
1363 //get all required contacts detail.
1364 if (!empty($contactIds)) {
1365 // get the contact details.
1366 list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
1367 FALSE, FALSE, NULL,
1368 array(),
1369 'CRM_Event_BAO_Participant'
1370 );
1371 foreach ($currentContactDetails as $contactId => $contactValues) {
1372 $contactDetails[$contactId] = $contactValues;
1373 }
1374 }
1375
1376 //get all required events detail.
1377 if (!empty($eventIds)) {
1378 foreach ($eventIds as $eventId) {
1379 //retrieve event information
1380 $eventParams = array('id' => $eventId);
1381 CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]);
1382
1383 //get default participant role.
1384 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1385
1386 //get the location info
1387 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1388 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
1389 }
1390 }
1391
1392 //now we are ready w/ all required data.
1393 //take a decision as per statuses.
1394
ddca8f33
TO
1395 $emailType = NULL;
1396 $toStatus = $statusTypes[$toStatusId];
6a488035
TO
1397 $fromStatus = CRM_Utils_Array::value($fromStatusId, $statusTypes);
1398
1399 switch ($toStatus) {
1400 case 'Pending from waitlist':
1401 case 'Pending from approval':
1402 switch ($fromStatus) {
1403 case 'On waitlist':
1404 case 'Awaiting approval':
1405 $emailType = 'Confirm';
1406 break;
1407 }
1408 break;
1409
1410 case 'Expired':
1411 //no matter from where u come send expired mail.
1412 $emailType = $toStatus;
1413 break;
1414
1415 case 'Cancelled':
1416 //no matter from where u come send cancel mail.
1417 $emailType = $toStatus;
1418 break;
1419 }
1420
1421 //as we process additional w/ primary, there might be case if user
1422 //select primary as well as additionals, so avoid double processing.
1423 $processedParticipantIds = array();
1424 $mailedParticipants = array();
1425
1426 //send mails and update status.
1427 foreach ($participantDetails as $participantId => $participantValues) {
1428 $updateParticipantIds = array();
1429 if (in_array($participantId, $processedParticipantIds)) {
1430 continue;
1431 }
1432
1433 //check is it primary and has additional.
1434 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
a0d6db1e 1435 foreach ($primaryANDAdditonalIds[$participantId] as $additionalId) {
6a488035
TO
1436
1437 if ($emailType) {
a0d6db1e 1438 $mail = self::sendTransitionParticipantMail($additionalId,
1439 $participantDetails[$additionalId],
1440 $eventDetails[$participantDetails[$additionalId]['event_id']],
1441 $contactDetails[$participantDetails[$additionalId]['contact_id']],
6a488035
TO
1442 $domainValues,
1443 $emailType
1444 );
1445
1446 //get the mail participant ids
1447 if ($mail) {
a0d6db1e 1448 $mailedParticipants[$additionalId] = $contactDetails[$participantDetails[$additionalId]['contact_id']]['display_name'];
6a488035
TO
1449 }
1450 }
a0d6db1e 1451 $updateParticipantIds[] = $additionalId;
1452 $processedParticipantIds[] = $additionalId;
6a488035
TO
1453 }
1454 }
1455
1456 //now send email appropriate mail to primary.
1457 if ($emailType) {
1458 $mail = self::sendTransitionParticipantMail($participantId,
1459 $participantValues,
1460 $eventDetails[$participantValues['event_id']],
1461 $contactDetails[$participantValues['contact_id']],
1462 $domainValues,
1463 $emailType
1464 );
1465
1466 //get the mail participant ids
1467 if ($mail) {
1468 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1469 }
1470 }
1471
1472 //now update status of group/one at once.
1473 $updateParticipantIds[] = $participantId;
1474
1475 //update the register date only when we,
1476 //move participant to pending class, CRM-6496
1477 $updateRegisterDate = FALSE;
1478 if (array_key_exists($toStatusId, $pendingStatuses)) {
1479 $updateRegisterDate = TRUE;
1480 }
1481 self::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1482 $processedParticipantIds[] = $participantId;
1483 }
1484
1485 //return result for cron.
1486 if ($returnResult) {
1487 $results = array(
1488 'mailedParticipants' => $mailedParticipants,
1489 'updatedParticipantIds' => $processedParticipantIds,
1490 );
1491
1492 return $results;
1493 }
1494 }
1495
1496 /**
100fef9d 1497 * Send mail and create activity
6a488035
TO
1498 * when participant status changed.
1499 *
d4dd1e85
TO
1500 * @param int $participantId
1501 * Participant id.
1502 * @param array $participantValues
1503 * Participant detail values. status id for participants.
1504 * @param array $eventDetails
1505 * Required event details.
1506 * @param array $contactDetails
1507 * Required contact details.
1508 * @param array $domainValues
1509 * Required domain values.
1510 * @param string $mailType
1511 * (eg 'approval', 'confirm', 'expired' ).
6a488035 1512 *
654ca41c 1513 * @return bool
6a488035 1514 */
2da40d21 1515 public static function sendTransitionParticipantMail(
6a488035
TO
1516 $participantId,
1517 $participantValues,
1518 $eventDetails,
1519 $contactDetails,
1520 &$domainValues,
1521 $mailType
1522 ) {
1523 //send emails.
1524 $mailSent = FALSE;
1525
1526 //don't send confirmation mail to additional
1527 //since only primary able to confirm registration.
a7488080 1528 if (!empty($participantValues['registered_by_id']) &&
6a488035
TO
1529 $mailType == 'Confirm'
1530 ) {
1531 return $mailSent;
1532 }
0cca0bf4
J
1533 $toEmail = CRM_Utils_Array::value('email', $contactDetails);
1534 if ($toEmail) {
6a488035
TO
1535
1536 $contactId = $participantValues['contact_id'];
1537 $participantName = $contactDetails['display_name'];
1538
1539 //calculate the checksum value.
1540 $checksumValue = NULL;
1541 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1542 $checksumLife = 'inf';
0cca0bf4
J
1543 $endDate = CRM_Utils_Array::value('end_date', $eventDetails);
1544 if ($endDate) {
6a488035
TO
1545 $checksumLife = (CRM_Utils_Date::unixTime($endDate) - time()) / (60 * 60);
1546 }
1547 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId, NULL, $checksumLife);
1548 }
1549
1550 //take a receipt from as event else domain.
1551 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
8cc574cf 1552 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
6a488035
TO
1553 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1554 }
1555
c6327d7d 1556 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
6a488035
TO
1557 array(
1558 'groupName' => 'msg_tpl_workflow_event',
1559 'valueName' => 'participant_' . strtolower($mailType),
1560 'contactId' => $contactId,
1561 'tplParams' => array(
1562 'contact' => $contactDetails,
1563 'domain' => $domainValues,
1564 'participant' => $participantValues,
1565 'event' => $eventDetails,
1566 'paidEvent' => CRM_Utils_Array::value('is_monetary', $eventDetails),
1567 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $eventDetails),
1568 'isAdditional' => $participantValues['registered_by_id'],
1569 'isExpired' => $mailType == 'Expired',
1570 'isConfirm' => $mailType == 'Confirm',
1571 'checksumValue' => $checksumValue,
1572 ),
1573 'from' => $receiptFrom,
1574 'toName' => $participantName,
1575 'toEmail' => $toEmail,
1576 'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails),
1577 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails),
1578 )
1579 );
1580
1581 // 3. create activity record.
1582 if ($mailSent) {
ddca8f33
TO
1583 $now = date('YmdHis');
1584 $activityType = 'Event Registration';
6a488035
TO
1585 $activityParams = array(
1586 'subject' => $subject,
1587 'source_contact_id' => $contactId,
1588 'source_record_id' => $participantId,
1589 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1590 $activityType,
1591 'name'
1592 ),
1593 'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
1594 'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']),
1595 'is_test' => $participantValues['is_test'],
1596 'status_id' => 2,
1597 );
1598
1599 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
1600 CRM_Core_Error::fatal('Failed creating Activity for expiration mail');
1601 }
1602 }
1603 }
1604
1605 return $mailSent;
1606 }
1607
1608 /**
100fef9d 1609 * Get participant status change message.
6a488035 1610 *
100fef9d 1611 * @param int $participantId
654ca41c 1612 * @param $statusChangeTo
100fef9d 1613 * @param int $fromStatusId
654ca41c 1614 *
6a488035 1615 * @return string
6a488035 1616 */
00be9182 1617 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
6a488035
TO
1618 $statusMsg = NULL;
1619 $results = self::transitionParticipants(array($participantId),
1620 $statusChangeTo, $fromStatusId, TRUE
1621 );
1622
1623 $allStatuses = CRM_Event_PseudoConstant::participantStatus();
1624 //give user message only when mail has sent.
1625 if (is_array($results) && !empty($results)) {
1626 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1627 foreach ($results['updatedParticipantIds'] as $processedId) {
1628 if (is_array($results['mailedParticipants']) &&
1629 array_key_exists($processedId, $results['mailedParticipants'])
1630 ) {
1631 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
ddca8f33
TO
1632 array(
1633 1 => $allStatuses[$statusChangeTo],
1634 2 => $results['mailedParticipants'][$processedId],
1635 )
1636 );
6a488035
TO
1637 }
1638 }
1639 }
1640 }
1641
1642 return $statusMsg;
1643 }
1644
1645 /**
100fef9d 1646 * Get event full and waiting list message.
6a488035 1647 *
100fef9d
CW
1648 * @param int $eventId
1649 * @param int $participantId
654ca41c 1650 *
6a488035 1651 * @return string
6a488035 1652 */
00be9182 1653 public static function eventFullMessage($eventId, $participantId = NULL) {
6a488035
TO
1654 $eventfullMsg = $dbStatusId = NULL;
1655 $checkEventFull = TRUE;
1656 if ($participantId) {
1657 $dbStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1658 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1'))) {
1659 //participant already in counted status no need to check for event full messages.
1660 $checkEventFull = FALSE;
1661 }
1662 }
1663
1664 //early return.
1665 if (!$eventId || !$checkEventFull) {
1666 return $eventfullMsg;
1667 }
1668
1669 //event is truly full.
1670 $emptySeats = self::eventFull($eventId, FALSE, FALSE);
1671 if (is_string($emptySeats) && $emptySeats !== NULL) {
1672 $maxParticipants = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1673 $eventfullMsg = ts("This event currently has the maximum number of participants registered (%1). However, you can still override this limit and register additional participants using this form.", array(
21dfd5f5 1674 1 => $maxParticipants,
ddca8f33 1675 )) . '<br />';
6a488035
TO
1676 }
1677
1678 $hasWaiting = FALSE;
1679 $waitListedCount = self::eventFull($eventId, FALSE, TRUE, TRUE);
1680 if (is_numeric($waitListedCount)) {
1681 $hasWaiting = TRUE;
1682 //only current processing participant is on waitlist.
1683 if ($waitListedCount == 1 && CRM_Event_PseudoConstant::participantStatus($dbStatusId) == 'On waitlist') {
1684 $hasWaiting = FALSE;
1685 }
1686 }
1687
1688 if ($hasWaiting) {
1689 $waitingStatusId = array_search('On waitlist',
1690 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'")
1691 );
1692 $viewWaitListUrl = CRM_Utils_System::url('civicrm/event/search',
1693 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1694 );
1695
1696 $eventfullMsg .= ts("There are %2 people currently on the waiting list for this event. You can <a href='%1'>view waitlisted registrations here</a>, or you can continue and register additional participants using this form.",
1697 array(
1698 1 => $viewWaitListUrl,
1699 2 => $waitListedCount,
1700 )
1701 );
1702 }
1703
1704 return $eventfullMsg;
1705 }
1706
1707 /**
66f9e52b 1708 * Check for whether participant is primary or not.
6a488035 1709 *
100fef9d 1710 * @param int $participantId
6a488035 1711 *
72b3a70c
CW
1712 * @return bool
1713 * true if participant is primary
6a488035 1714 */
00be9182 1715 public static function isPrimaryParticipant($participantId) {
6a488035
TO
1716
1717 $participant = new CRM_Event_DAO_Participant();
1718 $participant->registered_by_id = $participantId;
1719
1720 if ($participant->find(TRUE)) {
1721 return TRUE;
1722 }
1723 return FALSE;
1724 }
1725
1726 /**
66f9e52b 1727 * Get additional participant Ids for cascading with primary participant status.
6a488035 1728 *
d4dd1e85
TO
1729 * @param int $participantId
1730 * Participant id.
1731 * @param int $oldStatusId
1732 * Previous status.
1733 * @param int $newStatusId
1734 * New status.
6a488035 1735 *
72b3a70c
CW
1736 * @return bool
1737 * true if allowed
6a488035 1738 */
00be9182 1739 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
6a488035
TO
1740
1741 $additionalParticipantIds = array();
1742
1743 static $participantStatuses = array();
1744
1745 if (empty($participantStatuses)) {
1746 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1747 }
1748
1749 if (CRM_Utils_Array::value($participantStatuses[$oldStatusId], self::$_statusTransitionsRules) &&
1750 in_array($participantStatuses[$newStatusId], self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1751 ) {
1752 $additionalParticipantIds = self::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1753 }
1754
1755 return $additionalParticipantIds;
1756 }
1757
1758 /**
66f9e52b 1759 * Get participant record count for a Contact.
6a488035 1760 *
c490a46a 1761 * @param int $contactID
6a488035 1762 *
a6c01b45
CW
1763 * @return int
1764 * count of participant records
6a488035 1765 */
00be9182 1766 public static function getContactParticipantCount($contactID) {
6a488035
TO
1767 $query = "SELECT count(*)
1768FROM civicrm_participant
1769WHERE civicrm_participant.contact_id = {$contactID} AND
1770 civicrm_participant.is_test = 0";
1771 return CRM_Core_DAO::singleValueQuery($query);
1772 }
1773
1774 /**
66f9e52b 1775 * Get participant ids by contribution id.
6a488035 1776 *
d4dd1e85
TO
1777 * @param int $contributionId
1778 * Contribution Id.
1779 * @param bool $excludeCancelled
1780 * Exclude cancelled additional participant.
6a488035 1781 *
a6c01b45 1782 * @return array
6a488035 1783 */
00be9182 1784 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
6a488035
TO
1785
1786 $ids = array();
1787 if (!$contributionId) {
1788 return $ids;
1789 }
1790
1791 // get primary participant id
b677b23b
JP
1792 $query = "SELECT participant_id
1793 FROM civicrm_participant cp
1794 LEFT JOIN civicrm_participant_payment cpp ON cp.id = cpp.participant_id
1795 WHERE cpp.contribution_id = {$contributionId}
1796 AND cp.registered_by_id IS NULL";
1797 $participantPayment = CRM_Core_DAO::executeQuery($query);
6a488035
TO
1798
1799 // get additional participant ids (including cancelled)
b677b23b
JP
1800 while ($participantPayment->fetch()) {
1801 $ids = array_merge($ids, array_merge(array(
1802 $participantPayment->participant_id,
1803 ), self::getAdditionalParticipantIds($participantPayment->participant_id,
ddca8f33 1804 $excludeCancelled
b677b23b 1805 )));
6a488035
TO
1806 }
1807
1808 return $ids;
1809 }
1810
1811 /**
100fef9d 1812 * Get additional Participant edit & view url .
6a488035 1813 *
d4dd1e85
TO
1814 * @param array $participantIds
1815 * An array of additional participant ids.
6a488035 1816 *
a6c01b45 1817 * @return array
16b10e64 1818 * Array of Urls.
6a488035 1819 */
00be9182 1820 public static function getAdditionalParticipantUrl($participantIds) {
6a488035 1821 foreach ($participantIds as $value) {
ddca8f33 1822 $links = array();
6a488035
TO
1823 $details = self::participantDetails($value);
1824 $viewUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1825 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1826 );
1827 $editUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1828 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1829 );
1830 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1831 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1832 return $links;
1833 }
1834 }
1835
1836 /**
dc195289 1837 * create trxn entry if an event has discount.
6a488035 1838 *
d4dd1e85
TO
1839 * @param int $eventID
1840 * Event id.
1841 * @param array $contributionParams
1842 * Contribution params.
654ca41c 1843 *
362bd1b7 1844 * @param string $feeLevel (deprecated)
1845 * @param int $discountedPriceFieldOptionID
1846 * ID of the civicrm_price_field_value field for the discount id.
6a488035 1847 */
9a05ea52 1848 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID = NULL) {
362bd1b7 1849 $financialTypeID = $contributionParams['contribution']->financial_type_id;
1850 $total_amount = $contributionParams['total_amount'];
1851
0479b4c8 1852 $checkDiscount = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
6a488035 1853 if (!empty($checkDiscount)) {
362bd1b7 1854 $mainAmount = self::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
876b8ab0
PN
1855 $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount(
1856 $financialTypeID, 'Discounts Account is');
362bd1b7 1857 if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
1858 $transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
1859 $transactionParams['trxnParams']['payment_processor_id'] = NULL;
1860 $transactionParams['trxnParams']['payment_instrument_id'] = NULL;
1861 $transactionParams['trxnParams']['check_number'] = NULL;
1862 $transactionParams['trxnParams']['trxn_id'] = NULL;
1863 $transactionParams['trxnParams']['net_amount'] = NULL;
1864 $transactionParams['trxnParams']['fee_amount'] = NULL;
1865 CRM_Core_BAO_FinancialTrxn::create($transactionParams);
6a488035
TO
1866 }
1867 }
6a488035 1868 }
c3d24ba7
PN
1869
1870 /**
66f9e52b 1871 * Delete participants of contact.
c3d24ba7
PN
1872 *
1873 * CRM-12155
1874 *
d4dd1e85
TO
1875 * @param int $contactId
1876 * Contact id.
c3d24ba7 1877 *
c3d24ba7 1878 */
00be9182 1879 public static function deleteContactParticipant($contactId) {
c3d24ba7
PN
1880 $participant = new CRM_Event_DAO_Participant();
1881 $participant->contact_id = $contactId;
1882 $participant->find();
1883 while ($participant->fetch()) {
1884 self::deleteParticipant($participant->id);
1885 }
1886 }
6a488035 1887
0cf587a7 1888 /**
100fef9d 1889 * @param int $participantId
0cf587a7
EM
1890 * @param $activityType
1891 *
1892 * @throws CRM_Core_Exception
1893 */
00be9182 1894 public static function addActivityForSelection($participantId, $activityType) {
0aaf8fe9
PJ
1895 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
1896 $contactId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
1897
1898 $date = CRM_Utils_Date::currentDBDate();
1899 $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
28c64535 1900 $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array::value($eventId, $event));
0aaf8fe9
PJ
1901
1902 // activity params
1903 $activityParams = array(
a0d6db1e 1904 'source_contact_id' => $contactId,
1905 'source_record_id' => $participantId,
d66c61b6 1906 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
0aaf8fe9
PJ
1907 'subject' => $subject,
1908 'activity_date_time' => $date,
d66c61b6 1909 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
0aaf8fe9
PJ
1910 'skipRecentView' => TRUE,
1911 );
1912
1913 // create activity with target contacts
a0d6db1e 1914 $id = CRM_Core_Session::singleton()->getLoggedInContactID();;
0aaf8fe9
PJ
1915 if ($id) {
1916 $activityParams['source_contact_id'] = $id;
a0d6db1e 1917 $activityParams['target_contact_id'][] = $contactId;
0aaf8fe9 1918 }
d66c61b6 1919 // @todo use api & also look at duplication of similar methods.
0aaf8fe9
PJ
1920 CRM_Activity_BAO_Activity::create($activityParams);
1921 }
f76b27fe
CW
1922
1923 /**
1924 * Get options for a given field.
1925 * @see CRM_Core_DAO::buildOptions
1926 *
d4dd1e85
TO
1927 * @param string $fieldName
1928 * @param string $context
a1a2a83d 1929 * @see CRM_Core_DAO::buildOptionsContext
d4dd1e85 1930 * @param array $props
16b10e64 1931 * whatever is known about this dao object.
f76b27fe 1932 *
5c766a0b 1933 * @return array|bool
f76b27fe
CW
1934 */
1935 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1936 $params = array('condition' => array());
1937
1938 if ($fieldName == 'status_id' && $context != 'validate') {
1939 // Get rid of cart-related option if disabled
1940 // FIXME: Why does this option even exist if cart is disabled?
aaffa79f 1941 if (!Civi::settings()->get('enable_cart')) {
f76b27fe
CW
1942 $params['condition'][] = "name <> 'Pending in cart'";
1943 }
1944 }
1945
1946 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
1947 }
96025800 1948
c7d52684 1949 /**
c50429ca 1950 * CRM-17797 -- Format fields and setDefaults for primary and additional participants profile
1951 * @param int $contactId
1952 * @param CRM_Core_Form $form
c7d52684 1953 */
1954 public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
1955 if (!$contactId) {
1956 return;
1957 }
1958 $fields = array();
1959 if (!empty($form->_fields)) {
1960 $removeCustomFieldTypes = array('Participant');
1961
1962 foreach ($form->_fields as $name => $dontCare) {
1963 if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
1964 && !CRM_Core_BAO_CustomGroup::checkCustomField(substr($name, 7), $removeCustomFieldTypes))
1965 || substr($name, 0, 12) == 'participant_') {
1966 continue;
1967 }
1968 $fields[$name] = 1;
1969 }
1970
1971 if (!empty($fields)) {
1972 CRM_Core_BAO_UFGroup::setProfileDefaults($contactId, $fields, $form->_defaults);
1973 }
1974 }
1975 }
1976
37d5fc55 1977}