Merge pull request #9121 from totten/master-zanzibar
[civicrm-core.git] / CRM / Event / BAO / Participant.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
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
550 {$statusIdClause}
551 {$isTestClause}
552 {$skipParticipantClause}";
553
554 $lineItem = CRM_Core_DAO::executeQuery($sql, array(1 => array($eventId, 'Positive')));
555 while ($lineItem->fetch()) {
556 $count = $lineItem->count;
557 if (!$count) {
558 $count = 1;
559 }
560 if ($lineItem->html_type == 'Text') {
561 $count *= $lineItem->qty;
562 }
563 $optionsCount[$lineItem->valueId] = $count + CRM_Utils_Array::value($lineItem->valueId, $optionsCount, 0);
564 }
565
566 return $optionsCount;
567 }
568
569 /**
570 * Get the empty spaces for event those we can allocate
571 * to pending participant to become confirm.
572 *
d4dd1e85
TO
573 * @param int $eventId
574 * Event id.
6a488035 575 *
a6c01b45
CW
576 * @return int
577 * $spaces Number of Empty Seats/null.
6a488035 578 */
00be9182 579 public static function pendingToConfirmSpaces($eventId) {
6a488035
TO
580 $emptySeats = 0;
581 if (!$eventId) {
582 return $emptySeats;
583 }
584
585 $positiveStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Positive'");
586 $statusIds = '(' . implode(',', array_keys($positiveStatuses)) . ')';
587
588 $query = "
589 SELECT count(participant.id) as registered,
590 civicrm_event.max_participants
591 FROM civicrm_participant participant, civicrm_event
592 WHERE participant.event_id = {$eventId}
593 AND civicrm_event.id = participant.event_id
594 AND participant.status_id IN {$statusIds}
595GROUP BY participant.event_id
596";
597 $dao = CRM_Core_DAO::executeQuery($query);
598 if ($dao->fetch()) {
599
600 //unlimited space.
601 if ($dao->max_participants == NULL || $dao->max_participants <= 0) {
602 return NULL;
603 }
604
605 //no space.
606 if ($dao->registered >= $dao->max_participants) {
607 return $emptySeats;
608 }
609
610 //difference.
611 return $dao->max_participants - $dao->registered;
612 }
613
614 //space in case no registeration yet.
615 return CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
616 }
617
618 /**
66f9e52b 619 * Combine all the importable fields from the lower levels object.
6a488035 620 *
77035e4b
EM
621 * @param string $contactType
622 * @param bool $status
623 * @param bool $onlyParticipant
e9ff5391 624 * @param bool $checkPermission
625 * Is this a permissioned retrieval?
77035e4b 626 *
a6c01b45
CW
627 * @return array
628 * array of importable Fields
6a488035 629 */
e9ff5391 630 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE) {
6a488035
TO
631 if (!self::$_importableFields) {
632 if (!$onlyParticipant) {
633 if (!$status) {
634 $fields = array('' => array('title' => ts('- do not import -')));
635 }
636 else {
637 $fields = array('' => array('title' => ts('- Participant Fields -')));
638 }
639 }
640 else {
641 $fields = array();
642 }
643
644 $tmpFields = CRM_Event_DAO_Participant::import();
645
646 $note = array(
647 'participant_note' => array(
3cb8f9b2 648 'title' => ts('Participant Note'),
6a488035
TO
649 'name' => 'participant_note',
650 'headerPattern' => '/(participant.)?note$/i',
21dfd5f5 651 ),
ddca8f33 652 );
6a488035 653
3cb8f9b2
CW
654 // Split status and status id into 2 fields
655 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
6a488035
TO
656 $participantStatus = array(
657 'participant_status' => array(
3cb8f9b2 658 'title' => ts('Participant Status'),
6a488035
TO
659 'name' => 'participant_status',
660 'data_type' => CRM_Utils_Type::T_STRING,
21dfd5f5 661 ),
ddca8f33 662 );
3cb8f9b2 663 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
6a488035 664
3cb8f9b2
CW
665 // Split role and role id into 2 fields
666 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
6a488035
TO
667 $participantRole = array(
668 'participant_role' => array(
3cb8f9b2 669 'title' => ts('Participant Role'),
6a488035
TO
670 'name' => 'participant_role',
671 'data_type' => CRM_Utils_Type::T_STRING,
21dfd5f5 672 ),
ddca8f33 673 );
3cb8f9b2 674 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
6a488035
TO
675
676 $eventType = array(
677 'event_type' => array(
3cb8f9b2 678 'title' => ts('Event Type'),
6a488035
TO
679 'name' => 'event_type',
680 'data_type' => CRM_Utils_Type::T_STRING,
21dfd5f5 681 ),
ddca8f33 682 );
6a488035
TO
683
684 $tmpContactField = $contactFields = array();
0479b4c8 685 $contactFields = array();
6a488035
TO
686 if (!$onlyParticipant) {
687 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
688
689 // Using new Dedupe rule.
690 $ruleParams = array(
691 'contact_type' => $contactType,
ddca8f33 692 'used' => 'Unsupervised',
6a488035
TO
693 );
694 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
695
696 if (is_array($fieldsArray)) {
697 foreach ($fieldsArray as $value) {
698 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
699 $value,
700 'id',
701 'column_name'
702 );
703 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
704 $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
705 if (!$status) {
706 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
707 }
708 else {
709 $title = $tmpContactField[trim($value)]['title'];
710 }
711
712 $tmpContactField[trim($value)]['title'] = $title;
713 }
714 }
715 }
716 $extIdentifier = CRM_Utils_Array::value('external_identifier', $contactFields);
717 if ($extIdentifier) {
718 $tmpContactField['external_identifier'] = $extIdentifier;
6c552737 719 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array::value('title', $extIdentifier) . ' (match to contact)';
6a488035 720 }
6c552737 721 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
6a488035 722
6a488035
TO
723 $fields = array_merge($fields, $tmpContactField);
724 $fields = array_merge($fields, $tmpFields);
725 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
e9ff5391 726 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
6a488035
TO
727
728 self::$_importableFields = $fields;
729 }
730
731 return self::$_importableFields;
732 }
733
734 /**
e9ff5391 735 * Combine all the exportable fields from the lower level objects.
736 *
737 * @param bool $checkPermission
6a488035 738 *
a6c01b45
CW
739 * @return array
740 * array of exportable Fields
6a488035 741 */
e9ff5391 742 public static function &exportableFields($checkPermission = TRUE) {
6a488035
TO
743 if (!self::$_exportableFields) {
744 if (!self::$_exportableFields) {
745 self::$_exportableFields = array();
746 }
747
6a488035 748 $participantFields = CRM_Event_DAO_Participant::export();
e51b7372 749 $eventFields = CRM_Event_DAO_Event::export();
6a488035 750 $noteField = array(
0479b4c8 751 'participant_note' => array(
ddca8f33 752 'title' => 'Participant Note',
6a488035 753 'name' => 'participant_note',
e51b7372 754 'type' => CRM_Utils_Type::T_STRING,
a1a2a83d
TO
755 ),
756 );
6a488035 757
a1a2a83d 758 $participantStatus = array(
0479b4c8 759 'participant_status' => array(
ddca8f33 760 'title' => 'Participant Status',
6a488035 761 'name' => 'participant_status',
e51b7372 762 'type' => CRM_Utils_Type::T_STRING,
a1a2a83d
TO
763 ),
764 );
6a488035 765
a1a2a83d 766 $participantRole = array(
0479b4c8 767 'participant_role' => array(
ddca8f33 768 'title' => 'Participant Role',
6a488035 769 'name' => 'participant_role',
e51b7372 770 'type' => CRM_Utils_Type::T_STRING,
a1a2a83d
TO
771 ),
772 );
8b8fa582 773
a1a2a83d 774 $discountFields = CRM_Core_DAO_Discount::export();
6a488035 775
a1a2a83d 776 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
6a488035 777
a1a2a83d 778 // add custom data
e9ff5391 779 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
a1a2a83d 780 self::$_exportableFields = $fields;
6a488035
TO
781 }
782
783 return self::$_exportableFields;
784 }
785
786 /**
100fef9d 787 * Get the event name/sort name for a particular participation / participant
6a488035 788 *
d4dd1e85
TO
789 * @param int $participantId
790 * Id of the participant.
6a488035 791 *
a6c01b45
CW
792 * @return array
793 * associated array with sort_name and event title
6a488035 794 */
00be9182 795 public static function participantDetails($participantId) {
6a488035
TO
796 $query = "
797SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
798FROM civicrm_participant
799 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
800 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
801WHERE civicrm_participant.id = {$participantId}
802";
33621c4f 803 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
804
805 $details = array();
806 while ($dao->fetch()) {
ddca8f33 807 $details['name'] = $dao->name;
6a488035 808 $details['title'] = $dao->title;
ddca8f33 809 $details['cid'] = $dao->cid;
6a488035
TO
810 }
811
812 return $details;
813 }
814
815 /**
816 * Get the values for pseudoconstants for name->value and reverse.
817 *
d4dd1e85
TO
818 * @param array $defaults
819 * (reference) the default values, some of which need to be resolved.
820 * @param bool $reverse
821 * True if we want to resolve the values in the reverse direction (value -> name).
6a488035 822 */
00be9182 823 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
6a488035
TO
824 self::lookupValue($defaults, 'event', CRM_Event_PseudoConstant::event(), $reverse);
825 self::lookupValue($defaults, 'status', CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'), $reverse);
826 self::lookupValue($defaults, 'role', CRM_Event_PseudoConstant::participantRole(), $reverse);
827 }
828
829 /**
3bdf1f3a 830 * Convert associative array names to values and vice-versa.
6a488035
TO
831 *
832 * This function is used by both the web form layer and the api. Note that
833 * the api needs the name => value conversion, also the view layer typically
834 * requires value => name conversion
ad37ac8e 835 *
836 * @param array $defaults
837 * @param string $property
838 * @param string $lookup
839 * @param bool $reverse
840 *
841 * @return bool
6a488035 842 */
00be9182 843 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
6a488035
TO
844 $id = $property . '_id';
845
846 $src = $reverse ? $property : $id;
847 $dst = $reverse ? $id : $property;
848
849 if (!array_key_exists($src, $defaults)) {
850 return FALSE;
851 }
852
853 $look = $reverse ? array_flip($lookup) : $lookup;
854
855 if (is_array($look)) {
856 if (!array_key_exists($defaults[$src], $look)) {
857 return FALSE;
858 }
859 }
860 $defaults[$dst] = $look[$defaults[$src]];
861 return TRUE;
862 }
863
864 /**
3bdf1f3a 865 * Delete the records that are associated with this participation.
6a488035 866 *
d4dd1e85
TO
867 * @param int $id
868 * Id of the participation to delete.
6a488035 869 *
3bdf1f3a 870 * @return \CRM_Event_DAO_Participant
6a488035 871 */
00be9182 872 public static function deleteParticipant($id) {
6a488035
TO
873 CRM_Utils_Hook::pre('delete', 'Participant', $id, CRM_Core_DAO::$_nullArray);
874
875 $transaction = new CRM_Core_Transaction();
876
877 //delete activity record
878 $params = array(
879 'source_record_id' => $id,
880 // activity type id for event registration
881 'activity_type_id' => 5,
882 );
883
884 CRM_Activity_BAO_Activity::deleteActivity($params);
885
886 // delete the participant payment record
887 // we need to do this since the cascaded constraints
888 // dont work with join tables
889 $p = array('participant_id' => $id);
890 CRM_Event_BAO_ParticipantPayment::deleteParticipantPayment($p);
891
892 // cleanup line items.
ddca8f33
TO
893 $participantsId = array();
894 $participantsId = self::getAdditionalParticipantIds($id);
6a488035
TO
895 $participantsId[] = $id;
896 CRM_Price_BAO_LineItem::deleteLineItems($participantsId, 'civicrm_participant');
897
898 //delete note when participant deleted.
899 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_participant');
900 $noteId = key($note);
901 if ($noteId) {
902 CRM_Core_BAO_Note::del($noteId, FALSE);
903 }
904
905 $participant = new CRM_Event_DAO_Participant();
906 $participant->id = $id;
907 $participant->delete();
908
909 $transaction->commit();
910
911 CRM_Utils_Hook::post('delete', 'Participant', $participant->id, $participant);
912
913 // delete the recently created Participant
914 $participantRecent = array(
915 'id' => $id,
916 'type' => 'Participant',
917 );
918
919 CRM_Utils_Recent::del($participantRecent);
920
921 return $participant;
922 }
923
924 /**
66f9e52b 925 * Checks duplicate participants.
6a488035 926 *
d4dd1e85
TO
927 * @param array $input
928 * An assosiative array of name /value pairs.
16b10e64 929 * from other function
a1a2a83d
TO
930 * @param array $duplicates
931 * (reference ) an assoc array of name/value pairs.
6a488035 932 *
16b10e64 933 * @return CRM_Contribute_BAO_Contribution
6a488035 934 */
00be9182 935 public static function checkDuplicate($input, &$duplicates) {
6a488035
TO
936 $eventId = CRM_Utils_Array::value('event_id', $input);
937 $contactId = CRM_Utils_Array::value('contact_id', $input);
938
939 $clause = array();
940 $input = array();
941
942 if ($eventId) {
943 $clause[] = "event_id = %1";
944 $input[1] = array($eventId, 'Integer');
945 }
946
947 if ($contactId) {
948 $clause[] = "contact_id = %2";
949 $input[2] = array($contactId, 'Integer');
950 }
951
952 if (empty($clause)) {
953 return FALSE;
954 }
955
956 $clause = implode(' AND ', $clause);
957
ddca8f33
TO
958 $query = "SELECT id FROM civicrm_participant WHERE $clause";
959 $dao = CRM_Core_DAO::executeQuery($query, $input);
6a488035
TO
960 $result = FALSE;
961 while ($dao->fetch()) {
962 $duplicates[] = $dao->id;
963 $result = TRUE;
964 }
965 return $result;
966 }
967
968 /**
66f9e52b 969 * Fix the event level.
6a488035
TO
970 *
971 * When price sets are used as event fee, fee_level is set as ^A
77035e4b 972 * separated string. We need to change that string to comma
6a488035
TO
973 * separated string before using fee_level in view mode.
974 *
d4dd1e85 975 * @param string $eventLevel
3bdf1f3a 976 * Event_level string from db.
6a488035 977 */
00be9182 978 public static function fixEventLevel(&$eventLevel) {
6a488035
TO
979 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR) &&
980 (substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)
981 ) {
9747cc7e 982 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($eventLevel, 1, -1)));
0cca0bf4
J
983 $pos = strrpos($eventLevel, '(multiple participants)', 0);
984 if ($pos) {
6a488035
TO
985 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
986 }
987 }
988 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
989 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
ddca8f33
TO
990 substr($eventLevel, 0, 1)
991 ));
6a488035
TO
992 }
993 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
994 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
ddca8f33
TO
995 substr($eventLevel, 0, -1)
996 ));
6a488035
TO
997 }
998 }
999
1000 /**
100fef9d 1001 * Get the additional participant ids.
6a488035 1002 *
d4dd1e85
TO
1003 * @param int $primaryParticipantId
1004 * Primary partycipant Id.
1005 * @param bool $excludeCancel
1006 * Do not include participant those are cancelled.
654ca41c 1007 *
100fef9d 1008 * @param int $oldStatusId
6a488035 1009 *
a6c01b45 1010 * @return array
6a488035 1011 */
00be9182 1012 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
6a488035
TO
1013 $additionalParticipantIds = array();
1014 if (!$primaryParticipantId) {
1015 return $additionalParticipantIds;
1016 }
1017
1018 $where = "participant.registered_by_id={$primaryParticipantId}";
1019 if ($excludeCancel) {
ddca8f33 1020 $cancelStatusId = 0;
6a488035 1021 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
ddca8f33 1022 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
6a488035
TO
1023 $where .= " AND participant.status_id != {$cancelStatusId}";
1024 }
1025
1026 if ($oldStatusId) {
1027 $where .= " AND participant.status_id = {$oldStatusId}";
1028 }
1029
1030 $query = "
1031 SELECT participant.id
1032 FROM civicrm_participant participant
1033 WHERE {$where}";
1034
1035 $dao = CRM_Core_DAO::executeQuery($query);
1036 while ($dao->fetch()) {
1037 $additionalParticipantIds[$dao->id] = $dao->id;
1038 }
1039 return $additionalParticipantIds;
1040 }
1041
362bd1b7 1042 /**
1043 * Get the amount for the undiscounted version of the field.
1044 *
1045 * Note this function is part of the refactoring process rather than the best approach.
1046 *
1047 * @param int $eventID
1048 * @param int $discountedPriceFieldOptionID
1049 * @param string $feeLevel (deprecated)
1050 *
1051 * @return null|string
1052 */
1053 public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
1054 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID, NULL);
1055 $params = array(
1056 1 => array($priceSetId, 'Integer'),
1057 );
1058 if ($discountedPriceFieldOptionID) {
1059 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1060LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1061WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
1062 $params[2] = array($discountedPriceFieldOptionID, 'Integer');
1063 }
1064 else {
1065 $feeLevel = current($feeLevel);
1066 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1067LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1068WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
1069 $params[2] = array($feeLevel, 'String');
1070 }
1071 return CRM_Core_DAO::singleValueQuery($query, $params);
1072 }
1073
6a488035
TO
1074 /**
1075 * Get the event fee info for given participant ids
1076 * either from line item table / participant table.
1077 *
d4dd1e85
TO
1078 * @param array $participantIds
1079 * Participant ids.
1080 * @param bool $hasLineItems
1081 * Do fetch from line items.
6a488035 1082 *
a6c01b45 1083 * @return array
6a488035 1084 */
00be9182 1085 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
6a488035
TO
1086 $feeDetails = array();
1087 if (!is_array($participantIds) || empty($participantIds)) {
1088 return $feeDetails;
1089 }
1090
1091 $select = '
1092SELECT participant.id as id,
1093 participant.fee_level as fee_level,
1094 participant.fee_amount as fee_amount';
1095 $from = 'FROM civicrm_participant participant';
1096 if ($hasLineItems) {
1097 $select .= ' ,
1098lineItem.id as lineId,
1099lineItem.label as label,
1100lineItem.qty as qty,
1101lineItem.unit_price as unit_price,
1102lineItem.line_total as line_total,
1103field.label as field_title,
1104field.html_type as html_type,
1105field.id as price_field_id,
1106value.id as price_field_value_id,
1107value.description as description,
1108IF( value.count, value.count, 0 ) as participant_count';
1109 $from .= "
1110INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1111 AND lineItem.entity_id = participant.id )
1112INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1113INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1114";
1115 }
1116 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1117 $query = "$select $from $where";
1118
ddca8f33
TO
1119 $feeInfo = CRM_Core_DAO::executeQuery($query);
1120 $feeProperties = array('fee_level', 'fee_amount');
6a488035 1121 $lineProperties = array(
ddca8f33
TO
1122 'lineId',
1123 'label',
1124 'qty',
1125 'unit_price',
1126 'line_total',
1127 'field_title',
1128 'html_type',
1129 'price_field_id',
1130 'participant_count',
1131 'price_field_value_id',
1132 'description',
6a488035
TO
1133 );
1134 while ($feeInfo->fetch()) {
1135 if ($hasLineItems) {
1136 foreach ($lineProperties as $property) {
1137 $feeDetails[$feeInfo->id][$feeInfo->lineId][$property] = $feeInfo->$property;
1138 }
1139 }
1140 else {
ddca8f33
TO
1141 foreach ($feeProperties as $property) {
1142 $feeDetails[$feeInfo->id][$property] = $feeInfo->$property;
0479b4c8 1143 }
6a488035
TO
1144 }
1145 }
1146
1147 return $feeDetails;
1148 }
1149
1150 /**
1151 * Retrieve additional participants display-names and URL to view their participant records.
1152 * (excludes cancelled participants automatically)
1153 *
d4dd1e85
TO
1154 * @param int $primaryParticipantID
1155 * Id of primary participant record.
6a488035 1156 *
a6c01b45
CW
1157 * @return array
1158 * $displayName => $viewUrl
6a488035 1159 */
00be9182 1160 public static function getAdditionalParticipants($primaryParticipantID) {
6a488035
TO
1161 $additionalParticipantIDs = array();
1162 $additionalParticipantIDs = self::getAdditionalParticipantIds($primaryParticipantID);
1163 if (!empty($additionalParticipantIDs)) {
1164 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1165 $additionalContactID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1166 $additionalParticipantID,
1167 'contact_id', 'id'
1168 );
1169 $additionalContactName = CRM_Contact_BAO_Contact::displayName($additionalContactID);
1170 $pViewURL = CRM_Utils_System::url('civicrm/contact/view/participant',
1171 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1172 );
1173
1174 $additionalParticipants[$additionalContactName] = $pViewURL;
1175 }
1176 }
1177 return $additionalParticipants;
1178 }
1179
1180 /**
66f9e52b 1181 * Function for update primary and additional participant status.
6a488035 1182 *
d4dd1e85
TO
1183 * @param int $participantID
1184 * Primary participant's id.
100fef9d
CW
1185 * @param int $oldStatusID
1186 * @param int $newStatusID
654ca41c
EM
1187 * @param bool $updatePrimaryStatus
1188 *
a1a2a83d 1189 * @return bool|NULL
6a488035 1190 */
00be9182 1191 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
6a488035 1192 if (!$participantID || !$oldStatusID) {
a1a2a83d 1193 return NULL;
6a488035
TO
1194 }
1195
1196 if (!$newStatusID) {
1197 $newStatusID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1198 }
1199 elseif ($updatePrimaryStatus) {
1200 CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1201 }
1202
1203 $cascadeAdditionalIds = self::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1204
1205 if (!empty($cascadeAdditionalIds)) {
1206 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1207 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1208 $params = array(1 => array($newStatusID, 'Integer'));
1209 $dao = CRM_Core_DAO::executeQuery($query, $params);
1210 return TRUE;
1211 }
1212 return FALSE;
1213 }
1214
1215 /**
66f9e52b 1216 * Function for update status for given participant ids.
6a488035 1217 *
d4dd1e85
TO
1218 * @param int $participantIds
1219 * Array of participant ids.
1220 * @param int $statusId
1221 * Status id for participant.
654ca41c 1222 * @param bool $updateRegisterDate
6a488035 1223 */
00be9182 1224 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
6a488035
TO
1225 if (!is_array($participantIds) || empty($participantIds) || !$statusId) {
1226 return;
1227 }
1228
1229 //lets update register date as we update status to keep track
1230 //when we did update status, useful for moving participant
1231 //from pending to expired.
1232 $setClause = "status_id = {$statusId}";
1233 if ($updateRegisterDate) {
1234 $setClause .= ", register_date = NOW()";
1235 }
1236
1237 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1238
1239 $query = "
1240UPDATE civicrm_participant
1241 SET {$setClause}
1242 WHERE id IN {$participantIdClause}";
1243
1244 $dao = CRM_Core_DAO::executeQuery($query);
1245 }
1246
654ca41c 1247 /**
6a488035
TO
1248 * Function takes participant ids and statuses
1249 * update status from $fromStatusId to $toStatusId
1250 * and send mail + create activities.
1251 *
d4dd1e85
TO
1252 * @param array $participantIds
1253 * Participant ids.
1254 * @param int $toStatusId
1255 * Update status id.
1256 * @param int $fromStatusId
1257 * From status id.
654ca41c
EM
1258 * @param bool $returnResult
1259 * @param bool $skipCascadeRule
1260 *
a1a2a83d 1261 * @return array|NULL
6a488035 1262 */
2da40d21 1263 public static function transitionParticipants(
ddca8f33 1264 $participantIds, $toStatusId,
6a488035
TO
1265 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1266 ) {
1267 if (!is_array($participantIds) || empty($participantIds) || !$toStatusId) {
a1a2a83d 1268 return NULL;
6a488035
TO
1269 }
1270
1271 //thumb rule is if we triggering primary participant need to triggered additional
1272 $allParticipantIds = $primaryANDAdditonalIds = array();
1273 foreach ($participantIds as $id) {
1274 $allParticipantIds[] = $id;
1275 if (self::isPrimaryParticipant($id)) {
1276 //filter additional as per status transition rules, CRM-5403
1277 if ($skipCascadeRule) {
1278 $additionalIds = self::getAdditionalParticipantIds($id);
1279 }
1280 else {
1281 $additionalIds = self::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1282 }
1283 if (!empty($additionalIds)) {
1284 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1285 $primaryANDAdditonalIds[$id] = $additionalIds;
1286 }
1287 }
1288 }
1289
1290 //get the unique participant ids,
1291 $allParticipantIds = array_unique($allParticipantIds);
1292
1293 //pull required participants, contacts, events data, if not in hand
1294 static $eventDetails = array();
1295 static $domainValues = array();
1296 static $contactDetails = array();
1297
1298 $contactIds = $eventIds = $participantDetails = array();
1299
ddca8f33 1300 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
6a488035 1301 $participantRoles = CRM_Event_PseudoConstant::participantRole();
ddca8f33 1302 $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL,
6a488035
TO
1303 "class = 'Pending'"
1304 );
1305
1306 //first thing is pull all necessory data from db.
1307 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1308
1309 //get all participants data.
1310 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1311 $dao = CRM_Core_DAO::executeQuery($query);
1312 while ($dao->fetch()) {
1313 $participantDetails[$dao->id] = array(
1314 'id' => $dao->id,
1315 'role' => $participantRoles[$dao->role_id],
1316 'is_test' => $dao->is_test,
1317 'event_id' => $dao->event_id,
1318 'status_id' => $dao->status_id,
1319 'fee_amount' => $dao->fee_amount,
1320 'contact_id' => $dao->contact_id,
1321 'register_date' => $dao->register_date,
1322 'registered_by_id' => $dao->registered_by_id,
1323 );
1324 if (!array_key_exists($dao->contact_id, $contactDetails)) {
1325 $contactIds[$dao->contact_id] = $dao->contact_id;
1326 }
1327
1328 if (!array_key_exists($dao->event_id, $eventDetails)) {
1329 $eventIds[$dao->event_id] = $dao->event_id;
1330 }
1331 }
1332
1333 //get the domain values.
1334 if (empty($domainValues)) {
1335 // making all tokens available to templates.
1336 $domain = CRM_Core_BAO_Domain::getDomain();
0479b4c8 1337 $tokens = array(
ddca8f33 1338 'domain' => array('name', 'phone', 'address', 'email'),
6a488035
TO
1339 'contact' => CRM_Core_SelectValues::contactTokens(),
1340 );
1341
1342 foreach ($tokens['domain'] as $token) {
1343 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
1344 }
1345 }
1346
1347 //get all required contacts detail.
1348 if (!empty($contactIds)) {
1349 // get the contact details.
1350 list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
1351 FALSE, FALSE, NULL,
1352 array(),
1353 'CRM_Event_BAO_Participant'
1354 );
1355 foreach ($currentContactDetails as $contactId => $contactValues) {
1356 $contactDetails[$contactId] = $contactValues;
1357 }
1358 }
1359
1360 //get all required events detail.
1361 if (!empty($eventIds)) {
1362 foreach ($eventIds as $eventId) {
1363 //retrieve event information
1364 $eventParams = array('id' => $eventId);
1365 CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]);
1366
1367 //get default participant role.
1368 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1369
1370 //get the location info
1371 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1372 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
1373 }
1374 }
1375
1376 //now we are ready w/ all required data.
1377 //take a decision as per statuses.
1378
ddca8f33
TO
1379 $emailType = NULL;
1380 $toStatus = $statusTypes[$toStatusId];
6a488035
TO
1381 $fromStatus = CRM_Utils_Array::value($fromStatusId, $statusTypes);
1382
1383 switch ($toStatus) {
1384 case 'Pending from waitlist':
1385 case 'Pending from approval':
1386 switch ($fromStatus) {
1387 case 'On waitlist':
1388 case 'Awaiting approval':
1389 $emailType = 'Confirm';
1390 break;
1391 }
1392 break;
1393
1394 case 'Expired':
1395 //no matter from where u come send expired mail.
1396 $emailType = $toStatus;
1397 break;
1398
1399 case 'Cancelled':
1400 //no matter from where u come send cancel mail.
1401 $emailType = $toStatus;
1402 break;
1403 }
1404
1405 //as we process additional w/ primary, there might be case if user
1406 //select primary as well as additionals, so avoid double processing.
1407 $processedParticipantIds = array();
1408 $mailedParticipants = array();
1409
1410 //send mails and update status.
1411 foreach ($participantDetails as $participantId => $participantValues) {
1412 $updateParticipantIds = array();
1413 if (in_array($participantId, $processedParticipantIds)) {
1414 continue;
1415 }
1416
1417 //check is it primary and has additional.
1418 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1419 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1420
1421 if ($emailType) {
1422 $mail = self::sendTransitionParticipantMail($additonalId,
1423 $participantDetails[$additonalId],
1424 $eventDetails[$participantDetails[$additonalId]['event_id']],
1425 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1426 $domainValues,
1427 $emailType
1428 );
1429
1430 //get the mail participant ids
1431 if ($mail) {
1432 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1433 }
1434 }
1435 $updateParticipantIds[] = $additonalId;
1436 $processedParticipantIds[] = $additonalId;
1437 }
1438 }
1439
1440 //now send email appropriate mail to primary.
1441 if ($emailType) {
1442 $mail = self::sendTransitionParticipantMail($participantId,
1443 $participantValues,
1444 $eventDetails[$participantValues['event_id']],
1445 $contactDetails[$participantValues['contact_id']],
1446 $domainValues,
1447 $emailType
1448 );
1449
1450 //get the mail participant ids
1451 if ($mail) {
1452 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1453 }
1454 }
1455
1456 //now update status of group/one at once.
1457 $updateParticipantIds[] = $participantId;
1458
1459 //update the register date only when we,
1460 //move participant to pending class, CRM-6496
1461 $updateRegisterDate = FALSE;
1462 if (array_key_exists($toStatusId, $pendingStatuses)) {
1463 $updateRegisterDate = TRUE;
1464 }
1465 self::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1466 $processedParticipantIds[] = $participantId;
1467 }
1468
1469 //return result for cron.
1470 if ($returnResult) {
1471 $results = array(
1472 'mailedParticipants' => $mailedParticipants,
1473 'updatedParticipantIds' => $processedParticipantIds,
1474 );
1475
1476 return $results;
1477 }
1478 }
1479
1480 /**
100fef9d 1481 * Send mail and create activity
6a488035
TO
1482 * when participant status changed.
1483 *
d4dd1e85
TO
1484 * @param int $participantId
1485 * Participant id.
1486 * @param array $participantValues
1487 * Participant detail values. status id for participants.
1488 * @param array $eventDetails
1489 * Required event details.
1490 * @param array $contactDetails
1491 * Required contact details.
1492 * @param array $domainValues
1493 * Required domain values.
1494 * @param string $mailType
1495 * (eg 'approval', 'confirm', 'expired' ).
6a488035 1496 *
654ca41c 1497 * @return bool
6a488035 1498 */
2da40d21 1499 public static function sendTransitionParticipantMail(
6a488035
TO
1500 $participantId,
1501 $participantValues,
1502 $eventDetails,
1503 $contactDetails,
1504 &$domainValues,
1505 $mailType
1506 ) {
1507 //send emails.
1508 $mailSent = FALSE;
1509
1510 //don't send confirmation mail to additional
1511 //since only primary able to confirm registration.
a7488080 1512 if (!empty($participantValues['registered_by_id']) &&
6a488035
TO
1513 $mailType == 'Confirm'
1514 ) {
1515 return $mailSent;
1516 }
0cca0bf4
J
1517 $toEmail = CRM_Utils_Array::value('email', $contactDetails);
1518 if ($toEmail) {
6a488035
TO
1519
1520 $contactId = $participantValues['contact_id'];
1521 $participantName = $contactDetails['display_name'];
1522
1523 //calculate the checksum value.
1524 $checksumValue = NULL;
1525 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1526 $checksumLife = 'inf';
0cca0bf4
J
1527 $endDate = CRM_Utils_Array::value('end_date', $eventDetails);
1528 if ($endDate) {
6a488035
TO
1529 $checksumLife = (CRM_Utils_Date::unixTime($endDate) - time()) / (60 * 60);
1530 }
1531 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId, NULL, $checksumLife);
1532 }
1533
1534 //take a receipt from as event else domain.
1535 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
8cc574cf 1536 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
6a488035
TO
1537 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1538 }
1539
c6327d7d 1540 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
6a488035
TO
1541 array(
1542 'groupName' => 'msg_tpl_workflow_event',
1543 'valueName' => 'participant_' . strtolower($mailType),
1544 'contactId' => $contactId,
1545 'tplParams' => array(
1546 'contact' => $contactDetails,
1547 'domain' => $domainValues,
1548 'participant' => $participantValues,
1549 'event' => $eventDetails,
1550 'paidEvent' => CRM_Utils_Array::value('is_monetary', $eventDetails),
1551 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $eventDetails),
1552 'isAdditional' => $participantValues['registered_by_id'],
1553 'isExpired' => $mailType == 'Expired',
1554 'isConfirm' => $mailType == 'Confirm',
1555 'checksumValue' => $checksumValue,
1556 ),
1557 'from' => $receiptFrom,
1558 'toName' => $participantName,
1559 'toEmail' => $toEmail,
1560 'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails),
1561 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails),
1562 )
1563 );
1564
1565 // 3. create activity record.
1566 if ($mailSent) {
ddca8f33
TO
1567 $now = date('YmdHis');
1568 $activityType = 'Event Registration';
6a488035
TO
1569 $activityParams = array(
1570 'subject' => $subject,
1571 'source_contact_id' => $contactId,
1572 'source_record_id' => $participantId,
1573 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1574 $activityType,
1575 'name'
1576 ),
1577 'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
1578 'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']),
1579 'is_test' => $participantValues['is_test'],
1580 'status_id' => 2,
1581 );
1582
1583 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
1584 CRM_Core_Error::fatal('Failed creating Activity for expiration mail');
1585 }
1586 }
1587 }
1588
1589 return $mailSent;
1590 }
1591
1592 /**
100fef9d 1593 * Get participant status change message.
6a488035 1594 *
100fef9d 1595 * @param int $participantId
654ca41c 1596 * @param $statusChangeTo
100fef9d 1597 * @param int $fromStatusId
654ca41c 1598 *
6a488035 1599 * @return string
6a488035 1600 */
00be9182 1601 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
6a488035
TO
1602 $statusMsg = NULL;
1603 $results = self::transitionParticipants(array($participantId),
1604 $statusChangeTo, $fromStatusId, TRUE
1605 );
1606
1607 $allStatuses = CRM_Event_PseudoConstant::participantStatus();
1608 //give user message only when mail has sent.
1609 if (is_array($results) && !empty($results)) {
1610 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1611 foreach ($results['updatedParticipantIds'] as $processedId) {
1612 if (is_array($results['mailedParticipants']) &&
1613 array_key_exists($processedId, $results['mailedParticipants'])
1614 ) {
1615 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
ddca8f33
TO
1616 array(
1617 1 => $allStatuses[$statusChangeTo],
1618 2 => $results['mailedParticipants'][$processedId],
1619 )
1620 );
6a488035
TO
1621 }
1622 }
1623 }
1624 }
1625
1626 return $statusMsg;
1627 }
1628
1629 /**
100fef9d 1630 * Get event full and waiting list message.
6a488035 1631 *
100fef9d
CW
1632 * @param int $eventId
1633 * @param int $participantId
654ca41c 1634 *
6a488035 1635 * @return string
6a488035 1636 */
00be9182 1637 public static function eventFullMessage($eventId, $participantId = NULL) {
6a488035
TO
1638 $eventfullMsg = $dbStatusId = NULL;
1639 $checkEventFull = TRUE;
1640 if ($participantId) {
1641 $dbStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1642 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1'))) {
1643 //participant already in counted status no need to check for event full messages.
1644 $checkEventFull = FALSE;
1645 }
1646 }
1647
1648 //early return.
1649 if (!$eventId || !$checkEventFull) {
1650 return $eventfullMsg;
1651 }
1652
1653 //event is truly full.
1654 $emptySeats = self::eventFull($eventId, FALSE, FALSE);
1655 if (is_string($emptySeats) && $emptySeats !== NULL) {
1656 $maxParticipants = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1657 $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 1658 1 => $maxParticipants,
ddca8f33 1659 )) . '<br />';
6a488035
TO
1660 }
1661
1662 $hasWaiting = FALSE;
1663 $waitListedCount = self::eventFull($eventId, FALSE, TRUE, TRUE);
1664 if (is_numeric($waitListedCount)) {
1665 $hasWaiting = TRUE;
1666 //only current processing participant is on waitlist.
1667 if ($waitListedCount == 1 && CRM_Event_PseudoConstant::participantStatus($dbStatusId) == 'On waitlist') {
1668 $hasWaiting = FALSE;
1669 }
1670 }
1671
1672 if ($hasWaiting) {
1673 $waitingStatusId = array_search('On waitlist',
1674 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'")
1675 );
1676 $viewWaitListUrl = CRM_Utils_System::url('civicrm/event/search',
1677 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1678 );
1679
1680 $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.",
1681 array(
1682 1 => $viewWaitListUrl,
1683 2 => $waitListedCount,
1684 )
1685 );
1686 }
1687
1688 return $eventfullMsg;
1689 }
1690
1691 /**
66f9e52b 1692 * Check for whether participant is primary or not.
6a488035 1693 *
100fef9d 1694 * @param int $participantId
6a488035 1695 *
72b3a70c
CW
1696 * @return bool
1697 * true if participant is primary
6a488035 1698 */
00be9182 1699 public static function isPrimaryParticipant($participantId) {
6a488035
TO
1700
1701 $participant = new CRM_Event_DAO_Participant();
1702 $participant->registered_by_id = $participantId;
1703
1704 if ($participant->find(TRUE)) {
1705 return TRUE;
1706 }
1707 return FALSE;
1708 }
1709
1710 /**
66f9e52b 1711 * Get additional participant Ids for cascading with primary participant status.
6a488035 1712 *
d4dd1e85
TO
1713 * @param int $participantId
1714 * Participant id.
1715 * @param int $oldStatusId
1716 * Previous status.
1717 * @param int $newStatusId
1718 * New status.
6a488035 1719 *
72b3a70c
CW
1720 * @return bool
1721 * true if allowed
6a488035 1722 */
00be9182 1723 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
6a488035
TO
1724
1725 $additionalParticipantIds = array();
1726
1727 static $participantStatuses = array();
1728
1729 if (empty($participantStatuses)) {
1730 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1731 }
1732
1733 if (CRM_Utils_Array::value($participantStatuses[$oldStatusId], self::$_statusTransitionsRules) &&
1734 in_array($participantStatuses[$newStatusId], self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1735 ) {
1736 $additionalParticipantIds = self::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1737 }
1738
1739 return $additionalParticipantIds;
1740 }
1741
1742 /**
66f9e52b 1743 * Get participant record count for a Contact.
6a488035 1744 *
c490a46a 1745 * @param int $contactID
6a488035 1746 *
a6c01b45
CW
1747 * @return int
1748 * count of participant records
6a488035 1749 */
00be9182 1750 public static function getContactParticipantCount($contactID) {
6a488035
TO
1751 $query = "SELECT count(*)
1752FROM civicrm_participant
1753WHERE civicrm_participant.contact_id = {$contactID} AND
1754 civicrm_participant.is_test = 0";
1755 return CRM_Core_DAO::singleValueQuery($query);
1756 }
1757
1758 /**
66f9e52b 1759 * Get participant ids by contribution id.
6a488035 1760 *
d4dd1e85
TO
1761 * @param int $contributionId
1762 * Contribution Id.
1763 * @param bool $excludeCancelled
1764 * Exclude cancelled additional participant.
6a488035 1765 *
a6c01b45 1766 * @return array
6a488035 1767 */
00be9182 1768 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
6a488035
TO
1769
1770 $ids = array();
1771 if (!$contributionId) {
1772 return $ids;
1773 }
1774
1775 // get primary participant id
1776 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1777 $participantId = CRM_Core_DAO::singleValueQuery($query);
1778
1779 // get additional participant ids (including cancelled)
1780 if ($participantId) {
1781 $ids = array_merge(array(
21dfd5f5 1782 $participantId,
ddca8f33
TO
1783 ), self::getAdditionalParticipantIds($participantId,
1784 $excludeCancelled
1785 ));
6a488035
TO
1786 }
1787
1788 return $ids;
1789 }
1790
1791 /**
100fef9d 1792 * Get additional Participant edit & view url .
6a488035 1793 *
d4dd1e85
TO
1794 * @param array $participantIds
1795 * An array of additional participant ids.
6a488035 1796 *
a6c01b45 1797 * @return array
16b10e64 1798 * Array of Urls.
6a488035 1799 */
00be9182 1800 public static function getAdditionalParticipantUrl($participantIds) {
6a488035 1801 foreach ($participantIds as $value) {
ddca8f33 1802 $links = array();
6a488035
TO
1803 $details = self::participantDetails($value);
1804 $viewUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1805 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1806 );
1807 $editUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1808 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1809 );
1810 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1811 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1812 return $links;
1813 }
1814 }
1815
1816 /**
dc195289 1817 * create trxn entry if an event has discount.
6a488035 1818 *
d4dd1e85
TO
1819 * @param int $eventID
1820 * Event id.
1821 * @param array $contributionParams
1822 * Contribution params.
654ca41c 1823 *
362bd1b7 1824 * @param string $feeLevel (deprecated)
1825 * @param int $discountedPriceFieldOptionID
1826 * ID of the civicrm_price_field_value field for the discount id.
6a488035 1827 */
362bd1b7 1828 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID) {
1829 $financialTypeID = $contributionParams['contribution']->financial_type_id;
1830 $total_amount = $contributionParams['total_amount'];
1831
0479b4c8 1832 $checkDiscount = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
6a488035 1833 if (!empty($checkDiscount)) {
362bd1b7 1834 $mainAmount = self::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
f743a6eb 1835 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
362bd1b7 1836 $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
1837 $financialTypeID, $relationTypeId);
1838 if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
1839 $transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
1840 $transactionParams['trxnParams']['payment_processor_id'] = NULL;
1841 $transactionParams['trxnParams']['payment_instrument_id'] = NULL;
1842 $transactionParams['trxnParams']['check_number'] = NULL;
1843 $transactionParams['trxnParams']['trxn_id'] = NULL;
1844 $transactionParams['trxnParams']['net_amount'] = NULL;
1845 $transactionParams['trxnParams']['fee_amount'] = NULL;
1846 CRM_Core_BAO_FinancialTrxn::create($transactionParams);
6a488035
TO
1847 }
1848 }
6a488035 1849 }
c3d24ba7
PN
1850
1851 /**
66f9e52b 1852 * Delete participants of contact.
c3d24ba7
PN
1853 *
1854 * CRM-12155
1855 *
d4dd1e85
TO
1856 * @param int $contactId
1857 * Contact id.
c3d24ba7 1858 *
c3d24ba7 1859 */
00be9182 1860 public static function deleteContactParticipant($contactId) {
c3d24ba7
PN
1861 $participant = new CRM_Event_DAO_Participant();
1862 $participant->contact_id = $contactId;
1863 $participant->find();
1864 while ($participant->fetch()) {
1865 self::deleteParticipant($participant->id);
1866 }
1867 }
6a488035 1868
0cf587a7 1869 /**
c490a46a 1870 * @param array $params
100fef9d
CW
1871 * @param int $participantId
1872 * @param int $contributionId
0cf587a7 1873 * @param $feeBlock
100fef9d 1874 * @param array $lineItems
0cf587a7 1875 * @param $paidAmount
100fef9d 1876 * @param int $priceSetId
0cf587a7 1877 */
00be9182 1878 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) {
0aaf8fe9
PJ
1879 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1880 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
e59da3a9 1881 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
0aaf8fe9
PJ
1882 $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant');
1883 CRM_Price_BAO_PriceSet::processAmount($feeBlock,
1884 $params, $lineItems
1885 );
1886
1887 // get the submitted
1888 foreach ($feeBlock as $id => $values) {
1889 CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems);
1890 $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id');
1891 }
5b22467a
RK
1892 if (!empty($submittedLineItems)) {
1893 $insertLines = $submittedLineItems;
1894
1895 $submittedFieldValueIds = array_keys($submittedLineItems);
1896 $updateLines = array();
1897 foreach ($previousLineItems as $id => $previousLineItem) {
1898 // check through the submitted items if the previousItem exists,
1899 // if found in submitted items, do not use it for new item creations
1900 if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
1901 // if submitted line items are existing don't fire INSERT query
1902 unset($insertLines[$previousLineItem['price_field_value_id']]);
1903 // for updating the line items i.e. use-case - once deselect-option selecting again
1904 if (($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) ||
8ab8920e
BS
1905 ($submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1) ||
1906 ($previousLineItem['qty'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'])
ddca8f33 1907 ) {
5b22467a
RK
1908 $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
1909 $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
1910 }
0b2b58ea 1911 }
0aaf8fe9 1912 }
b0a9575b 1913
5b22467a
RK
1914 $submittedFields = implode(', ', $submittedFieldId);
1915 $submittedFieldValues = implode(', ', $submittedFieldValueIds);
1916 }
0aaf8fe9 1917 if (!empty($submittedFields) && !empty($submittedFieldValues)) {
13d4664b 1918 $updateLineItem = "UPDATE civicrm_line_item li
0aaf8fe9
PJ
1919INNER JOIN civicrm_financial_item fi
1920 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
0aaf8fe9 1921SET li.qty = 0,
5a18a545 1922 li.line_total = 0.00,
1923 li.tax_amount = NULL
0aaf8fe9 1924WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
13d4664b 1925 (price_field_value_id NOT IN ({$submittedFieldValues}))
0aaf8fe9
PJ
1926";
1927 CRM_Core_DAO::executeQuery($updateLineItem);
13d4664b
PJ
1928
1929 // gathering necessary info to record negative (deselected) financial_item
1930 $updateFinancialItem = "
3636b520 1931 SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
13d4664b
PJ
1932 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1933WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
3636b520 1934GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
13d4664b
PJ
1935";
1936 $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
a191ff3d 1937 $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId, 'DESC', TRUE);
13d4664b 1938 $trxnId['id'] = $trxn['financialTrxnId'];
aaffa79f 1939 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
5a18a545 1940 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
13d4664b 1941 $updateFinancialItemInfoValues = array();
a191ff3d 1942 $financialItemsArray = array();
13d4664b
PJ
1943 while ($updateFinancialItemInfoDAO->fetch()) {
1944 $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
1945 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
3636b520 1946 // the below params are not needed
1947 unset($updateFinancialItemInfoValues['id']);
1948 unset($updateFinancialItemInfoValues['created_date']);
13d4664b
PJ
1949 // if not submitted and difference is not 0 make it negative
1950 if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
1951 // INSERT negative financial_items
ddca8f33 1952 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
5a18a545 1953 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
b4df5f60
PN
1954 $updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
1955 $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
5a18a545 1956 if ($updateFinancialItemInfoValues['financial_type_id']) {
b4df5f60 1957 $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
5a18a545 1958 }
5a18a545 1959 }
b4df5f60
PN
1960 // INSERT negative financial_items for tax amount
1961 $financialItemsArray[] = $updateFinancialItemInfoValues;
13d4664b
PJ
1962 }
1963 // if submitted and difference is 0 add a positive entry again
1964 elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
1965 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
5a18a545 1966 // INSERT financial_items for tax amount
1967 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
1968 isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
1969 ) {
a191ff3d
PN
1970 $updateFinancialItemInfoValues['tax']['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
1971 $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
5a18a545 1972 if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
a191ff3d 1973 $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
5a18a545 1974 }
5a18a545 1975 }
2b76f3da 1976 $financialItemsArray[] = $updateFinancialItemInfoValues;
13d4664b
PJ
1977 }
1978 }
0aaf8fe9 1979 }
ddca8f33 1980 elseif (empty($submittedFields) && empty($submittedFieldValues)) {
5b22467a
RK
1981 $updateLineItem = "UPDATE civicrm_line_item li
1982 INNER JOIN civicrm_financial_item fi
1983 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1984 SET li.qty = 0,
1985 li.line_total = 0.00,
1986 li.tax_amount = NULL
1987 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
1988 CRM_Core_DAO::executeQuery($updateLineItem);
1989 }
b612d89b 1990 $amountLevel = array();
1991 $totalParticipant = $participantCount = 0;
0b2b58ea
PJ
1992 if (!empty($updateLines)) {
1993 foreach ($updateLines as $valueId => $vals) {
b612d89b 1994 $taxAmount = "NULL";
5525990d 1995 if (isset($vals['tax_amount'])) {
5a18a545 1996 $taxAmount = $vals['tax_amount'];
1997 }
b612d89b 1998 $amountLevel[] = $vals['label'] . ' - ' . (float) $vals['qty'];
1999 if (isset($vals['participant_count'])) {
2000 $participantCount = $vals['participant_count'];
2001 $totalParticipant += $vals['participant_count'];
5a18a545 2002 }
0b2b58ea
PJ
2003 $updateLineItem = "
2004UPDATE civicrm_line_item li
0b2b58ea 2005SET li.qty = {$vals['qty']},
8dfe9fe3 2006 li.line_total = {$vals['line_total']},
3b5db8ce 2007 li.tax_amount = {$taxAmount},
8dfe9fe3 2008 li.unit_price = {$vals['unit_price']},
b612d89b 2009 li.participant_count = {$participantCount},
122a36b9 2010 li.label = %1
0b2b58ea
PJ
2011WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
2012 (price_field_value_id = {$valueId})
2013";
122a36b9 2014 CRM_Core_DAO::executeQuery($updateLineItem, array(1 => array($vals['label'], 'String')));
0b2b58ea
PJ
2015 }
2016 }
b75ef57e
PJ
2017 // insert new 'adjusted amount' transaction entry and update contribution entry.
2018 // ensure entity_financial_trxn table has a linking of it.
28e4e707 2019 // insert new line items
5b22467a
RK
2020 if (!empty($insertLines)) {
2021 foreach ($insertLines as $valueId => $lineParams) {
2022 $lineParams['entity_table'] = 'civicrm_participant';
2023 $lineParams['entity_id'] = $participantId;
2024 $lineParams['contribution_id'] = $contributionId;
2025 $lineObj = CRM_Price_BAO_LineItem::create($lineParams);
2026 }
28e4e707
PJ
2027 }
2028
2029 // the recordAdjustedAmt code would execute over here
2030 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
2031 if (count($ids) > 1) {
2032 $total = 0;
2033 foreach ($ids as $val) {
2034 $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
2035 }
2036 $updatedAmount = $total;
2037 }
2038 else {
2039 $updatedAmount = $params['amount'];
2040 }
5a18a545 2041 if (strlen($params['tax_amount']) != 0) {
2042 $taxAmount = $params['tax_amount'];
2043 }
2044 else {
2045 $taxAmount = "NULL";
2046 }
b612d89b 2047 $displayParticipantCount = '';
2048 if ($totalParticipant > 0) {
2049 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
2050 }
2051 $updateAmountLevel = NULL;
2052 if (!empty($amountLevel)) {
2053 $updateAmountLevel = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
2054 }
2055 $trxn = self::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel);
a191ff3d
PN
2056 $trxnId = array();
2057 if ($trxn) {
2058 $trxnId['id'] = $trxn->id;
2059 foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
2060 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
2061 if (!empty($updateFinancialItemInfoValues['tax'])) {
2062 $updateFinancialItemInfoValues['tax']['amount'] = $updateFinancialItemInfoValues['amount'];
2063 $updateFinancialItemInfoValues['tax']['description'] = $updateFinancialItemInfoValues['description'];
2064 if (!empty($updateFinancialItemInfoValues['financial_account_id'])) {
2065 $updateFinancialItemInfoValues['financial_account_id'] = $updateFinancialItemInfoValues['tax']['financial_account_id'];
2066 }
2b76f3da 2067 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
a191ff3d
PN
2068 }
2069 }
2070 }
b75ef57e
PJ
2071 $fetchCon = array('id' => $contributionId);
2072 $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
28e4e707 2073 // insert financial items
5b22467a
RK
2074 if (!empty($insertLines)) {
2075 foreach ($insertLines as $valueId => $lineParams) {
2076 $lineParams['entity_table'] = 'civicrm_participant';
2077 $lineParams['entity_id'] = $participantId;
2078 $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
2079 // insert financial items
2080 // ensure entity_financial_trxn table has a linking of it.
a191ff3d 2081 $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $trxnId);
5b22467a 2082 if (isset($lineObj->tax_amount)) {
a191ff3d 2083 CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $trxnId);
5b22467a 2084 }
5a18a545 2085 }
0aaf8fe9 2086 }
f6bae84f 2087
d5397f2f
PJ
2088 // update participant fee_amount column
2089 $partUpdateFeeAmt['id'] = $participantId;
a1acfd53 2090 $getUpdatedLineItems = "SELECT *
2091FROM civicrm_line_item
e990bc36 2092WHERE (entity_table = 'civicrm_participant' AND entity_id = {$participantId} AND qty > 0)";
2093 $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
a1acfd53 2094 while ($getUpdatedLineItemsDAO->fetch()) {
2095 $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (float) $getUpdatedLineItemsDAO->qty;
3ce0c12e
C
2096 }
2097
2098 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
d5397f2f
PJ
2099 $partUpdateFeeAmt['fee_amount'] = $params['amount'];
2100 self::add($partUpdateFeeAmt);
2101
f6bae84f
PJ
2102 //activity creation
2103 self::addActivityForSelection($participantId, 'Change Registration');
2104 }
2105
0cf587a7 2106 /**
54957108 2107 * Record adjusted amount.
2108 *
2109 * @param int $updatedAmount
2110 * @param int $paidAmount
100fef9d 2111 * @param int $contributionId
54957108 2112 *
2113 * @param int $taxAmount
2114 * @param bool $updateAmountLevel
2115 *
2116 * @return bool|\CRM_Core_BAO_FinancialTrxn
0cf587a7 2117 */
b612d89b 2118 public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
18fdfcc3 2119 $pendingAmount = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
9cf473a4 2120 $pendingAmount = CRM_Utils_Array::value('total_amount', $pendingAmount, 0);
2121 $balanceAmt = $updatedAmount - $paidAmount;
2122 if ($paidAmount != $pendingAmount) {
2123 $balanceAmt -= $pendingAmount;
2124 }
2125
f6bae84f
PJ
2126 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2127 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
e59da3a9 2128 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
921bca19
DG
2129 $completedStatusId = array_search('Completed', $contributionStatuses);
2130
2131 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
2b76f3da 2132 $adjustedTrxn = $skip = FALSE;
0aaf8fe9 2133 if ($balanceAmt) {
c6191312 2134 if ($balanceAmt > 0 && $paidAmount != 0) {
0aaf8fe9
PJ
2135 $contributionStatusVal = $partiallyPaidStatusId;
2136 }
c6191312 2137 elseif ($balanceAmt < 0 && $paidAmount != 0) {
e59da3a9 2138 $contributionStatusVal = $pendingRefundStatusId;
0aaf8fe9 2139 }
921bca19 2140 elseif ($paidAmount == 0) {
e59da3a9
DG
2141 //skip updating the contribution status if no payment is made
2142 $skip = TRUE;
921bca19
DG
2143 $updatedContributionDAO->cancel_date = 'null';
2144 $updatedContributionDAO->cancel_reason = NULL;
2145 }
0aaf8fe9
PJ
2146 // update contribution status and total amount without trigger financial code
2147 // as this is handled in current BAO function used for change selection
0aaf8fe9 2148 $updatedContributionDAO->id = $contributionId;
e59da3a9
DG
2149 if (!$skip) {
2150 $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
2151 }
b8adb851 2152 $updatedContributionDAO->total_amount = $updatedContributionDAO->net_amount = $updatedAmount;
2153 $updatedContributionDAO->fee_amount = 0;
5a18a545 2154 $updatedContributionDAO->tax_amount = $taxAmount;
b612d89b 2155 if (!empty($updateAmountLevel)) {
2156 $updatedContributionDAO->amount_level = $updateAmountLevel;
2157 }
0aaf8fe9 2158 $updatedContributionDAO->save();
13d4664b 2159 // adjusted amount financial_trxn creation
18fdfcc3
PN
2160 $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(
2161 array('id' => $contributionId),
2162 CRM_Core_DAO::$_nullArray,
2163 CRM_Core_DAO::$_nullArray
2164 );
2165 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2166 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($updatedContribution->financial_type_id, $relationTypeId);
2167 $adjustedTrxnValues = array(
2168 'from_financial_account_id' => NULL,
2169 'to_financial_account_id' => $toFinancialAccount,
2170 'total_amount' => $balanceAmt,
9cf473a4 2171 'status_id' => $completedStatusId,
18fdfcc3
PN
2172 'payment_instrument_id' => $updatedContribution->payment_instrument_id,
2173 'contribution_id' => $updatedContribution->id,
2174 'trxn_date' => date('YmdHis'),
2175 'currency' => $updatedContribution->currency,
2176 );
2177 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
0aaf8fe9 2178 }
a191ff3d 2179 return $adjustedTrxn;
0aaf8fe9
PJ
2180 }
2181
0cf587a7 2182 /**
100fef9d 2183 * @param int $participantId
0cf587a7
EM
2184 * @param $activityType
2185 *
2186 * @throws CRM_Core_Exception
2187 */
00be9182 2188 public static function addActivityForSelection($participantId, $activityType) {
0aaf8fe9
PJ
2189 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
2190 $contactId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
2191
2192 $date = CRM_Utils_Date::currentDBDate();
2193 $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
2194 $eventTitle = $event[$eventId];
2195 $subject = "Registration selections changed for $eventTitle";
2196 $targetCid = $contactId;
2197 $srcRecId = $participantId;
2198
2199 // activity params
2200 $activityParams = array(
2201 'source_contact_id' => $targetCid,
2202 'source_record_id' => $srcRecId,
2203 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
2204 $activityType,
2205 'name'
2206 ),
2207 'subject' => $subject,
2208 'activity_date_time' => $date,
2209 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
2210 'Completed',
2211 'name'
2212 ),
2213 'skipRecentView' => TRUE,
2214 );
2215
2216 // create activity with target contacts
2217 $session = CRM_Core_Session::singleton();
2218 $id = $session->get('userID');
2219 if ($id) {
2220 $activityParams['source_contact_id'] = $id;
2221 $activityParams['target_contact_id'][] = $targetCid;
2222 }
2223 CRM_Activity_BAO_Activity::create($activityParams);
2224 }
f76b27fe
CW
2225
2226 /**
2227 * Get options for a given field.
2228 * @see CRM_Core_DAO::buildOptions
2229 *
d4dd1e85
TO
2230 * @param string $fieldName
2231 * @param string $context
a1a2a83d 2232 * @see CRM_Core_DAO::buildOptionsContext
d4dd1e85 2233 * @param array $props
16b10e64 2234 * whatever is known about this dao object.
f76b27fe 2235 *
5c766a0b 2236 * @return array|bool
f76b27fe
CW
2237 */
2238 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2239 $params = array('condition' => array());
2240
2241 if ($fieldName == 'status_id' && $context != 'validate') {
2242 // Get rid of cart-related option if disabled
2243 // FIXME: Why does this option even exist if cart is disabled?
aaffa79f 2244 if (!Civi::settings()->get('enable_cart')) {
f76b27fe
CW
2245 $params['condition'][] = "name <> 'Pending in cart'";
2246 }
2247 }
2248
2249 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
2250 }
96025800 2251
c7d52684 2252 /**
c50429ca 2253 * CRM-17797 -- Format fields and setDefaults for primary and additional participants profile
2254 * @param int $contactId
2255 * @param CRM_Core_Form $form
c7d52684 2256 */
2257 public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
2258 if (!$contactId) {
2259 return;
2260 }
2261 $fields = array();
2262 if (!empty($form->_fields)) {
2263 $removeCustomFieldTypes = array('Participant');
2264
2265 foreach ($form->_fields as $name => $dontCare) {
2266 if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
2267 && !CRM_Core_BAO_CustomGroup::checkCustomField(substr($name, 7), $removeCustomFieldTypes))
2268 || substr($name, 0, 12) == 'participant_') {
2269 continue;
2270 }
2271 $fields[$name] = 1;
2272 }
2273
2274 if (!empty($fields)) {
2275 CRM_Core_BAO_UFGroup::setProfileDefaults($contactId, $fields, $form->_defaults);
2276 }
2277 }
2278 }
2279
37d5fc55 2280}