Merge pull request #14934 from civicrm/5.16
[civicrm-core.git] / CRM / Event / Form / Participant.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
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
485 //setting default register date
486 if ($this->_action == CRM_Core_Action::ADD) {
487 $statuses = array_flip(CRM_Event_PseudoConstant::participantStatus());
488 $defaults[$this->_id]['status_id'] = CRM_Utils_Array::value('Registered', $statuses);
489 if (!empty($defaults[$this->_id]['event_id'])) {
490 $contributionTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
491 $defaults[$this->_id]['event_id'],
492 'financial_type_id'
493 );
494 if ($contributionTypeId) {
495 $defaults[$this->_id]['financial_type_id'] = $contributionTypeId;
496 }
497 }
498
499 if ($this->_mode) {
500 $fields["email-{$this->_bltID}"] = 1;
501 $fields['email-Primary'] = 1;
502
503 if ($this->_contactId) {
504 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactId, $fields, $defaults);
505 }
506
507 if (empty($defaults["email-{$this->_bltID}"]) &&
508 !empty($defaults['email-Primary'])
509 ) {
510 $defaults[$this->_id]["email-{$this->_bltID}"] = $defaults['email-Primary'];
511 }
512 }
513
514 $submittedRole = $this->getElementValue('role_id');
515 if (!empty($submittedRole[0])) {
516 $roleID = $submittedRole[0];
517 }
518 $submittedEvent = $this->getElementValue('event_id');
519 if (!empty($submittedEvent[0])) {
520 $eventID = $submittedEvent[0];
521 }
522 $defaults[$this->_id]['register_date'] = date('Y-m-d H:i:s');
523 }
524 else {
525 $defaults[$this->_id]['record_contribution'] = 0;
526
527 if ($defaults[$this->_id]['participant_is_pay_later']) {
528 $this->assign('participant_is_pay_later', TRUE);
529 }
530
531 $this->assign('participant_status_id', $defaults[$this->_id]['participant_status_id']);
532 $eventID = $defaults[$this->_id]['event_id'];
533
534 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
535
536 $this->_discountId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'discount_id');
537 if ($this->_discountId) {
538 $this->set('discountId', $this->_discountId);
539 }
540 }
541
542 //assign event and role id, this is needed for Custom data building
543 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
544 if (!empty($defaults[$this->_id]['participant_role_id'])) {
545 $roleIDs = explode($sep, $defaults[$this->_id]['participant_role_id']);
546 }
547 if (isset($_POST['event_id'])) {
548 $eventID = $_POST['event_id'];
549 }
550
551 if ($this->_eID) {
552 $eventID = $this->_eID;
553 //@todo - rationalise the $this->_eID with $POST['event_id'], $this->_eid is set when eid=x is in the url
554 $roleID = CRM_Core_DAO::getFieldValue(
555 'CRM_Event_DAO_Event',
556 $this->_eID,
557 'default_role_id'
558 );
559 if (empty($roleIDs)) {
560 $roleIDs = (array) $defaults[$this->_id]['participant_role_id'] = $roleID;
561 }
562 $defaults[$this->_id]['event_id'] = $eventID;
563 }
564 if (!empty($eventID)) {
565 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
566 }
567 //these should take precedence so we state them last
568 $urlRoleIDS = CRM_Utils_Request::retrieve('roles', 'String');
569 if ($urlRoleIDS) {
570 $roleIDs = explode(',', $urlRoleIDS);
571 }
572 if (isset($roleIDs)) {
573 $defaults[$this->_id]['role_id'] = implode(',', $roleIDs);
574 }
575
576 if (isset($eventID)) {
577 $this->assign('eventID', $eventID);
578 $this->set('eventId', $eventID);
579 }
580
581 if (isset($this->_eventTypeId)) {
582 $this->assign('eventTypeID', $this->_eventTypeId);
583 }
584
585 $this->assign('event_is_test', CRM_Utils_Array::value('event_is_test', $defaults[$this->_id]));
586 return $defaults[$this->_id];
587 }
588
589 /**
590 * Build the form object.
591 *
592 * @return void
593 * @throws \CRM_Core_Exception
594 * @throws \CiviCRM_API3_Exception
595 */
596 public function buildQuickForm() {
597
598 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
599 $partiallyPaidStatusId = array_search('Partially paid', $participantStatuses);
600 $this->assign('partiallyPaidStatusId', $partiallyPaidStatusId);
601
602 if ($this->_showFeeBlock) {
603 return CRM_Event_Form_EventFees::buildQuickForm($this);
604 }
605
606 //need to assign custom data type to the template
607 $this->assign('customDataType', 'Participant');
608
609 $this->applyFilter('__ALL__', 'trim');
610
611 if ($this->_action & CRM_Core_Action::DELETE) {
612 if ($this->_single) {
613 $additionalParticipant = count(CRM_Event_BAO_Event::buildCustomProfile($this->_id,
614 NULL,
615 $this->_contactId,
616 FALSE,
617 TRUE
618 )) - 1;
619 if ($additionalParticipant) {
620 $deleteParticipants = [
621 1 => ts('Delete this participant record along with associated participant record(s).'),
622 2 => ts('Delete only this participant record.'),
623 ];
624 $this->addRadio('delete_participant', NULL, $deleteParticipants, NULL, '<br />');
625 $this->setDefaults(['delete_participant' => 1]);
626 $this->assign('additionalParticipant', $additionalParticipant);
627 }
628 }
629 $this->addButtons([
630 [
631 'type' => 'next',
632 'name' => ts('Delete'),
633 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
634 'isDefault' => TRUE,
635 ],
636 [
637 'type' => 'cancel',
638 'name' => ts('Cancel'),
639 ],
640 ]);
641 return;
642 }
643
644 if ($this->_single && $this->_context == 'standalone') {
645 $this->addEntityRef('contact_id', ts('Contact'), [
646 'create' => TRUE,
647 'api' => ['extra' => ['email']],
648 ], TRUE);
649 }
650
651 $eventFieldParams = [
652 'entity' => 'Event',
653 'select' => ['minimumInputLength' => 0],
654 'api' => [
655 'extra' => ['campaign_id', 'default_role_id', 'event_type_id'],
656 ],
657 ];
658
659 if ($this->_mode) {
660 // exclude events which are not monetary when credit card registration is used
661 $eventFieldParams['api']['params']['is_monetary'] = 1;
662 }
663 $this->addPaymentProcessorSelect(TRUE, FALSE, FALSE);
664
665 $element = $this->addEntityRef('event_id', ts('Event'), $eventFieldParams, TRUE);
666
667 //frozen the field fix for CRM-4171
668 if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
669 if (CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
670 $this->_id, 'contribution_id', 'participant_id'
671 )
672 ) {
673 $element->freeze();
674 }
675 }
676
677 //CRM-7362 --add campaigns.
678 $campaignId = NULL;
679 if ($this->_id) {
680 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'campaign_id');
681 }
682 if (!$campaignId) {
683 $eventId = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
684 if ($eventId) {
685 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'campaign_id');
686 }
687 }
688 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
689 $this->add('datepicker', 'register_date', ts('Registration Date'), [], TRUE, ['time' => TRUE]);
690
691 if ($this->_id) {
692 $this->assign('entityID', $this->_id);
693 }
694
695 $this->addSelect('role_id', ['multiple' => TRUE, 'class' => 'huge'], TRUE);
696
697 // CRM-4395
698 $checkCancelledJs = ['onchange' => "return sendNotification( );"];
699 $confirmJS = NULL;
700 if ($this->_onlinePendingContributionId) {
701 $cancelledparticipantStatusId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus());
702 $cancelledContributionStatusId = array_search('Cancelled',
703 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
704 );
705 $checkCancelledJs = [
706 'onchange' => "checkCancelled( this.value, {$cancelledparticipantStatusId},{$cancelledContributionStatusId});",
707 ];
708
709 $participantStatusId = array_search('Pending from pay later',
710 CRM_Event_PseudoConstant::participantStatus()
711 );
712 $contributionStatusId = array_search('Completed',
713 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
714 );
715 $confirmJS = ['onclick' => "return confirmStatus( {$participantStatusId}, {$contributionStatusId} );"];
716 }
717
718 // get the participant status names to build special status array which is used to show notification
719 // checkbox below participant status select
720 $participantStatusName = CRM_Event_PseudoConstant::participantStatus();
721 $notificationStatuses = [
722 'Cancelled',
723 'Pending from waitlist',
724 'Pending from approval',
725 'Expired',
726 ];
727
728 // get the required status and then implode only ids
729 $notificationStatusIds = implode(',', array_keys(array_intersect($participantStatusName, $notificationStatuses)));
730 $this->assign('notificationStatusIds', $notificationStatusIds);
731
732 $this->_participantStatuses = $statusOptions = CRM_Event_BAO_Participant::buildOptions('status_id', 'create');
733
734 // Only show refund status when editing
735 if ($this->_action & CRM_Core_Action::ADD) {
736 $pendingRefundStatusId = array_search('Pending refund', $participantStatusName);
737 if ($pendingRefundStatusId) {
738 unset($statusOptions[$pendingRefundStatusId]);
739 }
740 }
741
742 $this->addSelect('status_id', $checkCancelledJs + [
743 'options' => $statusOptions,
744 'option_url' => 'civicrm/admin/participant_status',
745 ], TRUE);
746
747 $this->addElement('checkbox', 'is_notify', ts('Send Notification'), NULL);
748
749 $this->addField('source', ['entity' => 'Participant', 'name' => 'source']);
750 $noteAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
751 $this->add('textarea', 'note', ts('Notes'), $noteAttributes['note']);
752
753 $buttons[] = [
754 'type' => 'upload',
755 'name' => ts('Save'),
756 'isDefault' => TRUE,
757 'js' => $confirmJS,
758 ];
759
760 $path = CRM_Utils_System::currentPath();
761 $excludeForPaths = [
762 'civicrm/contact/search',
763 'civicrm/group/search',
764 ];
765 if (!in_array($path, $excludeForPaths)) {
766 $buttons[] = [
767 'type' => 'upload',
768 'name' => ts('Save and New'),
769 'subName' => 'new',
770 'js' => $confirmJS,
771 ];
772 }
773
774 $buttons[] = [
775 'type' => 'cancel',
776 'name' => ts('Cancel'),
777 ];
778
779 $this->addButtons($buttons);
780 if ($this->_action == CRM_Core_Action::VIEW) {
781 $this->freeze();
782 }
783 }
784
785 /**
786 * Add local and global form rules.
787 *
788 * @return void
789 */
790 public function addRules() {
791 $this->addFormRule(['CRM_Event_Form_Participant', 'formRule'], $this);
792 }
793
794 /**
795 * Global validation rules for the form.
796 *
797 * @param array $values
798 * Posted values of the form.
799 * @param $files
800 * @param $self
801 *
802 * @return array
803 * list of errors to be posted back to the form
804 */
805 public static function formRule($values, $files, $self) {
806 // If $values['_qf_Participant_next'] is Delete or
807 // $values['event_id'] is empty, then return
808 // instead of proceeding further.
809
810 if ((CRM_Utils_Array::value('_qf_Participant_next', $values) == 'Delete') ||
811 (!$values['event_id'])
812 ) {
813 return TRUE;
814 }
815
816 $errorMsg = [];
817
818 if (!empty($values['payment_processor_id'])) {
819 // make sure that payment instrument values (e.g. credit card number and cvv) are valid
820 CRM_Core_Payment_Form::validatePaymentInstrument($values['payment_processor_id'], $values, $errorMsg, NULL);
821 }
822
823 if (!empty($values['record_contribution'])) {
824 if (empty($values['financial_type_id'])) {
825 $errorMsg['financial_type_id'] = ts('Please enter the associated Financial Type');
826 }
827 if (empty($values['payment_instrument_id'])) {
828 $errorMsg['payment_instrument_id'] = ts('Payment Method is a required field.');
829 }
830 if (!empty($values['priceSetId'])) {
831 CRM_Price_BAO_PriceField::priceSetValidation($values['priceSetId'], $values, $errorMsg);
832 }
833 }
834
835 // validate contribution status for 'Failed'.
836 if ($self->_onlinePendingContributionId && !empty($values['record_contribution']) &&
837 (CRM_Utils_Array::value('contribution_status_id', $values) ==
838 array_search('Failed', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))
839 )
840 ) {
841 $errorMsg['contribution_status_id'] = ts('Please select a valid payment status before updating.');
842 }
843
844 // do the amount validations.
845 //skip for update mode since amount is freeze, CRM-6052
846 if ((!$self->_id && empty($values['total_amount']) &&
847 empty($self->_values['line_items'])
848 ) ||
849 ($self->_id && !$self->_paymentId && isset($self->_values['line_items']) && is_array($self->_values['line_items']))
850 ) {
851 if ($priceSetId = CRM_Utils_Array::value('priceSetId', $values)) {
852 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $values, $errorMsg, TRUE);
853 }
854 }
855 // For single additions - show validation error if the contact has already been registered
856 // for this event.
857 if ($self->_single && ($self->_action & CRM_Core_Action::ADD)) {
858 if ($self->_context == 'standalone') {
859 $contactId = CRM_Utils_Array::value('contact_id', $values);
860 }
861 else {
862 $contactId = $self->_contactId;
863 }
864
865 $eventId = CRM_Utils_Array::value('event_id', $values);
866
867 $event = new CRM_Event_DAO_Event();
868 $event->id = $eventId;
869 $event->find(TRUE);
870
871 if (!$event->allow_same_participant_emails && !empty($contactId) && !empty($eventId)) {
872 $cancelledStatusID = CRM_Core_PseudoConstant::getKey('CRM_Event_BAO_Participant', 'status_id', 'Cancelled');
873 $dupeCheck = new CRM_Event_BAO_Participant();
874 $dupeCheck->contact_id = $contactId;
875 $dupeCheck->event_id = $eventId;
876 $dupeCheck->whereAdd("status_id != {$cancelledStatusID} ");
877 $dupeCheck->find(TRUE);
878 if (!empty($dupeCheck->id)) {
879 $errorMsg['event_id'] = ts("This contact has already been assigned to this event.");
880 }
881 }
882 }
883 return CRM_Utils_Array::crmIsEmptyArray($errorMsg) ? TRUE : $errorMsg;
884 }
885
886 /**
887 * Process the form submission.
888 */
889 public function postProcess() {
890 // get the submitted form values.
891 $params = $this->controller->exportValues($this->_name);
892
893 if ($this->_action & CRM_Core_Action::DELETE) {
894 if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
895 $additionalId = (CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id));
896 $participantLinks = (CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId));
897 }
898 if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
899 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
900 foreach ($additionalIds as $value) {
901 CRM_Event_BAO_Participant::deleteParticipant($value);
902 }
903 }
904 CRM_Event_BAO_Participant::deleteParticipant($this->_id);
905 CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
906 if (!empty($participantLinks)) {
907 $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;
908 CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
909 }
910 return;
911 }
912 // When adding a single contact, the formRule prevents you from adding duplicates
913 // (See above in formRule()). When adding more than one contact, the duplicates are
914 // removed automatically and the user receives one notification.
915 if ($this->_action & CRM_Core_Action::ADD) {
916 $event_id = $this->_eventId;
917 if (empty($event_id) && !empty($params['event_id'])) {
918 $event_id = $params['event_id'];
919 }
920 if (!$this->_single && !empty($event_id)) {
921 $duplicateContacts = 0;
922 foreach ($this->_contactIds as $k => $dupeCheckContactId) {
923 // Eliminate contacts that have already been assigned to this event.
924 $dupeCheck = new CRM_Event_BAO_Participant();
925 $dupeCheck->contact_id = $dupeCheckContactId;
926 $dupeCheck->event_id = $event_id;
927 $dupeCheck->find(TRUE);
928 if (!empty($dupeCheck->id)) {
929 $duplicateContacts++;
930 unset($this->_contactIds[$k]);
931 }
932 }
933 if ($duplicateContacts > 0) {
934 $msg = ts(
935 "%1 contacts have already been assigned to this event. They were not added a second time.",
936 [1 => $duplicateContacts]
937 );
938 CRM_Core_Session::setStatus($msg);
939 }
940 if (count($this->_contactIds) == 0) {
941 CRM_Core_Session::setStatus(ts("No participants were added."));
942 return;
943 }
944 // We have to re-key $this->_contactIds so each contact has the same
945 // key as their corresponding record in the $participants array that
946 // will be created below.
947 $this->_contactIds = array_values($this->_contactIds);
948 }
949 }
950
951 $statusMsg = $this->submit($params);
952 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
953 $session = CRM_Core_Session::singleton();
954 $buttonName = $this->controller->getButtonName();
955 if ($this->_context == 'standalone') {
956 if ($buttonName == $this->getButtonName('upload', 'new')) {
957 $urlParams = 'reset=1&action=add&context=standalone';
958 if ($this->_mode) {
959 $urlParams .= '&mode=' . $this->_mode;
960 }
961 if ($this->_eID) {
962 $urlParams .= '&eid=' . $this->_eID;
963 }
964 $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
965 }
966 else {
967 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
968 "reset=1&cid={$this->_contactId}&selectedChild=participant"
969 ));
970 }
971 }
972 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
973 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant',
974 "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"
975 ));
976 }
977 }
978
979 /**
980 * Submit form.
981 *
982 * @param array $params
983 *
984 * @return string
985 * @throws \CRM_Core_Exception
986 * @throws \CiviCRM_API3_Exception
987 */
988 public function submit($params) {
989 $participantStatus = CRM_Event_PseudoConstant::participantStatus();
990 // set the contact, when contact is selected
991 if (!empty($params['contact_id'])) {
992 $this->_contactID = $this->_contactId = $params['contact_id'];
993 }
994 if ($this->_priceSetId && $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
995 $this->_quickConfig = $isQuickConfig;
996 }
997
998 if ($this->_id) {
999 $params['id'] = $this->_id;
1000 }
1001
1002 $config = CRM_Core_Config::singleton();
1003 if (isset($params['total_amount'])) {
1004 $params['total_amount'] = CRM_Utils_Rule::cleanMoney($params['total_amount']);
1005 }
1006 if ($this->_isPaidEvent) {
1007
1008 $contributionParams = ['skipCleanMoney' => TRUE];
1009 $lineItem = [];
1010 $additionalParticipantDetails = [];
1011 if (Civi::settings()->get('deferred_revenue_enabled')) {
1012 $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
1013 if (strtotime($eventStartDate) > strtotime(date('Ymt'))) {
1014 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
1015 }
1016 }
1017 if (($this->_id && $this->_action & CRM_Core_Action::UPDATE) && $this->_paymentId) {
1018 $participantBAO = new CRM_Event_BAO_Participant();
1019 $participantBAO->id = $this->_id;
1020 $participantBAO->find(TRUE);
1021 $contributionParams['total_amount'] = $participantBAO->fee_amount;
1022
1023 $params['discount_id'] = NULL;
1024 //re-enter the values for UPDATE mode
1025 $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
1026 $params['fee_amount'] = $participantBAO->fee_amount;
1027 if (isset($params['priceSetId'])) {
1028 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
1029 }
1030 //also add additional participant's fee level/priceset
1031 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
1032 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
1033 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
1034 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds,
1035 $hasLineItems
1036 );
1037 }
1038 }
1039 else {
1040
1041 // check that discount_id is set
1042 if (empty($params['discount_id'])) {
1043 $params['discount_id'] = 'null';
1044 }
1045
1046 //lets carry currency, CRM-4453
1047 $params['fee_currency'] = $config->defaultCurrency;
1048 if (!isset($lineItem[0])) {
1049 $lineItem[0] = [];
1050 }
1051 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'],
1052 $params, $lineItem[0]
1053 );
1054 //CRM-11529 for quick config backoffice transactions
1055 //when financial_type_id is passed in form, update the
1056 //lineitems with the financial type selected in form
1057 $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
1058 $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
1059 if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
1060 foreach ($lineItem[0] as &$values) {
1061 $values['financial_type_id'] = $submittedFinancialType;
1062 }
1063 }
1064
1065 $params['fee_level'] = $params['amount_level'];
1066 $contributionParams['total_amount'] = $params['amount'];
1067 if ($this->_quickConfig && !empty($params['total_amount']) &&
1068 $params['status_id'] != array_search('Partially paid', $participantStatus)
1069 ) {
1070 $params['fee_amount'] = $params['total_amount'];
1071 }
1072 else {
1073 //fix for CRM-3086
1074 $params['fee_amount'] = $params['amount'];
1075 }
1076 }
1077
1078 if (isset($params['priceSetId'])) {
1079 if (!empty($lineItem[0])) {
1080 $this->set('lineItem', $lineItem);
1081
1082 $this->_lineItem = $lineItem;
1083 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
1084
1085 $participantCount = [];
1086 foreach ($lineItem as $k) {
1087 foreach ($k as $v) {
1088 if (CRM_Utils_Array::value('participant_count', $v) > 0) {
1089 $participantCount[] = $v['participant_count'];
1090 }
1091 }
1092 }
1093 }
1094 if (isset($participantCount)) {
1095 $this->assign('pricesetFieldsCount', $participantCount);
1096 }
1097 $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
1098 }
1099 else {
1100 $this->assign('amount_level', $params['amount_level']);
1101 }
1102 }
1103
1104 $this->_params = $params;
1105 parent::beginPostProcess();
1106 $amountOwed = NULL;
1107 if (isset($params['amount'])) {
1108 $amountOwed = $params['amount'];
1109 unset($params['amount']);
1110 }
1111 $params['contact_id'] = $this->_contactId;
1112
1113 // overwrite actual payment amount if entered
1114 if (!empty($params['total_amount'])) {
1115 $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
1116 }
1117
1118 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1119 $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
1120
1121 if ($this->_contactId) {
1122 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
1123 }
1124
1125 //modify params according to parameter used in create
1126 //participant method (addParticipant)
1127 $this->_params['participant_status_id'] = $params['status_id'];
1128 $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
1129 $this->_params['participant_register_date'] = $params['register_date'];
1130 $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
1131
1132 $now = date('YmdHis');
1133
1134 if ($this->_mode) {
1135 if (!$this->_isPaidEvent) {
1136 CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
1137 }
1138
1139 $eventTitle
1140 = CRM_Core_DAO::getFieldValue(
1141 'CRM_Event_DAO_Event',
1142 $params['event_id'],
1143 'title'
1144 );
1145
1146 // set source if not set
1147 if (empty($params['source'])) {
1148 $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', [
1149 1 => $userName,
1150 2 => $eventTitle,
1151 ]);
1152 }
1153 else {
1154 $this->_params['participant_source'] = $params['source'];
1155 }
1156 $this->_params['description'] = $this->_params['participant_source'];
1157
1158 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1159 $this->_mode
1160 );
1161 $fields = [];
1162
1163 // set email for primary location.
1164 $fields['email-Primary'] = 1;
1165 $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
1166
1167 $params['register_date'] = $now;
1168
1169 // now set the values for the billing location.
1170 foreach ($this->_fields as $name => $dontCare) {
1171 $fields[$name] = 1;
1172 }
1173
1174 // also add location name to the array
1175 $params["address_name-{$this->_bltID}"]
1176 = CRM_Utils_Array::value('billing_first_name', $params) . ' ' .
1177 CRM_Utils_Array::value('billing_middle_name', $params) . ' ' .
1178 CRM_Utils_Array::value('billing_last_name', $params);
1179
1180 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1181 $fields["address_name-{$this->_bltID}"] = 1;
1182 $fields["email-{$this->_bltID}"] = 1;
1183 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
1184
1185 $nameFields = ['first_name', 'middle_name', 'last_name'];
1186
1187 foreach ($nameFields as $name) {
1188 $fields[$name] = 1;
1189 if (array_key_exists("billing_$name", $params)) {
1190 $params[$name] = $params["billing_{$name}"];
1191 $params['preserveDBName'] = TRUE;
1192 }
1193 }
1194 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
1195 }
1196
1197 if (!empty($this->_params['participant_role_id'])) {
1198 $customFieldsRole = [];
1199 foreach ($this->_params['participant_role_id'] as $roleKey) {
1200 $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant',
1201 FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
1202 }
1203 $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant',
1204 FALSE,
1205 FALSE,
1206 CRM_Utils_Array::value('event_id', $params),
1207 $this->_eventNameCustomDataTypeID
1208 );
1209 $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant',
1210 FALSE,
1211 FALSE,
1212 $this->_eventTypeId,
1213 $this->_eventTypeCustomDataTypeID
1214 );
1215 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
1216 CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
1217 );
1218 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
1219 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
1220
1221 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, $this->getDefaultEntity());
1222 }
1223
1224 //do cleanup line items if participant edit the Event Fee.
1225 if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
1226 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
1227 }
1228
1229 if ($this->_mode) {
1230 // add all the additional payment params we need
1231 $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
1232 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1233
1234 $this->_params['amount'] = $params['fee_amount'];
1235 $this->_params['amount_level'] = $params['amount_level'];
1236 $this->_params['currencyID'] = $config->defaultCurrency;
1237 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1238
1239 // at this point we've created a contact and stored its address etc
1240 // all the payment processors expect the name and address to be in the
1241 // so we copy stuff over to first_name etc.
1242 $paymentParams = $this->_params;
1243 if (!empty($this->_params['send_receipt'])) {
1244 $paymentParams['email'] = $this->_contributorEmail;
1245 }
1246
1247 // The only reason for merging in the 'contact_id' rather than ensuring it is set
1248 // is that this patch is being done around the time of the stable release
1249 // so more conservative approach is called for.
1250 // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
1251 // needs rationalising.
1252 $mapParams = array_merge(['contact_id' => $contactID], $this->_params);
1253 CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
1254
1255 $payment = $this->_paymentProcessor['object'];
1256
1257 // CRM-15622: fix for incorrect contribution.fee_amount
1258 $paymentParams['fee_amount'] = NULL;
1259 $result = $payment->doPayment($paymentParams);
1260
1261 if (is_a($result, 'CRM_Core_Error')) {
1262 CRM_Core_Error::displaySessionError($result);
1263 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant',
1264 "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"
1265 ));
1266 }
1267
1268 if ($result) {
1269 $this->_params = array_merge($this->_params, $result);
1270 }
1271
1272 $this->_params['receive_date'] = $now;
1273
1274 if (!empty($this->_params['send_receipt'])) {
1275 $this->_params['receipt_date'] = $now;
1276 }
1277 else {
1278 $this->_params['receipt_date'] = NULL;
1279 }
1280
1281 $this->set('params', $this->_params);
1282 $this->assign('trxn_id', $result['trxn_id']);
1283 $this->assign('receive_date', $this->_params['receive_date']);
1284
1285 //add contribution record
1286 $this->_params['financial_type_id']
1287 = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
1288 $this->_params['mode'] = $this->_mode;
1289
1290 //add contribution record
1291 $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution(
1292 $this, $this->_params,
1293 $result, $contactID,
1294 FALSE, FALSE,
1295 $this->_paymentProcessor
1296 );
1297
1298 // add participant record
1299 $participants = [];
1300 if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
1301 $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
1302 $this->_params['role_id']
1303 );
1304 }
1305
1306 //CRM-15372 patch to fix fee amount replacing amount
1307 $this->_params['fee_amount'] = $this->_params['amount'];
1308
1309 $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
1310
1311 //add custom data for participant
1312 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
1313 'civicrm_participant',
1314 $participants[0]->id,
1315 'Participant'
1316 );
1317 //add participant payment
1318 $paymentParticipant = [
1319 'participant_id' => $participants[0]->id,
1320 'contribution_id' => $contribution->id,
1321 ];
1322
1323 CRM_Event_BAO_ParticipantPayment::create($paymentParticipant);
1324 $this->_contactIds[] = $this->_contactId;
1325 }
1326 else {
1327 $participants = [];
1328 if ($this->_single) {
1329 if ($params['role_id']) {
1330 $params['role_id'] = $roleIdWithSeparator;
1331 }
1332 else {
1333 $params['role_id'] = 'NULL';
1334 }
1335 $participants[] = CRM_Event_BAO_Participant::create($params);
1336 }
1337 else {
1338 foreach ($this->_contactIds as $contactID) {
1339 $commonParams = $params;
1340 $commonParams['contact_id'] = $contactID;
1341 if ($commonParams['role_id']) {
1342 $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
1343 }
1344 else {
1345 $commonParams['role_id'] = 'NULL';
1346 }
1347 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
1348 }
1349 }
1350
1351 if (isset($params['event_id'])) {
1352 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
1353 $params['event_id'],
1354 'title'
1355 );
1356 }
1357
1358 if ($this->_single) {
1359 $this->_contactIds[] = $this->_contactId;
1360 }
1361
1362 $contributions = [];
1363 if (!empty($params['record_contribution'])) {
1364 if (!empty($params['id'])) {
1365 if ($this->_onlinePendingContributionId) {
1366 $ids['contribution'] = $this->_onlinePendingContributionId;
1367 }
1368 else {
1369 $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1370 $params['id'],
1371 'contribution_id',
1372 'participant_id'
1373 );
1374 }
1375 }
1376 unset($params['note']);
1377
1378 //build contribution params
1379 if (!$this->_onlinePendingContributionId) {
1380 if (empty($params['source'])) {
1381 $contributionParams['source'] = ts('%1 : Offline registration (by %2)', [
1382 1 => $eventTitle,
1383 2 => $userName,
1384 ]);
1385 }
1386 else {
1387 $contributionParams['source'] = $params['source'];
1388 }
1389 }
1390
1391 $contributionParams['currency'] = $config->defaultCurrency;
1392 $contributionParams['non_deductible_amount'] = 'null';
1393 $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
1394 $contributionParams['contact_id'] = $this->_contactID;
1395 $contributionParams['receive_date'] = CRM_Utils_Array::value('receive_date', $params, 'null');
1396
1397 $recordContribution = [
1398 'financial_type_id',
1399 'payment_instrument_id',
1400 'trxn_id',
1401 'contribution_status_id',
1402 'check_number',
1403 'campaign_id',
1404 'pan_truncation',
1405 'card_type_id',
1406 ];
1407
1408 foreach ($recordContribution as $f) {
1409 $contributionParams[$f] = CRM_Utils_Array::value($f, $this->_params);
1410 if ($f == 'trxn_id') {
1411 $this->assign('trxn_id', $contributionParams[$f]);
1412 }
1413 }
1414
1415 //insert financial type name in receipt.
1416 $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1417 $contributionParams['financial_type_id']));
1418 // legacy support
1419 $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
1420 $contributionParams['skipLineItem'] = 1;
1421 if ($this->_id) {
1422 $contributionParams['contribution_mode'] = 'participant';
1423 $contributionParams['participant_id'] = $this->_id;
1424 }
1425 // Set is_pay_later flag for back-office offline Pending status contributions
1426 if ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Pending')) {
1427 $contributionParams['is_pay_later'] = 1;
1428 }
1429 elseif ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Completed')) {
1430 $contributionParams['is_pay_later'] = 0;
1431 }
1432
1433 if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
1434 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
1435 $amountOwed = $params['fee_amount'];
1436 }
1437
1438 // if multiple participants are link, consider contribution total amount as the amount Owed
1439 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
1440 $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1441 $ids['contribution'],
1442 'total_amount'
1443 );
1444 }
1445
1446 // CRM-13964 partial_payment_total
1447 if ($amountOwed > $params['total_amount']) {
1448 // the owed amount
1449 $contributionParams['partial_payment_total'] = $amountOwed;
1450 // the actual amount paid
1451 $contributionParams['partial_amount_to_pay'] = $params['total_amount'];
1452 }
1453 }
1454
1455 if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
1456 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
1457 }
1458
1459 if ($this->_single) {
1460 if (empty($ids)) {
1461 $ids = [];
1462 }
1463 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1464 }
1465 else {
1466 $ids = [];
1467 foreach ($this->_contactIds as $contactID) {
1468 $contributionParams['contact_id'] = $contactID;
1469 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1470 }
1471 }
1472
1473 //insert payment record for this participation
1474 if (empty($ids['contribution'])) {
1475 foreach ($this->_contactIds as $num => $contactID) {
1476 $ppDAO = new CRM_Event_DAO_ParticipantPayment();
1477 $ppDAO->participant_id = $participants[$num]->id;
1478 $ppDAO->contribution_id = $contributions[$num]->id;
1479 $ppDAO->save();
1480 }
1481 }
1482 // next create the transaction record
1483 $transaction = new CRM_Core_Transaction();
1484
1485 // CRM-11124
1486 if ($this->_params['discount_id']) {
1487 CRM_Event_BAO_Participant::createDiscountTrxn(
1488 $this->_eventId,
1489 $contributionParams,
1490 NULL,
1491 CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params)
1492 );
1493 }
1494 $transaction->commit();
1495 }
1496 }
1497
1498 // also store lineitem stuff here
1499 if ((($this->_lineItem & $this->_action & CRM_Core_Action::ADD) ||
1500 ($this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId))
1501 ) {
1502 foreach ($this->_contactIds as $num => $contactID) {
1503 foreach ($this->_lineItem as $key => $value) {
1504 if (is_array($value) && $value != 'skip') {
1505 foreach ($value as $lineKey => $line) {
1506 //10117 update the line items for participants if contribution amount is recorded
1507 if ($this->_quickConfig && !empty($params['total_amount']) &&
1508 ($params['status_id'] != array_search('Partially paid', $participantStatus))
1509 ) {
1510 $line['unit_price'] = $line['line_total'] = $params['total_amount'];
1511 if (!empty($params['tax_amount'])) {
1512 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
1513 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
1514 }
1515 }
1516 $lineItem[$this->_priceSetId][$lineKey] = $line;
1517 }
1518 CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
1519 CRM_Contribute_BAO_Contribution::addPayments($contributions);
1520 }
1521 }
1522 }
1523 }
1524
1525 $updateStatusMsg = NULL;
1526 //send mail when participant status changed, CRM-4326
1527 if ($this->_id && $this->_statusId &&
1528 $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])
1529 ) {
1530
1531 $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id,
1532 $params['status_id'],
1533 $this->_statusId
1534 );
1535 }
1536
1537 $sent = [];
1538 $notSent = [];
1539 if (!empty($params['send_receipt'])) {
1540 if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
1541 $receiptFrom = $params['from_email_address'];
1542 }
1543
1544 $this->assign('module', 'Event Registration');
1545 //use of the message template below requires variables in different format
1546 $event = $events = [];
1547 $returnProperties = ['event_type_id', 'fee_label', 'start_date', 'end_date', 'is_show_location', 'title'];
1548
1549 //get all event details.
1550 CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
1551 $event = $events[$params['event_id']];
1552 unset($event['start_date']);
1553 unset($event['end_date']);
1554
1555 $role = CRM_Event_PseudoConstant::participantRole();
1556 $participantRoles = CRM_Utils_Array::value('role_id', $params);
1557 if (is_array($participantRoles)) {
1558 $selectedRoles = [];
1559 foreach ($participantRoles as $roleId) {
1560 $selectedRoles[] = $role[$roleId];
1561 }
1562 $event['participant_role'] = implode(', ', $selectedRoles);
1563 }
1564 else {
1565 $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
1566 }
1567 $event['is_monetary'] = $this->_isPaidEvent;
1568
1569 if ($params['receipt_text']) {
1570 $event['confirm_email_text'] = $params['receipt_text'];
1571 }
1572
1573 $this->assign('isAmountzero', 1);
1574 $this->assign('event', $event);
1575
1576 $this->assign('isShowLocation', $event['is_show_location']);
1577 if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
1578 $locationParams = [
1579 'entity_id' => $params['event_id'],
1580 'entity_table' => 'civicrm_event',
1581 ];
1582 $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
1583 $this->assign('location', $location);
1584 }
1585
1586 $status = CRM_Event_PseudoConstant::participantStatus();
1587 if ($this->_isPaidEvent) {
1588 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
1589 if (!$this->_mode) {
1590 if (isset($params['payment_instrument_id'])) {
1591 $this->assign('paidBy',
1592 CRM_Utils_Array::value($params['payment_instrument_id'],
1593 $paymentInstrument
1594 )
1595 );
1596 }
1597 }
1598
1599 $this->assign('totalAmount', $contributionParams['total_amount']);
1600 if (isset($contributionParams['partial_payment_total'])) {
1601 // balance amount
1602 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_to_pay'];
1603 $this->assign('balanceAmount', $balanceAmount);
1604 }
1605 $this->assign('isPrimary', 1);
1606 $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
1607 }
1608 if ($this->_mode) {
1609 $this->assignBillingName($params);
1610 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
1611 $this->_params,
1612 $this->_bltID
1613 ));
1614
1615 $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
1616 $date = CRM_Utils_Date::mysqlToIso($date);
1617 $this->assign('credit_card_exp_date', $date);
1618 $this->assign('credit_card_number',
1619 CRM_Utils_System::mungeCreditCard($params['credit_card_number'])
1620 );
1621 $this->assign('credit_card_type', $params['credit_card_type']);
1622 // The concept of contributeMode is deprecated.
1623 $this->assign('contributeMode', 'direct');
1624 $this->assign('isAmountzero', 0);
1625 $this->assign('is_pay_later', 0);
1626 $this->assign('isPrimary', 1);
1627 }
1628
1629 $this->assign('register_date', $params['register_date']);
1630 if (isset($params['receive_date'])) {
1631 $this->assign('receive_date', $params['receive_date']);
1632 }
1633
1634 $participant = [['participant_id', '=', $participants[0]->id, 0, 0]];
1635 // check whether its a test drive ref CRM-3075
1636 if (!empty($this->_defaultValues['is_test'])) {
1637 $participant[] = ['participant_test', '=', 1, 0, 0];
1638 }
1639
1640 $customGroup = [];
1641 //format submitted data
1642 foreach ($params['custom'] as $fieldID => $values) {
1643 foreach ($values as $fieldValue) {
1644 $isPublic = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $fieldValue['custom_group_id'], 'is_public');
1645 if ($isPublic) {
1646 $customFields[$fieldID]['id'] = $fieldID;
1647 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
1648 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
1649 }
1650 }
1651 }
1652
1653 foreach ($this->_contactIds as $num => $contactID) {
1654 // Retrieve the name and email of the contact - this will be the TO for receipt email
1655 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
1656
1657 $this->_contributorDisplayName = ($this->_contributorDisplayName == ' ') ? $this->_contributorEmail : $this->_contributorDisplayName;
1658
1659 $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1660 if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
1661 $this->assign('isOnWaitlist', TRUE);
1662 }
1663
1664 $this->assign('customGroup', $customGroup);
1665 $this->assign('contactID', $contactID);
1666 $this->assign('participantID', $participants[$num]->id);
1667
1668 $this->_id = $participants[$num]->id;
1669
1670 if ($this->_isPaidEvent) {
1671 // fix amount for each of participants ( for bulk mode )
1672 $eventAmount = [];
1673 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
1674 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1675 $totalTaxAmount = 0;
1676
1677 //add dataArray in the receipts in ADD and UPDATE condition
1678 $dataArray = [];
1679 if ($this->_action & CRM_Core_Action::ADD) {
1680 $line = isset($lineItem[0]) ? $lineItem[0] : [];
1681 }
1682 elseif ($this->_action & CRM_Core_Action::UPDATE) {
1683 $line = $this->_values['line_items'];
1684 }
1685 if ($invoicing) {
1686 foreach ($line as $key => $value) {
1687 if (isset($value['tax_amount'])) {
1688 $totalTaxAmount += $value['tax_amount'];
1689 if (isset($dataArray[(string) $value['tax_rate']])) {
1690 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1691 }
1692 else {
1693 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1694 }
1695 }
1696 }
1697 $this->assign('totalTaxAmount', $totalTaxAmount);
1698 $this->assign('taxTerm', $this->getSalesTaxTerm());
1699 $this->assign('dataArray', $dataArray);
1700 }
1701 if (!empty($additionalParticipantDetails)) {
1702 $params['amount_level'] = preg_replace('/\ 1/', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
1703 }
1704
1705 $eventAmount[$num] = [
1706 'label' => preg_replace('/\ 1/', '', $params['amount_level']),
1707 'amount' => $params['fee_amount'],
1708 ];
1709 //as we are using same template for online & offline registration.
1710 //So we have to build amount as array.
1711 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
1712 $this->assign('amount', $eventAmount);
1713 }
1714
1715 $sendTemplateParams = [
1716 'groupName' => 'msg_tpl_workflow_event',
1717 'valueName' => 'event_offline_receipt',
1718 'contactId' => $contactID,
1719 'isTest' => !empty($this->_defaultValues['is_test']),
1720 'PDFFilename' => ts('confirmation') . '.pdf',
1721 ];
1722
1723 // try to send emails only if email id is present
1724 // and the do-not-email option is not checked for that contact
1725 if ($this->_contributorEmail and !$this->_toDoNotEmail) {
1726 $sendTemplateParams['from'] = $receiptFrom;
1727 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
1728 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
1729 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
1730 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
1731 }
1732
1733 //send email with pdf invoice
1734 $template = CRM_Core_Smarty::singleton();
1735 $taxAmt = $template->get_template_vars('dataArray');
1736 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1737 $this->_id, 'contribution_id', 'participant_id'
1738 );
1739 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
1740 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
1741 if (!empty($taxAmt) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1742 $sendTemplateParams['isEmailPdf'] = TRUE;
1743 $sendTemplateParams['contributionId'] = $contributionId;
1744 }
1745 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
1746 if ($mailSent) {
1747 $sent[] = $contactID;
1748 foreach ($participants as $ids => $values) {
1749 if ($values->contact_id == $contactID) {
1750 $values->details = CRM_Utils_Array::value('receipt_text', $params);
1751 CRM_Activity_BAO_Activity::addActivity($values, 'Email');
1752 break;
1753 }
1754 }
1755 }
1756 else {
1757 $notSent[] = $contactID;
1758 }
1759 }
1760 }
1761
1762 // set the participant id if it is not set
1763 if (!$this->_id) {
1764 $this->_id = $participants[0]->id;
1765 }
1766
1767 return $this->getStatusMsg($params, $sent, $updateStatusMsg, $notSent);
1768 }
1769
1770 /**
1771 * Set the various IDs relating to custom data types.
1772 */
1773 public function setCustomDataTypes() {
1774 $customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
1775 $this->_roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
1776 $this->_eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
1777 $this->_eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
1778 $this->assign('roleCustomDataTypeID', $this->_roleCustomDataTypeID);
1779 $this->assign('eventNameCustomDataTypeID', $this->_eventNameCustomDataTypeID);
1780 $this->assign('eventTypeCustomDataTypeID', $this->_eventTypeCustomDataTypeID);
1781 }
1782
1783 /**
1784 * Get status message
1785 *
1786 * @param array $params
1787 * @param int $sent
1788 * @param string $updateStatusMsg
1789 * @param int $notSent
1790 *
1791 * @return string
1792 */
1793 protected function getStatusMsg($params, $sent, $updateStatusMsg, $notSent) {
1794 $statusMsg = '';
1795 if (($this->_action & CRM_Core_Action::UPDATE)) {
1796 $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $this->_contributorDisplayName]);
1797 if (!empty($params['send_receipt']) && count($sent)) {
1798 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', [1 => $this->_contributorEmail]);
1799 }
1800
1801 if ($updateStatusMsg) {
1802 $statusMsg = "{$statusMsg} {$updateStatusMsg}";
1803 }
1804 }
1805 elseif ($this->_action & CRM_Core_Action::ADD) {
1806 if ($this->_single) {
1807 $statusMsg = ts('Event registration for %1 has been added.', [1 => $this->_contributorDisplayName]);
1808 if (!empty($params['send_receipt']) && count($sent)) {
1809 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', [1 => $this->_contributorEmail]);
1810 }
1811 }
1812 else {
1813 $statusMsg = ts('Total Participant(s) added to event: %1.', [1 => count($this->_contactIds)]);
1814 if (count($notSent) > 0) {
1815 $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)]);
1816 }
1817 elseif (isset($params['send_receipt'])) {
1818 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
1819 }
1820 }
1821 }
1822 return $statusMsg;
1823 }
1824
1825 }