Merge pull request #7575 from saurabhbatra96/CRM-17801
[civicrm-core.git] / CRM / Event / BAO / Participant.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26
e70a7fc0 27 */
6a488035
TO
28
29/**
6a488035 30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
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
141 // reset the group contact cache for this group
142 CRM_Contact_BAO_GroupContactCache::remove();
143
a7488080 144 if (!empty($params['id'])) {
6a488035
TO
145 CRM_Utils_Hook::post('edit', 'Participant', $participantBAO->id, $participantBAO);
146 }
147 else {
148 CRM_Utils_Hook::post('create', 'Participant', $participantBAO->id, $participantBAO);
149 }
150
151 return $participantBAO;
152 }
153
154 /**
155 * Given the list of params in the params array, fetch the object
156 * and store the values in the values array
157 *
d4dd1e85
TO
158 * @param array $params
159 * Input parameters to find object.
160 * @param array $values
161 * Output values of the object.
6a488035 162 *
77035e4b
EM
163 * @param $ids
164 *
6a488035 165 * @return CRM_Event_BAO_Participant|null the found object or null
6a488035 166 */
00be9182 167 public static function getValues(&$params, &$values, &$ids) {
6a488035
TO
168 if (empty($params)) {
169 return NULL;
170 }
171 $participant = new CRM_Event_BAO_Participant();
172 $participant->copyValues($params);
173 $participant->find();
174 $participants = array();
175 while ($participant->fetch()) {
176 $ids['participant'] = $participant->id;
177 CRM_Core_DAO::storeValues($participant, $values[$participant->id]);
178 $participants[$participant->id] = $participant;
179 }
180 return $participants;
181 }
182
183 /**
66f9e52b 184 * Takes an associative array and creates a participant object.
6a488035 185 *
d4dd1e85
TO
186 * @param array $params
187 * (reference ) an assoc array of name/value pairs.
77035e4b 188 *
16b10e64 189 * @return CRM_Event_BAO_Participant
6a488035 190 */
00be9182 191 public static function create(&$params) {
6a488035
TO
192
193 $transaction = new CRM_Core_Transaction();
194 $status = NULL;
195
a7488080 196 if (!empty($params['id'])) {
6a488035
TO
197 $status = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
198 }
199
200 $participant = self::add($params);
201
202 if (is_a($participant, 'CRM_Core_Error')) {
203 $transaction->rollback();
204 return $participant;
205 }
206
207 if ((!CRM_Utils_Array::value('id', $params)) ||
9af2925b 208 (isset($params['status_id']) && $params['status_id'] != $status)
6a488035
TO
209 ) {
210 CRM_Activity_BAO_Activity::addActivity($participant);
211 }
212
213 //CRM-5403
214 //for update mode
215 if (self::isPrimaryParticipant($participant->id) && $status) {
216 self::updateParticipantStatus($participant->id, $status, $participant->status_id);
217 }
218
219 $session = CRM_Core_Session::singleton();
220 $id = $session->get('userID');
221 if (!$id) {
edf1b210 222 $id = CRM_Utils_Array::value('contact_id', $params);
6a488035
TO
223 }
224
225 // add custom field values
a7488080 226 if (!empty($params['custom']) &&
6a488035
TO
227 is_array($params['custom'])
228 ) {
229 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_participant', $participant->id);
230 }
231
232 //process note, CRM-7634
233 $noteId = NULL;
a7488080 234 if (!empty($params['id'])) {
6a488035
TO
235 $note = CRM_Core_BAO_Note::getNote($params['id'], 'civicrm_participant');
236 $noteId = key($note);
237 }
238 $noteValue = NULL;
239 $hasNoteField = FALSE;
240 foreach (array(
ddca8f33 241 'note',
21dfd5f5 242 'participant_note',
ddca8f33 243 ) as $noteFld) {
6a488035
TO
244 if (array_key_exists($noteFld, $params)) {
245 $noteValue = $params[$noteFld];
246 $hasNoteField = TRUE;
247 break;
248 }
249 }
250 if ($noteId || $noteValue) {
251 if ($noteValue) {
252 $noteParams = array(
253 'entity_table' => 'civicrm_participant',
254 'note' => $noteValue,
255 'entity_id' => $participant->id,
256 'contact_id' => $id,
257 'modified_date' => date('Ymd'),
258 );
259 $noteIDs = array();
260 if ($noteId) {
261 $noteIDs['id'] = $noteId;
262 }
263 CRM_Core_BAO_Note::add($noteParams, $noteIDs);
264 }
265 elseif ($noteId && $hasNoteField) {
266 CRM_Core_BAO_Note::del($noteId, FALSE);
267 }
268 }
269
270 // Log the information on successful add/edit of Participant data.
271 $logParams = array(
272 'entity_table' => 'civicrm_participant',
273 'entity_id' => $participant->id,
274 'data' => CRM_Event_PseudoConstant::participantStatus($participant->status_id),
275 'modified_id' => $id,
276 'modified_date' => date('Ymd'),
277 );
278
279 CRM_Core_BAO_Log::add($logParams);
280
281 $params['participant_id'] = $participant->id;
282
283 $transaction->commit();
284
285 // do not add to recent items for import, CRM-4399
a7488080 286 if (empty($params['skipRecentView'])) {
6a488035
TO
287
288 $url = CRM_Utils_System::url('civicrm/contact/view/participant',
289 "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
290 );
291
292 $recentOther = array();
293 if (CRM_Core_Permission::check('edit event participants')) {
294 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
295 "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
296 );
297 }
298 if (CRM_Core_Permission::check('delete in CiviEvent')) {
299 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
300 "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
301 );
302 }
303
304 $participantRoles = CRM_Event_PseudoConstant::participantRole();
305
306 if ($participant->role_id) {
307 $role = explode(CRM_Core_DAO::VALUE_SEPARATOR, $participant->role_id);
308
309 foreach ($role as & $roleValue) {
310 if (isset($roleValue)) {
311 $roleValue = $participantRoles[$roleValue];
312 }
313 }
314 $roles = implode(', ', $role);
315 }
316
317 $roleString = empty($roles) ? '' : $roles;
318 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $participant->event_id, 'title');
319 $title = CRM_Contact_BAO_Contact::displayName($participant->contact_id) . ' (' . $roleString . ' - ' . $eventTitle . ')';
320
321 // add the recently created Participant
322 CRM_Utils_Recent::add($title,
323 $url,
324 $participant->id,
325 'Participant',
326 $participant->contact_id,
327 NULL,
328 $recentOther
329 );
330 }
331
332 return $participant;
333 }
334
335 /**
66f9e52b 336 * Check whether the event is full for participation and return as.
6a488035
TO
337 * per requirements.
338 *
d4dd1e85
TO
339 * @param int $eventId
340 * Event id.
341 * @param bool $returnEmptySeats
342 * Are we require number if empty seats.
343 * @param bool $includeWaitingList
344 * Consider waiting list in event full.
6a488035
TO
345 * calculation or not. (it is for cron job purpose)
346 *
77035e4b
EM
347 * @param bool $returnWaitingCount
348 * @param bool $considerTestParticipant
6a488035 349 *
72b3a70c
CW
350 * @return bool|int|null|string
351 * 1. false => If event having some empty spaces.
6a488035 352 */
2da40d21 353 public static function eventFull(
6a488035
TO
354 $eventId,
355 $returnEmptySeats = FALSE,
356 $includeWaitingList = TRUE,
357 $returnWaitingCount = FALSE,
358 $considerTestParticipant = FALSE
359 ) {
360 $result = NULL;
361 if (!$eventId) {
362 return $result;
363 }
364
365 // consider event is full when.
366 // 1. (count(is_counted) >= event_size) or
367 // 2. (count(participants-with-status-on-waitlist) > 0)
368 // It might be case there are some empty spaces and still event
369 // is full, as waitlist might represent group require spaces > empty.
370
ddca8f33
TO
371 $participantRoles = CRM_Event_PseudoConstant::participantRole(NULL, 'filter = 1');
372 $countedStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
373 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
6a488035
TO
374 $onWaitlistStatusId = array_search('On waitlist', $waitingStatuses);
375
376 //when we do require only waiting count don't consider counted.
377 if (!$returnWaitingCount && !empty($countedStatuses)) {
378 $allStatusIds = array_keys($countedStatuses);
379 }
380
381 $where = array(' event.id = %1 ');
382 if (!$considerTestParticipant) {
383 $where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
384 }
385 if (!empty($participantRoles)) {
0906de17
MM
386 $escapedRoles = array();
387 foreach (array_keys($participantRoles) as $participantRole) {
388 $escapedRoles[] = CRM_Utils_Type::escape($participantRole, 'String');
389 }
390
aba574d4 391 $where[] = " participant.role_id IN ( '" . implode("', '", $escapedRoles) . "' ) ";
6a488035
TO
392 }
393
394 $eventParams = array(1 => array($eventId, 'Positive'));
395
396 //in case any waiting, straight forward event is full.
397 if ($includeWaitingList && $onWaitlistStatusId) {
398
399 //build the where clause.
ddca8f33
TO
400 $whereClause = ' WHERE ' . implode(' AND ', $where);
401 $whereClause .= " AND participant.status_id = $onWaitlistStatusId ";
6a488035
TO
402 $eventSeatsWhere = implode(' AND ', $where) . " AND ( participant.status_id = $onWaitlistStatusId )";
403
404 $query = "
405 SELECT participant.id id,
406 event.event_full_text as event_full_text
407 FROM civicrm_participant participant
408INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
409 {$whereClause}";
410
92d6c5f5 411 $eventFullText = ts('This event is full.');
6a488035
TO
412 $participants = CRM_Core_DAO::executeQuery($query, $eventParams);
413 while ($participants->fetch()) {
414 //oops here event is full and we don't want waiting count.
415 if ($returnWaitingCount) {
416 return CRM_Event_BAO_Event::eventTotalSeats($eventId, $eventSeatsWhere);
417 }
418 else {
419 return ($participants->event_full_text) ? $participants->event_full_text : $eventFullText;
420 }
421 }
422 }
423
424 //consider only counted participants.
ddca8f33
TO
425 $where[] = ' participant.status_id IN ( ' . implode(', ', array_keys($countedStatuses)) . ' ) ';
426 $whereClause = ' WHERE ' . implode(' AND ', $where);
6a488035
TO
427 $eventSeatsWhere = implode(' AND ', $where);
428
429 $query = "
430 SELECT participant.id id,
431 event.event_full_text as event_full_text,
432 event.max_participants as max_participants
433 FROM civicrm_participant participant
434INNER JOIN civicrm_event event ON ( event.id = participant.event_id )
435 {$whereClause}";
436
437 $eventMaxSeats = NULL;
92d6c5f5 438 $eventFullText = ts('This event is full.');
ddca8f33 439 $participants = CRM_Core_DAO::executeQuery($query, $eventParams);
6a488035
TO
440 while ($participants->fetch()) {
441 if ($participants->event_full_text) {
442 $eventFullText = $participants->event_full_text;
443 }
444 $eventMaxSeats = $participants->max_participants;
445 //don't have limit for event seats.
446 if ($participants->max_participants == NULL) {
447 return $result;
448 }
449 }
450
451 //get the total event seats occupied by these participants.
452 $eventRegisteredSeats = CRM_Event_BAO_Event::eventTotalSeats($eventId, $eventSeatsWhere);
453
454 if ($eventRegisteredSeats) {
455 if ($eventRegisteredSeats >= $eventMaxSeats) {
456 $result = $eventFullText;
457 }
458 elseif ($returnEmptySeats) {
459 $result = $eventMaxSeats - $eventRegisteredSeats;
460 }
461 return $result;
462 }
463 else {
464 $query = '
465SELECT event.event_full_text,
466 event.max_participants
467 FROM civicrm_event event
468 WHERE event.id = %1';
469 $event = CRM_Core_DAO::executeQuery($query, $eventParams);
470 while ($event->fetch()) {
471 $eventFullText = $event->event_full_text;
472 $eventMaxSeats = $event->max_participants;
473 }
474 }
475
476 // no limit for registration.
477 if ($eventMaxSeats == NULL) {
478 return $result;
479 }
480 if ($eventMaxSeats) {
481 return ($returnEmptySeats) ? (int) $eventMaxSeats : FALSE;
482 }
483
31312bdc 484 return $eventFullText;
6a488035
TO
485 }
486
487 /**
488 * Return the array of all price set field options,
489 * with total participant count that field going to carry.
490 *
d4dd1e85
TO
491 * @param int $eventId
492 * Event id.
493 * @param array $skipParticipantIds
494 * An array of participant ids those we should skip.
77035e4b
EM
495 * @param bool $considerCounted
496 * @param bool $considerWaiting
497 * @param bool $considerTestParticipants
498 *
a6c01b45
CW
499 * @return array
500 * an array of each option id and total count
6a488035 501 */
2da40d21 502 public static function priceSetOptionsCount(
6a488035
TO
503 $eventId,
504 $skipParticipantIds = array(),
505 $considerCounted = TRUE,
506 $considerWaiting = TRUE,
507 $considerTestParticipants = FALSE
508 ) {
509 $optionsCount = array();
510 if (!$eventId) {
511 return $optionsCount;
512 }
513
514 $allStatusIds = array();
515 if ($considerCounted) {
516 $countedStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
517 $allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
518 }
519 if ($considerWaiting) {
520 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
521 $allStatusIds = array_merge($allStatusIds, array_keys($waitingStatuses));
522 }
523 $statusIdClause = NULL;
524 if (!empty($allStatusIds)) {
525 $statusIdClause = ' AND participant.status_id IN ( ' . implode(', ', array_values($allStatusIds)) . ')';
526 }
527
528 $isTestClause = NULL;
529 if (!$considerTestParticipants) {
530 $isTestClause = ' AND ( participant.is_test IS NULL OR participant.is_test = 0 )';
531 }
532
533 $skipParticipantClause = NULL;
534 if (is_array($skipParticipantIds) && !empty($skipParticipantIds)) {
535 $skipParticipantClause = ' AND participant.id NOT IN ( ' . implode(', ', $skipParticipantIds) . ')';
536 }
537
538 $sql = "
539 SELECT line.id as lineId,
540 line.entity_id as entity_id,
541 line.qty,
542 value.id as valueId,
543 value.count,
544 field.html_type
545 FROM civicrm_line_item line
546INNER JOIN civicrm_participant participant ON ( line.entity_table = 'civicrm_participant'
547 AND participant.id = line.entity_id )
548INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
549INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
550 WHERE participant.event_id = %1
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',
21dfd5f5 652 ),
ddca8f33 653 );
6a488035 654
3cb8f9b2
CW
655 // Split status and status id into 2 fields
656 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
6a488035
TO
657 $participantStatus = array(
658 'participant_status' => array(
3cb8f9b2 659 'title' => ts('Participant Status'),
6a488035
TO
660 'name' => 'participant_status',
661 'data_type' => CRM_Utils_Type::T_STRING,
21dfd5f5 662 ),
ddca8f33 663 );
3cb8f9b2 664 $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
6a488035 665
3cb8f9b2
CW
666 // Split role and role id into 2 fields
667 // Fixme: it would be better to leave as 1 field and intelligently handle both during import
6a488035
TO
668 $participantRole = array(
669 'participant_role' => array(
3cb8f9b2 670 'title' => ts('Participant Role'),
6a488035
TO
671 'name' => 'participant_role',
672 'data_type' => CRM_Utils_Type::T_STRING,
21dfd5f5 673 ),
ddca8f33 674 );
3cb8f9b2 675 $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
6a488035
TO
676
677 $eventType = array(
678 'event_type' => array(
3cb8f9b2 679 'title' => ts('Event Type'),
6a488035
TO
680 'name' => 'event_type',
681 'data_type' => CRM_Utils_Type::T_STRING,
21dfd5f5 682 ),
ddca8f33 683 );
6a488035
TO
684
685 $tmpContactField = $contactFields = array();
0479b4c8 686 $contactFields = array();
6a488035
TO
687 if (!$onlyParticipant) {
688 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
689
690 // Using new Dedupe rule.
691 $ruleParams = array(
692 'contact_type' => $contactType,
ddca8f33 693 'used' => 'Unsupervised',
6a488035
TO
694 );
695 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
696
697 if (is_array($fieldsArray)) {
698 foreach ($fieldsArray as $value) {
699 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
700 $value,
701 'id',
702 'column_name'
703 );
704 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
705 $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
706 if (!$status) {
707 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
708 }
709 else {
710 $title = $tmpContactField[trim($value)]['title'];
711 }
712
713 $tmpContactField[trim($value)]['title'] = $title;
714 }
715 }
716 }
717 $extIdentifier = CRM_Utils_Array::value('external_identifier', $contactFields);
718 if ($extIdentifier) {
719 $tmpContactField['external_identifier'] = $extIdentifier;
6c552737 720 $tmpContactField['external_identifier']['title'] = CRM_Utils_Array::value('title', $extIdentifier) . ' (match to contact)';
6a488035 721 }
6c552737 722 $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
6a488035 723
6a488035
TO
724 $fields = array_merge($fields, $tmpContactField);
725 $fields = array_merge($fields, $tmpFields);
726 $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
e9ff5391 727 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
6a488035
TO
728
729 self::$_importableFields = $fields;
730 }
731
732 return self::$_importableFields;
733 }
734
735 /**
e9ff5391 736 * Combine all the exportable fields from the lower level objects.
737 *
738 * @param bool $checkPermission
6a488035 739 *
a6c01b45
CW
740 * @return array
741 * array of exportable Fields
6a488035 742 */
e9ff5391 743 public static function &exportableFields($checkPermission = TRUE) {
6a488035
TO
744 if (!self::$_exportableFields) {
745 if (!self::$_exportableFields) {
746 self::$_exportableFields = array();
747 }
748
6a488035 749 $participantFields = CRM_Event_DAO_Participant::export();
e51b7372 750 $eventFields = CRM_Event_DAO_Event::export();
6a488035 751 $noteField = array(
0479b4c8 752 'participant_note' => array(
ddca8f33 753 'title' => 'Participant Note',
6a488035 754 'name' => 'participant_note',
e51b7372 755 'type' => CRM_Utils_Type::T_STRING,
a1a2a83d
TO
756 ),
757 );
6a488035 758
a1a2a83d 759 $participantStatus = array(
0479b4c8 760 'participant_status' => array(
ddca8f33 761 'title' => 'Participant Status',
6a488035 762 'name' => 'participant_status',
e51b7372 763 'type' => CRM_Utils_Type::T_STRING,
a1a2a83d
TO
764 ),
765 );
6a488035 766
a1a2a83d 767 $participantRole = array(
0479b4c8 768 'participant_role' => array(
ddca8f33 769 'title' => 'Participant Role',
6a488035 770 'name' => 'participant_role',
e51b7372 771 'type' => CRM_Utils_Type::T_STRING,
a1a2a83d
TO
772 ),
773 );
8b8fa582 774
a1a2a83d 775 $discountFields = CRM_Core_DAO_Discount::export();
6a488035 776
a1a2a83d 777 $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields);
6a488035 778
a1a2a83d 779 // add custom data
e9ff5391 780 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
a1a2a83d 781 self::$_exportableFields = $fields;
6a488035
TO
782 }
783
784 return self::$_exportableFields;
785 }
786
787 /**
100fef9d 788 * Get the event name/sort name for a particular participation / participant
6a488035 789 *
d4dd1e85
TO
790 * @param int $participantId
791 * Id of the participant.
6a488035 792 *
a6c01b45
CW
793 * @return array
794 * associated array with sort_name and event title
6a488035 795 */
00be9182 796 public static function participantDetails($participantId) {
6a488035
TO
797 $query = "
798SELECT civicrm_contact.sort_name as name, civicrm_event.title as title, civicrm_contact.id as cid
799FROM civicrm_participant
800 LEFT JOIN civicrm_event ON (civicrm_participant.event_id = civicrm_event.id)
801 LEFT JOIN civicrm_contact ON (civicrm_participant.contact_id = civicrm_contact.id)
802WHERE civicrm_participant.id = {$participantId}
803";
804 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
805
806 $details = array();
807 while ($dao->fetch()) {
ddca8f33 808 $details['name'] = $dao->name;
6a488035 809 $details['title'] = $dao->title;
ddca8f33 810 $details['cid'] = $dao->cid;
6a488035
TO
811 }
812
813 return $details;
814 }
815
816 /**
817 * Get the values for pseudoconstants for name->value and reverse.
818 *
d4dd1e85
TO
819 * @param array $defaults
820 * (reference) the default values, some of which need to be resolved.
821 * @param bool $reverse
822 * True if we want to resolve the values in the reverse direction (value -> name).
6a488035 823 */
00be9182 824 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
6a488035
TO
825 self::lookupValue($defaults, 'event', CRM_Event_PseudoConstant::event(), $reverse);
826 self::lookupValue($defaults, 'status', CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'), $reverse);
827 self::lookupValue($defaults, 'role', CRM_Event_PseudoConstant::participantRole(), $reverse);
828 }
829
830 /**
3bdf1f3a 831 * Convert associative array names to values and vice-versa.
6a488035
TO
832 *
833 * This function is used by both the web form layer and the api. Note that
834 * the api needs the name => value conversion, also the view layer typically
835 * requires value => name conversion
ad37ac8e 836 *
837 * @param array $defaults
838 * @param string $property
839 * @param string $lookup
840 * @param bool $reverse
841 *
842 * @return bool
6a488035 843 */
00be9182 844 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
6a488035
TO
845 $id = $property . '_id';
846
847 $src = $reverse ? $property : $id;
848 $dst = $reverse ? $id : $property;
849
850 if (!array_key_exists($src, $defaults)) {
851 return FALSE;
852 }
853
854 $look = $reverse ? array_flip($lookup) : $lookup;
855
856 if (is_array($look)) {
857 if (!array_key_exists($defaults[$src], $look)) {
858 return FALSE;
859 }
860 }
861 $defaults[$dst] = $look[$defaults[$src]];
862 return TRUE;
863 }
864
865 /**
3bdf1f3a 866 * Delete the records that are associated with this participation.
6a488035 867 *
d4dd1e85
TO
868 * @param int $id
869 * Id of the participation to delete.
6a488035 870 *
3bdf1f3a 871 * @return \CRM_Event_DAO_Participant
6a488035 872 */
00be9182 873 public static function deleteParticipant($id) {
6a488035
TO
874 CRM_Utils_Hook::pre('delete', 'Participant', $id, CRM_Core_DAO::$_nullArray);
875
876 $transaction = new CRM_Core_Transaction();
877
878 //delete activity record
879 $params = array(
880 'source_record_id' => $id,
881 // activity type id for event registration
882 'activity_type_id' => 5,
883 );
884
885 CRM_Activity_BAO_Activity::deleteActivity($params);
886
887 // delete the participant payment record
888 // we need to do this since the cascaded constraints
889 // dont work with join tables
890 $p = array('participant_id' => $id);
891 CRM_Event_BAO_ParticipantPayment::deleteParticipantPayment($p);
892
893 // cleanup line items.
ddca8f33
TO
894 $participantsId = array();
895 $participantsId = self::getAdditionalParticipantIds($id);
6a488035
TO
896 $participantsId[] = $id;
897 CRM_Price_BAO_LineItem::deleteLineItems($participantsId, 'civicrm_participant');
898
899 //delete note when participant deleted.
900 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_participant');
901 $noteId = key($note);
902 if ($noteId) {
903 CRM_Core_BAO_Note::del($noteId, FALSE);
904 }
905
906 $participant = new CRM_Event_DAO_Participant();
907 $participant->id = $id;
908 $participant->delete();
909
910 $transaction->commit();
911
912 CRM_Utils_Hook::post('delete', 'Participant', $participant->id, $participant);
913
914 // delete the recently created Participant
915 $participantRecent = array(
916 'id' => $id,
917 'type' => 'Participant',
918 );
919
920 CRM_Utils_Recent::del($participantRecent);
921
922 return $participant;
923 }
924
925 /**
66f9e52b 926 * Checks duplicate participants.
6a488035 927 *
d4dd1e85
TO
928 * @param array $input
929 * An assosiative array of name /value pairs.
16b10e64 930 * from other function
a1a2a83d
TO
931 * @param array $duplicates
932 * (reference ) an assoc array of name/value pairs.
6a488035 933 *
16b10e64 934 * @return CRM_Contribute_BAO_Contribution
6a488035 935 */
00be9182 936 public static function checkDuplicate($input, &$duplicates) {
6a488035
TO
937 $eventId = CRM_Utils_Array::value('event_id', $input);
938 $contactId = CRM_Utils_Array::value('contact_id', $input);
939
940 $clause = array();
941 $input = array();
942
943 if ($eventId) {
944 $clause[] = "event_id = %1";
945 $input[1] = array($eventId, 'Integer');
946 }
947
948 if ($contactId) {
949 $clause[] = "contact_id = %2";
950 $input[2] = array($contactId, 'Integer');
951 }
952
953 if (empty($clause)) {
954 return FALSE;
955 }
956
957 $clause = implode(' AND ', $clause);
958
ddca8f33
TO
959 $query = "SELECT id FROM civicrm_participant WHERE $clause";
960 $dao = CRM_Core_DAO::executeQuery($query, $input);
6a488035
TO
961 $result = FALSE;
962 while ($dao->fetch()) {
963 $duplicates[] = $dao->id;
964 $result = TRUE;
965 }
966 return $result;
967 }
968
969 /**
66f9e52b 970 * Fix the event level.
6a488035
TO
971 *
972 * When price sets are used as event fee, fee_level is set as ^A
77035e4b 973 * separated string. We need to change that string to comma
6a488035
TO
974 * separated string before using fee_level in view mode.
975 *
d4dd1e85 976 * @param string $eventLevel
3bdf1f3a 977 * Event_level string from db.
6a488035 978 */
00be9182 979 public static function fixEventLevel(&$eventLevel) {
6a488035
TO
980 if ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR) &&
981 (substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)
982 ) {
9747cc7e 983 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($eventLevel, 1, -1)));
0cca0bf4
J
984 $pos = strrpos($eventLevel, '(multiple participants)', 0);
985 if ($pos) {
6a488035
TO
986 $eventLevel = substr_replace($eventLevel, "", $pos - 3, 1);
987 }
988 }
989 elseif ((substr($eventLevel, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
990 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
ddca8f33
TO
991 substr($eventLevel, 0, 1)
992 ));
6a488035
TO
993 }
994 elseif ((substr($eventLevel, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)) {
995 $eventLevel = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR,
ddca8f33
TO
996 substr($eventLevel, 0, -1)
997 ));
6a488035
TO
998 }
999 }
1000
1001 /**
100fef9d 1002 * Get the additional participant ids.
6a488035 1003 *
d4dd1e85
TO
1004 * @param int $primaryParticipantId
1005 * Primary partycipant Id.
1006 * @param bool $excludeCancel
1007 * Do not include participant those are cancelled.
654ca41c 1008 *
100fef9d 1009 * @param int $oldStatusId
6a488035 1010 *
a6c01b45 1011 * @return array
6a488035 1012 */
00be9182 1013 public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
6a488035
TO
1014 $additionalParticipantIds = array();
1015 if (!$primaryParticipantId) {
1016 return $additionalParticipantIds;
1017 }
1018
1019 $where = "participant.registered_by_id={$primaryParticipantId}";
1020 if ($excludeCancel) {
ddca8f33 1021 $cancelStatusId = 0;
6a488035 1022 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
ddca8f33 1023 $cancelStatusId = array_search('Cancelled', $negativeStatuses);
6a488035
TO
1024 $where .= " AND participant.status_id != {$cancelStatusId}";
1025 }
1026
1027 if ($oldStatusId) {
1028 $where .= " AND participant.status_id = {$oldStatusId}";
1029 }
1030
1031 $query = "
1032 SELECT participant.id
1033 FROM civicrm_participant participant
1034 WHERE {$where}";
1035
1036 $dao = CRM_Core_DAO::executeQuery($query);
1037 while ($dao->fetch()) {
1038 $additionalParticipantIds[$dao->id] = $dao->id;
1039 }
1040 return $additionalParticipantIds;
1041 }
1042
1043 /**
1044 * Get the event fee info for given participant ids
1045 * either from line item table / participant table.
1046 *
d4dd1e85
TO
1047 * @param array $participantIds
1048 * Participant ids.
1049 * @param bool $hasLineItems
1050 * Do fetch from line items.
6a488035 1051 *
a6c01b45 1052 * @return array
6a488035 1053 */
00be9182 1054 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
6a488035
TO
1055 $feeDetails = array();
1056 if (!is_array($participantIds) || empty($participantIds)) {
1057 return $feeDetails;
1058 }
1059
1060 $select = '
1061SELECT participant.id as id,
1062 participant.fee_level as fee_level,
1063 participant.fee_amount as fee_amount';
1064 $from = 'FROM civicrm_participant participant';
1065 if ($hasLineItems) {
1066 $select .= ' ,
1067lineItem.id as lineId,
1068lineItem.label as label,
1069lineItem.qty as qty,
1070lineItem.unit_price as unit_price,
1071lineItem.line_total as line_total,
1072field.label as field_title,
1073field.html_type as html_type,
1074field.id as price_field_id,
1075value.id as price_field_value_id,
1076value.description as description,
1077IF( value.count, value.count, 0 ) as participant_count';
1078 $from .= "
1079INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
1080 AND lineItem.entity_id = participant.id )
1081INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
1082INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
1083";
1084 }
1085 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
1086 $query = "$select $from $where";
1087
ddca8f33
TO
1088 $feeInfo = CRM_Core_DAO::executeQuery($query);
1089 $feeProperties = array('fee_level', 'fee_amount');
6a488035 1090 $lineProperties = array(
ddca8f33
TO
1091 'lineId',
1092 'label',
1093 'qty',
1094 'unit_price',
1095 'line_total',
1096 'field_title',
1097 'html_type',
1098 'price_field_id',
1099 'participant_count',
1100 'price_field_value_id',
1101 'description',
6a488035
TO
1102 );
1103 while ($feeInfo->fetch()) {
1104 if ($hasLineItems) {
1105 foreach ($lineProperties as $property) {
1106 $feeDetails[$feeInfo->id][$feeInfo->lineId][$property] = $feeInfo->$property;
1107 }
1108 }
1109 else {
ddca8f33
TO
1110 foreach ($feeProperties as $property) {
1111 $feeDetails[$feeInfo->id][$property] = $feeInfo->$property;
0479b4c8 1112 }
6a488035
TO
1113 }
1114 }
1115
1116 return $feeDetails;
1117 }
1118
1119 /**
1120 * Retrieve additional participants display-names and URL to view their participant records.
1121 * (excludes cancelled participants automatically)
1122 *
d4dd1e85
TO
1123 * @param int $primaryParticipantID
1124 * Id of primary participant record.
6a488035 1125 *
a6c01b45
CW
1126 * @return array
1127 * $displayName => $viewUrl
6a488035 1128 */
00be9182 1129 public static function getAdditionalParticipants($primaryParticipantID) {
6a488035
TO
1130 $additionalParticipantIDs = array();
1131 $additionalParticipantIDs = self::getAdditionalParticipantIds($primaryParticipantID);
1132 if (!empty($additionalParticipantIDs)) {
1133 foreach ($additionalParticipantIDs as $additionalParticipantID) {
1134 $additionalContactID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1135 $additionalParticipantID,
1136 'contact_id', 'id'
1137 );
1138 $additionalContactName = CRM_Contact_BAO_Contact::displayName($additionalContactID);
1139 $pViewURL = CRM_Utils_System::url('civicrm/contact/view/participant',
1140 "action=view&reset=1&id={$additionalParticipantID}&cid={$additionalContactID}"
1141 );
1142
1143 $additionalParticipants[$additionalContactName] = $pViewURL;
1144 }
1145 }
1146 return $additionalParticipants;
1147 }
1148
1149 /**
66f9e52b 1150 * Function for update primary and additional participant status.
6a488035 1151 *
d4dd1e85
TO
1152 * @param int $participantID
1153 * Primary participant's id.
100fef9d
CW
1154 * @param int $oldStatusID
1155 * @param int $newStatusID
654ca41c
EM
1156 * @param bool $updatePrimaryStatus
1157 *
a1a2a83d 1158 * @return bool|NULL
6a488035 1159 */
00be9182 1160 public static function updateParticipantStatus($participantID, $oldStatusID, $newStatusID = NULL, $updatePrimaryStatus = FALSE) {
6a488035 1161 if (!$participantID || !$oldStatusID) {
a1a2a83d 1162 return NULL;
6a488035
TO
1163 }
1164
1165 if (!$newStatusID) {
1166 $newStatusID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id');
1167 }
1168 elseif ($updatePrimaryStatus) {
1169 CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $participantID, 'status_id', $newStatusID);
1170 }
1171
1172 $cascadeAdditionalIds = self::getValidAdditionalIds($participantID, $oldStatusID, $newStatusID);
1173
1174 if (!empty($cascadeAdditionalIds)) {
1175 $cascadeAdditionalIds = implode(',', $cascadeAdditionalIds);
1176 $query = "UPDATE civicrm_participant cp SET cp.status_id = %1 WHERE cp.id IN ({$cascadeAdditionalIds})";
1177 $params = array(1 => array($newStatusID, 'Integer'));
1178 $dao = CRM_Core_DAO::executeQuery($query, $params);
1179 return TRUE;
1180 }
1181 return FALSE;
1182 }
1183
1184 /**
66f9e52b 1185 * Function for update status for given participant ids.
6a488035 1186 *
d4dd1e85
TO
1187 * @param int $participantIds
1188 * Array of participant ids.
1189 * @param int $statusId
1190 * Status id for participant.
654ca41c 1191 * @param bool $updateRegisterDate
6a488035 1192 */
00be9182 1193 public static function updateStatus($participantIds, $statusId, $updateRegisterDate = FALSE) {
6a488035
TO
1194 if (!is_array($participantIds) || empty($participantIds) || !$statusId) {
1195 return;
1196 }
1197
1198 //lets update register date as we update status to keep track
1199 //when we did update status, useful for moving participant
1200 //from pending to expired.
1201 $setClause = "status_id = {$statusId}";
1202 if ($updateRegisterDate) {
1203 $setClause .= ", register_date = NOW()";
1204 }
1205
1206 $participantIdClause = '( ' . implode(',', $participantIds) . ' )';
1207
1208 $query = "
1209UPDATE civicrm_participant
1210 SET {$setClause}
1211 WHERE id IN {$participantIdClause}";
1212
1213 $dao = CRM_Core_DAO::executeQuery($query);
1214 }
1215
654ca41c 1216 /**
6a488035
TO
1217 * Function takes participant ids and statuses
1218 * update status from $fromStatusId to $toStatusId
1219 * and send mail + create activities.
1220 *
d4dd1e85
TO
1221 * @param array $participantIds
1222 * Participant ids.
1223 * @param int $toStatusId
1224 * Update status id.
1225 * @param int $fromStatusId
1226 * From status id.
654ca41c
EM
1227 * @param bool $returnResult
1228 * @param bool $skipCascadeRule
1229 *
a1a2a83d 1230 * @return array|NULL
6a488035 1231 */
2da40d21 1232 public static function transitionParticipants(
ddca8f33 1233 $participantIds, $toStatusId,
6a488035
TO
1234 $fromStatusId = NULL, $returnResult = FALSE, $skipCascadeRule = FALSE
1235 ) {
1236 if (!is_array($participantIds) || empty($participantIds) || !$toStatusId) {
a1a2a83d 1237 return NULL;
6a488035
TO
1238 }
1239
1240 //thumb rule is if we triggering primary participant need to triggered additional
1241 $allParticipantIds = $primaryANDAdditonalIds = array();
1242 foreach ($participantIds as $id) {
1243 $allParticipantIds[] = $id;
1244 if (self::isPrimaryParticipant($id)) {
1245 //filter additional as per status transition rules, CRM-5403
1246 if ($skipCascadeRule) {
1247 $additionalIds = self::getAdditionalParticipantIds($id);
1248 }
1249 else {
1250 $additionalIds = self::getValidAdditionalIds($id, $fromStatusId, $toStatusId);
1251 }
1252 if (!empty($additionalIds)) {
1253 $allParticipantIds = array_merge($allParticipantIds, $additionalIds);
1254 $primaryANDAdditonalIds[$id] = $additionalIds;
1255 }
1256 }
1257 }
1258
1259 //get the unique participant ids,
1260 $allParticipantIds = array_unique($allParticipantIds);
1261
1262 //pull required participants, contacts, events data, if not in hand
1263 static $eventDetails = array();
1264 static $domainValues = array();
1265 static $contactDetails = array();
1266
1267 $contactIds = $eventIds = $participantDetails = array();
1268
ddca8f33 1269 $statusTypes = CRM_Event_PseudoConstant::participantStatus();
6a488035 1270 $participantRoles = CRM_Event_PseudoConstant::participantRole();
ddca8f33 1271 $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL,
6a488035
TO
1272 "class = 'Pending'"
1273 );
1274
1275 //first thing is pull all necessory data from db.
1276 $participantIdClause = '(' . implode(',', $allParticipantIds) . ')';
1277
1278 //get all participants data.
1279 $query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
1280 $dao = CRM_Core_DAO::executeQuery($query);
1281 while ($dao->fetch()) {
1282 $participantDetails[$dao->id] = array(
1283 'id' => $dao->id,
1284 'role' => $participantRoles[$dao->role_id],
1285 'is_test' => $dao->is_test,
1286 'event_id' => $dao->event_id,
1287 'status_id' => $dao->status_id,
1288 'fee_amount' => $dao->fee_amount,
1289 'contact_id' => $dao->contact_id,
1290 'register_date' => $dao->register_date,
1291 'registered_by_id' => $dao->registered_by_id,
1292 );
1293 if (!array_key_exists($dao->contact_id, $contactDetails)) {
1294 $contactIds[$dao->contact_id] = $dao->contact_id;
1295 }
1296
1297 if (!array_key_exists($dao->event_id, $eventDetails)) {
1298 $eventIds[$dao->event_id] = $dao->event_id;
1299 }
1300 }
1301
1302 //get the domain values.
1303 if (empty($domainValues)) {
1304 // making all tokens available to templates.
1305 $domain = CRM_Core_BAO_Domain::getDomain();
0479b4c8 1306 $tokens = array(
ddca8f33 1307 'domain' => array('name', 'phone', 'address', 'email'),
6a488035
TO
1308 'contact' => CRM_Core_SelectValues::contactTokens(),
1309 );
1310
1311 foreach ($tokens['domain'] as $token) {
1312 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
1313 }
1314 }
1315
1316 //get all required contacts detail.
1317 if (!empty($contactIds)) {
1318 // get the contact details.
1319 list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
1320 FALSE, FALSE, NULL,
1321 array(),
1322 'CRM_Event_BAO_Participant'
1323 );
1324 foreach ($currentContactDetails as $contactId => $contactValues) {
1325 $contactDetails[$contactId] = $contactValues;
1326 }
1327 }
1328
1329 //get all required events detail.
1330 if (!empty($eventIds)) {
1331 foreach ($eventIds as $eventId) {
1332 //retrieve event information
1333 $eventParams = array('id' => $eventId);
1334 CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]);
1335
1336 //get default participant role.
1337 $eventDetails[$eventId]['participant_role'] = CRM_Utils_Array::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
1338
1339 //get the location info
1340 $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
1341 $eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
1342 }
1343 }
1344
1345 //now we are ready w/ all required data.
1346 //take a decision as per statuses.
1347
ddca8f33
TO
1348 $emailType = NULL;
1349 $toStatus = $statusTypes[$toStatusId];
6a488035
TO
1350 $fromStatus = CRM_Utils_Array::value($fromStatusId, $statusTypes);
1351
1352 switch ($toStatus) {
1353 case 'Pending from waitlist':
1354 case 'Pending from approval':
1355 switch ($fromStatus) {
1356 case 'On waitlist':
1357 case 'Awaiting approval':
1358 $emailType = 'Confirm';
1359 break;
1360 }
1361 break;
1362
1363 case 'Expired':
1364 //no matter from where u come send expired mail.
1365 $emailType = $toStatus;
1366 break;
1367
1368 case 'Cancelled':
1369 //no matter from where u come send cancel mail.
1370 $emailType = $toStatus;
1371 break;
1372 }
1373
1374 //as we process additional w/ primary, there might be case if user
1375 //select primary as well as additionals, so avoid double processing.
1376 $processedParticipantIds = array();
1377 $mailedParticipants = array();
1378
1379 //send mails and update status.
1380 foreach ($participantDetails as $participantId => $participantValues) {
1381 $updateParticipantIds = array();
1382 if (in_array($participantId, $processedParticipantIds)) {
1383 continue;
1384 }
1385
1386 //check is it primary and has additional.
1387 if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
1388 foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
1389
1390 if ($emailType) {
1391 $mail = self::sendTransitionParticipantMail($additonalId,
1392 $participantDetails[$additonalId],
1393 $eventDetails[$participantDetails[$additonalId]['event_id']],
1394 $contactDetails[$participantDetails[$additonalId]['contact_id']],
1395 $domainValues,
1396 $emailType
1397 );
1398
1399 //get the mail participant ids
1400 if ($mail) {
1401 $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
1402 }
1403 }
1404 $updateParticipantIds[] = $additonalId;
1405 $processedParticipantIds[] = $additonalId;
1406 }
1407 }
1408
1409 //now send email appropriate mail to primary.
1410 if ($emailType) {
1411 $mail = self::sendTransitionParticipantMail($participantId,
1412 $participantValues,
1413 $eventDetails[$participantValues['event_id']],
1414 $contactDetails[$participantValues['contact_id']],
1415 $domainValues,
1416 $emailType
1417 );
1418
1419 //get the mail participant ids
1420 if ($mail) {
1421 $mailedParticipants[$participantId] = $contactDetails[$participantValues['contact_id']]['display_name'];
1422 }
1423 }
1424
1425 //now update status of group/one at once.
1426 $updateParticipantIds[] = $participantId;
1427
1428 //update the register date only when we,
1429 //move participant to pending class, CRM-6496
1430 $updateRegisterDate = FALSE;
1431 if (array_key_exists($toStatusId, $pendingStatuses)) {
1432 $updateRegisterDate = TRUE;
1433 }
1434 self::updateStatus($updateParticipantIds, $toStatusId, $updateRegisterDate);
1435 $processedParticipantIds[] = $participantId;
1436 }
1437
1438 //return result for cron.
1439 if ($returnResult) {
1440 $results = array(
1441 'mailedParticipants' => $mailedParticipants,
1442 'updatedParticipantIds' => $processedParticipantIds,
1443 );
1444
1445 return $results;
1446 }
1447 }
1448
1449 /**
100fef9d 1450 * Send mail and create activity
6a488035
TO
1451 * when participant status changed.
1452 *
d4dd1e85
TO
1453 * @param int $participantId
1454 * Participant id.
1455 * @param array $participantValues
1456 * Participant detail values. status id for participants.
1457 * @param array $eventDetails
1458 * Required event details.
1459 * @param array $contactDetails
1460 * Required contact details.
1461 * @param array $domainValues
1462 * Required domain values.
1463 * @param string $mailType
1464 * (eg 'approval', 'confirm', 'expired' ).
6a488035 1465 *
654ca41c 1466 * @return bool
6a488035 1467 */
2da40d21 1468 public static function sendTransitionParticipantMail(
6a488035
TO
1469 $participantId,
1470 $participantValues,
1471 $eventDetails,
1472 $contactDetails,
1473 &$domainValues,
1474 $mailType
1475 ) {
1476 //send emails.
1477 $mailSent = FALSE;
1478
1479 //don't send confirmation mail to additional
1480 //since only primary able to confirm registration.
a7488080 1481 if (!empty($participantValues['registered_by_id']) &&
6a488035
TO
1482 $mailType == 'Confirm'
1483 ) {
1484 return $mailSent;
1485 }
0cca0bf4
J
1486 $toEmail = CRM_Utils_Array::value('email', $contactDetails);
1487 if ($toEmail) {
6a488035
TO
1488
1489 $contactId = $participantValues['contact_id'];
1490 $participantName = $contactDetails['display_name'];
1491
1492 //calculate the checksum value.
1493 $checksumValue = NULL;
1494 if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
1495 $checksumLife = 'inf';
0cca0bf4
J
1496 $endDate = CRM_Utils_Array::value('end_date', $eventDetails);
1497 if ($endDate) {
6a488035
TO
1498 $checksumLife = (CRM_Utils_Date::unixTime($endDate) - time()) / (60 * 60);
1499 }
1500 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId, NULL, $checksumLife);
1501 }
1502
1503 //take a receipt from as event else domain.
1504 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
8cc574cf 1505 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
6a488035
TO
1506 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
1507 }
1508
c6327d7d 1509 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
6a488035
TO
1510 array(
1511 'groupName' => 'msg_tpl_workflow_event',
1512 'valueName' => 'participant_' . strtolower($mailType),
1513 'contactId' => $contactId,
1514 'tplParams' => array(
1515 'contact' => $contactDetails,
1516 'domain' => $domainValues,
1517 'participant' => $participantValues,
1518 'event' => $eventDetails,
1519 'paidEvent' => CRM_Utils_Array::value('is_monetary', $eventDetails),
1520 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $eventDetails),
1521 'isAdditional' => $participantValues['registered_by_id'],
1522 'isExpired' => $mailType == 'Expired',
1523 'isConfirm' => $mailType == 'Confirm',
1524 'checksumValue' => $checksumValue,
1525 ),
1526 'from' => $receiptFrom,
1527 'toName' => $participantName,
1528 'toEmail' => $toEmail,
1529 'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails),
1530 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails),
1531 )
1532 );
1533
1534 // 3. create activity record.
1535 if ($mailSent) {
ddca8f33
TO
1536 $now = date('YmdHis');
1537 $activityType = 'Event Registration';
6a488035
TO
1538 $activityParams = array(
1539 'subject' => $subject,
1540 'source_contact_id' => $contactId,
1541 'source_record_id' => $participantId,
1542 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1543 $activityType,
1544 'name'
1545 ),
1546 'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
1547 'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']),
1548 'is_test' => $participantValues['is_test'],
1549 'status_id' => 2,
1550 );
1551
1552 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
1553 CRM_Core_Error::fatal('Failed creating Activity for expiration mail');
1554 }
1555 }
1556 }
1557
1558 return $mailSent;
1559 }
1560
1561 /**
100fef9d 1562 * Get participant status change message.
6a488035 1563 *
100fef9d 1564 * @param int $participantId
654ca41c 1565 * @param $statusChangeTo
100fef9d 1566 * @param int $fromStatusId
654ca41c 1567 *
6a488035 1568 * @return string
6a488035 1569 */
00be9182 1570 public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
6a488035
TO
1571 $statusMsg = NULL;
1572 $results = self::transitionParticipants(array($participantId),
1573 $statusChangeTo, $fromStatusId, TRUE
1574 );
1575
1576 $allStatuses = CRM_Event_PseudoConstant::participantStatus();
1577 //give user message only when mail has sent.
1578 if (is_array($results) && !empty($results)) {
1579 if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
1580 foreach ($results['updatedParticipantIds'] as $processedId) {
1581 if (is_array($results['mailedParticipants']) &&
1582 array_key_exists($processedId, $results['mailedParticipants'])
1583 ) {
1584 $statusMsg .= '<br /> ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
ddca8f33
TO
1585 array(
1586 1 => $allStatuses[$statusChangeTo],
1587 2 => $results['mailedParticipants'][$processedId],
1588 )
1589 );
6a488035
TO
1590 }
1591 }
1592 }
1593 }
1594
1595 return $statusMsg;
1596 }
1597
1598 /**
100fef9d 1599 * Get event full and waiting list message.
6a488035 1600 *
100fef9d
CW
1601 * @param int $eventId
1602 * @param int $participantId
654ca41c 1603 *
6a488035 1604 * @return string
6a488035 1605 */
00be9182 1606 public static function eventFullMessage($eventId, $participantId = NULL) {
6a488035
TO
1607 $eventfullMsg = $dbStatusId = NULL;
1608 $checkEventFull = TRUE;
1609 if ($participantId) {
1610 $dbStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id');
1611 if (array_key_exists($dbStatusId, CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1'))) {
1612 //participant already in counted status no need to check for event full messages.
1613 $checkEventFull = FALSE;
1614 }
1615 }
1616
1617 //early return.
1618 if (!$eventId || !$checkEventFull) {
1619 return $eventfullMsg;
1620 }
1621
1622 //event is truly full.
1623 $emptySeats = self::eventFull($eventId, FALSE, FALSE);
1624 if (is_string($emptySeats) && $emptySeats !== NULL) {
1625 $maxParticipants = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
1626 $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 1627 1 => $maxParticipants,
ddca8f33 1628 )) . '<br />';
6a488035
TO
1629 }
1630
1631 $hasWaiting = FALSE;
1632 $waitListedCount = self::eventFull($eventId, FALSE, TRUE, TRUE);
1633 if (is_numeric($waitListedCount)) {
1634 $hasWaiting = TRUE;
1635 //only current processing participant is on waitlist.
1636 if ($waitListedCount == 1 && CRM_Event_PseudoConstant::participantStatus($dbStatusId) == 'On waitlist') {
1637 $hasWaiting = FALSE;
1638 }
1639 }
1640
1641 if ($hasWaiting) {
1642 $waitingStatusId = array_search('On waitlist',
1643 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'")
1644 );
1645 $viewWaitListUrl = CRM_Utils_System::url('civicrm/event/search',
1646 "reset=1&force=1&event={$eventId}&status={$waitingStatusId}"
1647 );
1648
1649 $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.",
1650 array(
1651 1 => $viewWaitListUrl,
1652 2 => $waitListedCount,
1653 )
1654 );
1655 }
1656
1657 return $eventfullMsg;
1658 }
1659
1660 /**
66f9e52b 1661 * Check for whether participant is primary or not.
6a488035 1662 *
100fef9d 1663 * @param int $participantId
6a488035 1664 *
72b3a70c
CW
1665 * @return bool
1666 * true if participant is primary
6a488035 1667 */
00be9182 1668 public static function isPrimaryParticipant($participantId) {
6a488035
TO
1669
1670 $participant = new CRM_Event_DAO_Participant();
1671 $participant->registered_by_id = $participantId;
1672
1673 if ($participant->find(TRUE)) {
1674 return TRUE;
1675 }
1676 return FALSE;
1677 }
1678
1679 /**
66f9e52b 1680 * Get additional participant Ids for cascading with primary participant status.
6a488035 1681 *
d4dd1e85
TO
1682 * @param int $participantId
1683 * Participant id.
1684 * @param int $oldStatusId
1685 * Previous status.
1686 * @param int $newStatusId
1687 * New status.
6a488035 1688 *
72b3a70c
CW
1689 * @return bool
1690 * true if allowed
6a488035 1691 */
00be9182 1692 public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
6a488035
TO
1693
1694 $additionalParticipantIds = array();
1695
1696 static $participantStatuses = array();
1697
1698 if (empty($participantStatuses)) {
1699 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1700 }
1701
1702 if (CRM_Utils_Array::value($participantStatuses[$oldStatusId], self::$_statusTransitionsRules) &&
1703 in_array($participantStatuses[$newStatusId], self::$_statusTransitionsRules[$participantStatuses[$oldStatusId]])
1704 ) {
1705 $additionalParticipantIds = self::getAdditionalParticipantIds($participantId, TRUE, $oldStatusId);
1706 }
1707
1708 return $additionalParticipantIds;
1709 }
1710
1711 /**
66f9e52b 1712 * Get participant record count for a Contact.
6a488035 1713 *
c490a46a 1714 * @param int $contactID
6a488035 1715 *
a6c01b45
CW
1716 * @return int
1717 * count of participant records
6a488035 1718 */
00be9182 1719 public static function getContactParticipantCount($contactID) {
6a488035
TO
1720 $query = "SELECT count(*)
1721FROM civicrm_participant
1722WHERE civicrm_participant.contact_id = {$contactID} AND
1723 civicrm_participant.is_test = 0";
1724 return CRM_Core_DAO::singleValueQuery($query);
1725 }
1726
1727 /**
66f9e52b 1728 * Get participant ids by contribution id.
6a488035 1729 *
d4dd1e85
TO
1730 * @param int $contributionId
1731 * Contribution Id.
1732 * @param bool $excludeCancelled
1733 * Exclude cancelled additional participant.
6a488035 1734 *
a6c01b45 1735 * @return array
6a488035 1736 */
00be9182 1737 public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
6a488035
TO
1738
1739 $ids = array();
1740 if (!$contributionId) {
1741 return $ids;
1742 }
1743
1744 // get primary participant id
1745 $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
1746 $participantId = CRM_Core_DAO::singleValueQuery($query);
1747
1748 // get additional participant ids (including cancelled)
1749 if ($participantId) {
1750 $ids = array_merge(array(
21dfd5f5 1751 $participantId,
ddca8f33
TO
1752 ), self::getAdditionalParticipantIds($participantId,
1753 $excludeCancelled
1754 ));
6a488035
TO
1755 }
1756
1757 return $ids;
1758 }
1759
1760 /**
100fef9d 1761 * Get additional Participant edit & view url .
6a488035 1762 *
d4dd1e85
TO
1763 * @param array $participantIds
1764 * An array of additional participant ids.
6a488035 1765 *
a6c01b45 1766 * @return array
16b10e64 1767 * Array of Urls.
6a488035 1768 */
00be9182 1769 public static function getAdditionalParticipantUrl($participantIds) {
6a488035 1770 foreach ($participantIds as $value) {
ddca8f33 1771 $links = array();
6a488035
TO
1772 $details = self::participantDetails($value);
1773 $viewUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1774 "action=view&reset=1&id={$value}&cid={$details['cid']}"
1775 );
1776 $editUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
1777 "action=update&reset=1&id={$value}&cid={$details['cid']}"
1778 );
1779 $links[] = "<td><a href='{$viewUrl}'>" . $details['name'] . "</a></td><td></td><td><a href='{$editUrl}'>" . ts('Edit') . "</a></td>";
1780 $links = "<table><tr>" . implode("</tr><tr>", $links) . "</tr></table>";
1781 return $links;
1782 }
1783 }
1784
1785 /**
dc195289 1786 * create trxn entry if an event has discount.
6a488035 1787 *
d4dd1e85
TO
1788 * @param int $eventID
1789 * Event id.
1790 * @param array $contributionParams
1791 * Contribution params.
654ca41c
EM
1792 *
1793 * @param $feeLevel
6a488035 1794 *
6a488035 1795 */
00be9182 1796 public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel) {
6a488035 1797 // CRM-11124
0479b4c8 1798 $checkDiscount = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
6a488035
TO
1799 if (!empty($checkDiscount)) {
1800 $feeLevel = current($feeLevel);
9da8dc8c 1801 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID, NULL);
6a488035
TO
1802 $query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
1803LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
1804WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
0479b4c8 1805 $params = array(
ddca8f33 1806 1 => array($priceSetId, 'Integer'),
21dfd5f5 1807 2 => array($feeLevel, 'String'),
ddca8f33 1808 );
6a488035 1809 $mainAmount = CRM_Core_DAO::singleValueQuery($query, $params);
f743a6eb 1810 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
6a488035
TO
1811 $contributionParams['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
1812 $contributionParams['contribution']->financial_type_id, $relationTypeId);
a7488080 1813 if (!empty($contributionParams['trxnParams']['from_financial_account_id'])) {
6a488035 1814 $contributionParams['trxnParams']['total_amount'] = $mainAmount - $contributionParams['total_amount'];
6c552737
TO
1815 $contributionParams['trxnParams']['payment_processor_id'] = NULL;
1816 $contributionParams['trxnParams']['payment_instrument_id'] = NULL;
1817 $contributionParams['trxnParams']['check_number'] = NULL;
1818 $contributionParams['trxnParams']['trxn_id'] = NULL;
1819 $contributionParams['trxnParams']['net_amount'] = NULL;
1820 $contributionParams['trxnParams']['fee_amount'] = NULL;
6a488035
TO
1821
1822 CRM_Core_BAO_FinancialTrxn::create($contributionParams['trxnParams']);
1823 }
1824 }
6a488035 1825 }
c3d24ba7
PN
1826
1827 /**
66f9e52b 1828 * Delete participants of contact.
c3d24ba7
PN
1829 *
1830 * CRM-12155
1831 *
d4dd1e85
TO
1832 * @param int $contactId
1833 * Contact id.
c3d24ba7 1834 *
c3d24ba7 1835 */
00be9182 1836 public static function deleteContactParticipant($contactId) {
c3d24ba7
PN
1837 $participant = new CRM_Event_DAO_Participant();
1838 $participant->contact_id = $contactId;
1839 $participant->find();
1840 while ($participant->fetch()) {
1841 self::deleteParticipant($participant->id);
1842 }
1843 }
6a488035 1844
0cf587a7 1845 /**
c490a46a 1846 * @param array $params
100fef9d
CW
1847 * @param int $participantId
1848 * @param int $contributionId
0cf587a7 1849 * @param $feeBlock
100fef9d 1850 * @param array $lineItems
0cf587a7 1851 * @param $paidAmount
100fef9d 1852 * @param int $priceSetId
0cf587a7 1853 */
00be9182 1854 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) {
0aaf8fe9
PJ
1855 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1856 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
e59da3a9 1857 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
0aaf8fe9
PJ
1858 $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant');
1859 CRM_Price_BAO_PriceSet::processAmount($feeBlock,
1860 $params, $lineItems
1861 );
1862
1863 // get the submitted
1864 foreach ($feeBlock as $id => $values) {
1865 CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems);
1866 $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id');
1867 }
5b22467a
RK
1868 if (!empty($submittedLineItems)) {
1869 $insertLines = $submittedLineItems;
1870
1871 $submittedFieldValueIds = array_keys($submittedLineItems);
1872 $updateLines = array();
1873 foreach ($previousLineItems as $id => $previousLineItem) {
1874 // check through the submitted items if the previousItem exists,
1875 // if found in submitted items, do not use it for new item creations
1876 if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
1877 // if submitted line items are existing don't fire INSERT query
1878 unset($insertLines[$previousLineItem['price_field_value_id']]);
1879 // for updating the line items i.e. use-case - once deselect-option selecting again
1880 if (($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) ||
8ab8920e
BS
1881 ($submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1) ||
1882 ($previousLineItem['qty'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'])
ddca8f33 1883 ) {
5b22467a
RK
1884 $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
1885 $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
1886 }
0b2b58ea 1887 }
0aaf8fe9 1888 }
b0a9575b 1889
5b22467a
RK
1890 $submittedFields = implode(', ', $submittedFieldId);
1891 $submittedFieldValues = implode(', ', $submittedFieldValueIds);
1892 }
0aaf8fe9 1893 if (!empty($submittedFields) && !empty($submittedFieldValues)) {
13d4664b 1894 $updateLineItem = "UPDATE civicrm_line_item li
0aaf8fe9
PJ
1895INNER JOIN civicrm_financial_item fi
1896 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
0aaf8fe9 1897SET li.qty = 0,
5a18a545 1898 li.line_total = 0.00,
1899 li.tax_amount = NULL
0aaf8fe9 1900WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
13d4664b 1901 (price_field_value_id NOT IN ({$submittedFieldValues}))
0aaf8fe9
PJ
1902";
1903 CRM_Core_DAO::executeQuery($updateLineItem);
13d4664b
PJ
1904
1905 // gathering necessary info to record negative (deselected) financial_item
1906 $updateFinancialItem = "
5a18a545 1907 SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
13d4664b
PJ
1908 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1909WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
1910GROUP BY li.entity_table, li.entity_id, price_field_value_id
1911";
1912 $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
a191ff3d 1913 $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId, 'DESC', TRUE);
13d4664b 1914 $trxnId['id'] = $trxn['financialTrxnId'];
aaffa79f 1915 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
5a18a545 1916 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
13d4664b 1917 $updateFinancialItemInfoValues = array();
a191ff3d 1918 $financialItemsArray = array();
13d4664b
PJ
1919 while ($updateFinancialItemInfoDAO->fetch()) {
1920 $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
1921 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
1922 // the below params are not needed
1923 unset($updateFinancialItemInfoValues['id']);
1924 unset($updateFinancialItemInfoValues['created_date']);
1925 // if not submitted and difference is not 0 make it negative
1926 if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
1927 // INSERT negative financial_items
ddca8f33 1928 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
5a18a545 1929 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
b4df5f60
PN
1930 $updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
1931 $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
5a18a545 1932 if ($updateFinancialItemInfoValues['financial_type_id']) {
b4df5f60 1933 $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
5a18a545 1934 }
5a18a545 1935 }
b4df5f60
PN
1936 // INSERT negative financial_items for tax amount
1937 $financialItemsArray[] = $updateFinancialItemInfoValues;
13d4664b
PJ
1938 }
1939 // if submitted and difference is 0 add a positive entry again
1940 elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
1941 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
5a18a545 1942 // INSERT financial_items for tax amount
1943 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
1944 isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
1945 ) {
a191ff3d
PN
1946 $updateFinancialItemInfoValues['tax']['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
1947 $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
5a18a545 1948 if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
a191ff3d 1949 $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
5a18a545 1950 }
5a18a545 1951 }
2b76f3da 1952 $financialItemsArray[] = $updateFinancialItemInfoValues;
13d4664b
PJ
1953 }
1954 }
0aaf8fe9 1955 }
ddca8f33 1956 elseif (empty($submittedFields) && empty($submittedFieldValues)) {
5b22467a
RK
1957 $updateLineItem = "UPDATE civicrm_line_item li
1958 INNER JOIN civicrm_financial_item fi
1959 ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1960 SET li.qty = 0,
1961 li.line_total = 0.00,
1962 li.tax_amount = NULL
1963 WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
1964 CRM_Core_DAO::executeQuery($updateLineItem);
1965 }
b612d89b 1966 $amountLevel = array();
1967 $totalParticipant = $participantCount = 0;
0b2b58ea
PJ
1968 if (!empty($updateLines)) {
1969 foreach ($updateLines as $valueId => $vals) {
b612d89b 1970 $taxAmount = "NULL";
5525990d 1971 if (isset($vals['tax_amount'])) {
5a18a545 1972 $taxAmount = $vals['tax_amount'];
1973 }
b612d89b 1974 $amountLevel[] = $vals['label'] . ' - ' . (float) $vals['qty'];
1975 if (isset($vals['participant_count'])) {
1976 $participantCount = $vals['participant_count'];
1977 $totalParticipant += $vals['participant_count'];
5a18a545 1978 }
0b2b58ea
PJ
1979 $updateLineItem = "
1980UPDATE civicrm_line_item li
0b2b58ea 1981SET li.qty = {$vals['qty']},
8dfe9fe3 1982 li.line_total = {$vals['line_total']},
3b5db8ce 1983 li.tax_amount = {$taxAmount},
8dfe9fe3 1984 li.unit_price = {$vals['unit_price']},
b612d89b 1985 li.participant_count = {$participantCount},
122a36b9 1986 li.label = %1
0b2b58ea
PJ
1987WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
1988 (price_field_value_id = {$valueId})
1989";
122a36b9 1990 CRM_Core_DAO::executeQuery($updateLineItem, array(1 => array($vals['label'], 'String')));
0b2b58ea
PJ
1991 }
1992 }
b75ef57e
PJ
1993 // insert new 'adjusted amount' transaction entry and update contribution entry.
1994 // ensure entity_financial_trxn table has a linking of it.
28e4e707 1995 // insert new line items
5b22467a
RK
1996 if (!empty($insertLines)) {
1997 foreach ($insertLines as $valueId => $lineParams) {
1998 $lineParams['entity_table'] = 'civicrm_participant';
1999 $lineParams['entity_id'] = $participantId;
2000 $lineParams['contribution_id'] = $contributionId;
2001 $lineObj = CRM_Price_BAO_LineItem::create($lineParams);
2002 }
28e4e707
PJ
2003 }
2004
2005 // the recordAdjustedAmt code would execute over here
2006 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
2007 if (count($ids) > 1) {
2008 $total = 0;
2009 foreach ($ids as $val) {
2010 $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
2011 }
2012 $updatedAmount = $total;
2013 }
2014 else {
2015 $updatedAmount = $params['amount'];
2016 }
5a18a545 2017 if (strlen($params['tax_amount']) != 0) {
2018 $taxAmount = $params['tax_amount'];
2019 }
2020 else {
2021 $taxAmount = "NULL";
2022 }
b612d89b 2023 $displayParticipantCount = '';
2024 if ($totalParticipant > 0) {
2025 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
2026 }
2027 $updateAmountLevel = NULL;
2028 if (!empty($amountLevel)) {
2029 $updateAmountLevel = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
2030 }
2031 $trxn = self::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel);
a191ff3d
PN
2032 $trxnId = array();
2033 if ($trxn) {
2034 $trxnId['id'] = $trxn->id;
2035 foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
2036 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
2037 if (!empty($updateFinancialItemInfoValues['tax'])) {
2038 $updateFinancialItemInfoValues['tax']['amount'] = $updateFinancialItemInfoValues['amount'];
2039 $updateFinancialItemInfoValues['tax']['description'] = $updateFinancialItemInfoValues['description'];
2040 if (!empty($updateFinancialItemInfoValues['financial_account_id'])) {
2041 $updateFinancialItemInfoValues['financial_account_id'] = $updateFinancialItemInfoValues['tax']['financial_account_id'];
2042 }
2b76f3da 2043 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
a191ff3d
PN
2044 }
2045 }
2046 }
b75ef57e
PJ
2047 $fetchCon = array('id' => $contributionId);
2048 $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
28e4e707 2049 // insert financial items
5b22467a
RK
2050 if (!empty($insertLines)) {
2051 foreach ($insertLines as $valueId => $lineParams) {
2052 $lineParams['entity_table'] = 'civicrm_participant';
2053 $lineParams['entity_id'] = $participantId;
2054 $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
2055 // insert financial items
2056 // ensure entity_financial_trxn table has a linking of it.
a191ff3d 2057 $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $trxnId);
5b22467a 2058 if (isset($lineObj->tax_amount)) {
a191ff3d 2059 CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $trxnId);
5b22467a 2060 }
5a18a545 2061 }
0aaf8fe9 2062 }
f6bae84f 2063
d5397f2f
PJ
2064 // update participant fee_amount column
2065 $partUpdateFeeAmt['id'] = $participantId;
a1acfd53 2066 $getUpdatedLineItems = "SELECT *
2067FROM civicrm_line_item
e990bc36 2068WHERE (entity_table = 'civicrm_participant' AND entity_id = {$participantId} AND qty > 0)";
2069 $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
a1acfd53 2070 while ($getUpdatedLineItemsDAO->fetch()) {
2071 $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (float) $getUpdatedLineItemsDAO->qty;
3ce0c12e
C
2072 }
2073
2074 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
d5397f2f
PJ
2075 $partUpdateFeeAmt['fee_amount'] = $params['amount'];
2076 self::add($partUpdateFeeAmt);
2077
f6bae84f
PJ
2078 //activity creation
2079 self::addActivityForSelection($participantId, 'Change Registration');
2080 }
2081
0cf587a7 2082 /**
54957108 2083 * Record adjusted amount.
2084 *
2085 * @param int $updatedAmount
2086 * @param int $paidAmount
100fef9d 2087 * @param int $contributionId
54957108 2088 *
2089 * @param int $taxAmount
2090 * @param bool $updateAmountLevel
2091 *
2092 * @return bool|\CRM_Core_BAO_FinancialTrxn
0cf587a7 2093 */
b612d89b 2094 public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
18fdfcc3 2095 $pendingAmount = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
9cf473a4 2096 $pendingAmount = CRM_Utils_Array::value('total_amount', $pendingAmount, 0);
2097 $balanceAmt = $updatedAmount - $paidAmount;
2098 if ($paidAmount != $pendingAmount) {
2099 $balanceAmt -= $pendingAmount;
2100 }
2101
f6bae84f
PJ
2102 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2103 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
e59da3a9 2104 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
921bca19
DG
2105 $completedStatusId = array_search('Completed', $contributionStatuses);
2106
2107 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
2b76f3da 2108 $adjustedTrxn = $skip = FALSE;
0aaf8fe9 2109 if ($balanceAmt) {
c6191312 2110 if ($balanceAmt > 0 && $paidAmount != 0) {
0aaf8fe9
PJ
2111 $contributionStatusVal = $partiallyPaidStatusId;
2112 }
c6191312 2113 elseif ($balanceAmt < 0 && $paidAmount != 0) {
e59da3a9 2114 $contributionStatusVal = $pendingRefundStatusId;
0aaf8fe9 2115 }
921bca19 2116 elseif ($paidAmount == 0) {
e59da3a9
DG
2117 //skip updating the contribution status if no payment is made
2118 $skip = TRUE;
921bca19
DG
2119 $updatedContributionDAO->cancel_date = 'null';
2120 $updatedContributionDAO->cancel_reason = NULL;
2121 }
0aaf8fe9
PJ
2122 // update contribution status and total amount without trigger financial code
2123 // as this is handled in current BAO function used for change selection
0aaf8fe9 2124 $updatedContributionDAO->id = $contributionId;
e59da3a9
DG
2125 if (!$skip) {
2126 $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
2127 }
b8adb851 2128 $updatedContributionDAO->total_amount = $updatedContributionDAO->net_amount = $updatedAmount;
2129 $updatedContributionDAO->fee_amount = 0;
5a18a545 2130 $updatedContributionDAO->tax_amount = $taxAmount;
b612d89b 2131 if (!empty($updateAmountLevel)) {
2132 $updatedContributionDAO->amount_level = $updateAmountLevel;
2133 }
0aaf8fe9 2134 $updatedContributionDAO->save();
13d4664b 2135 // adjusted amount financial_trxn creation
18fdfcc3
PN
2136 $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(
2137 array('id' => $contributionId),
2138 CRM_Core_DAO::$_nullArray,
2139 CRM_Core_DAO::$_nullArray
2140 );
2141 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2142 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($updatedContribution->financial_type_id, $relationTypeId);
2143 $adjustedTrxnValues = array(
2144 'from_financial_account_id' => NULL,
2145 'to_financial_account_id' => $toFinancialAccount,
2146 'total_amount' => $balanceAmt,
9cf473a4 2147 'status_id' => $completedStatusId,
18fdfcc3
PN
2148 'payment_instrument_id' => $updatedContribution->payment_instrument_id,
2149 'contribution_id' => $updatedContribution->id,
2150 'trxn_date' => date('YmdHis'),
2151 'currency' => $updatedContribution->currency,
2152 );
2153 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
0aaf8fe9 2154 }
a191ff3d 2155 return $adjustedTrxn;
0aaf8fe9
PJ
2156 }
2157
0cf587a7 2158 /**
100fef9d 2159 * @param int $participantId
0cf587a7
EM
2160 * @param $activityType
2161 *
2162 * @throws CRM_Core_Exception
2163 */
00be9182 2164 public static function addActivityForSelection($participantId, $activityType) {
0aaf8fe9
PJ
2165 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id');
2166 $contactId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id');
2167
2168 $date = CRM_Utils_Date::currentDBDate();
2169 $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
2170 $eventTitle = $event[$eventId];
2171 $subject = "Registration selections changed for $eventTitle";
2172 $targetCid = $contactId;
2173 $srcRecId = $participantId;
2174
2175 // activity params
2176 $activityParams = array(
2177 'source_contact_id' => $targetCid,
2178 'source_record_id' => $srcRecId,
2179 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
2180 $activityType,
2181 'name'
2182 ),
2183 'subject' => $subject,
2184 'activity_date_time' => $date,
2185 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
2186 'Completed',
2187 'name'
2188 ),
2189 'skipRecentView' => TRUE,
2190 );
2191
2192 // create activity with target contacts
2193 $session = CRM_Core_Session::singleton();
2194 $id = $session->get('userID');
2195 if ($id) {
2196 $activityParams['source_contact_id'] = $id;
2197 $activityParams['target_contact_id'][] = $targetCid;
2198 }
2199 CRM_Activity_BAO_Activity::create($activityParams);
2200 }
f76b27fe
CW
2201
2202 /**
2203 * Get options for a given field.
2204 * @see CRM_Core_DAO::buildOptions
2205 *
d4dd1e85
TO
2206 * @param string $fieldName
2207 * @param string $context
a1a2a83d 2208 * @see CRM_Core_DAO::buildOptionsContext
d4dd1e85 2209 * @param array $props
16b10e64 2210 * whatever is known about this dao object.
f76b27fe 2211 *
5c766a0b 2212 * @return array|bool
f76b27fe
CW
2213 */
2214 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2215 $params = array('condition' => array());
2216
2217 if ($fieldName == 'status_id' && $context != 'validate') {
2218 // Get rid of cart-related option if disabled
2219 // FIXME: Why does this option even exist if cart is disabled?
aaffa79f 2220 if (!Civi::settings()->get('enable_cart')) {
f76b27fe
CW
2221 $params['condition'][] = "name <> 'Pending in cart'";
2222 }
2223 }
2224
2225 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
2226 }
96025800 2227
37d5fc55 2228}