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