CRM-18701 minor, tangental tidy up
[civicrm-core.git] / CRM / Event / Form / Registration / Confirm.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
fa938177 30 * @copyright CiviCRM LLC (c) 2004-2016
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
229159bf
CW
307 $contribButton = ts('Continue');
308 $this->addButtons(array(
309 array(
310 'type' => 'back',
311 'name' => ts('Go Back'),
312 ),
313 array(
314 'type' => 'next',
315 'name' => $contribButton,
316 'isDefault' => TRUE,
317 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
318 ),
319 )
320 );
6a488035
TO
321
322 $defaults = array();
323 $fields = array();
324 if (!empty($this->_fields)) {
325 foreach ($this->_fields as $name => $dontCare) {
326 $fields[$name] = 1;
327 }
328 }
329 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
330 foreach ($fields as $name => $dontCare) {
331 if (isset($this->_params[0][$name])) {
332 $defaults[$name] = $this->_params[0][$name];
333 if (substr($name, 0, 7) == 'custom_') {
334 $timeField = "{$name}_time";
335 if (isset($this->_params[0][$timeField])) {
336 $defaults[$timeField] = $this->_params[0][$timeField];
337 }
338 if (isset($this->_params[0]["{$name}_id"])) {
339 $defaults["{$name}_id"] = $this->_params[0]["{$name}_id"];
340 }
341 }
342 elseif (in_array($name, CRM_Contact_BAO_Contact::$_greetingTypes)
343 && !empty($this->_params[0][$name . '_custom'])
344 ) {
345 $defaults[$name . '_custom'] = $this->_params[0][$name . '_custom'];
346 }
347 }
348 }
349
6a488035
TO
350 $this->setDefaults($defaults);
351 $this->freeze();
352
353 //lets give meaningful status message, CRM-4320.
354 $this->assign('isOnWaitlist', $this->_allowWaitlist);
355 $this->assign('isRequireApproval', $this->_requireApproval);
356
357 // Assign Participant Count to Lineitem Table
9da8dc8c 358 $this->assign('pricesetFieldsCount', CRM_Price_BAO_PriceSet::getPricesetCount($this->_priceSetId));
79b152ac 359 $this->addFormRule(array('CRM_Event_Form_Registration_Confirm', 'formRule'), $this);
6a488035
TO
360 }
361
ca87146b 362 /**
3bdf1f3a 363 * Apply form rule.
364 *
365 * @param array $fields
366 * @param array $files
367 * @param CRM_Core_Form $self
ca87146b
EM
368 *
369 * @return array|bool
370 */
00be9182 371 public static function formRule($fields, $files, $self) {
79b152ac 372 $errors = array();
373 $eventFull = CRM_Event_BAO_Participant::eventFull($self->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $self->_values['event']));
374 if ($eventFull && empty($self->_allowConfirmation)) {
375 if (empty($self->_allowWaitlist)) {
0479b4c8 376 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "reset=1&id={$self->_eventId}", FALSE, NULL, FALSE, TRUE));
79b152ac 377 }
378 }
379 $self->_feeBlock = $self->_values['fee'];
380 CRM_Event_Form_Registration_Register::formatFieldsForOptionFull($self);
381
0dc0b759 382 if (!empty($self->_priceSetId) &&
383 !$self->_requireApproval && !$self->_allowWaitlist
384 ) {
79b152ac 385 $priceSetErrors = self::validatePriceSet($self, $self->_params);
0dc0b759 386 if (!empty($priceSetErrors)) {
2ae4d103 387 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 388 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');
389 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "_qf_Register_display=true&qfKey={$fields['qfKey']}"));
390 }
79b152ac 391 }
392
0dc0b759 393 return empty($priceSetErrors) ? TRUE : $priceSetErrors;
79b152ac 394 }
353ffa53 395
6a488035 396 /**
66f9e52b 397 * Process the form submission.
6a488035
TO
398 */
399 public function postProcess() {
353ffa53 400 $now = date('YmdHis');
af72b8c7 401
6a488035 402 $this->_params = $this->get('params');
a7488080 403 if (!empty($this->_params[0]['contact_id'])) {
e1ce628e 404 // unclear when this would be set & whether it could be checked in getContactID.
405 // perhaps it relates to when cid is in the url
406 //@todo someone who knows add comments on the various contactIDs in this form
6a488035
TO
407 $contactID = $this->_params[0]['contact_id'];
408 }
409 else {
5c280496 410 $contactID = $this->getContactID();
6a488035
TO
411 }
412
413 // if a discount has been applied, lets now deduct it from the amount
414 // and fix the fee level
8cc574cf 415 if (!empty($this->_params[0]['discount']) && !empty($this->_params[0]['discount']['applied'])) {
6a488035 416 foreach ($this->_params as $k => $v) {
8cc574cf 417 if (CRM_Utils_Array::value('amount', $this->_params[$k]) > 0 && !empty($this->_params[$k]['discountAmount'])) {
6a488035
TO
418 $this->_params[$k]['amount'] -= $this->_params[$k]['discountAmount'];
419 $this->_params[$k]['amount_level'] .= CRM_Utils_Array::value('discountMessage', $this->_params[$k]);
420 }
421 }
422 $this->set('params', $this->_params);
423 }
424
425 // CRM-4320, lets build array of cancelled additional participant ids
426 // those are drop or skip by primary at the time of confirmation.
427 // get all in and then unset those we want to process.
428 $cancelledIds = $this->_additionalParticipantIds;
429
430 $params = $this->_params;
1909126f 431 if ($this->_values['event']['is_monetary']) {
432 $this->set('finalAmount', $this->_amount);
433 }
6a488035
TO
434 $participantCount = array();
435
436 //unset the skip participant from params.
437 //build the $participantCount array.
438 //maintain record for all participants.
439 foreach ($params as $participantNum => $record) {
440 if ($record == 'skip') {
441 unset($params[$participantNum]);
442 $participantCount[$participantNum] = 'skip';
443 }
444 elseif ($participantNum) {
445 $participantCount[$participantNum] = 'participant';
446 }
447
448 //lets get additional participant id to cancel.
449 if ($this->_allowConfirmation && is_array($cancelledIds)) {
450 $additonalId = CRM_Utils_Array::value('participant_id', $record);
451 if ($additonalId && $key = array_search($additonalId, $cancelledIds)) {
452 unset($cancelledIds[$key]);
453 }
454 }
455 }
456
457 $payment = $registerByID = $primaryCurrencyID = $contribution = NULL;
458 $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.');
459
460 $this->participantIDS = array();
461 $fields = array();
462 foreach ($params as $key => $value) {
a9f7d48b 463 CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields, $this);
6a488035
TO
464 //unset the billing parameters if it is pay later mode
465 //to avoid creation of billing location
0b05b9a9 466 // @todo - the reasoning for this is unclear - elsewhere we check what fields are provided by
467 // the form & if billing fields exist we create the address, relying on the form to collect
468 // only information we intend to store.
8ae4d0d3 469 if ($this->_allowWaitlist
470 || $this->_requireApproval
471 || (!empty($value['is_pay_later']) && !$this->_isBillingAddressRequiredForPayLater)
472 || empty($value['is_primary'])
473 ) {
6a488035
TO
474 $billingFields = array(
475 "email-{$this->_bltID}",
476 'billing_first_name',
477 'billing_middle_name',
478 'billing_last_name',
479 "billing_street_address-{$this->_bltID}",
480 "billing_city-{$this->_bltID}",
481 "billing_state_province-{$this->_bltID}",
482 "billing_state_province_id-{$this->_bltID}",
483 "billing_postal_code-{$this->_bltID}",
484 "billing_country-{$this->_bltID}",
485 "billing_country_id-{$this->_bltID}",
486 "address_name-{$this->_bltID}",
487 );
488 foreach ($billingFields as $field) {
489 unset($value[$field]);
490 }
a7488080 491 if (!empty($value['is_pay_later'])) {
6a488035
TO
492 $this->_values['params']['is_pay_later'] = TRUE;
493 }
494 }
495
496 //Unset ContactID for additional participants and set RegisterBy Id.
a7488080 497 if (empty($value['is_primary'])) {
6a488035
TO
498 $contactID = CRM_Utils_Array::value('contact_id', $value);
499 $registerByID = $this->get('registerByID');
500 if ($registerByID) {
501 $value['registered_by_id'] = $registerByID;
502 }
503 }
504 else {
505 $value['amount'] = $this->_totalAmount;
506 }
507
a9f7d48b 508 $contactID = CRM_Event_Form_Registration_Confirm::updateContactFields($contactID, $value, $fields, $this);
6a488035
TO
509
510 // lets store the contactID in the session
511 // we dont store in userID in case the user is doing multiple
512 // transactions etc
513 // for things like tell a friend
8cc574cf 514 if (!$this->getContactID() && !empty($value['is_primary'])) {
af72b8c7 515 $session = CRM_Core_Session::singleton();
6a488035
TO
516 $session->set('transaction.userID', $contactID);
517 }
518
519 $value['description'] = ts('Online Event Registration') . ': ' . $this->_values['event']['title'];
520 $value['accountingCode'] = CRM_Utils_Array::value('accountingCode',
521 $this->_values['event']
522 );
523
752f450d 524 $pending = FALSE;
67c8322d
J
525 if ($this->_allowWaitlist || $this->_requireApproval) {
526 //get the participant statuses.
527 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
528 if ($this->_allowWaitlist) {
529 $value['participant_status_id'] = $value['participant_status'] = array_search('On waitlist', $waitingStatuses);
530 }
531 else {
532 $value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
533 }
534
535 //there might be case user seleted pay later and
536 //now becomes part of run time waiting list.
537 $value['is_pay_later'] = FALSE;
538 }
539
6a488035 540 // required only if paid event
67c8322d 541 if ($this->_values['event']['is_monetary'] && !($this->_allowWaitlist || $this->_requireApproval)) {
6a488035 542 if (is_array($this->_paymentProcessor)) {
077017db 543 $payment = $this->_paymentProcessor['object'];
6a488035 544 }
ec022878 545 if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) {
546 $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
547 $value = array_merge($value, $preApprovalParams);
548 }
6a488035
TO
549 $result = NULL;
550
67c8322d 551 if (!empty($value['is_pay_later']) ||
6a488035 552 $value['amount'] == 0 ||
0f2b049e 553 // The concept of contributeMode is deprecated.
6a488035
TO
554 $this->_contributeMode == 'checkout' ||
555 $this->_contributeMode == 'notify'
556 ) {
557 if ($value['amount'] != 0) {
558 $pending = TRUE;
559 //get the participant statuses.
560 $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'");
0d8afee2 561 $status = !empty($value['is_pay_later']) ? 'Pending from pay later' : 'Pending from incomplete transaction';
6a488035
TO
562 $value['participant_status_id'] = $value['participant_status'] = array_search($status, $pendingStatuses);
563 }
564 }
a7488080 565 elseif (!empty($value['is_primary'])) {
6a488035 566 CRM_Core_Payment_Form::mapParams($this->_bltID, $value, $value, TRUE);
bd7b39e7
PJ
567 // payment email param can be empty for _bltID mapping
568 // thus provide mapping for it with a different email value
569 if (empty($value['email'])) {
570 $value['email'] = CRM_Utils_Array::valueByRegexKey('/^email-/', $value);
571 }
572
6a488035 573 if (is_object($payment)) {
248141b9
EM
574 try {
575 $result = $payment->doPayment($value);
576 $value = array_merge($value, $result);
577 }
578 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
069ad5a0 579 CRM_Core_Session::singleton()->setStatus($e->getMessage());
248141b9
EM
580 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "id={$this->_eventId}"));
581 }
6a488035
TO
582 }
583 else {
584 CRM_Core_Error::fatal($paymentObjError);
585 }
586 }
587
6a488035
TO
588 $value['receive_date'] = $now;
589 if ($this->_allowConfirmation) {
590 $value['participant_register_date'] = $this->_values['participant']['register_date'];
591 }
592
593 $createContrib = ($value['amount'] != 0) ? TRUE : FALSE;
594 // force to create zero amount contribution, CRM-5095
595 if (!$createContrib && ($value['amount'] == 0)
596 && $this->_priceSetId && $this->_lineItem
597 ) {
598 $createContrib = TRUE;
599 }
600
8cc574cf 601 if ($createContrib && !empty($value['is_primary']) &&
6a488035
TO
602 !$this->_allowWaitlist && !$this->_requireApproval
603 ) {
604 // if paid event add a contribution record
605 //if primary participant contributing additional amount
606 //append (multiple participants) to its fee level. CRM-4196.
607 $isAdditionalAmount = FALSE;
608 if (count($params) > 1) {
609 $isAdditionalAmount = TRUE;
610 }
611
612 //passing contribution id is already registered.
317fceb4 613 $contribution = self::processContribution($this, $value, $result, $contactID, $pending, $isAdditionalAmount);
6a488035
TO
614 $value['contributionID'] = $contribution->id;
615 $value['contributionTypeID'] = $contribution->financial_type_id;
616 $value['receive_date'] = $contribution->receive_date;
617 $value['trxn_id'] = $contribution->trxn_id;
618 $value['contributionID'] = $contribution->id;
619 $value['contributionTypeID'] = $contribution->financial_type_id;
620 }
621 $value['contactID'] = $contactID;
353ffa53 622 $value['eventID'] = $this->_eventId;
6a488035
TO
623 $value['item_name'] = $value['description'];
624 }
9a32a8fc
GC
625
626 if (!empty($value['contributionID'])) {
627 $this->_values['contributionId'] = $value['contributionID'];
628 }
6a488035
TO
629
630 //CRM-4453.
a7488080 631 if (!empty($value['is_primary'])) {
6a488035
TO
632 $primaryCurrencyID = CRM_Utils_Array::value('currencyID', $value);
633 }
a7488080 634 if (empty($value['currencyID'])) {
6a488035
TO
635 $value['currencyID'] = $primaryCurrencyID;
636 }
637
1909126f 638 // CRM-11182 - Confirmation page might not be monetary
639 if ($this->_values['event']['is_monetary']) {
640 if (!$pending && !empty($value['is_primary']) &&
641 !$this->_allowWaitlist && !$this->_requireApproval
642 ) {
643 // transactionID & receive date required while building email template
644 $this->assign('trxn_id', $value['trxn_id']);
645 $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($value['receive_date']));
646 $this->set('receiveDate', CRM_Utils_Date::mysqlToIso($value['receive_date']));
647 $this->set('trxnId', CRM_Utils_Array::value('trxn_id', $value));
648 }
6a488035 649 }
f55dc004 650
ffcec972 651 $value['fee_amount'] = CRM_Utils_Array::value('amount', $value);
6a488035
TO
652 $this->set('value', $value);
653
654 // handle register date CRM-4320
655 if ($this->_allowConfirmation) {
481a74f4 656 $registerDate = CRM_Utils_Array::value('participant_register_date', $params);
6a488035 657 }
a7488080 658 elseif (!empty($params['participant_register_date']) &&
6a488035
TO
659 is_array($params['participant_register_date']) &&
660 !empty($params['participant_register_date'])
661 ) {
662 $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
663 }
664 else {
665 $registerDate = date('YmdHis');
666 }
667 $this->assign('register_date', $registerDate);
668
669 $this->confirmPostProcess($contactID, $contribution, $payment);
670 }
671
672 //handle if no additional participant.
673 if (!$registerByID) {
674 $registerByID = $this->get('registerByID');
675 }
676
677 $this->set('participantIDs', $this->_participantIDS);
678
679 // create line items, CRM-5313
680 if ($this->_priceSetId &&
681 !empty($this->_lineItem)
682 ) {
683 // take all processed participant ids.
684 $allParticipantIds = $this->_participantIDS;
685
686 // when participant re-walk wizard.
687 if ($this->_allowConfirmation &&
688 !empty($this->_additionalParticipantIds)
689 ) {
690 $allParticipantIds = array_merge(array($registerByID), $this->_additionalParticipantIds);
691 }
692
693 $entityTable = 'civicrm_participant';
aaffa79f 694 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
03b412ae 695 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
79d001a2
PB
696 $totalTaxAmount = 0;
697 $dataArray = array();
6a488035 698 foreach ($this->_lineItem as $key => $value) {
e189cf22 699 if ($value == 'skip') {
700 continue;
701 }
702 if ($entityId = CRM_Utils_Array::value($key, $allParticipantIds)) {
6a488035
TO
703 // do cleanup line items if participant re-walking wizard.
704 if ($this->_allowConfirmation) {
705 CRM_Price_BAO_LineItem::deleteLineItems($entityId, $entityTable);
706 }
707 $lineItem[$this->_priceSetId] = $value;
708 CRM_Price_BAO_LineItem::processPriceSet($entityId, $lineItem, $contribution, $entityTable);
709 }
03b412ae
PB
710 if ($invoicing) {
711 foreach ($value as $line) {
712 if (isset($line['tax_amount']) && isset($line['tax_rate'])) {
713 $totalTaxAmount = $line['tax_amount'] + $totalTaxAmount;
714 if (isset($dataArray[$line['tax_rate']])) {
715 $dataArray[$line['tax_rate']] = $dataArray[$line['tax_rate']] + CRM_Utils_Array::value('tax_amount', $line);
716 }
717 else {
718 $dataArray[$line['tax_rate']] = CRM_Utils_Array::value('tax_amount', $line);
719 }
79d001a2
PB
720 }
721 }
722 }
6a488035 723 }
03b412ae
PB
724 if ($invoicing) {
725 $this->assign('dataArray', $dataArray);
726 $this->assign('totalTaxAmount', $totalTaxAmount);
727 }
6a488035
TO
728 }
729
b44e3f84 730 //update status and send mail to cancelled additional participants, CRM-4320
6a488035
TO
731 if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
732 $cancelledId = array_search('Cancelled',
733 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'")
734 );
735 CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
736 }
737
738 $isTest = FALSE;
739 if ($this->_action & CRM_Core_Action::PREVIEW) {
740 $isTest = TRUE;
741 }
742
743 // for Transfer checkout.
0f2b049e 744 // The concept of contributeMode is deprecated.
6a488035
TO
745 if (($this->_contributeMode == 'checkout' ||
746 $this->_contributeMode == 'notify'
8cc574cf 747 ) && empty($params[0]['is_pay_later']) &&
6a488035
TO
748 !$this->_allowWaitlist && !$this->_requireApproval &&
749 $this->_totalAmount > 0
750 ) {
751
752 $primaryParticipant = $this->get('primaryParticipant');
753
a7488080 754 if (empty($primaryParticipant['participantID'])) {
6a488035
TO
755 $primaryParticipant['participantID'] = $registerByID;
756 }
757
758 //build an array of custom profile and assigning it to template
759 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($registerByID, $this->_values, NULL, $isTest);
760 if (count($customProfile)) {
761 $this->assign('customProfile', $customProfile);
762 $this->set('customProfile', $customProfile);
763 }
764
765 // do a transfer only if a monetary payment greater than 0
766 if ($this->_values['event']['is_monetary'] && $primaryParticipant) {
767 if ($payment && is_object($payment)) {
03665663 768 //CRM 14512 provide line items of all participants to payment gateway
769 $primaryContactId = $this->get('primaryContactId');
fb3b1f9a 770
03665663 771 //build an array of cId/pId of participants
772 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL, $primaryContactId, $isTest, TRUE);
773
774 //need to copy, since we are unsetting on the way.
775 $copyParticipantCountLines = $participantCount;
776
777 //lets carry all participant params w/ values.
778 foreach ($additionalIDs as $participantID => $contactId) {
779 $participantNum = NULL;
780 $participantNum = $participantID;
781 if ($participantID == $registerByID) {
3bdf1f3a 782 // This is the is primary participant.
783 $participantNum = 0;
03665663 784 }
785 else {
786 if ($participantNum = array_search('participant', $copyParticipantCountLines)) {
787 //if no participant found break.
788 if ($participantNum === NULL) {
789 break;
790 }
791 //unset current particpant so we don't check them again
792 unset($copyParticipantCountLines[$participantNum]);
793 }
794 }
795 // get values of line items
796 if ($this->_amount) {
797 $amount = array();
798 $amount[$participantNum]['label'] = preg_replace('/\ 1/', '', $params[$participantNum]['amount_level']);
799 $amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
800 $params[$participantNum]['amounts'] = $amount;
801 }
802
803 if (!empty($this->_lineItem)) {
353ffa53
TO
804 $lineItems = $this->_lineItem;
805 $lineItem = array();
03665663 806 if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
807 $lineItem[] = $lineItemValue;
808 }
809 $params[$participantNum]['lineItem'] = $lineItem;
810 }
811
812 //only add additional particpants and not the primary particpant as we already have that
813 //added to $primaryParticipant so that this change doesn't break or require changes to
814 //existing gateway implementations
815 $primaryParticipant['participants_info'][$participantID] = $params[$participantNum];
816 }
817
818 //get event custom field information
819 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this, $this->_eventId, 0, $this->_values['event']['event_type_id']);
820 $primaryParticipant['eventCustomFields'] = $groupTree;
fb3b1f9a 821
6a488035
TO
822 // call postprocess hook before leaving
823 $this->postProcessHook();
824 // this does not return
248141b9 825 $payment->doPayment($primaryParticipant, 'event');
6a488035
TO
826 }
827 else {
828 CRM_Core_Error::fatal($paymentObjError);
829 }
830 }
831 }
832 else {
833 //otherwise send mail Confirmation/Receipt
834 $primaryContactId = $this->get('primaryContactId');
835
836 //build an array of cId/pId of participants
837 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID,
838 NULL, $primaryContactId, $isTest,
839 TRUE
840 );
841 //lets send mails to all with meaningful text, CRM-4320.
842 $this->assign('isOnWaitlist', $this->_allowWaitlist);
843 $this->assign('isRequireApproval', $this->_requireApproval);
844
845 //need to copy, since we are unsetting on the way.
846 $copyParticipantCount = $participantCount;
847
848 //lets carry all paticipant params w/ values.
849 foreach ($additionalIDs as $participantID => $contactId) {
850 $participantNum = NULL;
851 if ($participantID == $registerByID) {
852 $participantNum = 0;
853 }
854 else {
855 if ($participantNum = array_search('participant', $copyParticipantCount)) {
856 unset($copyParticipantCount[$participantNum]);
857 }
858 }
0479b4c8
TO
859 if ($participantNum === NULL) {
860 break;
861 }
6a488035
TO
862
863 //carry the participant submitted values.
864 $this->_values['params'][$participantID] = $params[$participantNum];
865 }
866
867 foreach ($additionalIDs as $participantID => $contactId) {
868 $participantNum = 0;
869 if ($participantID == $registerByID) {
870 //set as Primary Participant
871 $this->assign('isPrimary', 1);
872 //build an array of custom profile and assigning it to template.
873 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
874
875 if (count($customProfile)) {
876 $this->assign('customProfile', $customProfile);
877 $this->set('customProfile', $customProfile);
878 }
879 $this->_values['params']['additionalParticipant'] = FALSE;
880 }
881 else {
882 //take the Additional participant number.
883 if ($participantNum = array_search('participant', $participantCount)) {
884 unset($participantCount[$participantNum]);
885 }
4abc4ee1 886 // Change $this->_values['participant'] to include additional participant values
887 $ids = $participantValues = array();
888 $participantParams = array('id' => $participantID);
889 CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
890 $this->_values['participant'] = $participantValues[$participantID];
891
6a488035
TO
892 $this->assign('isPrimary', 0);
893 $this->assign('customProfile', NULL);
894 //Additional Participant should get only it's payment information
1909126f 895 if (!empty($this->_amount)) {
6a488035
TO
896 $amount = array();
897 $params = $this->get('params');
898 $amount[$participantNum]['label'] = preg_replace('/\ 1/', '', $params[$participantNum]['amount_level']);
899 $amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
900 $this->assign('amounts', $amount);
901 }
902 if ($this->_lineItem) {
353ffa53
TO
903 $lineItems = $this->_lineItem;
904 $lineItem = array();
6a488035
TO
905 if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
906 $lineItem[] = $lineItemValue;
907 }
75b065ce 908 if ($invoicing) {
909 $individual = $this->get('individual');
910 $dataArray[key($dataArray)] = $individual[$participantNum]['totalTaxAmt'];
911 $this->assign('dataArray', $dataArray);
912 $this->assign('totalAmount', $individual[$participantNum]['totalAmtWithTax']);
913 $this->assign('totalTaxAmount', $individual[$participantNum]['totalTaxAmt']);
914 $this->assign('individual', array($individual[$participantNum]));
915 }
6a488035
TO
916 $this->assign('lineItem', $lineItem);
917 }
918 $this->_values['params']['additionalParticipant'] = TRUE;
7d92d486 919 $this->assign('isAdditionalParticipant', $this->_values['params']['additionalParticipant']);
6a488035
TO
920 }
921
922 //pass these variables since these are run time calculated.
923 $this->_values['params']['isOnWaitlist'] = $this->_allowWaitlist;
924 $this->_values['params']['isRequireApproval'] = $this->_requireApproval;
925
926 //send mail to primary as well as additional participants.
927 $this->assign('contactID', $contactId);
928 $this->assign('participantID', $participantID);
929 CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
930 }
931 }
932 }
6a488035
TO
933
934 /**
66f9e52b 935 * Process the contribution.
6a488035 936 *
c490a46a
CW
937 * @param CRM_Core_Form $form
938 * @param array $params
3bdf1f3a 939 * @param array $result
100fef9d 940 * @param int $contactID
dd244018
EM
941 * @param bool $pending
942 * @param bool $isAdditionalAmount
943 *
3bdf1f3a 944 * @return \CRM_Contribute_BAO_Contribution
6a488035 945 */
317fceb4 946 public static function processContribution(
ddca8f33 947 &$form, $params, $result, $contactID,
6a488035
TO
948 $pending = FALSE, $isAdditionalAmount = FALSE
949 ) {
950 $transaction = new CRM_Core_Transaction();
951
353ffa53 952 $now = date('YmdHis');
6a488035
TO
953 $receiptDate = NULL;
954
bf2c70af 955 if (!empty($form->_values['event']['is_email_confirm'])) {
6a488035
TO
956 $receiptDate = $now;
957 }
958 //CRM-4196
959 if ($isAdditionalAmount) {
960 $params['amount_level'] = $params['amount_level'] . ts(' (multiple participants)') . CRM_Core_DAO::VALUE_SEPARATOR;
961 }
962
963 $contribParams = array(
964 'contact_id' => $contactID,
353ffa53 965 'financial_type_id' => !empty($form->_values['event']['financial_type_id']) ? $form->_values['event']['financial_type_id'] : $params['financial_type_id'],
6a488035
TO
966 'receive_date' => $now,
967 'total_amount' => $params['amount'],
d91b8b33 968 'tax_amount' => $params['tax_amount'],
6a488035
TO
969 'amount_level' => $params['amount_level'],
970 'invoice_id' => $params['invoiceID'],
971 'currency' => $params['currencyID'],
13bb29e4 972 'source' => !empty($params['participant_source']) ? $params['participant_source'] : $params['description'],
6a488035
TO
973 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
974 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
975 );
976
a7488080 977 if (empty($params['is_pay_later'])) {
6a488035
TO
978 $contribParams['payment_instrument_id'] = 1;
979 }
980
981 if (!$pending && $result) {
982 $contribParams += array(
983 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
984 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']),
985 'trxn_id' => $result['trxn_id'],
986 'receipt_date' => $receiptDate,
987 );
988 }
989
990 $allStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
991 $contribParams['contribution_status_id'] = array_search('Completed', $allStatuses);
992 if ($pending) {
993 $contribParams['contribution_status_id'] = array_search('Pending', $allStatuses);
994 }
995
996 $contribParams['is_test'] = 0;
997 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
998 $contribParams['is_test'] = 1;
999 }
1000
1001 $contribID = NULL;
a7488080 1002 if (!empty($contribParams['invoice_id'])) {
6a488035
TO
1003 $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1004 $contribParams['invoice_id'],
1005 'id',
1006 'invoice_id'
1007 );
1008 }
1009
1010 $ids = array();
1011 if ($contribID) {
1012 $ids['contribution'] = $contribID;
1013 $contribParams['id'] = $contribID;
1014 }
1015
1016 //create an contribution address
0f2b049e 1017 // The concept of contributeMode is deprecated. Elsewhere we use the function processBillingAddress() - although
1018 // currently that is only inherited by back-office forms.
8cc574cf 1019 if ($form->_contributeMode != 'notify' && empty($params['is_pay_later'])) {
6a488035
TO
1020 $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
1021 }
1022
6a488035
TO
1023 $contribParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $params);
1024 $contribParams['skipLineItem'] = 1;
1025 // create contribution record
1026 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
1027 // CRM-11124
b03a5fb5 1028 CRM_Event_BAO_Participant::createDiscountTrxn($form->_eventId, $contribParams, CRM_Utils_Array::value('amount_priceset_level_radio', $params, NULL));
6a488035
TO
1029
1030 // process soft credit / pcp pages
7a13735b 1031 if (!empty($params['pcp_made_through_id'])) {
03b0e225 1032 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
7a13735b 1033 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
1034 }
6a488035
TO
1035
1036 $transaction->commit();
1037
1038 return $contribution;
1039 }
1040
1041 /**
66f9e52b 1042 * Fix the Location Fields.
6a488035 1043 *
b7a83c2c
J
1044 * @todo Reconcile with the contribution method formatParamsForPaymentProcessor
1045 * rather than adding different logic to check when to keep the billing
1046 * fields. There might be a difference in handling guest/multiple
1047 * participants though.
1048 *
c490a46a 1049 * @param array $params
3bdf1f3a 1050 * @param array $fields
c490a46a 1051 * @param CRM_Core_Form $form
6a488035 1052 */
4fb756af 1053 public static function fixLocationFields(&$params, &$fields, &$form) {
a9f7d48b
AS
1054 if (!empty($form->_fields)) {
1055 foreach ($form->_fields as $name => $dontCare) {
6a488035
TO
1056 $fields[$name] = 1;
1057 }
1058 }
1059
08318d90
J
1060 // If there's no 'first_name' in the profile then overwrite the names from
1061 // the billing fields (if they are set)
6a488035
TO
1062 if (is_array($fields)) {
1063 if (!array_key_exists('first_name', $fields)) {
1064 $nameFields = array('first_name', 'middle_name', 'last_name');
1065 foreach ($nameFields as $name) {
1066 $fields[$name] = 1;
1067 if (array_key_exists("billing_$name", $params)) {
1068 $params[$name] = $params["billing_{$name}"];
1069 $params['preserveDBName'] = TRUE;
1070 }
1071 }
1072 }
1073 }
1074
08318d90 1075 // Add the billing names to the billing address, if a billing name is set
5329bf02 1076 if (!empty($params['billing_first_name'])) {
a9f7d48b
AS
1077 $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);
1078 $fields["address_name-{$form->_bltID}"] = 1;
6a488035 1079 }
08318d90 1080
a9f7d48b 1081 $fields["email-{$form->_bltID}"] = 1;
6a488035
TO
1082 $fields['email-Primary'] = 1;
1083
1084 //if its pay later or additional participant set email address as primary.
8cc574cf 1085 if ((!empty($params['is_pay_later']) || empty($params['is_primary']) ||
a9f7d48b
AS
1086 !$form->_values['event']['is_monetary'] ||
1087 $form->_allowWaitlist ||
1088 $form->_requireApproval
353ffa53
TO
1089 ) && !empty($params["email-{$form->_bltID}"])
1090 ) {
a9f7d48b 1091 $params['email-Primary'] = $params["email-{$form->_bltID}"];
6a488035
TO
1092 }
1093 }
1094
1095 /**
66f9e52b 1096 * Update contact fields.
6a488035 1097 *
100fef9d 1098 * @param int $contactID
c490a46a 1099 * @param array $params
3bdf1f3a 1100 * @param array $fields
c490a46a 1101 * @param CRM_Core_Form $form
dd244018 1102 *
3bdf1f3a 1103 * @return int
6a488035 1104 */
4fb756af 1105 public static function updateContactFields($contactID, $params, $fields, &$form) {
6a488035
TO
1106 //add the contact to group, if add to group is selected for a
1107 //particular uf group
1108
1109 // get the add to groups
1110 $addToGroups = array();
1111
a9f7d48b
AS
1112 if (!empty($form->_fields)) {
1113 foreach ($form->_fields as $key => $value) {
a7488080 1114 if (!empty($value['add_to_group_id'])) {
6a488035
TO
1115 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
1116 }
1117 }
1118 }
1119
1120 // check for profile double opt-in and get groups to be subscribed
1121 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
1122
1123 foreach ($addToGroups as $k) {
1124 if (array_key_exists($k, $subscribeGroupIds)) {
1125 unset($addToGroups[$k]);
1126 }
1127 }
1128
1129 // since we are directly adding contact to group lets unset it from mailing
1130 if (!empty($addToGroups)) {
1131 foreach ($addToGroups as $groupId) {
1132 if (isset($subscribeGroupIds[$groupId])) {
1133 unset($subscribeGroupIds[$groupId]);
1134 }
1135 }
1136 }
1137 if ($contactID) {
1138 $ctype = CRM_Core_DAO::getFieldValue(
1139 'CRM_Contact_DAO_Contact',
1140 $contactID,
1141 'contact_type'
1142 );
e1ce628e 1143
22e263ad 1144 if (array_key_exists('contact_id', $params) && empty($params['contact_id'])) {
e1ce628e 1145 // we unset this here because the downstream function ignores the contactID we give it
1146 // if it is set & it is difficult to understand the implications of 'fixing' this downstream
1147 // but if we are passing a contact id into this function it's reasonable to assume we don't
1148 // want it ignored
1149 unset($params['contact_id']);
1150 }
1151
6a488035
TO
1152 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
1153 $params,
1154 $fields,
1155 $contactID,
1156 $addToGroups,
1157 NULL,
1158 $ctype,
1159 TRUE
1160 );
1161 }
1162 else {
1163
1164 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1165 if (!isset($params[$greeting . '_id'])) {
1166 $params[$greeting . '_id'] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
1167 }
1168 }
1169
1170 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params,
1171 $fields,
1172 NULL,
1173 $addToGroups,
1174 NULL,
1175 NULL,
1176 TRUE
1177 );
a9f7d48b 1178 $form->set('contactID', $contactID);
6a488035
TO
1179 }
1180
1181 //get email primary first if exist
1182 $subscribtionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
1183 if (!$subscribtionEmail['email']) {
a9f7d48b 1184 $subscribtionEmail['email'] = CRM_Utils_Array::value("email-{$form->_bltID}", $params);
6a488035
TO
1185 }
1186 // subscribing contact to groups
1187 if (!empty($subscribeGroupIds) && $subscribtionEmail['email']) {
1188 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscribtionEmail, $contactID);
1189 }
1190
1191 return $contactID;
1192 }
5bdcb00b 1193
0cf587a7 1194 /**
3bdf1f3a 1195 * Assign Profiles.
1196 *
1197 * @param CRM_Core_Form $form
0cf587a7 1198 */
5bdcb00b 1199 public static function assignProfiles(&$form) {
5bdcb00b
PJ
1200 $participantParams = $form->_params;
1201 $formattedValues = $profileFields = array();
353ffa53 1202 $count = 1;
5bdcb00b
PJ
1203 foreach ($participantParams as $participantNum => $participantValue) {
1204 if ($participantNum) {
0479b4c8
TO
1205 $prefix1 = 'additional';
1206 $prefix2 = 'additional_';
0db6c3e1
TO
1207 }
1208 else {
0479b4c8
TO
1209 $prefix1 = '';
1210 $prefix2 = '';
5bdcb00b
PJ
1211 }
1212 if ($participantValue != 'skip') {
1213 //get the customPre profile info
1214 if (!empty($form->_values[$prefix2 . 'custom_pre_id'])) {
1215 $values = $groupName = array();
1216 CRM_Event_BAO_Event::displayProfile($participantValue,
0479b4c8 1217 $form->_values[$prefix2 . 'custom_pre_id'],
5bdcb00b
PJ
1218 $groupName,
1219 $values,
1220 $profileFields
1221 );
1222
1223 if (count($values)) {
1224 $formattedValues[$count][$prefix1 . 'CustomPre'] = $values;
1225 }
1226 $formattedValues[$count][$prefix1 . 'CustomPreGroupTitle'] = CRM_Utils_Array::value('groupTitle', $groupName);
1227 }
1228 //get the customPost profile info
1229 if (!empty($form->_values[$prefix2 . 'custom_post_id'])) {
1230 $values = $groupName = array();
1231 foreach ($form->_values[$prefix2 . 'custom_post_id'] as $gids) {
1232 $val = array();
1233 CRM_Event_BAO_Event::displayProfile($participantValue,
1234 $gids,
1235 $group,
1236 $val,
1237 $profileFields
1238 );
1239 $values[$gids] = $val;
1240 $groupName[$gids] = $group;
1241 }
1242
1243 if (count($values)) {
1244 $formattedValues[$count][$prefix1 . 'CustomPost'] = $values;
1245 }
1246
1247 if (isset($formattedValues[$count][$prefix1 . 'CustomPre'])) {
1248 $formattedValues[$count][$prefix1 . 'CustomPost'] = array_diff_assoc($formattedValues[$count][$prefix1 . 'CustomPost'],
1249 $formattedValues[$count][$prefix1 . 'CustomPre']
1250 );
1251 }
1252
1253 $formattedValues[$count][$prefix1 . 'CustomPostGroupTitle'] = $groupName;
1254 }
1255 $count++;
1256 }
1257 $form->_fields = $profileFields;
1258 }
481a74f4 1259 if (!empty($formattedValues)) {
5bdcb00b 1260 $form->assign('primaryParticipantProfile', $formattedValues[1]);
0479b4c8 1261 $form->set('primaryParticipantProfile', $formattedValues[1]);
5bdcb00b
PJ
1262 if ($count > 2) {
1263 unset($formattedValues[1]);
1264 $form->assign('addParticipantProfile', $formattedValues);
0479b4c8 1265 $form->set('addParticipantProfile', $formattedValues);
5bdcb00b
PJ
1266 }
1267 }
1268 }
96025800 1269
6a488035 1270}