synchronizeUsers minor fixups
[civicrm-core.git] / CRM / Event / Form / Registration / Confirm.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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/**
6a488035 29 * @package CRM
e7112fa7 30 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
31 */
32
33/**
3bdf1f3a 34 * This class generates form components for processing Event.
6a488035
TO
35 */
36class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
37
38 /**
66f9e52b 39 * The values for the contribution db object.
6a488035
TO
40 *
41 * @var array
6a488035
TO
42 */
43 public $_values;
44
45 /**
66f9e52b 46 * The total amount.
6a488035
TO
47 *
48 * @var float
6a488035
TO
49 */
50 public $_totalAmount;
51
52 /**
66f9e52b 53 * Set variables up before form is built.
6a488035 54 */
00be9182 55 public function preProcess() {
6a488035
TO
56 parent::preProcess();
57
58 // lineItem isn't set until Register postProcess
59 $this->_lineItem = $this->get('lineItem');
60
61 $this->_params = $this->get('params');
d91b8b33 62 $this->_params[0]['tax_amount'] = $this->get('tax_amount');
6a488035
TO
63
64 $this->_params[0]['is_pay_later'] = $this->get('is_pay_later');
65 $this->assign('is_pay_later', $this->_params[0]['is_pay_later']);
66 if ($this->_params[0]['is_pay_later']) {
67 $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
68 }
69
70 CRM_Utils_Hook::eventDiscount($this, $this->_params);
71
8cc574cf 72 if (!empty($this->_params[0]['discount']) && !empty($this->_params[0]['discount']['applied'])) {
6a488035
TO
73 $this->set('hookDiscount', $this->_params[0]['discount']);
74 $this->assign('hookDiscount', $this->_params[0]['discount']);
75 }
76
0f2b049e 77 // The concept of contributeMode is deprecated.
6a488035
TO
78 if ($this->_contributeMode == 'express') {
79 $params = array();
80 // rfp == redirect from paypal
9a1b1b8e 81 // rfp is probably not required - the getPreApprovalDetails should deal with any payment-processor specific 'stuff'
6a488035
TO
82 $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean',
83 CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET'
84 );
85
86 //we lost rfp in case of additional participant. So set it explicitly.
87 if ($rfp || CRM_Utils_Array::value('additional_participants', $this->_params[0], FALSE)) {
9a1b1b8e 88 if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) {
89 $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
90 $params = array_merge($this->_params, $preApprovalParams);
0479b4c8 91 }
9a1b1b8e 92 CRM_Core_Payment_Form::mapParams($this->_bltID, $params, $params, FALSE);
6a488035 93
9a1b1b8e 94 // set a few other parameters that are not really specific to this method because we don't know what
95 // will break if we change this.
6a488035 96 $params['amount'] = $this->_params[0]['amount'];
a7488080 97 if (!empty($this->_params[0]['discount'])) {
6a488035
TO
98 $params['discount'] = $this->_params[0]['discount'];
99 $params['discountAmount'] = $this->_params[0]['discountAmount'];
100 $params['discountMessage'] = $this->_params[0]['discountMessage'];
101 }
4233eb14 102 if (!empty($this->_params[0]['amount_priceset_level_radio'])) {
103 $params['amount_priceset_level_radio'] = $this->_params[0]['amount_priceset_level_radio'];
104 }
6a488035
TO
105 $params['amount_level'] = $this->_params[0]['amount_level'];
106 $params['currencyID'] = $this->_params[0]['currencyID'];
6a488035
TO
107
108 // also merge all the other values from the profile fields
109 $values = $this->controller->exportValues('Register');
110 $skipFields = array(
111 'amount',
112 "street_address-{$this->_bltID}",
113 "city-{$this->_bltID}",
114 "state_province_id-{$this->_bltID}",
115 "postal_code-{$this->_bltID}",
116 "country_id-{$this->_bltID}",
117 );
118
119 foreach ($values as $name => $value) {
120 // skip amount field
121 if (!in_array($name, $skipFields)) {
122 $params[$name] = $value;
123 }
bb2240a2 124 if (substr($name, 0, 6) == 'price_') {
b5b712c1 125 $params[$name] = $this->_params[0][$name];
bb2240a2 126 }
6a488035
TO
127 }
128 $this->set('getExpressCheckoutDetails', $params);
129 }
9a1b1b8e 130 $this->_params[0] = array_merge($this->_params[0], $params);
6a488035
TO
131 $this->_params[0]['is_primary'] = 1;
132 }
133 else {
134 //process only primary participant params.
135 $registerParams = $this->_params[0];
136 if (isset($registerParams["billing_state_province_id-{$this->_bltID}"])
137 && $registerParams["billing_state_province_id-{$this->_bltID}"]
138 ) {
139 $registerParams["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($registerParams["billing_state_province_id-{$this->_bltID}"]);
140 }
141
142 if (isset($registerParams["billing_country_id-{$this->_bltID}"]) && $registerParams["billing_country_id-{$this->_bltID}"]) {
143 $registerParams["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($registerParams["billing_country_id-{$this->_bltID}"]);
144 }
145 if (isset($registerParams['credit_card_exp_date'])) {
353ffa53 146 $registerParams['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($registerParams);
6a488035
TO
147 $registerParams['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($registerParams);
148 }
149 if ($this->_values['event']['is_monetary']) {
150 $registerParams['ip_address'] = CRM_Utils_System::ipAddress();
151 $registerParams['currencyID'] = $this->_params[0]['currencyID'];
6a488035
TO
152 }
153 //assign back primary participant params.
154 $this->_params[0] = $registerParams;
155 }
156
157 if ($this->_values['event']['is_monetary']) {
158 $this->_params[0]['invoiceID'] = $this->get('invoiceID');
159 }
160 $this->assign('defaultRole', FALSE);
161 if (CRM_Utils_Array::value('defaultRole', $this->_params[0]) == 1) {
162 $this->assign('defaultRole', TRUE);
163 }
164
a7488080 165 if (empty($this->_params[0]['participant_role_id']) &&
6a488035
TO
166 $this->_values['event']['default_role_id']
167 ) {
168 $this->_params[0]['participant_role_id'] = $this->_values['event']['default_role_id'];
169 }
170
171 if (isset($this->_values['event']['confirm_title'])) {
172 CRM_Utils_System::setTitle($this->_values['event']['confirm_title']);
173 }
174
175 if ($this->_pcpId) {
176 $params = CRM_Contribute_Form_Contribution_Confirm::processPcp($this, $this->_params[0]);
177 $this->_params[0] = $params;
178 }
179
180 $this->set('params', $this->_params);
181 }
182
183 /**
3bdf1f3a 184 * Overwrite action, since we are only showing elements in frozen mode no help display needed.
6a488035
TO
185 *
186 * @return int
6a488035 187 */
00be9182 188 public function getAction() {
6a488035
TO
189 if ($this->_action & CRM_Core_Action::PREVIEW) {
190 return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
191 }
192 else {
193 return CRM_Core_Action::VIEW;
194 }
195 }
196
197 /**
66f9e52b 198 * Build the form object.
6a488035
TO
199 */
200 public function buildQuickForm() {
201 $this->assignToTemplate();
1909126f 202
203 if ($this->_values['event']['is_monetary'] &&
204 ($this->_params[0]['amount'] || $this->_params[0]['amount'] == 0)
205 ) {
6a488035
TO
206 $this->_amount = array();
207
79d001a2 208 $taxAmount = 0;
6a488035 209 foreach ($this->_params as $k => $v) {
7bde3600 210 if ($v == 'skip') {
211 continue;
212 }
75b065ce 213 $individualTaxAmount = 0;
79d001a2
PB
214 //display tax amount on confirmation page
215 $taxAmount += $v['tax_amount'];
6a488035
TO
216 if (is_array($v)) {
217 foreach (array(
353ffa53 218 'first_name',
317fceb4 219 'last_name',
353ffa53 220 ) as $name) {
6a488035
TO
221 if (isset($v['billing_' . $name]) &&
222 !isset($v[$name])
223 ) {
224 $v[$name] = $v['billing_' . $name];
225 }
226 }
227
8cc574cf 228 if (!empty($v['first_name']) && !empty($v['last_name'])) {
6a488035
TO
229 $append = $v['first_name'] . ' ' . $v['last_name'];
230 }
231 else {
232 //use an email if we have one
233 foreach ($v as $v_key => $v_val) {
234 if (substr($v_key, 0, 6) == 'email-') {
235 $append = $v[$v_key];
236 }
237 }
238 }
239
240 $this->_amount[$k]['amount'] = $v['amount'];
a7488080 241 if (!empty($v['discountAmount'])) {
6a488035
TO
242 $this->_amount[$k]['amount'] -= $v['discountAmount'];
243 }
244
245 $this->_amount[$k]['label'] = preg_replace('/\ 1/', '', $v['amount_level']) . ' - ' . $append;
246 $this->_part[$k]['info'] = CRM_Utils_Array::value('first_name', $v) . ' ' . CRM_Utils_Array::value('last_name', $v);
a7488080 247 if (empty($v['first_name'])) {
6a488035
TO
248 $this->_part[$k]['info'] = $append;
249 }
75b065ce 250
251 /*CRM-16320 */
252 $individual[$k]['totalAmtWithTax'] = $this->_amount[$k]['amount'];
253 $individual[$k]['totalTaxAmt'] = $individualTaxAmount + $v['tax_amount'];
6a488035 254 $this->_totalAmount = $this->_totalAmount + $this->_amount[$k]['amount'];
a7488080 255 if (!empty($v['is_primary'])) {
6a488035
TO
256 $this->set('primaryParticipantAmount', $this->_amount[$k]['amount']);
257 }
258 }
259 }
260
aaffa79f 261 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
03b412ae
PB
262 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
263 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
03b412ae
PB
264 if ($invoicing) {
265 $this->assign('totalTaxAmount', $taxAmount);
d9e4ebe7 266 $this->assign('taxTerm', $taxTerm);
75b065ce 267 $this->assign('individual', $individual);
268 $this->set('individual', $individual);
03b412ae 269 }
75b065ce 270
6a488035
TO
271 $this->assign('part', $this->_part);
272 $this->set('part', $this->_part);
273 $this->assign('amounts', $this->_amount);
274 $this->assign('totalAmount', $this->_totalAmount);
275 $this->set('totalAmount', $this->_totalAmount);
276 }
277
9da8dc8c 278 if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
6a488035 279 $lineItemForTemplate = array();
03b412ae 280 $getTaxDetails = FALSE;
26fe6f4c 281 if (!empty($this->_lineItem) && is_array($this->_lineItem)) {
282 foreach ($this->_lineItem as $key => $value) {
283 if (!empty($value)) {
284 $lineItemForTemplate[$key] = $value;
285 }
286 if ($invoicing) {
287 foreach ($value as $v) {
288 if (isset($v['tax_rate'])) {
289 $getTaxDetails = TRUE;
290 }
03b412ae
PB
291 }
292 }
293 }
6a488035
TO
294 }
295 if (!empty($lineItemForTemplate)) {
296 $this->assign('lineItem', $lineItemForTemplate);
297 }
d9e4ebe7 298 $this->assign('getTaxDetails', $getTaxDetails);
6a488035
TO
299 }
300
301 //display additional participants profile.
5bdcb00b 302 self::assignProfiles($this);
6a488035
TO
303
304 //consider total amount.
305 $this->assign('isAmountzero', ($this->_totalAmount <= 0) ? TRUE : FALSE);
306
f48e6cf7 307 // @todo this needs to GO! We are getting rid of references to processor types in the code base in favour of
308 // over-ride-able functions on them.
309 // The processor effectively has a 'buildForm' hook it can use if it needs to.
310 // The tricky thing is that we have no way of testing this code out - perhaps it hasn't worked for years!
8cc574cf 311 if ($this->_paymentProcessor['payment_processor_type'] == 'Google_Checkout' && empty($this->_params[0]['is_pay_later']) && !($this->_params[0]['amount'] == 0) &&
6a488035
TO
312 !$this->_allowWaitlist && !$this->_requireApproval
313 ) {
314 $this->_checkoutButtonName = $this->getButtonName('next', 'checkout');
315 $this->add('image',
316 $this->_checkoutButtonName,
317 $this->_paymentProcessor['url_button'],
97e557d7 318 array('class' => 'crm-form-submit')
6a488035
TO
319 );
320
321 $this->addButtons(array(
322 array(
323 'type' => 'back',
f212d37d 324 'name' => ts('Go Back'),
6a488035
TO
325 ),
326 )
327 );
328 }
329 else {
f212d37d 330 $contribButton = ts('Continue');
6a488035 331 $this->addButtons(array(
f2ce2ad2
J
332 array(
333 'type' => 'back',
f212d37d 334 'name' => ts('Go Back'),
f2ce2ad2 335 ),
6a488035
TO
336 array(
337 'type' => 'next',
338 'name' => $contribButton,
339 'isDefault' => TRUE,
340 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
341 ),
6a488035
TO
342 )
343 );
344 }
345
346 $defaults = array();
347 $fields = array();
348 if (!empty($this->_fields)) {
349 foreach ($this->_fields as $name => $dontCare) {
350 $fields[$name] = 1;
351 }
352 }
353 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
354 foreach ($fields as $name => $dontCare) {
355 if (isset($this->_params[0][$name])) {
356 $defaults[$name] = $this->_params[0][$name];
357 if (substr($name, 0, 7) == 'custom_') {
358 $timeField = "{$name}_time";
359 if (isset($this->_params[0][$timeField])) {
360 $defaults[$timeField] = $this->_params[0][$timeField];
361 }
362 if (isset($this->_params[0]["{$name}_id"])) {
363 $defaults["{$name}_id"] = $this->_params[0]["{$name}_id"];
364 }
365 }
366 elseif (in_array($name, CRM_Contact_BAO_Contact::$_greetingTypes)
367 && !empty($this->_params[0][$name . '_custom'])
368 ) {
369 $defaults[$name . '_custom'] = $this->_params[0][$name . '_custom'];
370 }
371 }
372 }
373
6a488035
TO
374 $this->setDefaults($defaults);
375 $this->freeze();
376
377 //lets give meaningful status message, CRM-4320.
378 $this->assign('isOnWaitlist', $this->_allowWaitlist);
379 $this->assign('isRequireApproval', $this->_requireApproval);
380
381 // Assign Participant Count to Lineitem Table
9da8dc8c 382 $this->assign('pricesetFieldsCount', CRM_Price_BAO_PriceSet::getPricesetCount($this->_priceSetId));
79b152ac 383 $this->addFormRule(array('CRM_Event_Form_Registration_Confirm', 'formRule'), $this);
6a488035
TO
384 }
385
ca87146b 386 /**
3bdf1f3a 387 * Apply form rule.
388 *
389 * @param array $fields
390 * @param array $files
391 * @param CRM_Core_Form $self
ca87146b
EM
392 *
393 * @return array|bool
394 */
00be9182 395 public static function formRule($fields, $files, $self) {
79b152ac 396 $errors = array();
397 $eventFull = CRM_Event_BAO_Participant::eventFull($self->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $self->_values['event']));
398 if ($eventFull && empty($self->_allowConfirmation)) {
399 if (empty($self->_allowWaitlist)) {
0479b4c8 400 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "reset=1&id={$self->_eventId}", FALSE, NULL, FALSE, TRUE));
79b152ac 401 }
402 }
403 $self->_feeBlock = $self->_values['fee'];
404 CRM_Event_Form_Registration_Register::formatFieldsForOptionFull($self);
405
0dc0b759 406 if (!empty($self->_priceSetId) &&
407 !$self->_requireApproval && !$self->_allowWaitlist
408 ) {
79b152ac 409 $priceSetErrors = self::validatePriceSet($self, $self->_params);
0dc0b759 410 if (!empty($priceSetErrors)) {
2ae4d103 411 CRM_Core_Session::setStatus(ts('You have been returned to the start of the registration process and any sold out events have been removed from your selections. You will not be able to continue until you review your booking and select different events if you wish.'), ts('Unfortunately some of your options have now sold out for one or more participants.'), 'error');
0dc0b759 412 CRM_Core_Session::setStatus(ts('Please note that the options which are marked or selected are sold out for participant being viewed.'), ts('Sold out:'), 'error');
413 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "_qf_Register_display=true&qfKey={$fields['qfKey']}"));
414 }
79b152ac 415 }
416
0dc0b759 417 return empty($priceSetErrors) ? TRUE : $priceSetErrors;
79b152ac 418 }
353ffa53 419
6a488035 420 /**
66f9e52b 421 * Process the form submission.
6a488035
TO
422 */
423 public function postProcess() {
353ffa53 424 $now = date('YmdHis');
af72b8c7 425
6a488035 426 $this->_params = $this->get('params');
a7488080 427 if (!empty($this->_params[0]['contact_id'])) {
e1ce628e 428 // unclear when this would be set & whether it could be checked in getContactID.
429 // perhaps it relates to when cid is in the url
430 //@todo someone who knows add comments on the various contactIDs in this form
6a488035
TO
431 $contactID = $this->_params[0]['contact_id'];
432 }
433 else {
5c280496 434 $contactID = $this->getContactID();
6a488035
TO
435 }
436
437 // if a discount has been applied, lets now deduct it from the amount
438 // and fix the fee level
8cc574cf 439 if (!empty($this->_params[0]['discount']) && !empty($this->_params[0]['discount']['applied'])) {
6a488035 440 foreach ($this->_params as $k => $v) {
8cc574cf 441 if (CRM_Utils_Array::value('amount', $this->_params[$k]) > 0 && !empty($this->_params[$k]['discountAmount'])) {
6a488035
TO
442 $this->_params[$k]['amount'] -= $this->_params[$k]['discountAmount'];
443 $this->_params[$k]['amount_level'] .= CRM_Utils_Array::value('discountMessage', $this->_params[$k]);
444 }
445 }
446 $this->set('params', $this->_params);
447 }
448
449 // CRM-4320, lets build array of cancelled additional participant ids
450 // those are drop or skip by primary at the time of confirmation.
451 // get all in and then unset those we want to process.
452 $cancelledIds = $this->_additionalParticipantIds;
453
454 $params = $this->_params;
1909126f 455 if ($this->_values['event']['is_monetary']) {
456 $this->set('finalAmount', $this->_amount);
457 }
6a488035
TO
458 $participantCount = array();
459
460 //unset the skip participant from params.
461 //build the $participantCount array.
462 //maintain record for all participants.
463 foreach ($params as $participantNum => $record) {
464 if ($record == 'skip') {
465 unset($params[$participantNum]);
466 $participantCount[$participantNum] = 'skip';
467 }
468 elseif ($participantNum) {
469 $participantCount[$participantNum] = 'participant';
470 }
471
472 //lets get additional participant id to cancel.
473 if ($this->_allowConfirmation && is_array($cancelledIds)) {
474 $additonalId = CRM_Utils_Array::value('participant_id', $record);
475 if ($additonalId && $key = array_search($additonalId, $cancelledIds)) {
476 unset($cancelledIds[$key]);
477 }
478 }
479 }
480
481 $payment = $registerByID = $primaryCurrencyID = $contribution = NULL;
482 $paymentObjError = ts('The system did not record payment details for this payment and so could not process the transaction. Please report this error to the site administrator.');
483
484 $this->participantIDS = array();
485 $fields = array();
486 foreach ($params as $key => $value) {
a9f7d48b 487 CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields, $this);
6a488035
TO
488 //unset the billing parameters if it is pay later mode
489 //to avoid creation of billing location
0b05b9a9 490 // @todo - the reasoning for this is unclear - elsewhere we check what fields are provided by
491 // the form & if billing fields exist we create the address, relying on the form to collect
492 // only information we intend to store.
8ae4d0d3 493 if ($this->_allowWaitlist
494 || $this->_requireApproval
495 || (!empty($value['is_pay_later']) && !$this->_isBillingAddressRequiredForPayLater)
496 || empty($value['is_primary'])
497 ) {
6a488035
TO
498 $billingFields = array(
499 "email-{$this->_bltID}",
500 'billing_first_name',
501 'billing_middle_name',
502 'billing_last_name',
503 "billing_street_address-{$this->_bltID}",
504 "billing_city-{$this->_bltID}",
505 "billing_state_province-{$this->_bltID}",
506 "billing_state_province_id-{$this->_bltID}",
507 "billing_postal_code-{$this->_bltID}",
508 "billing_country-{$this->_bltID}",
509 "billing_country_id-{$this->_bltID}",
510 "address_name-{$this->_bltID}",
511 );
512 foreach ($billingFields as $field) {
513 unset($value[$field]);
514 }
a7488080 515 if (!empty($value['is_pay_later'])) {
6a488035
TO
516 $this->_values['params']['is_pay_later'] = TRUE;
517 }
518 }
519
520 //Unset ContactID for additional participants and set RegisterBy Id.
a7488080 521 if (empty($value['is_primary'])) {
6a488035
TO
522 $contactID = CRM_Utils_Array::value('contact_id', $value);
523 $registerByID = $this->get('registerByID');
524 if ($registerByID) {
525 $value['registered_by_id'] = $registerByID;
526 }
527 }
528 else {
529 $value['amount'] = $this->_totalAmount;
530 }
531
a9f7d48b 532 $contactID = CRM_Event_Form_Registration_Confirm::updateContactFields($contactID, $value, $fields, $this);
6a488035
TO
533
534 // lets store the contactID in the session
535 // we dont store in userID in case the user is doing multiple
536 // transactions etc
537 // for things like tell a friend
8cc574cf 538 if (!$this->getContactID() && !empty($value['is_primary'])) {
af72b8c7 539 $session = CRM_Core_Session::singleton();
6a488035
TO
540 $session->set('transaction.userID', $contactID);
541 }
542
543 $value['description'] = ts('Online Event Registration') . ': ' . $this->_values['event']['title'];
544 $value['accountingCode'] = CRM_Utils_Array::value('accountingCode',
545 $this->_values['event']
546 );
547
752f450d 548 $pending = FALSE;
67c8322d
J
549 if ($this->_allowWaitlist || $this->_requireApproval) {
550 //get the participant statuses.
551 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
552 if ($this->_allowWaitlist) {
553 $value['participant_status_id'] = $value['participant_status'] = array_search('On waitlist', $waitingStatuses);
554 }
555 else {
556 $value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
557 }
558
559 //there might be case user seleted pay later and
560 //now becomes part of run time waiting list.
561 $value['is_pay_later'] = FALSE;
562 }
563
6a488035 564 // required only if paid event
67c8322d 565 if ($this->_values['event']['is_monetary'] && !($this->_allowWaitlist || $this->_requireApproval)) {
6a488035 566 if (is_array($this->_paymentProcessor)) {
077017db 567 $payment = $this->_paymentProcessor['object'];
6a488035 568 }
ec022878 569 if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) {
570 $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
571 $value = array_merge($value, $preApprovalParams);
572 }
6a488035
TO
573 $result = NULL;
574
67c8322d 575 if (!empty($value['is_pay_later']) ||
6a488035 576 $value['amount'] == 0 ||
0f2b049e 577 // The concept of contributeMode is deprecated.
6a488035
TO
578 $this->_contributeMode == 'checkout' ||
579 $this->_contributeMode == 'notify'
580 ) {
581 if ($value['amount'] != 0) {
582 $pending = TRUE;
583 //get the participant statuses.
584 $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'");
0d8afee2 585 $status = !empty($value['is_pay_later']) ? 'Pending from pay later' : 'Pending from incomplete transaction';
6a488035
TO
586 $value['participant_status_id'] = $value['participant_status'] = array_search($status, $pendingStatuses);
587 }
588 }
a7488080 589 elseif (!empty($value['is_primary'])) {
6a488035 590 CRM_Core_Payment_Form::mapParams($this->_bltID, $value, $value, TRUE);
bd7b39e7
PJ
591 // payment email param can be empty for _bltID mapping
592 // thus provide mapping for it with a different email value
593 if (empty($value['email'])) {
594 $value['email'] = CRM_Utils_Array::valueByRegexKey('/^email-/', $value);
595 }
596
6a488035 597 if (is_object($payment)) {
248141b9
EM
598 try {
599 $result = $payment->doPayment($value);
600 $value = array_merge($value, $result);
601 }
602 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
069ad5a0 603 CRM_Core_Session::singleton()->setStatus($e->getMessage());
248141b9
EM
604 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "id={$this->_eventId}"));
605 }
6a488035
TO
606 }
607 else {
608 CRM_Core_Error::fatal($paymentObjError);
609 }
610 }
611
6a488035
TO
612 $value['receive_date'] = $now;
613 if ($this->_allowConfirmation) {
614 $value['participant_register_date'] = $this->_values['participant']['register_date'];
615 }
616
617 $createContrib = ($value['amount'] != 0) ? TRUE : FALSE;
618 // force to create zero amount contribution, CRM-5095
619 if (!$createContrib && ($value['amount'] == 0)
620 && $this->_priceSetId && $this->_lineItem
621 ) {
622 $createContrib = TRUE;
623 }
624
8cc574cf 625 if ($createContrib && !empty($value['is_primary']) &&
6a488035
TO
626 !$this->_allowWaitlist && !$this->_requireApproval
627 ) {
628 // if paid event add a contribution record
629 //if primary participant contributing additional amount
630 //append (multiple participants) to its fee level. CRM-4196.
631 $isAdditionalAmount = FALSE;
632 if (count($params) > 1) {
633 $isAdditionalAmount = TRUE;
634 }
635
636 //passing contribution id is already registered.
317fceb4 637 $contribution = self::processContribution($this, $value, $result, $contactID, $pending, $isAdditionalAmount);
6a488035
TO
638 $value['contributionID'] = $contribution->id;
639 $value['contributionTypeID'] = $contribution->financial_type_id;
640 $value['receive_date'] = $contribution->receive_date;
641 $value['trxn_id'] = $contribution->trxn_id;
642 $value['contributionID'] = $contribution->id;
643 $value['contributionTypeID'] = $contribution->financial_type_id;
644 }
645 $value['contactID'] = $contactID;
353ffa53 646 $value['eventID'] = $this->_eventId;
6a488035
TO
647 $value['item_name'] = $value['description'];
648 }
9a32a8fc
GC
649
650 if (!empty($value['contributionID'])) {
651 $this->_values['contributionId'] = $value['contributionID'];
652 }
6a488035
TO
653
654 //CRM-4453.
a7488080 655 if (!empty($value['is_primary'])) {
6a488035
TO
656 $primaryCurrencyID = CRM_Utils_Array::value('currencyID', $value);
657 }
a7488080 658 if (empty($value['currencyID'])) {
6a488035
TO
659 $value['currencyID'] = $primaryCurrencyID;
660 }
661
1909126f 662 // CRM-11182 - Confirmation page might not be monetary
663 if ($this->_values['event']['is_monetary']) {
664 if (!$pending && !empty($value['is_primary']) &&
665 !$this->_allowWaitlist && !$this->_requireApproval
666 ) {
667 // transactionID & receive date required while building email template
668 $this->assign('trxn_id', $value['trxn_id']);
669 $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($value['receive_date']));
670 $this->set('receiveDate', CRM_Utils_Date::mysqlToIso($value['receive_date']));
671 $this->set('trxnId', CRM_Utils_Array::value('trxn_id', $value));
672 }
6a488035 673 }
f55dc004 674
ffcec972 675 $value['fee_amount'] = CRM_Utils_Array::value('amount', $value);
6a488035
TO
676 $this->set('value', $value);
677
678 // handle register date CRM-4320
679 if ($this->_allowConfirmation) {
481a74f4 680 $registerDate = CRM_Utils_Array::value('participant_register_date', $params);
6a488035 681 }
a7488080 682 elseif (!empty($params['participant_register_date']) &&
6a488035
TO
683 is_array($params['participant_register_date']) &&
684 !empty($params['participant_register_date'])
685 ) {
686 $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
687 }
688 else {
689 $registerDate = date('YmdHis');
690 }
691 $this->assign('register_date', $registerDate);
692
693 $this->confirmPostProcess($contactID, $contribution, $payment);
694 }
695
696 //handle if no additional participant.
697 if (!$registerByID) {
698 $registerByID = $this->get('registerByID');
699 }
700
701 $this->set('participantIDs', $this->_participantIDS);
702
703 // create line items, CRM-5313
704 if ($this->_priceSetId &&
705 !empty($this->_lineItem)
706 ) {
707 // take all processed participant ids.
708 $allParticipantIds = $this->_participantIDS;
709
710 // when participant re-walk wizard.
711 if ($this->_allowConfirmation &&
712 !empty($this->_additionalParticipantIds)
713 ) {
714 $allParticipantIds = array_merge(array($registerByID), $this->_additionalParticipantIds);
715 }
716
717 $entityTable = 'civicrm_participant';
aaffa79f 718 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
03b412ae 719 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
79d001a2
PB
720 $totalTaxAmount = 0;
721 $dataArray = array();
6a488035 722 foreach ($this->_lineItem as $key => $value) {
e189cf22 723 if ($value == 'skip') {
724 continue;
725 }
726 if ($entityId = CRM_Utils_Array::value($key, $allParticipantIds)) {
6a488035
TO
727 // do cleanup line items if participant re-walking wizard.
728 if ($this->_allowConfirmation) {
729 CRM_Price_BAO_LineItem::deleteLineItems($entityId, $entityTable);
730 }
731 $lineItem[$this->_priceSetId] = $value;
732 CRM_Price_BAO_LineItem::processPriceSet($entityId, $lineItem, $contribution, $entityTable);
733 }
03b412ae
PB
734 if ($invoicing) {
735 foreach ($value as $line) {
736 if (isset($line['tax_amount']) && isset($line['tax_rate'])) {
737 $totalTaxAmount = $line['tax_amount'] + $totalTaxAmount;
738 if (isset($dataArray[$line['tax_rate']])) {
739 $dataArray[$line['tax_rate']] = $dataArray[$line['tax_rate']] + CRM_Utils_Array::value('tax_amount', $line);
740 }
741 else {
742 $dataArray[$line['tax_rate']] = CRM_Utils_Array::value('tax_amount', $line);
743 }
79d001a2
PB
744 }
745 }
746 }
6a488035 747 }
03b412ae
PB
748 if ($invoicing) {
749 $this->assign('dataArray', $dataArray);
750 $this->assign('totalTaxAmount', $totalTaxAmount);
751 }
6a488035
TO
752 }
753
b44e3f84 754 //update status and send mail to cancelled additional participants, CRM-4320
6a488035
TO
755 if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
756 $cancelledId = array_search('Cancelled',
757 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'")
758 );
759 CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
760 }
761
762 $isTest = FALSE;
763 if ($this->_action & CRM_Core_Action::PREVIEW) {
764 $isTest = TRUE;
765 }
766
767 // for Transfer checkout.
0f2b049e 768 // The concept of contributeMode is deprecated.
6a488035
TO
769 if (($this->_contributeMode == 'checkout' ||
770 $this->_contributeMode == 'notify'
8cc574cf 771 ) && empty($params[0]['is_pay_later']) &&
6a488035
TO
772 !$this->_allowWaitlist && !$this->_requireApproval &&
773 $this->_totalAmount > 0
774 ) {
775
776 $primaryParticipant = $this->get('primaryParticipant');
777
a7488080 778 if (empty($primaryParticipant['participantID'])) {
6a488035
TO
779 $primaryParticipant['participantID'] = $registerByID;
780 }
781
782 //build an array of custom profile and assigning it to template
783 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($registerByID, $this->_values, NULL, $isTest);
784 if (count($customProfile)) {
785 $this->assign('customProfile', $customProfile);
786 $this->set('customProfile', $customProfile);
787 }
788
789 // do a transfer only if a monetary payment greater than 0
790 if ($this->_values['event']['is_monetary'] && $primaryParticipant) {
791 if ($payment && is_object($payment)) {
03665663 792 //CRM 14512 provide line items of all participants to payment gateway
793 $primaryContactId = $this->get('primaryContactId');
fb3b1f9a 794
03665663 795 //build an array of cId/pId of participants
796 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL, $primaryContactId, $isTest, TRUE);
797
798 //need to copy, since we are unsetting on the way.
799 $copyParticipantCountLines = $participantCount;
800
801 //lets carry all participant params w/ values.
802 foreach ($additionalIDs as $participantID => $contactId) {
803 $participantNum = NULL;
804 $participantNum = $participantID;
805 if ($participantID == $registerByID) {
3bdf1f3a 806 // This is the is primary participant.
807 $participantNum = 0;
03665663 808 }
809 else {
810 if ($participantNum = array_search('participant', $copyParticipantCountLines)) {
811 //if no participant found break.
812 if ($participantNum === NULL) {
813 break;
814 }
815 //unset current particpant so we don't check them again
816 unset($copyParticipantCountLines[$participantNum]);
817 }
818 }
819 // get values of line items
820 if ($this->_amount) {
821 $amount = array();
822 $amount[$participantNum]['label'] = preg_replace('/\ 1/', '', $params[$participantNum]['amount_level']);
823 $amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
824 $params[$participantNum]['amounts'] = $amount;
825 }
826
827 if (!empty($this->_lineItem)) {
353ffa53
TO
828 $lineItems = $this->_lineItem;
829 $lineItem = array();
03665663 830 if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
831 $lineItem[] = $lineItemValue;
832 }
833 $params[$participantNum]['lineItem'] = $lineItem;
834 }
835
836 //only add additional particpants and not the primary particpant as we already have that
837 //added to $primaryParticipant so that this change doesn't break or require changes to
838 //existing gateway implementations
839 $primaryParticipant['participants_info'][$participantID] = $params[$participantNum];
840 }
841
842 //get event custom field information
843 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this, $this->_eventId, 0, $this->_values['event']['event_type_id']);
844 $primaryParticipant['eventCustomFields'] = $groupTree;
fb3b1f9a 845
6a488035
TO
846 // call postprocess hook before leaving
847 $this->postProcessHook();
848 // this does not return
248141b9 849 $payment->doPayment($primaryParticipant, 'event');
6a488035
TO
850 }
851 else {
852 CRM_Core_Error::fatal($paymentObjError);
853 }
854 }
855 }
856 else {
857 //otherwise send mail Confirmation/Receipt
858 $primaryContactId = $this->get('primaryContactId');
859
860 //build an array of cId/pId of participants
861 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID,
862 NULL, $primaryContactId, $isTest,
863 TRUE
864 );
865 //lets send mails to all with meaningful text, CRM-4320.
866 $this->assign('isOnWaitlist', $this->_allowWaitlist);
867 $this->assign('isRequireApproval', $this->_requireApproval);
868
869 //need to copy, since we are unsetting on the way.
870 $copyParticipantCount = $participantCount;
871
872 //lets carry all paticipant params w/ values.
873 foreach ($additionalIDs as $participantID => $contactId) {
874 $participantNum = NULL;
875 if ($participantID == $registerByID) {
876 $participantNum = 0;
877 }
878 else {
879 if ($participantNum = array_search('participant', $copyParticipantCount)) {
880 unset($copyParticipantCount[$participantNum]);
881 }
882 }
0479b4c8
TO
883 if ($participantNum === NULL) {
884 break;
885 }
6a488035
TO
886
887 //carry the participant submitted values.
888 $this->_values['params'][$participantID] = $params[$participantNum];
889 }
890
891 foreach ($additionalIDs as $participantID => $contactId) {
892 $participantNum = 0;
893 if ($participantID == $registerByID) {
894 //set as Primary Participant
895 $this->assign('isPrimary', 1);
896 //build an array of custom profile and assigning it to template.
897 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
898
899 if (count($customProfile)) {
900 $this->assign('customProfile', $customProfile);
901 $this->set('customProfile', $customProfile);
902 }
903 $this->_values['params']['additionalParticipant'] = FALSE;
904 }
905 else {
906 //take the Additional participant number.
907 if ($participantNum = array_search('participant', $participantCount)) {
908 unset($participantCount[$participantNum]);
909 }
910 $this->assign('isPrimary', 0);
911 $this->assign('customProfile', NULL);
912 //Additional Participant should get only it's payment information
1909126f 913 if (!empty($this->_amount)) {
6a488035
TO
914 $amount = array();
915 $params = $this->get('params');
916 $amount[$participantNum]['label'] = preg_replace('/\ 1/', '', $params[$participantNum]['amount_level']);
917 $amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
918 $this->assign('amounts', $amount);
919 }
920 if ($this->_lineItem) {
353ffa53
TO
921 $lineItems = $this->_lineItem;
922 $lineItem = array();
6a488035
TO
923 if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
924 $lineItem[] = $lineItemValue;
925 }
75b065ce 926 if ($invoicing) {
927 $individual = $this->get('individual');
928 $dataArray[key($dataArray)] = $individual[$participantNum]['totalTaxAmt'];
929 $this->assign('dataArray', $dataArray);
930 $this->assign('totalAmount', $individual[$participantNum]['totalAmtWithTax']);
931 $this->assign('totalTaxAmount', $individual[$participantNum]['totalTaxAmt']);
932 $this->assign('individual', array($individual[$participantNum]));
933 }
6a488035
TO
934 $this->assign('lineItem', $lineItem);
935 }
936 $this->_values['params']['additionalParticipant'] = TRUE;
7d92d486 937 $this->assign('isAdditionalParticipant', $this->_values['params']['additionalParticipant']);
6a488035
TO
938 }
939
940 //pass these variables since these are run time calculated.
941 $this->_values['params']['isOnWaitlist'] = $this->_allowWaitlist;
942 $this->_values['params']['isRequireApproval'] = $this->_requireApproval;
943
944 //send mail to primary as well as additional participants.
945 $this->assign('contactID', $contactId);
946 $this->assign('participantID', $participantID);
947 CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
948 }
949 }
950 }
6a488035
TO
951
952 /**
66f9e52b 953 * Process the contribution.
6a488035 954 *
c490a46a
CW
955 * @param CRM_Core_Form $form
956 * @param array $params
3bdf1f3a 957 * @param array $result
100fef9d 958 * @param int $contactID
dd244018
EM
959 * @param bool $pending
960 * @param bool $isAdditionalAmount
961 *
3bdf1f3a 962 * @return \CRM_Contribute_BAO_Contribution
6a488035 963 */
317fceb4 964 public static function processContribution(
ddca8f33 965 &$form, $params, $result, $contactID,
6a488035
TO
966 $pending = FALSE, $isAdditionalAmount = FALSE
967 ) {
968 $transaction = new CRM_Core_Transaction();
969
353ffa53 970 $now = date('YmdHis');
6a488035
TO
971 $receiptDate = NULL;
972
bf2c70af 973 if (!empty($form->_values['event']['is_email_confirm'])) {
6a488035
TO
974 $receiptDate = $now;
975 }
976 //CRM-4196
977 if ($isAdditionalAmount) {
978 $params['amount_level'] = $params['amount_level'] . ts(' (multiple participants)') . CRM_Core_DAO::VALUE_SEPARATOR;
979 }
980
981 $contribParams = array(
982 'contact_id' => $contactID,
353ffa53 983 'financial_type_id' => !empty($form->_values['event']['financial_type_id']) ? $form->_values['event']['financial_type_id'] : $params['financial_type_id'],
6a488035
TO
984 'receive_date' => $now,
985 'total_amount' => $params['amount'],
d91b8b33 986 'tax_amount' => $params['tax_amount'],
6a488035
TO
987 'amount_level' => $params['amount_level'],
988 'invoice_id' => $params['invoiceID'],
989 'currency' => $params['currencyID'],
13bb29e4 990 'source' => !empty($params['participant_source']) ? $params['participant_source'] : $params['description'],
6a488035
TO
991 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
992 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
993 );
994
a7488080 995 if (empty($params['is_pay_later'])) {
6a488035
TO
996 $contribParams['payment_instrument_id'] = 1;
997 }
998
999 if (!$pending && $result) {
1000 $contribParams += array(
1001 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
1002 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']),
1003 'trxn_id' => $result['trxn_id'],
1004 'receipt_date' => $receiptDate,
1005 );
1006 }
1007
1008 $allStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1009 $contribParams['contribution_status_id'] = array_search('Completed', $allStatuses);
1010 if ($pending) {
1011 $contribParams['contribution_status_id'] = array_search('Pending', $allStatuses);
1012 }
1013
1014 $contribParams['is_test'] = 0;
1015 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
1016 $contribParams['is_test'] = 1;
1017 }
1018
1019 $contribID = NULL;
a7488080 1020 if (!empty($contribParams['invoice_id'])) {
6a488035
TO
1021 $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1022 $contribParams['invoice_id'],
1023 'id',
1024 'invoice_id'
1025 );
1026 }
1027
1028 $ids = array();
1029 if ($contribID) {
1030 $ids['contribution'] = $contribID;
1031 $contribParams['id'] = $contribID;
1032 }
1033
1034 //create an contribution address
0f2b049e 1035 // The concept of contributeMode is deprecated. Elsewhere we use the function processBillingAddress() - although
1036 // currently that is only inherited by back-office forms.
8cc574cf 1037 if ($form->_contributeMode != 'notify' && empty($params['is_pay_later'])) {
6a488035
TO
1038 $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
1039 }
1040
6a488035
TO
1041 $contribParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $params);
1042 $contribParams['skipLineItem'] = 1;
1043 // create contribution record
1044 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
1045 // CRM-11124
b03a5fb5 1046 CRM_Event_BAO_Participant::createDiscountTrxn($form->_eventId, $contribParams, CRM_Utils_Array::value('amount_priceset_level_radio', $params, NULL));
6a488035
TO
1047
1048 // process soft credit / pcp pages
7a13735b 1049 if (!empty($params['pcp_made_through_id'])) {
1050 CRM_Contribute_Form_Contribution_Confirm::formatSoftCreditParams($params, $form);
1051 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
1052 }
6a488035
TO
1053
1054 $transaction->commit();
1055
1056 return $contribution;
1057 }
1058
1059 /**
66f9e52b 1060 * Fix the Location Fields.
6a488035 1061 *
c490a46a 1062 * @param array $params
3bdf1f3a 1063 * @param array $fields
c490a46a 1064 * @param CRM_Core_Form $form
6a488035 1065 */
4fb756af 1066 public static function fixLocationFields(&$params, &$fields, &$form) {
a9f7d48b
AS
1067 if (!empty($form->_fields)) {
1068 foreach ($form->_fields as $name => $dontCare) {
6a488035
TO
1069 $fields[$name] = 1;
1070 }
1071 }
1072
1073 if (is_array($fields)) {
1074 if (!array_key_exists('first_name', $fields)) {
1075 $nameFields = array('first_name', 'middle_name', 'last_name');
1076 foreach ($nameFields as $name) {
1077 $fields[$name] = 1;
1078 if (array_key_exists("billing_$name", $params)) {
1079 $params[$name] = $params["billing_{$name}"];
1080 $params['preserveDBName'] = TRUE;
1081 }
1082 }
1083 }
1084 }
1085
1086 // also add location name to the array
a9f7d48b
AS
1087 if ($form->_values['event']['is_monetary']) {
1088 $params["address_name-{$form->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
1089 $fields["address_name-{$form->_bltID}"] = 1;
6a488035 1090 }
a9f7d48b 1091 $fields["email-{$form->_bltID}"] = 1;
6a488035
TO
1092 $fields['email-Primary'] = 1;
1093
1094 //if its pay later or additional participant set email address as primary.
8cc574cf 1095 if ((!empty($params['is_pay_later']) || empty($params['is_primary']) ||
a9f7d48b
AS
1096 !$form->_values['event']['is_monetary'] ||
1097 $form->_allowWaitlist ||
1098 $form->_requireApproval
353ffa53
TO
1099 ) && !empty($params["email-{$form->_bltID}"])
1100 ) {
a9f7d48b 1101 $params['email-Primary'] = $params["email-{$form->_bltID}"];
6a488035
TO
1102 }
1103 }
1104
1105 /**
66f9e52b 1106 * Update contact fields.
6a488035 1107 *
100fef9d 1108 * @param int $contactID
c490a46a 1109 * @param array $params
3bdf1f3a 1110 * @param array $fields
c490a46a 1111 * @param CRM_Core_Form $form
dd244018 1112 *
3bdf1f3a 1113 * @return int
6a488035 1114 */
4fb756af 1115 public static function updateContactFields($contactID, $params, $fields, &$form) {
6a488035
TO
1116 //add the contact to group, if add to group is selected for a
1117 //particular uf group
1118
1119 // get the add to groups
1120 $addToGroups = array();
1121
a9f7d48b
AS
1122 if (!empty($form->_fields)) {
1123 foreach ($form->_fields as $key => $value) {
a7488080 1124 if (!empty($value['add_to_group_id'])) {
6a488035
TO
1125 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
1126 }
1127 }
1128 }
1129
1130 // check for profile double opt-in and get groups to be subscribed
1131 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
1132
1133 foreach ($addToGroups as $k) {
1134 if (array_key_exists($k, $subscribeGroupIds)) {
1135 unset($addToGroups[$k]);
1136 }
1137 }
1138
1139 // since we are directly adding contact to group lets unset it from mailing
1140 if (!empty($addToGroups)) {
1141 foreach ($addToGroups as $groupId) {
1142 if (isset($subscribeGroupIds[$groupId])) {
1143 unset($subscribeGroupIds[$groupId]);
1144 }
1145 }
1146 }
1147 if ($contactID) {
1148 $ctype = CRM_Core_DAO::getFieldValue(
1149 'CRM_Contact_DAO_Contact',
1150 $contactID,
1151 'contact_type'
1152 );
e1ce628e 1153
22e263ad 1154 if (array_key_exists('contact_id', $params) && empty($params['contact_id'])) {
e1ce628e 1155 // we unset this here because the downstream function ignores the contactID we give it
1156 // if it is set & it is difficult to understand the implications of 'fixing' this downstream
1157 // but if we are passing a contact id into this function it's reasonable to assume we don't
1158 // want it ignored
1159 unset($params['contact_id']);
1160 }
1161
6a488035
TO
1162 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
1163 $params,
1164 $fields,
1165 $contactID,
1166 $addToGroups,
1167 NULL,
1168 $ctype,
1169 TRUE
1170 );
1171 }
1172 else {
1173
1174 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1175 if (!isset($params[$greeting . '_id'])) {
1176 $params[$greeting . '_id'] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
1177 }
1178 }
1179
1180 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params,
1181 $fields,
1182 NULL,
1183 $addToGroups,
1184 NULL,
1185 NULL,
1186 TRUE
1187 );
a9f7d48b 1188 $form->set('contactID', $contactID);
6a488035
TO
1189 }
1190
1191 //get email primary first if exist
1192 $subscribtionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
1193 if (!$subscribtionEmail['email']) {
a9f7d48b 1194 $subscribtionEmail['email'] = CRM_Utils_Array::value("email-{$form->_bltID}", $params);
6a488035
TO
1195 }
1196 // subscribing contact to groups
1197 if (!empty($subscribeGroupIds) && $subscribtionEmail['email']) {
1198 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscribtionEmail, $contactID);
1199 }
1200
1201 return $contactID;
1202 }
5bdcb00b 1203
0cf587a7 1204 /**
3bdf1f3a 1205 * Assign Profiles.
1206 *
1207 * @param CRM_Core_Form $form
0cf587a7 1208 */
5bdcb00b 1209 public static function assignProfiles(&$form) {
5bdcb00b
PJ
1210 $participantParams = $form->_params;
1211 $formattedValues = $profileFields = array();
353ffa53 1212 $count = 1;
5bdcb00b
PJ
1213 foreach ($participantParams as $participantNum => $participantValue) {
1214 if ($participantNum) {
0479b4c8
TO
1215 $prefix1 = 'additional';
1216 $prefix2 = 'additional_';
0db6c3e1
TO
1217 }
1218 else {
0479b4c8
TO
1219 $prefix1 = '';
1220 $prefix2 = '';
5bdcb00b
PJ
1221 }
1222 if ($participantValue != 'skip') {
1223 //get the customPre profile info
1224 if (!empty($form->_values[$prefix2 . 'custom_pre_id'])) {
1225 $values = $groupName = array();
1226 CRM_Event_BAO_Event::displayProfile($participantValue,
0479b4c8 1227 $form->_values[$prefix2 . 'custom_pre_id'],
5bdcb00b
PJ
1228 $groupName,
1229 $values,
1230 $profileFields
1231 );
1232
1233 if (count($values)) {
1234 $formattedValues[$count][$prefix1 . 'CustomPre'] = $values;
1235 }
1236 $formattedValues[$count][$prefix1 . 'CustomPreGroupTitle'] = CRM_Utils_Array::value('groupTitle', $groupName);
1237 }
1238 //get the customPost profile info
1239 if (!empty($form->_values[$prefix2 . 'custom_post_id'])) {
1240 $values = $groupName = array();
1241 foreach ($form->_values[$prefix2 . 'custom_post_id'] as $gids) {
1242 $val = array();
1243 CRM_Event_BAO_Event::displayProfile($participantValue,
1244 $gids,
1245 $group,
1246 $val,
1247 $profileFields
1248 );
1249 $values[$gids] = $val;
1250 $groupName[$gids] = $group;
1251 }
1252
1253 if (count($values)) {
1254 $formattedValues[$count][$prefix1 . 'CustomPost'] = $values;
1255 }
1256
1257 if (isset($formattedValues[$count][$prefix1 . 'CustomPre'])) {
1258 $formattedValues[$count][$prefix1 . 'CustomPost'] = array_diff_assoc($formattedValues[$count][$prefix1 . 'CustomPost'],
1259 $formattedValues[$count][$prefix1 . 'CustomPre']
1260 );
1261 }
1262
1263 $formattedValues[$count][$prefix1 . 'CustomPostGroupTitle'] = $groupName;
1264 }
1265 $count++;
1266 }
1267 $form->_fields = $profileFields;
1268 }
481a74f4 1269 if (!empty($formattedValues)) {
5bdcb00b 1270 $form->assign('primaryParticipantProfile', $formattedValues[1]);
0479b4c8 1271 $form->set('primaryParticipantProfile', $formattedValues[1]);
5bdcb00b
PJ
1272 if ($count > 2) {
1273 unset($formattedValues[1]);
1274 $form->assign('addParticipantProfile', $formattedValues);
0479b4c8 1275 $form->set('addParticipantProfile', $formattedValues);
5bdcb00b
PJ
1276 }
1277 }
1278 }
96025800 1279
6a488035 1280}