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