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