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