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