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