Array formatting
[civicrm-core.git] / CRM / Event / Form / Participant.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Back office participant form.
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18
19 /**
20 * Back office participant form.
21 */
22 class CRM_Event_Form_Participant extends CRM_Contribute_Form_AbstractEditPayment {
23
24 /**
25 * Participant ID - use getParticipantID.
26 *
27 * @var int
28 */
29 public $_pId;
30
31 /**
32 * ID of discount record.
33 *
34 * @var int
35 */
36 public $_discountId;
37
38 public $useLivePageJS = TRUE;
39
40 /**
41 * The values for the contribution db object.
42 *
43 * @var array
44 */
45 public $_values;
46
47 /**
48 * The values for the quickconfig for priceset.
49 *
50 * @var bool
51 */
52 public $_quickConfig = NULL;
53
54 /**
55 * Price Set ID, if the new price set method is used
56 *
57 * @var int
58 */
59 public $_priceSetId;
60
61 /**
62 * Array of fields for the price set.
63 *
64 * @var array
65 */
66 public $_priceSet;
67
68 /**
69 * The id of the participation that we are processing.
70 *
71 * @var int
72 */
73 public $_id;
74
75 /**
76 * The id of the note.
77 *
78 * @var int
79 */
80 protected $_noteId = NULL;
81
82 /**
83 *
84 * Use parent $this->contactID
85 *
86 * The id of the contact associated with this participation.
87 *
88 * @var int
89 * @deprecated
90 */
91 public $_contactId;
92
93 /**
94 * Array of event values.
95 *
96 * @var array
97 */
98 protected $_event;
99
100 /**
101 * Are we operating in "single mode", i.e. adding / editing only
102 * one participant record, or is this a batch add operation
103 *
104 * @var bool
105 */
106 public $_single = FALSE;
107
108 /**
109 * If event is paid or unpaid.
110 *
111 * @var bool
112 */
113 public $_isPaidEvent;
114
115 /**
116 * Page action.
117 *
118 * @var int
119 */
120 public $_action;
121
122 /**
123 * Role Id.
124 *
125 * @var int
126 */
127 protected $_roleId = NULL;
128
129 /**
130 * Event Type Id.
131 *
132 * @var int
133 */
134 protected $_eventTypeId = NULL;
135
136 /**
137 * Participant status Id.
138 *
139 * @var int
140 */
141 protected $_statusId = NULL;
142
143 /**
144 * Cache all the participant statuses.
145 *
146 * @var array
147 */
148 protected $_participantStatuses;
149
150 /**
151 * Participant mode.
152 *
153 * @var string
154 */
155 public $_mode = NULL;
156
157 /**
158 * Event ID preselect.
159 *
160 * @var int
161 */
162 public $_eID = NULL;
163
164 /**
165 * Line Item for Price Set.
166 *
167 * @var array
168 */
169 public $_lineItem = NULL;
170
171 /**
172 * Contribution mode for event registration for offline mode.
173 *
174 * @var string
175 * @deprecated
176 */
177 public $_contributeMode = 'direct';
178
179 public $_online;
180
181 /**
182 * Store id of role custom data type ( option value )
183 *
184 * @var int
185 */
186 protected $_roleCustomDataTypeID;
187
188 /**
189 * Store id of event Name custom data type ( option value)
190 *
191 * @var int
192 */
193 protected $_eventNameCustomDataTypeID;
194
195 /**
196 * Selected discount id.
197 *
198 * @var int
199 */
200 public $_originalDiscountId = NULL;
201
202 /**
203 * Event id.
204 *
205 * @var int
206 */
207 public $_eventId = NULL;
208
209 /**
210 * Id of payment, if any
211 *
212 * @var int
213 */
214 public $_paymentId = NULL;
215
216 /**
217 * @var null
218 * @todo add explanatory note about this
219 */
220 public $_onlinePendingContributionId = NULL;
221
222 /**
223 * Stored participant record.
224 *
225 * @var array
226 */
227 protected $participantRecord;
228
229 /**
230 * Explicitly declare the entity api name.
231 */
232 public function getDefaultEntity() {
233 return 'Participant';
234 }
235
236 /**
237 * Default form context used as part of addField()
238 */
239 public function getDefaultContext() {
240 return 'create';
241 }
242
243 /**
244 * Set variables up before form is built.
245 *
246 * @return void
247 * @throws \CRM_Core_Exception
248 */
249 public function preProcess() {
250 parent::preProcess();
251 $this->_showFeeBlock = CRM_Utils_Array::value('eventId', $_GET);
252 $this->assign('showFeeBlock', FALSE);
253 $this->assign('feeBlockPaid', FALSE);
254
255 // @todo eliminate this duplication.
256 $this->_contactId = $this->_contactID;
257 $this->_eID = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
258 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
259 $this->assign('context', $this->_context);
260
261 if ($this->_contactID) {
262 $this->setPageTitle(ts('Event Registration for %1', [1 => $this->userDisplayName]));
263 }
264 else {
265 $this->setPageTitle(ts('Event Registration'));
266 }
267
268 // check the current path, if search based, then dont get participantID
269 // CRM-5792
270 $path = CRM_Utils_System::currentPath();
271 if (
272 strpos($path, 'civicrm/contact/search') === 0 ||
273 strpos($path, 'civicrm/group/search') === 0
274 ) {
275 $this->_id = NULL;
276 }
277 else {
278 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
279 }
280
281 if ($this->_id) {
282 $this->assign('participantId', $this->_id);
283
284 $this->_paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
285 $this->_id, 'id', 'participant_id'
286 );
287
288 $this->assign('hasPayment', $this->_paymentId);
289 $this->assign('componentId', $this->_id);
290 $this->assign('component', 'event');
291
292 // CRM-12615 - Get payment information from the primary registration
293 if ((!$this->_paymentId) && ($this->_action == CRM_Core_Action::UPDATE)) {
294 $registered_by_id = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
295 $this->_id, 'registered_by_id', 'id'
296 );
297 if ($registered_by_id) {
298 $this->_paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
299 $registered_by_id, 'id', 'participant_id'
300 );
301 $this->assign('registeredByParticipantId', $registered_by_id);
302 }
303 }
304 }
305 $this->setCustomDataTypes();
306
307 if ($this->_mode) {
308 $this->assign('participantMode', $this->_mode);
309 }
310
311 if ($this->_showFeeBlock) {
312 $this->assign('showFeeBlock', TRUE);
313 $isMonetary = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_showFeeBlock, 'is_monetary');
314 if ($isMonetary) {
315 $this->assign('feeBlockPaid', TRUE);
316 }
317 return CRM_Event_Form_EventFees::preProcess($this);
318 }
319
320 //check the mode when this form is called either single or as
321 //search task action
322 if ($this->_id || $this->_contactId || $this->_context == 'standalone') {
323 $this->_single = TRUE;
324 $this->assign('urlPath', 'civicrm/contact/view/participant');
325 if (!$this->_id && !$this->_contactId) {
326 $breadCrumbs = [
327 [
328 'title' => ts('CiviEvent Dashboard'),
329 'url' => CRM_Utils_System::url('civicrm/event', 'reset=1'),
330 ],
331 ];
332
333 CRM_Utils_System::appendBreadCrumb($breadCrumbs);
334 }
335 }
336 else {
337 //set the appropriate action
338 $context = $this->get('context');
339 $urlString = 'civicrm/contact/search';
340 $this->_action = CRM_Core_Action::BASIC;
341 switch ($context) {
342 case 'advanced':
343 $urlString = 'civicrm/contact/search/advanced';
344 $this->_action = CRM_Core_Action::ADVANCED;
345 break;
346
347 case 'builder':
348 $urlString = 'civicrm/contact/search/builder';
349 $this->_action = CRM_Core_Action::PROFILE;
350 break;
351
352 case 'basic':
353 $urlString = 'civicrm/contact/search/basic';
354 $this->_action = CRM_Core_Action::BASIC;
355 break;
356
357 case 'custom':
358 $urlString = 'civicrm/contact/search/custom';
359 $this->_action = CRM_Core_Action::COPY;
360 break;
361 }
362 CRM_Contact_Form_Task::preProcessCommon($this);
363
364 $this->_single = FALSE;
365 $this->_contactId = NULL;
366
367 //set ajax path, this used for custom data building
368 $this->assign('urlPath', $urlString);
369 $this->assign('urlPathVar', "_qf_Participant_display=true&qfKey={$this->controller->_key}");
370 }
371
372 $this->assign('single', $this->_single);
373
374 if (!$this->_id) {
375 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
376 }
377 $this->assign('action', $this->_action);
378
379 // check for edit permission
380 if (!CRM_Core_Permission::checkActionPermission('CiviEvent', $this->_action)) {
381 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
382 }
383
384 if ($this->_action & CRM_Core_Action::DELETE) {
385 // check delete permission for contribution
386 if ($this->_id && $this->_paymentId && !CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
387 CRM_Core_Error::statusBounce(ts("This Participant is linked to a contribution. You must have 'delete in CiviContribute' permission in order to delete this record."));
388 }
389 return;
390 }
391
392 if ($this->_id) {
393 // assign participant id to the template
394 $this->assign('participantId', $this->_id);
395 $this->_roleId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'role_id');
396 }
397
398 // when fee amount is included in form
399 if (!empty($_POST['hidden_feeblock']) || !empty($_POST['send_receipt'])) {
400 CRM_Event_Form_EventFees::preProcess($this);
401 $this->buildEventFeeForm($this);
402 CRM_Event_Form_EventFees::setDefaultValues($this);
403 }
404
405 // when custom data is included in this page
406 if (!empty($_POST['hidden_custom'])) {
407 $eventId = (int) CRM_Utils_Array::value('event_id', $_POST);
408 // Custom data of type participant role
409 // Note: Some earlier commits imply $_POST['role_id'] could be a comma separated string,
410 // not sure if that ever really happens
411 if (!empty($_POST['role_id'])) {
412 foreach ($_POST['role_id'] as $roleID) {
413 CRM_Custom_Form_CustomData::preProcess($this, $this->_roleCustomDataTypeID, $roleID, 1, 'Participant', $this->_id);
414 CRM_Custom_Form_CustomData::buildQuickForm($this);
415 CRM_Custom_Form_CustomData::setDefaultValues($this);
416 }
417 }
418
419 //custom data of type participant event
420 CRM_Custom_Form_CustomData::preProcess($this, $this->_eventNameCustomDataTypeID, $eventId, 1, 'Participant', $this->_id);
421 CRM_Custom_Form_CustomData::buildQuickForm($this);
422 CRM_Custom_Form_CustomData::setDefaultValues($this);
423
424 // custom data of type participant event type
425 $eventTypeId = NULL;
426 if ($eventId) {
427 $eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'event_type_id', 'id');
428 }
429 CRM_Custom_Form_CustomData::preProcess($this, $this->_eventTypeCustomDataTypeID, $eventTypeId,
430 1, 'Participant', $this->_id
431 );
432 CRM_Custom_Form_CustomData::buildQuickForm($this);
433 CRM_Custom_Form_CustomData::setDefaultValues($this);
434
435 //custom data of type participant, ( we 'null' to reset subType and subName)
436 CRM_Custom_Form_CustomData::preProcess($this, 'null', 'null', 1, 'Participant', $this->_id);
437 CRM_Custom_Form_CustomData::buildQuickForm($this);
438 CRM_Custom_Form_CustomData::setDefaultValues($this);
439 }
440
441 // CRM-4395, get the online pending contribution id.
442 $this->_onlinePendingContributionId = NULL;
443 if (!$this->_mode && $this->_id && ($this->_action & CRM_Core_Action::UPDATE)) {
444 $this->_onlinePendingContributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($this->_id,
445 'Event'
446 );
447 }
448 $this->set('onlinePendingContributionId', $this->_onlinePendingContributionId);
449 }
450
451 /**
452 * This function sets the default values for the form in edit/view mode
453 * the default values are retrieved from the database
454 *
455 * @return array
456 * @throws \CRM_Core_Exception
457 */
458 public function setDefaultValues() {
459 if ($this->_showFeeBlock) {
460 return CRM_Event_Form_EventFees::setDefaultValues($this);
461 }
462
463 $defaults = [];
464
465 if ($this->_action & CRM_Core_Action::DELETE) {
466 return $defaults;
467 }
468
469 if ($this->_id) {
470 $ids = [];
471 $params = ['id' => $this->_id];
472
473 CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
474 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
475 if ($defaults[$this->_id]['role_id']) {
476 $roleIDs = explode($sep, $defaults[$this->_id]['role_id']);
477 }
478 $this->_contactId = $defaults[$this->_id]['contact_id'];
479 $this->_statusId = $defaults[$this->_id]['participant_status_id'];
480
481 //set defaults for note
482 $noteDetails = CRM_Core_BAO_Note::getNote($this->_id, 'civicrm_participant');
483 $defaults[$this->_id]['note'] = array_pop($noteDetails);
484
485 // Check if this is a primaryParticipant (registered for others) and retrieve additional participants if true (CRM-4859)
486 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
487 $this->assign('additionalParticipants', CRM_Event_BAO_Participant::getAdditionalParticipants($this->_id));
488 }
489
490 // Get registered_by contact ID and display_name if participant was registered by someone else (CRM-4859)
491 if (!empty($defaults[$this->_id]['participant_registered_by_id'])) {
492 $registered_by_contact_id = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
493 $defaults[$this->_id]['participant_registered_by_id'],
494 'contact_id', 'id'
495 );
496 $this->assign('participant_registered_by_id', $defaults[$this->_id]['participant_registered_by_id']);
497 $this->assign('registered_by_contact_id', $registered_by_contact_id);
498 $this->assign('registered_by_display_name', CRM_Contact_BAO_Contact::displayName($registered_by_contact_id));
499 }
500 }
501 elseif ($this->_contactID) {
502 $defaults[$this->_id]['contact_id'] = $this->_contactID;
503 }
504
505 //setting default register date
506 if ($this->_action == CRM_Core_Action::ADD) {
507 $statuses = array_flip(CRM_Event_PseudoConstant::participantStatus());
508 $defaults[$this->_id]['status_id'] = CRM_Utils_Array::value('Registered', $statuses);
509 if (!empty($defaults[$this->_id]['event_id'])) {
510 $contributionTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
511 $defaults[$this->_id]['event_id'],
512 'financial_type_id'
513 );
514 if ($contributionTypeId) {
515 $defaults[$this->_id]['financial_type_id'] = $contributionTypeId;
516 }
517 }
518
519 if ($this->_mode) {
520 $fields["email-{$this->_bltID}"] = 1;
521 $fields['email-Primary'] = 1;
522
523 if ($this->_contactId) {
524 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactId, $fields, $defaults);
525 }
526
527 if (empty($defaults["email-{$this->_bltID}"]) &&
528 !empty($defaults['email-Primary'])
529 ) {
530 $defaults[$this->_id]["email-{$this->_bltID}"] = $defaults['email-Primary'];
531 }
532 }
533
534 $submittedRole = $this->getElementValue('role_id');
535 if (!empty($submittedRole[0])) {
536 $roleID = $submittedRole[0];
537 }
538 $submittedEvent = $this->getElementValue('event_id');
539 if (!empty($submittedEvent[0])) {
540 $eventID = $submittedEvent[0];
541 }
542 $defaults[$this->_id]['register_date'] = date('Y-m-d H:i:s');
543 }
544 else {
545 $defaults[$this->_id]['record_contribution'] = 0;
546
547 if ($defaults[$this->_id]['participant_is_pay_later']) {
548 $this->assign('participant_is_pay_later', TRUE);
549 }
550
551 $this->assign('participant_status_id', $defaults[$this->_id]['participant_status_id']);
552 $eventID = $defaults[$this->_id]['event_id'];
553
554 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
555
556 $this->_discountId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'discount_id');
557 if ($this->_discountId) {
558 $this->set('discountId', $this->_discountId);
559 }
560 }
561
562 //assign event and role id, this is needed for Custom data building
563 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
564 if (!empty($defaults[$this->_id]['participant_role_id'])) {
565 $roleIDs = explode($sep, $defaults[$this->_id]['participant_role_id']);
566 }
567 if (isset($_POST['event_id'])) {
568 $eventID = $_POST['event_id'];
569 }
570
571 if ($this->_eID) {
572 $eventID = $this->_eID;
573 //@todo - rationalise the $this->_eID with $POST['event_id'], $this->_eid is set when eid=x is in the url
574 $roleID = CRM_Core_DAO::getFieldValue(
575 'CRM_Event_DAO_Event',
576 $this->_eID,
577 'default_role_id'
578 );
579 if (empty($roleIDs)) {
580 $roleIDs = (array) $defaults[$this->_id]['participant_role_id'] = $roleID;
581 }
582 $defaults[$this->_id]['event_id'] = $eventID;
583 }
584 if (!empty($eventID)) {
585 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
586 }
587 //these should take precedence so we state them last
588 $urlRoleIDS = CRM_Utils_Request::retrieve('roles', 'String');
589 if ($urlRoleIDS) {
590 $roleIDs = explode(',', $urlRoleIDS);
591 }
592 if (isset($roleIDs)) {
593 $defaults[$this->_id]['role_id'] = implode(',', $roleIDs);
594 }
595
596 if (isset($eventID)) {
597 $this->assign('eventID', $eventID);
598 $this->set('eventId', $eventID);
599 }
600
601 if (isset($this->_eventTypeId)) {
602 $this->assign('eventTypeID', $this->_eventTypeId);
603 }
604
605 $this->assign('event_is_test', CRM_Utils_Array::value('event_is_test', $defaults[$this->_id]));
606 return $defaults[$this->_id];
607 }
608
609 /**
610 * Build the form object.
611 *
612 * @return void
613 * @throws \CRM_Core_Exception
614 * @throws \CiviCRM_API3_Exception
615 */
616 public function buildQuickForm() {
617
618 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
619 $partiallyPaidStatusId = array_search('Partially paid', $participantStatuses);
620 $this->assign('partiallyPaidStatusId', $partiallyPaidStatusId);
621
622 if ($this->_showFeeBlock) {
623 return $this->buildEventFeeForm($this);
624 }
625
626 //need to assign custom data type to the template
627 $this->assign('customDataType', 'Participant');
628
629 $this->applyFilter('__ALL__', 'trim');
630
631 if ($this->_action & CRM_Core_Action::DELETE) {
632 if ($this->_single) {
633 $additionalParticipant = count(CRM_Event_BAO_Event::buildCustomProfile($this->_id,
634 NULL,
635 $this->_contactId,
636 FALSE,
637 TRUE
638 )) - 1;
639 if ($additionalParticipant) {
640 $deleteParticipants = [
641 1 => ts('Delete this participant record along with associated participant record(s).'),
642 2 => ts('Delete only this participant record.'),
643 ];
644 $this->addRadio('delete_participant', NULL, $deleteParticipants, NULL, '<br />');
645 $this->setDefaults(['delete_participant' => 1]);
646 $this->assign('additionalParticipant', $additionalParticipant);
647 }
648 }
649 $this->addButtons([
650 [
651 'type' => 'next',
652 'name' => ts('Delete'),
653 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
654 'isDefault' => TRUE,
655 ],
656 [
657 'type' => 'cancel',
658 'name' => ts('Cancel'),
659 ],
660 ]);
661 return;
662 }
663
664 if ($this->_single) {
665 $contactField = $this->addEntityRef('contact_id', ts('Participant'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
666 if ($this->_context != 'standalone') {
667 $contactField->freeze();
668 }
669 }
670
671 $eventFieldParams = [
672 'entity' => 'Event',
673 'select' => ['minimumInputLength' => 0],
674 'api' => [
675 'extra' => ['campaign_id', 'default_role_id', 'event_type_id'],
676 ],
677 ];
678
679 if ($this->_mode) {
680 // exclude events which are not monetary when credit card registration is used
681 $eventFieldParams['api']['params']['is_monetary'] = 1;
682 }
683 $this->addPaymentProcessorSelect(TRUE, FALSE, FALSE);
684
685 $element = $this->addEntityRef('event_id', ts('Event'), $eventFieldParams, TRUE);
686
687 //frozen the field fix for CRM-4171
688 if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
689 if (CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
690 $this->_id, 'contribution_id', 'participant_id'
691 )
692 ) {
693 $element->freeze();
694 }
695 }
696
697 //CRM-7362 --add campaigns.
698 $campaignId = NULL;
699 if ($this->_id) {
700 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'campaign_id');
701 }
702 if (!$campaignId) {
703 $eventId = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
704 if ($eventId) {
705 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'campaign_id');
706 }
707 }
708 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
709 $this->add('datepicker', 'register_date', ts('Registration Date'), [], TRUE, ['time' => TRUE]);
710
711 if ($this->_id) {
712 $this->assign('entityID', $this->_id);
713 }
714
715 $this->addSelect('role_id', ['multiple' => TRUE, 'class' => 'huge'], TRUE);
716
717 // CRM-4395
718 $checkCancelledJs = ['onchange' => "return sendNotification( );"];
719 $confirmJS = NULL;
720 if ($this->_onlinePendingContributionId) {
721 $cancelledparticipantStatusId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus());
722 $cancelledContributionStatusId = array_search('Cancelled',
723 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
724 );
725 $checkCancelledJs = [
726 'onchange' => "checkCancelled( this.value, {$cancelledparticipantStatusId},{$cancelledContributionStatusId});",
727 ];
728
729 $participantStatusId = array_search('Pending from pay later',
730 CRM_Event_PseudoConstant::participantStatus()
731 );
732 $contributionStatusId = array_search('Completed',
733 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
734 );
735 $confirmJS = ['onclick' => "return confirmStatus( {$participantStatusId}, {$contributionStatusId} );"];
736 }
737
738 // get the participant status names to build special status array which is used to show notification
739 // checkbox below participant status select
740 $participantStatusName = CRM_Event_PseudoConstant::participantStatus();
741 $notificationStatuses = [
742 'Cancelled',
743 'Pending from waitlist',
744 'Pending from approval',
745 'Expired',
746 ];
747
748 // get the required status and then implode only ids
749 $notificationStatusIds = implode(',', array_keys(array_intersect($participantStatusName, $notificationStatuses)));
750 $this->assign('notificationStatusIds', $notificationStatusIds);
751
752 $this->_participantStatuses = $statusOptions = CRM_Event_BAO_Participant::buildOptions('status_id', 'create');
753
754 // Only show refund status when editing
755 if ($this->_action & CRM_Core_Action::ADD) {
756 $pendingRefundStatusId = array_search('Pending refund', $participantStatusName);
757 if ($pendingRefundStatusId) {
758 unset($statusOptions[$pendingRefundStatusId]);
759 }
760 }
761
762 $this->addSelect('status_id', $checkCancelledJs + [
763 'options' => $statusOptions,
764 'option_url' => 'civicrm/admin/participant_status',
765 ], TRUE);
766
767 $this->addElement('checkbox', 'is_notify', ts('Send Notification'), NULL);
768
769 $this->addField('source', ['entity' => 'Participant', 'name' => 'source']);
770 $noteAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
771 $this->add('textarea', 'note', ts('Notes'), $noteAttributes['note']);
772
773 $buttons[] = [
774 'type' => 'upload',
775 'name' => ts('Save'),
776 'isDefault' => TRUE,
777 'js' => $confirmJS,
778 ];
779
780 $path = CRM_Utils_System::currentPath();
781 $excludeForPaths = [
782 'civicrm/contact/search',
783 'civicrm/group/search',
784 ];
785 if (!in_array($path, $excludeForPaths)) {
786 $buttons[] = [
787 'type' => 'upload',
788 'name' => ts('Save and New'),
789 'subName' => 'new',
790 'js' => $confirmJS,
791 ];
792 }
793
794 $buttons[] = [
795 'type' => 'cancel',
796 'name' => ts('Cancel'),
797 ];
798
799 $this->addButtons($buttons);
800 if ($this->_action == CRM_Core_Action::VIEW) {
801 $this->freeze();
802 }
803 }
804
805 /**
806 * Add local and global form rules.
807 *
808 * @return void
809 */
810 public function addRules() {
811 $this->addFormRule(['CRM_Event_Form_Participant', 'formRule'], $this);
812 }
813
814 /**
815 * Global validation rules for the form.
816 *
817 * @param array $values
818 * Posted values of the form.
819 * @param $files
820 * @param $self
821 *
822 * @return array
823 * list of errors to be posted back to the form
824 */
825 public static function formRule($values, $files, $self) {
826 // If $values['_qf_Participant_next'] is Delete or
827 // $values['event_id'] is empty, then return
828 // instead of proceeding further.
829
830 if ((CRM_Utils_Array::value('_qf_Participant_next', $values) == 'Delete') ||
831 (!$values['event_id'])
832 ) {
833 return TRUE;
834 }
835
836 $errorMsg = [];
837
838 if (!empty($values['payment_processor_id'])) {
839 // make sure that payment instrument values (e.g. credit card number and cvv) are valid
840 CRM_Core_Payment_Form::validatePaymentInstrument($values['payment_processor_id'], $values, $errorMsg, NULL);
841 }
842
843 if (!empty($values['record_contribution'])) {
844 if (empty($values['financial_type_id'])) {
845 $errorMsg['financial_type_id'] = ts('Please enter the associated Financial Type');
846 }
847 if (empty($values['payment_instrument_id'])) {
848 $errorMsg['payment_instrument_id'] = ts('Payment Method is a required field.');
849 }
850 if (!empty($values['priceSetId'])) {
851 CRM_Price_BAO_PriceField::priceSetValidation($values['priceSetId'], $values, $errorMsg);
852 }
853 }
854
855 // validate contribution status for 'Failed'.
856 if ($self->_onlinePendingContributionId && !empty($values['record_contribution']) &&
857 (CRM_Utils_Array::value('contribution_status_id', $values) ==
858 array_search('Failed', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))
859 )
860 ) {
861 $errorMsg['contribution_status_id'] = ts('Please select a valid payment status before updating.');
862 }
863
864 // do the amount validations.
865 //skip for update mode since amount is freeze, CRM-6052
866 if ((!$self->_id && empty($values['total_amount']) &&
867 empty($self->_values['line_items'])
868 ) ||
869 ($self->_id && !$self->_paymentId && isset($self->_values['line_items']) && is_array($self->_values['line_items']))
870 ) {
871 if ($priceSetId = CRM_Utils_Array::value('priceSetId', $values)) {
872 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $values, $errorMsg, TRUE);
873 }
874 }
875 // For single additions - show validation error if the contact has already been registered
876 // for this event.
877 if ($self->_single && ($self->_action & CRM_Core_Action::ADD)) {
878 if ($self->_context == 'standalone') {
879 $contactId = CRM_Utils_Array::value('contact_id', $values);
880 }
881 else {
882 $contactId = $self->_contactId;
883 }
884
885 $eventId = CRM_Utils_Array::value('event_id', $values);
886
887 $event = new CRM_Event_DAO_Event();
888 $event->id = $eventId;
889 $event->find(TRUE);
890
891 if (!$event->allow_same_participant_emails && !empty($contactId) && !empty($eventId)) {
892 $cancelledStatusID = CRM_Core_PseudoConstant::getKey('CRM_Event_BAO_Participant', 'status_id', 'Cancelled');
893 $dupeCheck = new CRM_Event_BAO_Participant();
894 $dupeCheck->contact_id = $contactId;
895 $dupeCheck->event_id = $eventId;
896 $dupeCheck->whereAdd("status_id != {$cancelledStatusID} ");
897 $dupeCheck->find(TRUE);
898 if (!empty($dupeCheck->id)) {
899 $errorMsg['event_id'] = ts("This contact has already been assigned to this event.");
900 }
901 }
902 }
903 return CRM_Utils_Array::crmIsEmptyArray($errorMsg) ? TRUE : $errorMsg;
904 }
905
906 /**
907 * Process the form submission.
908 */
909 public function postProcess() {
910 // get the submitted form values.
911 $params = $this->controller->exportValues($this->_name);
912
913 if ($this->_action & CRM_Core_Action::DELETE) {
914 if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
915 $additionalId = (CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id));
916 $participantLinks = (CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId));
917 }
918 if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
919 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
920 foreach ($additionalIds as $value) {
921 CRM_Event_BAO_Participant::deleteParticipant($value);
922 }
923 }
924 CRM_Event_BAO_Participant::deleteParticipant($this->_id);
925 CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
926 if (!empty($participantLinks)) {
927 $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
928 CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
929 }
930 return;
931 }
932 // When adding a single contact, the formRule prevents you from adding duplicates
933 // (See above in formRule()). When adding more than one contact, the duplicates are
934 // removed automatically and the user receives one notification.
935 if ($this->_action & CRM_Core_Action::ADD) {
936 $event_id = $this->_eventId;
937 if (empty($event_id) && !empty($params['event_id'])) {
938 $event_id = $params['event_id'];
939 }
940 if (!$this->_single && !empty($event_id)) {
941 $duplicateContacts = 0;
942 foreach ($this->_contactIds as $k => $dupeCheckContactId) {
943 // Eliminate contacts that have already been assigned to this event.
944 $dupeCheck = new CRM_Event_BAO_Participant();
945 $dupeCheck->contact_id = $dupeCheckContactId;
946 $dupeCheck->event_id = $event_id;
947 $dupeCheck->find(TRUE);
948 if (!empty($dupeCheck->id)) {
949 $duplicateContacts++;
950 unset($this->_contactIds[$k]);
951 }
952 }
953 if ($duplicateContacts > 0) {
954 $msg = ts(
955 "%1 contacts have already been assigned to this event. They were not added a second time.",
956 [1 => $duplicateContacts]
957 );
958 CRM_Core_Session::setStatus($msg);
959 }
960 if (count($this->_contactIds) == 0) {
961 CRM_Core_Session::setStatus(ts("No participants were added."));
962 return;
963 }
964 // We have to re-key $this->_contactIds so each contact has the same
965 // key as their corresponding record in the $participants array that
966 // will be created below.
967 $this->_contactIds = array_values($this->_contactIds);
968 }
969 }
970
971 $statusMsg = $this->submit($params);
972 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
973 $session = CRM_Core_Session::singleton();
974 $buttonName = $this->controller->getButtonName();
975 if ($this->_context == 'standalone') {
976 if ($buttonName == $this->getButtonName('upload', 'new')) {
977 $urlParams = 'reset=1&action=add&context=standalone';
978 if ($this->_mode) {
979 $urlParams .= '&mode=' . $this->_mode;
980 }
981 if ($this->_eID) {
982 $urlParams .= '&eid=' . $this->_eID;
983 }
984 $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
985 }
986 else {
987 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
988 "reset=1&cid={$this->_contactId}&selectedChild=participant"
989 ));
990 }
991 }
992 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
993 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant',
994 "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"
995 ));
996 }
997 }
998
999 /**
1000 * Submit form.
1001 *
1002 * @param array $params
1003 *
1004 * @return string
1005 * @throws \CRM_Core_Exception
1006 * @throws \CiviCRM_API3_Exception
1007 */
1008 public function submit($params) {
1009 if ($this->_mode && !$this->_isPaidEvent) {
1010 CRM_Core_Error::statusBounce(ts('Selected Event is not Paid Event '));
1011 }
1012 $participantStatus = CRM_Event_PseudoConstant::participantStatus();
1013 // set the contact, when contact is selected
1014 if (!empty($params['contact_id'])) {
1015 $this->_contactID = $this->_contactId = $params['contact_id'];
1016 }
1017 if ($this->_priceSetId && $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1018 $this->_quickConfig = $isQuickConfig;
1019 }
1020
1021 if ($this->_id) {
1022 $params['id'] = $this->_id;
1023 }
1024
1025 $config = CRM_Core_Config::singleton();
1026 if (isset($params['total_amount'])) {
1027 $params['total_amount'] = CRM_Utils_Rule::cleanMoney($params['total_amount']);
1028 }
1029 if ($this->_isPaidEvent) {
1030 list($contributionParams, $lineItem, $additionalParticipantDetails, $params) = $this->preparePaidEventProcessing($params);
1031 }
1032
1033 $this->_params = $params;
1034 parent::beginPostProcess();
1035 $amountOwed = NULL;
1036 if (isset($params['amount'])) {
1037 $amountOwed = $params['amount'];
1038 unset($params['amount']);
1039 }
1040 $params['contact_id'] = $this->_contactId;
1041
1042 // overwrite actual payment amount if entered
1043 if (!empty($params['total_amount'])) {
1044 $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
1045 }
1046
1047 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1048 $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
1049
1050 if ($this->_contactId) {
1051 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
1052 }
1053
1054 //modify params according to parameter used in create
1055 //participant method (addParticipant)
1056 $this->_params['participant_status_id'] = $params['status_id'];
1057 $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
1058 $this->_params['participant_register_date'] = $params['register_date'];
1059 $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
1060
1061 $now = date('YmdHis');
1062
1063 if ($this->_mode) {
1064 // set source if not set
1065 if (empty($params['source'])) {
1066 $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', [
1067 1 => $userName,
1068 2 => $this->getEventValue('title'),
1069 ]);
1070 }
1071 else {
1072 $this->_params['participant_source'] = $params['source'];
1073 }
1074 $this->_params['description'] = $this->_params['participant_source'];
1075
1076 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1077 $this->_mode
1078 );
1079 $fields = [];
1080
1081 // set email for primary location.
1082 $fields['email-Primary'] = 1;
1083 $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
1084
1085 $params['register_date'] = $now;
1086
1087 // now set the values for the billing location.
1088 foreach ($this->_fields as $name => $dontCare) {
1089 $fields[$name] = 1;
1090 }
1091
1092 // also add location name to the array
1093 $params["address_name-{$this->_bltID}"]
1094 = CRM_Utils_Array::value('billing_first_name', $params) . ' ' .
1095 CRM_Utils_Array::value('billing_middle_name', $params) . ' ' .
1096 CRM_Utils_Array::value('billing_last_name', $params);
1097
1098 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1099 $fields["address_name-{$this->_bltID}"] = 1;
1100 $fields["email-{$this->_bltID}"] = 1;
1101 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
1102
1103 $nameFields = ['first_name', 'middle_name', 'last_name'];
1104
1105 foreach ($nameFields as $name) {
1106 $fields[$name] = 1;
1107 if (array_key_exists("billing_$name", $params)) {
1108 $params[$name] = $params["billing_{$name}"];
1109 $params['preserveDBName'] = TRUE;
1110 }
1111 }
1112 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
1113 }
1114
1115 if (!empty($this->_params['participant_role_id'])) {
1116 $customFieldsRole = [];
1117 foreach ($this->_params['participant_role_id'] as $roleKey) {
1118 $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant',
1119 FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
1120 }
1121 $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant',
1122 FALSE,
1123 FALSE,
1124 CRM_Utils_Array::value('event_id', $params),
1125 $this->_eventNameCustomDataTypeID
1126 );
1127 $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant',
1128 FALSE,
1129 FALSE,
1130 $this->_eventTypeId,
1131 $this->_eventTypeCustomDataTypeID
1132 );
1133 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
1134 CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
1135 );
1136 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
1137 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
1138
1139 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, $this->getDefaultEntity());
1140 }
1141
1142 //do cleanup line items if participant edit the Event Fee.
1143 if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
1144 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
1145 }
1146
1147 if ($this->_mode) {
1148 // add all the additional payment params we need
1149 $this->_params = $this->prepareParamsForPaymentProcessor($this->_params);
1150 $this->_params['amount'] = $params['fee_amount'];
1151 $this->_params['amount_level'] = $params['amount_level'];
1152 $this->_params['currencyID'] = $config->defaultCurrency;
1153 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1154
1155 // at this point we've created a contact and stored its address etc
1156 // all the payment processors expect the name and address to be in the
1157 // so we copy stuff over to first_name etc.
1158 $paymentParams = $this->_params;
1159 if (!empty($this->_params['send_receipt'])) {
1160 $paymentParams['email'] = $this->_contributorEmail;
1161 }
1162
1163 // The only reason for merging in the 'contact_id' rather than ensuring it is set
1164 // is that this patch is being done around the time of the stable release
1165 // so more conservative approach is called for.
1166 // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
1167 // needs rationalising.
1168 $mapParams = array_merge(['contact_id' => $contactID], $this->_params);
1169 CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
1170
1171 $payment = $this->_paymentProcessor['object'];
1172
1173 // CRM-15622: fix for incorrect contribution.fee_amount
1174 $paymentParams['fee_amount'] = NULL;
1175 try {
1176 $result = $payment->doPayment($paymentParams);
1177 }
1178 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
1179 // @todo un comment the following line out when we are creating a contribution before we get to this point
1180 // see dev/financial#53 about ensuring we create a pending contribution before we try processing payment
1181 // CRM_Contribute_BAO_Contribution::failPayment($contributionID);
1182 CRM_Core_Session::singleton()->setStatus($e->getMessage());
1183 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant',
1184 "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"
1185 ));
1186 }
1187
1188 if ($result) {
1189 $this->_params = array_merge($this->_params, $result);
1190 }
1191
1192 $this->_params['receive_date'] = $now;
1193
1194 if (!empty($this->_params['send_receipt'])) {
1195 $this->_params['receipt_date'] = $now;
1196 }
1197 else {
1198 $this->_params['receipt_date'] = NULL;
1199 }
1200
1201 $this->set('params', $this->_params);
1202 $this->assign('trxn_id', $result['trxn_id']);
1203 $this->assign('receive_date', $this->_params['receive_date']);
1204
1205 //add contribution record
1206 $this->_params['financial_type_id']
1207 = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
1208 $this->_params['mode'] = $this->_mode;
1209
1210 //add contribution record
1211 $contributions[] = $contribution = $this->processContribution(
1212 $this, $this->_params,
1213 $result, $contactID,
1214 FALSE,
1215 $this->_paymentProcessor
1216 );
1217
1218 // add participant record
1219 $participants = [];
1220 if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
1221 $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
1222 $this->_params['role_id']
1223 );
1224 }
1225
1226 //CRM-15372 patch to fix fee amount replacing amount
1227 $this->_params['fee_amount'] = $this->_params['amount'];
1228
1229 $participants[] = $this->addParticipant($this, $this->_params, $contactID);
1230
1231 //add custom data for participant
1232 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
1233 'civicrm_participant',
1234 $participants[0]->id,
1235 'Participant'
1236 );
1237
1238 // Add participant payment
1239 $participantPaymentParams = [
1240 'participant_id' => $participants[0]->id,
1241 'contribution_id' => $contribution->id,
1242 ];
1243 civicrm_api3('ParticipantPayment', 'create', $participantPaymentParams);
1244
1245 $this->_contactIds[] = $this->_contactId;
1246 }
1247 else {
1248 $participants = [];
1249 if ($this->_single) {
1250 if ($params['role_id']) {
1251 $params['role_id'] = $roleIdWithSeparator;
1252 }
1253 else {
1254 $params['role_id'] = 'NULL';
1255 }
1256 $participants[] = CRM_Event_BAO_Participant::create($params);
1257 }
1258 else {
1259 foreach ($this->_contactIds as $contactID) {
1260 $commonParams = $params;
1261 $commonParams['contact_id'] = $contactID;
1262 if ($commonParams['role_id']) {
1263 $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
1264 }
1265 else {
1266 $commonParams['role_id'] = 'NULL';
1267 }
1268 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
1269 }
1270 }
1271
1272 if ($this->_single) {
1273 $this->_contactIds[] = $this->_contactId;
1274 }
1275
1276 $contributions = [];
1277 if (!empty($params['record_contribution'])) {
1278 if (!empty($params['id'])) {
1279 if ($this->_onlinePendingContributionId) {
1280 $contributionParams['id'] = $this->_onlinePendingContributionId;
1281 }
1282 else {
1283 $contributionParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1284 $params['id'],
1285 'contribution_id',
1286 'participant_id'
1287 );
1288 }
1289 }
1290 unset($params['note']);
1291
1292 //build contribution params
1293 if (!$this->_onlinePendingContributionId) {
1294 if (empty($params['source'])) {
1295 $contributionParams['source'] = ts('%1 : Offline registration (by %2)', [
1296 1 => $this->getEventValue('title'),
1297 2 => $userName,
1298 ]);
1299 }
1300 else {
1301 $contributionParams['source'] = $params['source'];
1302 }
1303 }
1304
1305 $contributionParams['currency'] = $config->defaultCurrency;
1306 $contributionParams['non_deductible_amount'] = 'null';
1307 $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
1308 $contributionParams['contact_id'] = $this->_contactID;
1309 $contributionParams['receive_date'] = CRM_Utils_Array::value('receive_date', $params, 'null');
1310
1311 $recordContribution = [
1312 'financial_type_id',
1313 'payment_instrument_id',
1314 'trxn_id',
1315 'contribution_status_id',
1316 'check_number',
1317 'campaign_id',
1318 'pan_truncation',
1319 'card_type_id',
1320 ];
1321
1322 foreach ($recordContribution as $f) {
1323 $contributionParams[$f] = CRM_Utils_Array::value($f, $this->_params);
1324 if ($f == 'trxn_id') {
1325 $this->assign('trxn_id', $contributionParams[$f]);
1326 }
1327 }
1328
1329 //insert financial type name in receipt.
1330 $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1331 $contributionParams['financial_type_id']));
1332 // legacy support
1333 $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
1334 $contributionParams['skipLineItem'] = 1;
1335 if ($this->_id) {
1336 $contributionParams['contribution_mode'] = 'participant';
1337 $contributionParams['participant_id'] = $this->_id;
1338 }
1339 // Set is_pay_later flag for back-office offline Pending status contributions
1340 if ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Pending')) {
1341 $contributionParams['is_pay_later'] = 1;
1342 }
1343 elseif ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Completed')) {
1344 $contributionParams['is_pay_later'] = 0;
1345 }
1346
1347 if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
1348 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
1349 $amountOwed = $params['fee_amount'];
1350 }
1351
1352 // if multiple participants are link, consider contribution total amount as the amount Owed
1353 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
1354 $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1355 $contributionParams['id'],
1356 'total_amount'
1357 );
1358 }
1359
1360 // CRM-13964 partial_payment_total
1361 if ($amountOwed > $params['total_amount']) {
1362 // the owed amount
1363 $contributionParams['partial_payment_total'] = $amountOwed;
1364 // the actual amount paid
1365 $contributionParams['partial_amount_to_pay'] = $params['total_amount'];
1366 $this->assign('balanceAmount', $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_to_pay']);
1367 }
1368 }
1369
1370 if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
1371 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
1372 }
1373
1374 if ($this->_single) {
1375 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams);
1376 }
1377 else {
1378 foreach ($this->_contactIds as $contactID) {
1379 $contributionParams['contact_id'] = $contactID;
1380 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams);
1381 }
1382 }
1383
1384 // Insert payment record for this participant
1385 if (empty($contributionParams['id'])) {
1386 foreach ($this->_contactIds as $num => $contactID) {
1387 $participantPaymentParams = [
1388 'participant_id' => $participants[$num]->id,
1389 'contribution_id' => $contributions[$num]->id,
1390 ];
1391 civicrm_api3('ParticipantPayment', 'create', $participantPaymentParams);
1392 }
1393 }
1394
1395 // CRM-11124
1396 if ($this->_params['discount_id']) {
1397 CRM_Event_BAO_Participant::createDiscountTrxn(
1398 $this->_eventId,
1399 $contributionParams,
1400 NULL,
1401 CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params)
1402 );
1403 }
1404 }
1405 }
1406
1407 // also store lineitem stuff here
1408 if ((($this->_lineItem & $this->_action & CRM_Core_Action::ADD) ||
1409 ($this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId))
1410 ) {
1411 foreach ($this->_contactIds as $num => $contactID) {
1412 foreach ($this->_lineItem as $key => $value) {
1413 if (is_array($value) && $value != 'skip') {
1414 foreach ($value as $lineKey => $line) {
1415 //10117 update the line items for participants if contribution amount is recorded
1416 if ($this->_quickConfig && !empty($params['total_amount']) &&
1417 ($params['status_id'] != array_search('Partially paid', $participantStatus))
1418 ) {
1419 $line['unit_price'] = $line['line_total'] = $params['total_amount'];
1420 if (!empty($params['tax_amount'])) {
1421 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
1422 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
1423 }
1424 }
1425 $lineItem[$this->_priceSetId][$lineKey] = $line;
1426 }
1427 CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
1428 CRM_Contribute_BAO_Contribution::addPayments($contributions);
1429 }
1430 }
1431 }
1432 }
1433
1434 $updateStatusMsg = NULL;
1435 //send mail when participant status changed, CRM-4326
1436 if ($this->_id && $this->_statusId &&
1437 $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])
1438 ) {
1439
1440 $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id,
1441 $params['status_id'],
1442 $this->_statusId
1443 );
1444 }
1445
1446 $sent = [];
1447 $notSent = [];
1448 if (!empty($params['send_receipt'])) {
1449 if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
1450 $receiptFrom = $params['from_email_address'];
1451 }
1452
1453 $this->assign('module', 'Event Registration');
1454 $this->assignEventDetailsToTpl($params['event_id'], CRM_Utils_Array::value('role_id', $params), CRM_Utils_Array::value('receipt_text', $params), $this->_isPaidEvent);
1455 $this->assign('isAmountzero', 1);
1456
1457 if ($this->_isPaidEvent) {
1458 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
1459 if (!$this->_mode) {
1460 if (isset($params['payment_instrument_id'])) {
1461 $this->assign('paidBy',
1462 CRM_Utils_Array::value($params['payment_instrument_id'],
1463 $paymentInstrument
1464 )
1465 );
1466 }
1467 }
1468
1469 $this->assign('totalAmount', $contributionParams['total_amount']);
1470 $this->assign('isPrimary', 1);
1471 $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
1472 }
1473 if ($this->_mode) {
1474 $this->assignBillingName($params);
1475 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
1476 $this->_params,
1477 $this->_bltID
1478 ));
1479
1480 $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
1481 $date = CRM_Utils_Date::mysqlToIso($date);
1482 $this->assign('credit_card_exp_date', $date);
1483 $this->assign('credit_card_number',
1484 CRM_Utils_System::mungeCreditCard($params['credit_card_number'])
1485 );
1486 $this->assign('credit_card_type', $params['credit_card_type']);
1487 // The concept of contributeMode is deprecated.
1488 $this->assign('contributeMode', 'direct');
1489 $this->assign('isAmountzero', 0);
1490 $this->assign('is_pay_later', 0);
1491 $this->assign('isPrimary', 1);
1492 }
1493
1494 $this->assign('register_date', $params['register_date']);
1495 if (isset($params['receive_date'])) {
1496 $this->assign('receive_date', $params['receive_date']);
1497 }
1498
1499 $customGroup = [];
1500 //format submitted data
1501 foreach ($params['custom'] as $fieldID => $values) {
1502 foreach ($values as $fieldValue) {
1503 $isPublic = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $fieldValue['custom_group_id'], 'is_public');
1504 if ($isPublic) {
1505 $customFields[$fieldID]['id'] = $fieldID;
1506 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
1507 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
1508 }
1509 }
1510 }
1511
1512 foreach ($this->_contactIds as $num => $contactID) {
1513 // Retrieve the name and email of the contact - this will be the TO for receipt email
1514 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
1515
1516 $this->_contributorDisplayName = ($this->_contributorDisplayName == ' ') ? $this->_contributorEmail : $this->_contributorDisplayName;
1517
1518 $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1519 if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
1520 $this->assign('isOnWaitlist', TRUE);
1521 }
1522
1523 $this->assign('customGroup', $customGroup);
1524 $this->assign('contactID', $contactID);
1525 $this->assign('participantID', $participants[$num]->id);
1526
1527 $this->_id = $participants[$num]->id;
1528
1529 if ($this->_isPaidEvent) {
1530 // fix amount for each of participants ( for bulk mode )
1531 $eventAmount = [];
1532 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
1533 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1534 $totalTaxAmount = 0;
1535
1536 //add dataArray in the receipts in ADD and UPDATE condition
1537 $dataArray = [];
1538 if ($this->_action & CRM_Core_Action::ADD) {
1539 $line = isset($lineItem[0]) ? $lineItem[0] : [];
1540 }
1541 elseif ($this->_action & CRM_Core_Action::UPDATE) {
1542 $line = $this->_values['line_items'];
1543 }
1544 if ($invoicing) {
1545 foreach ($line as $key => $value) {
1546 if (isset($value['tax_amount'])) {
1547 $totalTaxAmount += $value['tax_amount'];
1548 if (isset($dataArray[(string) $value['tax_rate']])) {
1549 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1550 }
1551 else {
1552 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1553 }
1554 }
1555 }
1556 $this->assign('totalTaxAmount', $totalTaxAmount);
1557 $this->assign('taxTerm', $this->getSalesTaxTerm());
1558 $this->assign('dataArray', $dataArray);
1559 }
1560 if (!empty($additionalParticipantDetails)) {
1561 $params['amount_level'] = preg_replace('/\ 1/', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
1562 }
1563
1564 $eventAmount[$num] = [
1565 'label' => preg_replace('/\ 1/', '', $params['amount_level']),
1566 'amount' => $params['fee_amount'],
1567 ];
1568 //as we are using same template for online & offline registration.
1569 //So we have to build amount as array.
1570 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
1571 $this->assign('amount', $eventAmount);
1572 }
1573
1574 $sendTemplateParams = [
1575 'groupName' => 'msg_tpl_workflow_event',
1576 'valueName' => 'event_offline_receipt',
1577 'contactId' => $contactID,
1578 'isTest' => !empty($this->_defaultValues['is_test']),
1579 'PDFFilename' => ts('confirmation') . '.pdf',
1580 ];
1581
1582 // try to send emails only if email id is present
1583 // and the do-not-email option is not checked for that contact
1584 if ($this->_contributorEmail and !$this->_toDoNotEmail) {
1585 $sendTemplateParams['from'] = $receiptFrom;
1586 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
1587 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
1588 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
1589 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
1590 }
1591
1592 //send email with pdf invoice
1593 $template = CRM_Core_Smarty::singleton();
1594 $taxAmt = $template->get_template_vars('dataArray');
1595 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1596 $this->_id, 'contribution_id', 'participant_id'
1597 );
1598 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
1599 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
1600 if (!empty($taxAmt) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1601 $sendTemplateParams['isEmailPdf'] = TRUE;
1602 $sendTemplateParams['contributionId'] = $contributionId;
1603 }
1604 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
1605 if ($mailSent) {
1606 $sent[] = $contactID;
1607 foreach ($participants as $ids => $values) {
1608 if ($values->contact_id == $contactID) {
1609 $values->details = CRM_Utils_Array::value('receipt_text', $params);
1610 CRM_Activity_BAO_Activity::addActivity($values, 'Email');
1611 break;
1612 }
1613 }
1614 }
1615 else {
1616 $notSent[] = $contactID;
1617 }
1618 }
1619 }
1620
1621 // set the participant id if it is not set
1622 if (!$this->_id) {
1623 $this->_id = $participants[0]->id;
1624 }
1625
1626 return $this->getStatusMsg($params, $sent, $updateStatusMsg, $notSent);
1627 }
1628
1629 /**
1630 * Set the various IDs relating to custom data types.
1631 */
1632 public function setCustomDataTypes() {
1633 $customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
1634 $this->_roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
1635 $this->_eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
1636 $this->_eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
1637 $this->assign('roleCustomDataTypeID', $this->_roleCustomDataTypeID);
1638 $this->assign('eventNameCustomDataTypeID', $this->_eventNameCustomDataTypeID);
1639 $this->assign('eventTypeCustomDataTypeID', $this->_eventTypeCustomDataTypeID);
1640 }
1641
1642 /**
1643 * Get status message
1644 *
1645 * @param array $params
1646 * @param int $sent
1647 * @param string $updateStatusMsg
1648 * @param int $notSent
1649 *
1650 * @return string
1651 */
1652 protected function getStatusMsg($params, $sent, $updateStatusMsg, $notSent) {
1653 $statusMsg = '';
1654 if (($this->_action & CRM_Core_Action::UPDATE)) {
1655 $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $this->_contributorDisplayName]);
1656 if (!empty($params['send_receipt']) && count($sent)) {
1657 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', [1 => $this->_contributorEmail]);
1658 }
1659
1660 if ($updateStatusMsg) {
1661 $statusMsg = "{$statusMsg} {$updateStatusMsg}";
1662 }
1663 }
1664 elseif ($this->_action & CRM_Core_Action::ADD) {
1665 if ($this->_single) {
1666 $statusMsg = ts('Event registration for %1 has been added.', [1 => $this->_contributorDisplayName]);
1667 if (!empty($params['send_receipt']) && count($sent)) {
1668 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', [1 => $this->_contributorEmail]);
1669 }
1670 }
1671 else {
1672 $statusMsg = ts('Total Participant(s) added to event: %1.', [1 => count($this->_contactIds)]);
1673 if (count($notSent) > 0) {
1674 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', [1 => count($notSent)]);
1675 }
1676 elseif (isset($params['send_receipt'])) {
1677 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
1678 }
1679 }
1680 }
1681 return $statusMsg;
1682 }
1683
1684 /**
1685 * Build the form object.
1686 *
1687 * @param \CRM_Event_Form_Participant $form
1688 *
1689 * @return bool
1690 * @throws \CRM_Core_Exception
1691 * @throws \Exception
1692 */
1693 public function buildEventFeeForm($form) {
1694 if ($form->_eventId) {
1695 $form->_isPaidEvent = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_eventId, 'is_monetary');
1696 if ($form->_isPaidEvent) {
1697 $form->addElement('hidden', 'hidden_feeblock', 1);
1698 }
1699
1700 $eventfullMsg = CRM_Event_BAO_Participant::eventFullMessage($form->_eventId, $this->getParticipantID());
1701 $form->addElement('hidden', 'hidden_eventFullMsg', $eventfullMsg, ['id' => 'hidden_eventFullMsg']);
1702 }
1703
1704 if ($form->_isPaidEvent) {
1705 $params = ['id' => $form->_eventId];
1706 CRM_Event_BAO_Event::retrieve($params, $event);
1707
1708 //retrieve custom information
1709 $form->_values = [];
1710 CRM_Event_Form_Registration::initEventFee($form, $event['id']);
1711 CRM_Event_Form_Registration_Register::buildAmount($form, TRUE, $form->_discountId);
1712 $lineItem = [];
1713 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
1714 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1715 $totalTaxAmount = 0;
1716 if (!CRM_Utils_System::isNull(CRM_Utils_Array::value('line_items', $form->_values))) {
1717 $lineItem[] = $form->_values['line_items'];
1718 foreach ($form->_values['line_items'] as $key => $value) {
1719 $totalTaxAmount = $value['tax_amount'] + $totalTaxAmount;
1720 }
1721 }
1722 if ($invoicing) {
1723 $form->assign('totalTaxAmount', $totalTaxAmount);
1724 }
1725 $form->assign('lineItem', empty($lineItem) ? FALSE : $lineItem);
1726 $discounts = [];
1727 if (!empty($form->_values['discount'])) {
1728 foreach ($form->_values['discount'] as $key => $value) {
1729 $value = current($value);
1730 $discounts[$key] = $value['name'];
1731 }
1732
1733 $element = $form->add('select', 'discount_id',
1734 ts('Discount Set'),
1735 [
1736 0 => ts('- select -'),
1737 ] + $discounts,
1738 FALSE,
1739 ['class' => "crm-select2"]
1740 );
1741 }
1742 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
1743 && !CRM_Utils_Array::value('fee', $form->_values)
1744 && CRM_Utils_Array::value('snippet', $_REQUEST) == CRM_Core_Smarty::PRINT_NOFORM
1745 ) {
1746 CRM_Core_Session::setStatus(ts('You do not have all the permissions needed for this page.'), 'Permission Denied', 'error');
1747 return FALSE;
1748 }
1749
1750 CRM_Core_Payment_Form::buildPaymentForm($form, $form->_paymentProcessor, FALSE, TRUE, self::getDefaultPaymentInstrumentId());
1751 if (!$form->_mode) {
1752 $form->addElement('checkbox', 'record_contribution', ts('Record Payment?'), NULL,
1753 ['onclick' => "return showHideByValue('record_contribution','','payment_information','table-row','radio',false);"]
1754 );
1755 // Check permissions for financial type first
1756 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
1757 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $form->_action);
1758 }
1759 else {
1760 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
1761 }
1762
1763 $form->add('select', 'financial_type_id',
1764 ts('Financial Type'),
1765 ['' => ts('- select -')] + $financialTypes
1766 );
1767
1768 $form->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
1769
1770 $form->add('select', 'payment_instrument_id',
1771 ts('Payment Method'),
1772 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
1773 FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
1774 );
1775 // don't show transaction id in batch update mode
1776 $path = CRM_Utils_System::currentPath();
1777 $form->assign('showTransactionId', FALSE);
1778 if ($path != 'civicrm/contact/search/basic') {
1779 $form->add('text', 'trxn_id', ts('Transaction ID'));
1780 $form->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
1781 'objectExists', ['CRM_Contribute_DAO_Contribution', $form->_eventId, 'trxn_id']
1782 );
1783 $form->assign('showTransactionId', TRUE);
1784 }
1785
1786 $form->add('select', 'contribution_status_id',
1787 ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses('participant')
1788 );
1789
1790 $form->add('text', 'check_number', ts('Check Number'),
1791 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
1792 );
1793
1794 $form->add('text', 'total_amount', ts('Amount'),
1795 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'total_amount')
1796 );
1797 }
1798 }
1799 else {
1800 $form->add('text', 'amount', ts('Event Fee(s)'));
1801 }
1802 $form->assign('onlinePendingContributionId', $form->get('onlinePendingContributionId'));
1803
1804 $form->assign('paid', $form->_isPaidEvent);
1805
1806 $form->addElement('checkbox',
1807 'send_receipt',
1808 ts('Send Confirmation?'), NULL,
1809 ['onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);"]
1810 );
1811
1812 $form->add('select', 'from_email_address', ts('Receipt From'), $form->_fromEmails['from_email_id']);
1813
1814 $form->add('textarea', 'receipt_text', ts('Confirmation Message'));
1815
1816 // Retrieve the name and email of the contact - form will be the TO for receipt email ( only if context is not standalone)
1817 if ($form->_context != 'standalone') {
1818 if ($form->_contactId) {
1819 list($form->_contributorDisplayName,
1820 $form->_contributorEmail
1821 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($form->_contactId);
1822 $form->assign('email', $form->_contributorEmail);
1823 }
1824 else {
1825 //show email block for batch update for event
1826 $form->assign('batchEmail', TRUE);
1827 }
1828 }
1829
1830 $mailingInfo = Civi::settings()->get('mailing_backend');
1831 $form->assign('outBound_option', $mailingInfo['outBound_option']);
1832 $form->assign('hasPayment', $form->_paymentId);
1833 }
1834
1835 /**
1836 * Extracted code relating to paid events.
1837 *
1838 * @param $params
1839 *
1840 * @return array
1841 *
1842 * @throws \CiviCRM_API3_Exception
1843 */
1844 protected function preparePaidEventProcessing($params): array {
1845 $participantStatus = CRM_Event_PseudoConstant::participantStatus();
1846 $contributionParams = [
1847 'skipCleanMoney' => TRUE,
1848 'revenue_recognition_date' => $this->getRevenueRecognitionDate(),
1849 ];
1850 $lineItem = [];
1851 $additionalParticipantDetails = [];
1852
1853 if ($this->isPaymentOnExistingContribution()) {
1854 $contributionParams['total_amount'] = $this->getParticipantValue('fee_amount');
1855
1856 $params['discount_id'] = NULL;
1857 //re-enter the values for UPDATE mode
1858 $params['fee_level'] = $params['amount_level'] = $this->getParticipantValue('fee_level');
1859 $params['fee_amount'] = $this->getParticipantValue('fee_amount');
1860 if (isset($params['priceSetId'])) {
1861 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
1862 }
1863 //also add additional participant's fee level/priceset
1864 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
1865 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
1866 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
1867 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds,
1868 $hasLineItems
1869 );
1870 }
1871 }
1872 else {
1873
1874 // check that discount_id is set
1875 if (empty($params['discount_id'])) {
1876 $params['discount_id'] = 'null';
1877 }
1878
1879 //lets carry currency, CRM-4453
1880 $params['fee_currency'] = CRM_Core_Config::singleton()->defaultCurrency;
1881 if (!isset($lineItem[0])) {
1882 $lineItem[0] = [];
1883 }
1884 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'],
1885 $params, $lineItem[0]
1886 );
1887 //CRM-11529 for quick config backoffice transactions
1888 //when financial_type_id is passed in form, update the
1889 //lineitems with the financial type selected in form
1890 $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
1891 $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
1892 if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
1893 foreach ($lineItem[0] as &$values) {
1894 $values['financial_type_id'] = $submittedFinancialType;
1895 }
1896 }
1897
1898 $params['fee_level'] = $params['amount_level'];
1899 $contributionParams['total_amount'] = $params['amount'];
1900 if ($this->_quickConfig && !empty($params['total_amount']) &&
1901 $params['status_id'] != array_search('Partially paid', $participantStatus)
1902 ) {
1903 $params['fee_amount'] = $params['total_amount'];
1904 }
1905 else {
1906 //fix for CRM-3086
1907 $params['fee_amount'] = $params['amount'];
1908 }
1909 }
1910
1911 if (isset($params['priceSetId'])) {
1912 if (!empty($lineItem[0])) {
1913 $this->set('lineItem', $lineItem);
1914
1915 $this->_lineItem = $lineItem;
1916 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
1917
1918 $participantCount = [];
1919 foreach ($lineItem as $k) {
1920 foreach ($k as $v) {
1921 if (CRM_Utils_Array::value('participant_count', $v) > 0) {
1922 $participantCount[] = $v['participant_count'];
1923 }
1924 }
1925 }
1926 }
1927 if (isset($participantCount)) {
1928 $this->assign('pricesetFieldsCount', $participantCount);
1929 }
1930 $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
1931 }
1932 else {
1933 $this->assign('amount_level', $params['amount_level']);
1934 }
1935 return [$contributionParams, $lineItem, $additionalParticipantDetails, $params];
1936 }
1937
1938 /**
1939 * @param $eventID
1940 * @param $participantRoles
1941 * @param $receiptText
1942 * @param $isPaidEvent
1943 *
1944 * @return void
1945 */
1946 protected function assignEventDetailsToTpl($eventID, $participantRoles, $receiptText, $isPaidEvent) {
1947 //use of the message template below requires variables in different format
1948 $events = [];
1949 $returnProperties = ['event_type_id', 'fee_label', 'start_date', 'end_date', 'is_show_location', 'title'];
1950
1951 //get all event details.
1952 CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $eventID, $events, $returnProperties);
1953 $event = $events[$eventID];
1954 unset($event['start_date']);
1955 unset($event['end_date']);
1956
1957 $role = CRM_Event_PseudoConstant::participantRole();
1958
1959 if (is_array($participantRoles)) {
1960 $selectedRoles = [];
1961 foreach ($participantRoles as $roleId) {
1962 $selectedRoles[] = $role[$roleId];
1963 }
1964 $event['participant_role'] = implode(', ', $selectedRoles);
1965 }
1966 else {
1967 $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
1968 }
1969 $event['is_monetary'] = $isPaidEvent;
1970
1971 if ($receiptText) {
1972 $event['confirm_email_text'] = $receiptText;
1973 }
1974 $this->assign('event', $event);
1975 $this->assign('isShowLocation', $event['is_show_location']);
1976 if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
1977 $locationParams = [
1978 'entity_id' => $eventID,
1979 'entity_table' => 'civicrm_event',
1980 ];
1981 $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
1982 $this->assign('location', $location);
1983 }
1984 }
1985
1986 /**
1987 * Process the contribution.
1988 *
1989 * @param CRM_Core_Form $form
1990 * @param array $params
1991 * @param array $result
1992 * @param int $contactID
1993 * @param bool $pending
1994 * @param array $paymentProcessor
1995 *
1996 * @return \CRM_Contribute_BAO_Contribution
1997 *
1998 * @throws \CRM_Core_Exception
1999 * @throws \CiviCRM_API3_Exception
2000 */
2001 public function processContribution(
2002 &$form, $params, $result, $contactID,
2003 $pending = FALSE,
2004 $paymentProcessor = NULL
2005 ) {
2006 $transaction = new CRM_Core_Transaction();
2007
2008 $now = date('YmdHis');
2009 $receiptDate = NULL;
2010
2011 if (!empty($form->_values['event']['is_email_confirm'])) {
2012 $receiptDate = $now;
2013 }
2014
2015 // CRM-20264: fetch CC type ID and number (last 4 digit) and assign it back to $params
2016 CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($params);
2017
2018 $contribParams = [
2019 'contact_id' => $contactID,
2020 'financial_type_id' => !empty($form->_values['event']['financial_type_id']) ? $form->_values['event']['financial_type_id'] : $params['financial_type_id'],
2021 'receive_date' => $now,
2022 'total_amount' => $params['amount'],
2023 'tax_amount' => $params['tax_amount'],
2024 'amount_level' => $params['amount_level'],
2025 'invoice_id' => $params['invoiceID'],
2026 'currency' => $params['currencyID'],
2027 'source' => !empty($params['participant_source']) ? $params['participant_source'] : $params['description'],
2028 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
2029 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
2030 'card_type_id' => CRM_Utils_Array::value('card_type_id', $params),
2031 'pan_truncation' => CRM_Utils_Array::value('pan_truncation', $params),
2032 ];
2033
2034 if ($paymentProcessor) {
2035 $contribParams['payment_instrument_id'] = $paymentProcessor['payment_instrument_id'];
2036 $contribParams['payment_processor'] = $paymentProcessor['id'];
2037 }
2038
2039 if (!$pending && $result) {
2040 $contribParams += [
2041 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
2042 'trxn_id' => $result['trxn_id'],
2043 'receipt_date' => $receiptDate,
2044 ];
2045 }
2046
2047 $allStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2048 $contribParams['contribution_status_id'] = array_search('Completed', $allStatuses);
2049 if ($pending) {
2050 $contribParams['contribution_status_id'] = array_search('Pending', $allStatuses);
2051 }
2052
2053 $contribParams['is_test'] = 0;
2054 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
2055 $contribParams['is_test'] = 1;
2056 }
2057
2058 if (!empty($contribParams['invoice_id'])) {
2059 $contribParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2060 $contribParams['invoice_id'],
2061 'id',
2062 'invoice_id'
2063 );
2064 }
2065 $contribParams['revenue_recognition_date'] = $this->getRevenueRecognitionDate();
2066
2067 //create an contribution address
2068 // The concept of contributeMode is deprecated. Elsewhere we use the function processBillingAddress() - although
2069 // currently that is only inherited by back-office forms.
2070 if ($form->_contributeMode != 'notify' && empty($params['is_pay_later'])) {
2071 $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
2072 }
2073
2074 $contribParams['skipLineItem'] = 1;
2075 $contribParams['skipCleanMoney'] = 1;
2076 // create contribution record
2077 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
2078 // CRM-11124
2079 CRM_Event_BAO_Participant::createDiscountTrxn($form->_eventId, $contribParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($params));
2080
2081 // process soft credit / pcp pages
2082 if (!empty($params['pcp_made_through_id'])) {
2083 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
2084 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
2085 }
2086
2087 $transaction->commit();
2088
2089 return $contribution;
2090 }
2091
2092 /**
2093 * Process the participant.
2094 *
2095 * @param CRM_Core_Form $form
2096 * @param array $params
2097 * @param int $contactID
2098 *
2099 * @return \CRM_Event_BAO_Participant
2100 * @throws \CRM_Core_Exception
2101 */
2102 protected function addParticipant(&$form, $params, $contactID) {
2103 $transaction = new CRM_Core_Transaction();
2104
2105 // handle register date CRM-4320
2106 $registerDate = NULL;
2107 if (!empty($form->_allowConfirmation) && $form->_participantId) {
2108 $registerDate = $params['participant_register_date'];
2109 }
2110 elseif (!empty($params['participant_register_date']) &&
2111 is_array($params['participant_register_date']) &&
2112 !empty($params['participant_register_date'])
2113 ) {
2114 $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
2115 }
2116
2117 $participantFields = CRM_Event_DAO_Participant::fields();
2118 $participantParams = [
2119 'id' => CRM_Utils_Array::value('participant_id', $params),
2120 'contact_id' => $contactID,
2121 'event_id' => $form->_eventId ? $form->_eventId : $params['event_id'],
2122 'status_id' => CRM_Utils_Array::value('participant_status',
2123 $params, 1
2124 ),
2125 'role_id' => CRM_Utils_Array::value('participant_role_id', $params) ?: self::getDefaultRoleID(),
2126 'register_date' => ($registerDate) ? $registerDate : date('YmdHis'),
2127 'source' => CRM_Utils_String::ellipsify(
2128 isset($params['participant_source']) ? CRM_Utils_Array::value('participant_source', $params) : CRM_Utils_Array::value('description', $params),
2129 $participantFields['participant_source']['maxlength']
2130 ),
2131 'fee_level' => CRM_Utils_Array::value('amount_level', $params),
2132 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
2133 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
2134 'registered_by_id' => CRM_Utils_Array::value('registered_by_id', $params),
2135 'discount_id' => CRM_Utils_Array::value('discount_id', $params),
2136 'fee_currency' => CRM_Utils_Array::value('currencyID', $params),
2137 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
2138 ];
2139
2140 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
2141 $participantParams['is_test'] = 1;
2142 }
2143 else {
2144 $participantParams['is_test'] = 0;
2145 }
2146
2147 if (!empty($form->_params['note'])) {
2148 $participantParams['note'] = $form->_params['note'];
2149 }
2150 elseif (!empty($form->_params['participant_note'])) {
2151 $participantParams['note'] = $form->_params['participant_note'];
2152 }
2153
2154 // reuse id if one already exists for this one (can happen
2155 // with back button being hit etc)
2156 if (!$participantParams['id'] && !empty($params['contributionID'])) {
2157 $pID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
2158 $params['contributionID'],
2159 'participant_id',
2160 'contribution_id'
2161 );
2162 $participantParams['id'] = $pID;
2163 }
2164 $participantParams['discount_id'] = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
2165
2166 if (!$participantParams['discount_id']) {
2167 $participantParams['discount_id'] = "null";
2168 }
2169
2170 $participant = CRM_Event_BAO_Participant::create($participantParams);
2171
2172 $transaction->commit();
2173
2174 return $participant;
2175 }
2176
2177 /**
2178 * Is a payment being made on an existing contribution.
2179 *
2180 * Note
2181 * 1) ideally we should not permit this on this form! Perhaps we don't & this is just cruft.
2182 * 2) _paymentID is the contribution id.
2183 *
2184 * @return bool
2185 */
2186 protected function isPaymentOnExistingContribution(): bool {
2187 return ($this->getParticipantID() && $this->_action & CRM_Core_Action::UPDATE) && $this->_paymentId;
2188 }
2189
2190 /**
2191 * Get the value for a field relating to the event.
2192 *
2193 * @param string $fieldName
2194 *
2195 * @return mixed
2196 * @throws \CiviCRM_API3_Exception
2197 */
2198 protected function getEventValue(string $fieldName) {
2199 if (!isset($this->_event)) {
2200 $this->_event = civicrm_api3('Event', 'getsingle', ['id' => $this->_eventId]);
2201 }
2202 return $this->_event[$fieldName];
2203 }
2204
2205 /**
2206 * Get a value from the existing participant record (applies to edits).
2207 *
2208 * @param string $fieldName
2209 *
2210 * @return array
2211 * @throws \CiviCRM_API3_Exception
2212 */
2213 protected function getParticipantValue($fieldName) {
2214 if (!$this->participantRecord) {
2215 $this->participantRecord = civicrm_api3('Participant', 'get', ['id' => $this->_id]);
2216 }
2217 return $this->participantRecord[$fieldName];
2218 }
2219
2220 /**
2221 * Get id of participant being edited.
2222 *
2223 * @return int|null
2224 */
2225 protected function getParticipantID() {
2226 return $this->_id ?? $this->_pId;
2227 }
2228
2229 /**
2230 * Get the value for the revenue recognition date field.
2231 *
2232 * @return string
2233 *
2234 * @throws \CiviCRM_API3_Exception
2235 */
2236 protected function getRevenueRecognitionDate() {
2237 if (Civi::settings()->get('deferred_revenue_enabled')) {
2238 $eventStartDate = $this->getEventValue('start_date');
2239 if (strtotime($eventStartDate) > strtotime(date('Ymt'))) {
2240 return date('Ymd', strtotime($eventStartDate));
2241 }
2242 }
2243 return '';
2244 }
2245
2246 }