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