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