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