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