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