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