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