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