Merge pull request #8039 from JKingsnorth/CRM-18311
[civicrm-core.git] / CRM / Contribute / Form / Contribution / Confirm.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
6a488035
TO
32 */
33
34/**
35 * form to process actions on the group aspect of Custom Data
36 */
37class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_ContributionBase {
38
39 /**
fe482240 40 * The id of the contact associated with this contribution.
6a488035
TO
41 *
42 * @var int
6a488035
TO
43 */
44 public $_contactID;
45
1f1740fe
DL
46
47 /**
fe482240 48 * The id of the contribution object that is created when the form is submitted.
1f1740fe
DL
49 *
50 * @var int
1f1740fe
DL
51 */
52 public $_contributionID;
53
c8bde7ea 54 /**
fe482240 55 * Set the parameters to be passed to contribution create function.
c8bde7ea
EM
56 *
57 * @param array $params
100fef9d 58 * @param int $financialTypeID
ceb9fecb 59 * @param float $nonDeductibleAmount
ceb9fecb 60 * @param bool $pending
ab8fe4ef 61 * @param array $paymentProcessorOutcome
62 * @param string $receiptDate
100fef9d 63 * @param int $recurringContributionID
c8bde7ea 64 *
c8bde7ea
EM
65 * @return array
66 */
a13f3d8c 67 public static function getContributionParams(
3febe800 68 $params, $financialTypeID, $nonDeductibleAmount, $pending,
f6261e9d 69 $paymentProcessorOutcome, $receiptDate, $recurringContributionID) {
c8bde7ea 70 $contributionParams = array(
c8bde7ea 71 'financial_type_id' => $financialTypeID,
c8bde7ea
EM
72 'receive_date' => (CRM_Utils_Array::value('receive_date', $params)) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'),
73 'non_deductible_amount' => $nonDeductibleAmount,
74 'total_amount' => $params['amount'],
17ab42dd 75 'tax_amount' => CRM_Utils_Array::value('tax_amount', $params),
c8bde7ea
EM
76 'amount_level' => CRM_Utils_Array::value('amount_level', $params),
77 'invoice_id' => $params['invoiceID'],
78 'currency' => $params['currencyID'],
c8bde7ea
EM
79 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
80 //configure cancel reason, cancel date and thankyou date
81 //from 'contribution' type profile if included
82 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0),
a1a2a83d
TO
83 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : NULL,
84 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : NULL,
c8bde7ea 85 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
21dfd5f5 86 'skipLineItem' => CRM_Utils_Array::value('skipLineItem', $params, 0),
c8bde7ea 87 );
3febe800 88
a7a33651
EM
89 if ($paymentProcessorOutcome) {
90 $contributionParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $paymentProcessorOutcome);
91 }
c8bde7ea
EM
92 if (!$pending && $paymentProcessorOutcome) {
93 $contributionParams += array(
94 'fee_amount' => CRM_Utils_Array::value('fee_amount', $paymentProcessorOutcome),
95 'net_amount' => CRM_Utils_Array::value('net_amount', $paymentProcessorOutcome, $params['amount']),
96 'trxn_id' => $paymentProcessorOutcome['trxn_id'],
97 'receipt_date' => $receiptDate,
98 // also add financial_trxn details as part of fix for CRM-4724
99 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $paymentProcessorOutcome),
c8bde7ea
EM
100 );
101 }
102
103 // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
104 $contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contributionParams['non_deductible_amount'], ' '));
105 $contributionParams['total_amount'] = trim(CRM_Utils_Money::format($contributionParams['total_amount'], ' '));
106
107 if ($recurringContributionID) {
108 $contributionParams['contribution_recur_id'] = $recurringContributionID;
109 }
110
c51070b5 111 $contributionParams['contribution_status_id'] = $pending ? 2 : 1;
c8bde7ea
EM
112 if (isset($contributionParams['invoice_id'])) {
113 $contributionParams['id'] = CRM_Core_DAO::getFieldValue(
114 'CRM_Contribute_DAO_Contribution',
115 $contributionParams['invoice_id'],
116 'id',
117 'invoice_id'
118 );
119 }
120
121 return $contributionParams;
122 }
123
fda99f2f
EM
124 /**
125 * Get non-deductible amount.
126 *
127 * This is a bit too much about wierd form interpretation to be this deep.
128 *
129 * CRM-11885
130 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
131 * it.
ceb9fecb
EM
132 *
133 * @param array $params
134 * @param CRM_Financial_BAO_FinancialType $financialType
135 * @param bool $online
fda99f2f
EM
136 *
137 * @return array
138 */
139 protected static function getNonDeductibleAmount($params, $financialType, $online) {
140 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
141 return $params['non_deductible_amount'];
142 }
143 else {
144 if ($financialType->is_deductible) {
145 if ($online && isset($params['selectProduct'])) {
146 $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
147 }
148 if (!$online && isset($params['product_name'][0])) {
149 $selectProduct = $params['product_name'][0];
150 }
151 // if there is a product - compare the value to the contribution amount
152 if (isset($selectProduct) &&
153 $selectProduct != 'no_thanks'
154 ) {
155 $productDAO = new CRM_Contribute_DAO_Product();
156 $productDAO->id = $selectProduct;
157 $productDAO->find(TRUE);
158 // product value exceeds contribution amount
159 if ($params['amount'] < $productDAO->price) {
160 $nonDeductibleAmount = $params['amount'];
161 return $nonDeductibleAmount;
162 }
163 // product value does NOT exceed contribution amount
164 else {
165 return $productDAO->price;
166 }
167 }
168 // contribution is deductible - but there is no product
169 else {
170 return '0.00';
171 }
172 }
173 // contribution is NOT deductible
174 else {
175 return $params['amount'];
176 }
177 }
178 }
179
6a488035 180 /**
fe482240 181 * Set variables up before form is built.
6a488035
TO
182 */
183 public function preProcess() {
184 $config = CRM_Core_Config::singleton();
185 parent::preProcess();
cde484fd 186
6a488035
TO
187 // lineItem isn't set until Register postProcess
188 $this->_lineItem = $this->get('lineItem');
189 $this->_paymentProcessor = $this->get('paymentProcessor');
a9768188
EM
190 $this->_params = $this->controller->exportValues('Main');
191 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
192 $this->_params['amount'] = $this->get('amount');
193 if (isset($this->_params['amount'])) {
194 $this->setFormAmountFields($this->_params['priceSetId']);
6a488035 195 }
6a488035 196
a9768188
EM
197 $this->_params['tax_amount'] = $this->get('tax_amount');
198 $this->_useForMember = $this->get('useForMember');
6a488035 199
a9768188
EM
200 if (isset($this->_params['credit_card_exp_date'])) {
201 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
202 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
203 }
5df36634 204
a9768188 205 $this->_params['currencyID'] = $config->defaultCurrency;
6a488035 206
a9768188
EM
207 if (!empty($this->_membershipBlock)) {
208 $this->_params['selectMembership'] = $this->get('selectMembership');
209 }
210 if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) {
211 $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
212 $this->_params = array_merge($this->_params, $preApprovalParams);
213 }
cde484fd 214
a9768188
EM
215 // We may have fetched some billing details from the getPreApprovalDetails function so we
216 // want to ensure we set this after that function has been called.
217 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $this->_params, FALSE);
6a488035
TO
218
219 $this->_params['is_pay_later'] = $this->get('is_pay_later');
220 $this->assign('is_pay_later', $this->_params['is_pay_later']);
221 if ($this->_params['is_pay_later']) {
222 $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
223 }
224 // if onbehalf-of-organization
4779abb3 225 if (!empty($this->_values['onbehalf_profile_id']) && !empty($this->_params['onbehalf']['organization_name'])) {
7028a38f 226 $this->_params['organization_id'] = CRM_Utils_Array::value('onbehalfof_id', $this->_params);
6a488035
TO
227 $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name'];
228 $addressBlocks = array(
a13f3d8c
TO
229 'street_address',
230 'city',
231 'state_province',
232 'postal_code',
233 'country',
234 'supplemental_address_1',
235 'supplemental_address_2',
236 'supplemental_address_3',
237 'postal_code_suffix',
238 'geo_code_1',
239 'geo_code_2',
240 'address_name',
6a488035
TO
241 );
242
243 $blocks = array('email', 'phone', 'im', 'url', 'openid');
244 foreach ($this->_params['onbehalf'] as $loc => $value) {
245 $field = $typeId = NULL;
246 if (strstr($loc, '-')) {
247 list($field, $locType) = explode('-', $loc);
248 }
249
250 if (in_array($field, $addressBlocks)) {
251 if ($locType == 'Primary') {
252 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
253 $locType = $defaultLocationType->id;
cde484fd
DL
254 }
255
6a488035
TO
256 if ($field == 'country') {
257 $value = CRM_Core_PseudoConstant::countryIsoCode($value);
258 }
259 elseif ($field == 'state_province') {
260 $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
261 }
cde484fd 262
6a488035
TO
263 $isPrimary = 1;
264 if (isset($this->_params['onbehalf_location']['address'])
a13f3d8c
TO
265 && count($this->_params['onbehalf_location']['address']) > 0
266 ) {
6a488035
TO
267 $isPrimary = 0;
268 }
cde484fd 269
6a488035 270 $this->_params['onbehalf_location']['address'][$locType][$field] = $value;
a7488080 271 if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) {
6a488035 272 $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
a13f3d8c 273 }
6a488035
TO
274 $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
275 }
276 elseif (in_array($field, $blocks)) {
277 if (!$typeId || is_numeric($typeId)) {
a13f3d8c
TO
278 $blockName = $fieldName = $field;
279 $locationType = 'location_type_id';
280 if ($locType == 'Primary') {
6a488035
TO
281 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
282 $locationValue = $defaultLocationType->id;
283 }
284 else {
285 $locationValue = $locType;
286 }
a13f3d8c 287 $locTypeId = '';
6a488035
TO
288 $phoneExtField = array();
289
290 if ($field == 'url') {
a13f3d8c 291 $blockName = 'website';
887e764d
PN
292 $locationType = 'website_type_id';
293 list($field, $locationValue) = explode('-', $loc);
6a488035
TO
294 }
295 elseif ($field == 'im') {
296 $fieldName = 'name';
297 $locTypeId = 'provider_id';
a13f3d8c 298 $typeId = $this->_params['onbehalf']["{$loc}-provider_id"];
6a488035
TO
299 }
300 elseif ($field == 'phone') {
301 list($field, $locType, $typeId) = explode('-', $loc);
302 $locTypeId = 'phone_type_id';
303
304 //check if extension field exists
a13f3d8c 305 $extField = str_replace('phone', 'phone_ext', $loc);
6a488035
TO
306 if (isset($this->_params['onbehalf'][$extField])) {
307 $phoneExtField = array('phone_ext' => $this->_params['onbehalf'][$extField]);
308 }
309 }
310
311 $isPrimary = 1;
a13f3d8c
TO
312 if (isset ($this->_params['onbehalf_location'][$blockName])
313 && count($this->_params['onbehalf_location'][$blockName]) > 0
314 ) {
315 $isPrimary = 0;
6a488035
TO
316 }
317 if ($locationValue) {
318 $blockValues = array(
a13f3d8c 319 $fieldName => $value,
6a488035 320 $locationType => $locationValue,
a13f3d8c 321 'is_primary' => $isPrimary,
6a488035
TO
322 );
323
324 if ($locTypeId) {
a13f3d8c 325 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
6a488035
TO
326 }
327 if (!empty($phoneExtField)) {
328 $blockValues = array_merge($blockValues, $phoneExtField);
329 }
330
331 $this->_params['onbehalf_location'][$blockName][] = $blockValues;
332 }
333 }
334 }
335 elseif (strstr($loc, 'custom')) {
336 if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) {
337 $value = $this->_params['onbehalf']["{$loc}_id"];
338 }
339 $this->_params['onbehalf_location']["{$loc}"] = $value;
340 }
341 else {
342 if ($loc == 'contact_sub_type') {
343 $this->_params['onbehalf_location'][$loc] = $value;
344 }
345 else {
346 $this->_params['onbehalf_location'][$field] = $value;
347 }
348 }
349 }
350 }
a7488080 351 elseif (!empty($this->_values['is_for_organization'])) {
6a488035
TO
352 // no on behalf of an organization, CRM-5519
353 // so reset loc blocks from main params.
354 foreach (array(
a13f3d8c
TO
355 'phone',
356 'email',
21dfd5f5 357 'address',
a13f3d8c 358 ) as $blk) {
6a488035
TO
359 if (isset($this->_params[$blk])) {
360 unset($this->_params[$blk]);
361 }
362 }
363 }
90102a32 364 $this->setRecurringMembershipParams();
6a488035
TO
365
366 if ($this->_pcpId) {
367 $params = $this->processPcp($this, $this->_params);
368 $this->_params = $params;
369 }
370 $this->_params['invoiceID'] = $this->get('invoiceID');
371
372 //carry campaign from profile.
373 if (array_key_exists('contribution_campaign_id', $this->_params)) {
374 $this->_params['campaign_id'] = $this->_params['contribution_campaign_id'];
375 }
376
569df8ec
DG
377 // assign contribution page id to the template so we can add css class for it
378 $this->assign('contributionPageID', $this->_id);
de5ce535 379 $this->assign('is_for_organization', CRM_Utils_Array::value('is_for_organization', $this->_params));
569df8ec 380
6a488035
TO
381 $this->set('params', $this->_params);
382 }
383
384 /**
fe482240 385 * Build the form object.
6a488035
TO
386 */
387 public function buildQuickForm() {
388 $this->assignToTemplate();
389
390 $params = $this->_params;
6a488035 391 // make sure we have values for it
4779abb3 392 if (!empty($this->_values['honoree_profile_id']) && !empty($params['soft_credit_type_id'])) {
a13f3d8c 393 $honorName = NULL;
133e2c99 394 $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
395
133e2c99 396 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
4779abb3 397 CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($this, $params['honor']);
6a488035 398
133e2c99 399 $fieldTypes = array('Contact');
4779abb3 400 $fieldTypes[] = CRM_Core_BAO_UFGroup::getContactType($this->_values['honoree_profile_id']);
401 $this->buildCustom($this->_values['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
6a488035
TO
402 }
403 $this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values));
404 $amount_block_is_active = $this->get('amount_block_is_active');
405 $this->assign('amount_block_is_active', $amount_block_is_active);
406
aaffa79f 407 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
03b412ae
PB
408 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
409 if ($invoicing) {
410 $getTaxDetails = FALSE;
411 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
412 foreach ($this->_lineItem as $key => $value) {
413 foreach ($value as $v) {
414 if (isset($v['tax_rate'])) {
415 if ($v['tax_rate'] != '') {
416 $getTaxDetails = TRUE;
417 }
418 }
419 }
420 }
421 $this->assign('getTaxDetails', $getTaxDetails);
422 $this->assign('taxTerm', $taxTerm);
423 $this->assign('totalTaxAmount', $params['tax_amount']);
424 }
a7488080 425 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
6a488035
TO
426 $option = CRM_Utils_Array::value('options_' . $params['selectProduct'], $params);
427 $productID = $params['selectProduct'];
428 CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE,
429 $productID, $option
430 );
431 $this->set('productID', $productID);
432 $this->set('option', $option);
433 }
434 $config = CRM_Core_Config::singleton();
435 if (in_array('CiviMember', $config->enableComponents)) {
436 if (isset($params['selectMembership']) &&
437 $params['selectMembership'] != 'no_thanks'
438 ) {
42e3a033 439 $this->buildMembershipBlock(
5b757295 440 $this->_membershipContactID,
6a488035
TO
441 FALSE,
442 $params['selectMembership'],
5b757295 443 FALSE
6a488035 444 );
9cc96227 445 if (!empty($params['auto_renew'])) {
446 $this->assign('auto_renew', TRUE);
447 }
6a488035
TO
448 }
449 else {
450 $this->assign('membershipBlock', FALSE);
451 }
452 }
453 $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE);
454 $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE);
455
a9653117 456 if (!empty($this->_values['onbehalf_profile_id']) &&
457 !empty($params['onbehalf']) &&
458 ($this->_values['is_for_organization'] == 2 ||
459 !empty($params['is_for_organization'])
460 )
461 ) {
a13f3d8c 462 $fieldTypes = array('Contact', 'Organization');
6a488035 463 $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
a13f3d8c 464 $fieldTypes = array_merge($fieldTypes, $contactSubType);
6a488035
TO
465 if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
466 $fieldTypes = array_merge($fieldTypes, array('Membership'));
467 }
468 else {
469 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
470 }
471
4779abb3 472 $this->buildCustom($this->_values['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
6a488035
TO
473 }
474
475 $this->_separateMembershipPayment = $this->get('separateMembershipPayment');
476 $this->assign('is_separate_payment', $this->_separateMembershipPayment);
9da8dc8c 477 if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
6a488035 478 $this->assign('lineItem', $this->_lineItem);
a13f3d8c
TO
479 }
480 else {
6a488035
TO
481 $this->assign('is_quick_config', 1);
482 $this->_params['is_quick_config'] = 1;
483 }
484 $this->assign('priceSetID', $this->_priceSetId);
6a488035 485
229159bf
CW
486 // The concept of contributeMode is deprecated.
487 // the is_monetary concept probably should be too as it can be calculated from
488 // the existence of 'amount' & seems fragile.
489 if ($this->_contributeMode == 'notify' || !$this->_values['is_monetary'] ||
490 $this->_amount <= 0.0 || $this->_params['is_pay_later'] ||
491 ($this->_separateMembershipPayment && $this->_amount <= 0.0)
492 ) {
493 $contribButton = ts('Continue');
494 $this->assign('button', ts('Continue'));
6a488035
TO
495 }
496 else {
229159bf
CW
497 $contribButton = ts('Make Contribution');
498 $this->assign('button', ts('Make Contribution'));
6a488035 499 }
229159bf
CW
500 $this->addButtons(array(
501 array(
502 'type' => 'next',
503 'name' => $contribButton,
504 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
505 'isDefault' => TRUE,
506 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
507 ),
508 array(
509 'type' => 'back',
510 'name' => ts('Go Back'),
511 ),
512 )
513 );
6a488035
TO
514
515 $defaults = array();
9c80939e 516 $fields = array_fill_keys(array_keys($this->_fields), 1);
6a488035
TO
517 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
518
519 $contact = $this->_params;
520 foreach ($fields as $name => $dontCare) {
9c80939e
CW
521 // Recursively set defaults for nested fields
522 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' || $name == 'honor')) {
523 foreach ($contact[$name] as $fieldName => $fieldValue) {
a13f3d8c
TO
524 if (is_array($fieldValue) && !in_array($this->_fields[$name][$fieldName]['html_type'], array(
525 'Multi-Select',
21dfd5f5 526 'AdvMulti-Select',
a13f3d8c
TO
527 ))
528 ) {
38b95e0f 529 foreach ($fieldValue as $key => $value) {
530 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
531 }
532 }
533 else {
534 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
535 }
9c80939e
CW
536 }
537 }
538 elseif (isset($contact[$name])) {
6a488035
TO
539 $defaults[$name] = $contact[$name];
540 if (substr($name, 0, 7) == 'custom_') {
541 $timeField = "{$name}_time";
542 if (isset($contact[$timeField])) {
543 $defaults[$timeField] = $contact[$timeField];
544 }
545 if (isset($contact["{$name}_id"])) {
546 $defaults["{$name}_id"] = $contact["{$name}_id"];
547 }
548 }
a13f3d8c
TO
549 elseif (in_array($name, array(
550 'addressee',
551 'email_greeting',
21dfd5f5 552 'postal_greeting',
a13f3d8c
TO
553 )) && !empty($contact[$name . '_custom'])
554 ) {
6a488035
TO
555 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
556 }
557 }
558 }
559
560 $this->assign('useForMember', $this->get('useForMember'));
561
6a488035
TO
562 $this->setDefaults($defaults);
563
564 $this->freeze();
565 }
566
567 /**
ab8fe4ef 568 * Overwrite action.
569 *
570 * Since we are only showing elements in frozen mode no help display needed.
6a488035
TO
571 *
572 * @return int
6a488035 573 */
00be9182 574 public function getAction() {
6a488035
TO
575 if ($this->_action & CRM_Core_Action::PREVIEW) {
576 return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
577 }
578 else {
579 return CRM_Core_Action::VIEW;
580 }
581 }
582
583 /**
5e4f7f74 584 * Set default values for the form.
6a488035 585 *
5e4f7f74
EM
586 * Note that in edit/view mode
587 * the default values are retrieved from the database
6a488035 588 */
a13f3d8c
TO
589 public function setDefaultValues() {
590 }
6a488035
TO
591
592 /**
fe482240 593 * Process the form.
6a488035
TO
594 */
595 public function postProcess() {
da8d9879 596 $contactID = $this->getContactID();
75637f22
EM
597 $result = $this->processFormSubmission($contactID);
598 if (is_array($result) && !empty($result['is_payment_failure'])) {
73baf02a
EM
599 // We will probably have the function that gets this error throw an exception on the next round of refactoring.
600 CRM_Core_Session::singleton()->setStatus(ts("Payment Processor Error message :") .
601 $result['error']->getMessage());
75637f22
EM
602 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact',
603 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
604 ));
cc789d46 605 }
5fb28746
EM
606 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
607 $this->set('params', $this->_params);
75637f22 608 }
6a488035 609
75637f22
EM
610 /**
611 * Wrangle financial type ID.
612 *
613 * This wrangling of the financialType ID was happening in a shared function rather than in the form it relates to & hence has been moved to that form
614 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
615 *
616 * Comments from previous refactor indicate doubt as to what was going on.
617 *
618 * @param int $contributionTypeId
619 *
620 * @return null|string
621 */
622 public function wrangleFinancialTypeID($contributionTypeId) {
623 if (isset($paymentParams['financial_type'])) {
624 $contributionTypeId = $paymentParams['financial_type'];
6a488035 625 }
75637f22
EM
626 elseif (!empty($this->_values['pledge_id'])) {
627 $contributionTypeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
628 $this->_values['pledge_id'],
629 'financial_type_id'
630 );
6a488035 631 }
75637f22
EM
632 return $contributionTypeId;
633 }
6a488035 634
75637f22
EM
635 /**
636 * Process the form.
637 *
638 * @param array $premiumParams
639 * @param CRM_Contribute_BAO_Contribution $contribution
640 */
5fb28746 641 protected function postProcessPremium($premiumParams, $contribution) {
75637f22
EM
642 $hour = $minute = $second = 0;
643 // assigning Premium information to receipt tpl
644 $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
645 if ($selectProduct &&
646 $selectProduct != 'no_thanks'
647 ) {
648 $startDate = $endDate = "";
649 $this->assign('selectPremium', TRUE);
650 $productDAO = new CRM_Contribute_DAO_Product();
651 $productDAO->id = $selectProduct;
652 $productDAO->find(TRUE);
653 $this->assign('product_name', $productDAO->name);
654 $this->assign('price', $productDAO->price);
655 $this->assign('sku', $productDAO->sku);
656 $this->assign('option', CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams));
6a488035 657
75637f22 658 $periodType = $productDAO->period_type;
6a488035 659
75637f22
EM
660 if ($periodType) {
661 $fixed_period_start_day = $productDAO->fixed_period_start_day;
662 $duration_unit = $productDAO->duration_unit;
663 $duration_interval = $productDAO->duration_interval;
664 if ($periodType == 'rolling') {
665 $startDate = date('Y-m-d');
666 }
667 elseif ($periodType == 'fixed') {
668 if ($fixed_period_start_day) {
669 $date = explode('-', date('Y-m-d'));
670 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
671 $day = substr($fixed_period_start_day, -2) . "<br/>";
672 $year = $date[0];
673 $startDate = $year . '-' . $month . '-' . $day;
674 }
675 else {
676 $startDate = date('Y-m-d');
677 }
6a488035 678 }
6a488035 679
75637f22
EM
680 $date = explode('-', $startDate);
681 $year = $date[0];
682 $month = $date[1];
683 $day = $date[2];
6a488035 684
75637f22
EM
685 switch ($duration_unit) {
686 case 'year':
687 $year = $year + $duration_interval;
688 break;
6a488035 689
75637f22
EM
690 case 'month':
691 $month = $month + $duration_interval;
692 break;
6a488035 693
75637f22
EM
694 case 'day':
695 $day = $day + $duration_interval;
696 break;
6a488035 697
75637f22
EM
698 case 'week':
699 $day = $day + ($duration_interval * 7);
6a488035 700 }
75637f22
EM
701 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
702 $this->assign('start_date', $startDate);
703 $this->assign('end_date', $endDate);
6a488035
TO
704 }
705
75637f22
EM
706 $dao = new CRM_Contribute_DAO_Premium();
707 $dao->entity_table = 'civicrm_contribution_page';
708 $dao->entity_id = $this->_id;
709 $dao->find(TRUE);
710 $this->assign('contact_phone', $dao->premiums_contact_phone);
711 $this->assign('contact_email', $dao->premiums_contact_email);
712
713 //create Premium record
714 $params = array(
715 'product_id' => $premiumParams['selectProduct'],
716 'contribution_id' => $contribution->id,
717 'product_option' => CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams),
718 'quantity' => 1,
719 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
720 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
721 );
722 if (!empty($premiumParams['selectProduct'])) {
723 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
724 $daoPremiumsProduct->product_id = $premiumParams['selectProduct'];
725 $daoPremiumsProduct->premiums_id = $dao->id;
726 $daoPremiumsProduct->find(TRUE);
727 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id;
6a488035 728 }
75637f22
EM
729 //Fixed For CRM-3901
730 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
731 $daoContrProd->contribution_id = $contribution->id;
732 if ($daoContrProd->find(TRUE)) {
733 $params['id'] = $daoContrProd->id;
6a488035 734 }
6a488035 735
75637f22
EM
736 CRM_Contribute_BAO_Contribution::addPremium($params);
737 if ($productDAO->cost && !empty($params['financial_type_id'])) {
738 $trxnParams = array(
739 'cost' => $productDAO->cost,
740 'currency' => $productDAO->currency,
741 'financial_type_id' => $params['financial_type_id'],
742 'contributionId' => $contribution->id,
743 );
744 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
6a488035
TO
745 }
746 }
75637f22
EM
747 elseif ($selectProduct == 'no_thanks') {
748 //Fixed For CRM-3901
749 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
750 $daoContrProd->contribution_id = $contribution->id;
751 if ($daoContrProd->find(TRUE)) {
752 $daoContrProd->delete();
6a488035
TO
753 }
754 }
75637f22 755 }
6a488035 756
75637f22
EM
757 /**
758 * Process the contribution.
759 *
760 * @param CRM_Core_Form $form
761 * @param array $params
762 * @param array $result
f6261e9d 763 * @param array $contributionParams
764 * Parameters to be passed to contribution create action.
3febe800 765 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
766 * passed consistently & 2) documenting them here.
767 * - contact_id
768 * - line_item
769 * - is_test
770 * - campaign_id
771 * - contribution_page_id
772 * - source
773 * - payment_type_id
774 * - thankyou_date (not all forms will set this)
775 *
75637f22 776 * @param CRM_Financial_DAO_FinancialType $financialType
75637f22 777 * @param bool $online
3febe800 778 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
75637f22 779 *
75637f22
EM
780 * @param int $billingLocationID
781 * ID of billing location type.
10490499 782 * @param bool $isRecur
783 * Is this recurring?
75637f22
EM
784 *
785 * @return \CRM_Contribute_DAO_Contribution
786 * @throws \Exception
787 */
788 public static function processFormContribution(
789 &$form,
790 $params,
791 $result,
f6261e9d 792 $contributionParams,
75637f22 793 $financialType,
75637f22 794 $online,
449f4c90 795 $billingLocationID,
796 $isRecur
75637f22
EM
797 ) {
798 $transaction = new CRM_Core_Transaction();
f6261e9d 799 $contactID = $contributionParams['contact_id'];
800
75637f22 801 $isEmailReceipt = !empty($form->_values['is_email_receipt']);
09108d7d 802 $isSeparateMembershipPayment = empty($params['separate_membership_payment']) ? FALSE : TRUE;
530a05b3 803 $pledgeID = !empty($params['pledge_id']) ? $params['pledge_id'] : CRM_Utils_Array::value('pledge_id', $form->_values);
75637f22 804 if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) &&
09108d7d 805 (!empty($params['is_pledge']) || $pledgeID)) {
75637f22 806 $isPledge = TRUE;
6a488035
TO
807 }
808 else {
75637f22 809 $isPledge = FALSE;
6a488035
TO
810 }
811
75637f22
EM
812 // add these values for the recurringContrib function ,CRM-10188
813 $params['financial_type_id'] = $financialType->id;
6a488035 814
3febe800 815 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID);
6a488035 816
75637f22
EM
817 //@todo - this is being set from the form to resolve CRM-10188 - an
818 // eNotice caused by it not being set @ the front end
819 // however, we then get it being over-written with null for backend contributions
820 // a better fix would be to set the values in the respective forms rather than require
821 // a function being shared by two forms to deal with their respective values
822 // moving it to the BAO & not taking the $form as a param would make sense here.
823 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
824 $params['is_email_receipt'] = $isEmailReceipt;
51e89def 825 }
449f4c90 826 $params['is_recur'] = $isRecur;
827 $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType);
75637f22 828 $nonDeductibleAmount = self::getNonDeductibleAmount($params, $financialType, $online);
51e89def 829
75637f22
EM
830 $now = date('YmdHis');
831 $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
832 if ($isEmailReceipt) {
833 $receiptDate = $now;
6a488035
TO
834 }
835
75637f22 836 if (isset($params['amount'])) {
f6261e9d 837 $contributionParams = array_merge(self::getContributionParams(
f7248cb7 838 $params, $financialType->id, $nonDeductibleAmount, TRUE,
f6261e9d 839 $result, $receiptDate,
840 $recurringContributionID), $contributionParams
75637f22 841 );
f6261e9d 842 $contribution = CRM_Contribute_BAO_Contribution::add($contributionParams);
6a488035 843
aaffa79f 844 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
75637f22
EM
845 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
846 if ($invoicing) {
847 $dataArray = array();
f6261e9d 848 // @todo - interrogate the line items passed in on the params array.
849 // No reason to assume line items will be set on the form.
75637f22
EM
850 foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
851 foreach ($lineItemValue as $key => $value) {
852 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
853 if (isset($dataArray[$value['tax_rate']])) {
854 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
855 }
856 else {
857 $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
858 }
859 }
6a488035
TO
860 }
861 }
75637f22
EM
862 $smarty = CRM_Core_Smarty::singleton();
863 $smarty->assign('dataArray', $dataArray);
864 $smarty->assign('totalTaxAmount', $params['tax_amount']);
865 }
866 if (is_a($contribution, 'CRM_Core_Error')) {
867 $message = CRM_Core_Error::getMessages($contribution);
868 CRM_Core_Error::fatal($message);
6a488035
TO
869 }
870
75637f22
EM
871 // lets store it in the form variable so postProcess hook can get to this and use it
872 $form->_contributionID = $contribution->id;
873 }
6a488035 874
7a13735b 875 // process soft credit / pcp params first
876 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
75637f22 877
7a13735b 878 //CRM-13981, processing honor contact into soft-credit contribution
879 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
75637f22
EM
880
881 //handle pledge stuff.
882 if ($isPledge) {
883 if ($pledgeID) {
884 //when user doing pledge payments.
885 //update the schedule when payment(s) are made
a5d8acb9 886 $amount = $params['amount'];
887 $pledgePaymentParams = array();
09108d7d 888 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
75637f22
EM
889 $scheduledAmount = CRM_Core_DAO::getFieldValue(
890 'CRM_Pledge_DAO_PledgePayment',
891 $paymentId,
892 'scheduled_amount',
893 'id'
894 );
895
a5d8acb9 896 $pledgePayment = ($amount >= $scheduledAmount) ? $scheduledAmount : $amount;
897 if ($pledgePayment > 0) {
898 $pledgePaymentParams[] = array(
899 'id' => $paymentId,
900 'contribution_id' => $contribution->id,
901 'status_id' => $contribution->contribution_status_id,
902 'actual_amount' => $pledgePayment,
903 );
904 $amount -= $pledgePayment;
905 }
906 }
907 if ($amount > 0 && count($pledgePaymentParams)) {
908 $pledgePaymentParams[count($pledgePaymentParams) - 1]['actual_amount'] += $amount;
909 }
910 foreach ($pledgePaymentParams as $p) {
911 CRM_Pledge_BAO_PledgePayment::add($p);
6a488035 912 }
75637f22
EM
913
914 //update pledge status according to the new payment statuses
915 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID);
6a488035 916 }
75637f22
EM
917 else {
918 //when user creating pledge record.
919 $pledgeParams = array();
920 $pledgeParams['contact_id'] = $contribution->contact_id;
921 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
922 $pledgeParams['contribution_id'] = $contribution->id;
923 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
924 $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
925 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
926 $pledgeParams['installments'] = $params['pledge_installments'];
927 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
928 if ($pledgeParams['frequency_unit'] == 'month') {
929 $pledgeParams['frequency_day'] = intval(date("d"));
9ce8bcfc 930 }
75637f22
EM
931 else {
932 $pledgeParams['frequency_day'] = 1;
933 }
934 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
935 $pledgeParams['status_id'] = $contribution->contribution_status_id;
936 $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
937 $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
938 $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
939 $pledgeParams['is_test'] = $contribution->is_test;
940 $pledgeParams['acknowledge_date'] = date('Ymd');
941 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
942
943 //inherit campaign from contirb page.
3febe800 944 $pledgeParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $contributionParams);
75637f22
EM
945
946 $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
947
948 $form->_params['pledge_id'] = $pledge->id;
949
950 //send acknowledgment email. only when pledge is created
47352b73 951 if ($pledge->id && $isEmailReceipt) {
75637f22
EM
952 //build params to send acknowledgment.
953 $pledgeParams['id'] = $pledge->id;
954 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
955 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
956
957 //scheduled amount will be same as installment_amount.
958 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
959
960 //get total pledge amount.
961 $pledgeParams['total_pledge_amount'] = $pledge->amount;
962
963 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
fa9d0451 964 }
9ce8bcfc 965 }
6a488035 966 }
6a488035 967
75637f22 968 if ($online && $contribution) {
09108d7d 969 CRM_Core_BAO_CustomValueTable::postProcess($params,
75637f22
EM
970 'civicrm_contribution',
971 $contribution->id,
972 'Contribution'
973 );
974 }
975 elseif ($contribution) {
976 //handle custom data.
977 $params['contribution_id'] = $contribution->id;
978 if (!empty($params['custom']) &&
979 is_array($params['custom']) &&
980 !is_a($contribution, 'CRM_Core_Error')
6a488035 981 ) {
75637f22 982 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
6a488035 983 }
75637f22
EM
984 }
985 // Save note
986 if ($contribution && !empty($params['contribution_note'])) {
987 $noteParams = array(
988 'entity_table' => 'civicrm_contribution',
989 'note' => $params['contribution_note'],
990 'entity_id' => $contribution->id,
991 'contact_id' => $contribution->contact_id,
992 'modified_date' => date('Ymd'),
cc789d46 993 );
75637f22
EM
994
995 CRM_Core_BAO_Note::add($noteParams, array());
cc789d46 996 }
cc789d46 997
75637f22
EM
998 if (isset($params['related_contact'])) {
999 $contactID = $params['related_contact'];
cc789d46 1000 }
75637f22
EM
1001 elseif (isset($params['cms_contactID'])) {
1002 $contactID = $params['cms_contactID'];
6a488035 1003 }
75637f22
EM
1004
1005 //create contribution activity w/ individual and target
1006 //activity w/ organisation contact id when onbelf, CRM-4027
1007 $targetContactID = NULL;
1008 if (!empty($params['hidden_onbehalf_profile'])) {
1009 $targetContactID = $contribution->contact_id;
1010 $contribution->contact_id = $contactID;
1011 }
1012
1013 // create an activity record
1014 if ($contribution) {
1015 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
1016 }
1017
1018 $transaction->commit();
1019 // CRM-13074 - create the CMSUser after the transaction is completed as it
1020 // is not appropriate to delete a valid contribution if a user create problem occurs
1021 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params,
1022 $contactID,
1023 'email-' . $billingLocationID
1024 );
1025 return $contribution;
6a488035
TO
1026 }
1027
1028 /**
75637f22 1029 * Create the recurring contribution record.
6a488035 1030 *
75637f22
EM
1031 * @param CRM_Core_Form $form
1032 * @param array $params
1033 * @param int $contactID
1034 * @param string $contributionType
75637f22 1035 *
449f4c90 1036 * @return int|null
6a488035 1037 */
449f4c90 1038 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType) {
cde484fd 1039
449f4c90 1040 if (empty($params['is_recur'])) {
75637f22
EM
1041 return NULL;
1042 }
6a488035 1043
75637f22
EM
1044 $recurParams = array('contact_id' => $contactID);
1045 $recurParams['amount'] = CRM_Utils_Array::value('amount', $params);
1046 $recurParams['auto_renew'] = CRM_Utils_Array::value('auto_renew', $params);
1047 $recurParams['frequency_unit'] = CRM_Utils_Array::value('frequency_unit', $params);
1048 $recurParams['frequency_interval'] = CRM_Utils_Array::value('frequency_interval', $params);
1049 $recurParams['installments'] = CRM_Utils_Array::value('installments', $params);
1050 $recurParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params);
1051 $recurParams['currency'] = CRM_Utils_Array::value('currency', $params);
6a488035 1052
75637f22
EM
1053 // CRM-14354: For an auto-renewing membership with an additional contribution,
1054 // if separate payments is not enabled, make sure only the membership fee recurs
1055 if (!empty($form->_membershipBlock)
1056 && $form->_membershipBlock['is_separate_payment'] === '0'
1057 && isset($params['selectMembership'])
1058 && $form->_values['is_allow_other_amount'] == '1'
1059 // CRM-16331
1060 && !empty($form->_membershipTypeValues)
1061 && !empty($form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'])
1062 ) {
1063 $recurParams['amount'] = $form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'];
1064 }
6a488035 1065
75637f22
EM
1066 $recurParams['is_test'] = 0;
1067 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1068 (isset($form->_mode) && ($form->_mode == 'test'))
1069 ) {
1070 $recurParams['is_test'] = 1;
1071 }
6a488035 1072
75637f22
EM
1073 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1074 if (!empty($params['receive_date'])) {
1075 $recurParams['start_date'] = $params['receive_date'];
1076 }
1077 $recurParams['invoice_id'] = CRM_Utils_Array::value('invoiceID', $params);
1078 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1079 $recurParams['payment_processor_id'] = CRM_Utils_Array::value('payment_processor_id', $params);
1080 $recurParams['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params);
1081 // we need to add a unique trxn_id to avoid a unique key error
1082 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1083 $recurParams['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params, $params['invoiceID']);
1084 $recurParams['financial_type_id'] = $contributionType->id;
6a488035 1085
449f4c90 1086 if ($form->_values['is_monetary']) {
75637f22
EM
1087 $recurParams['payment_instrument_id'] = 1;
1088 }
cde484fd 1089
449f4c90 1090 $campaignId = CRM_Utils_Array::value('campaign_id', $params, CRM_Utils_Array::value('campaign_id', $form->_values));
75637f22
EM
1091 $recurParams['campaign_id'] = $campaignId;
1092
1093 $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
1094 if (is_a($recurring, 'CRM_Core_Error')) {
1095 CRM_Core_Error::displaySessionError($recurring);
1096 $urlString = 'civicrm/contribute/transact';
1097 $urlParams = '_qf_Main_display=true';
1098 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1099 $urlString = 'civicrm/contact/view/contribution';
1100 $urlParams = "action=add&cid={$form->_contactID}";
1101 if ($form->_mode) {
1102 $urlParams .= "&mode={$form->_mode}";
1103 }
6a488035 1104 }
75637f22 1105 CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
6a488035 1106 }
75637f22
EM
1107
1108 return $recurring->id;
6a488035
TO
1109 }
1110
1111 /**
75637f22 1112 * Add on behalf of organization and it's location.
cd6994fc 1113 *
75637f22
EM
1114 * This situation occurs when on behalf of is enabled for the contribution page and the person
1115 * signing up does so on behalf of an organization.
a1a94e61 1116 *
75637f22
EM
1117 * @param array $behalfOrganization
1118 * array of organization info.
1119 * @param int $contactID
1120 * individual contact id. One.
1121 * who is doing the process of signup / contribution.
9fc4e1d9 1122 *
75637f22
EM
1123 * @param array $values
1124 * form values array.
1125 * @param array $params
1126 * @param array $fields
1127 * Array of fields from the onbehalf profile relevant to the organization.
6a488035 1128 */
75637f22 1129 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
33260076 1130 $isNotCurrentEmployer = FALSE;
75637f22
EM
1131 $dupeIDs = array();
1132 $orgID = NULL;
6cc679d2 1133 if (!empty($behalfOrganization['organization_id'])) {
75637f22
EM
1134 $orgID = $behalfOrganization['organization_id'];
1135 unset($behalfOrganization['organization_id']);
33260076 1136 }
1137 // create employer relationship with $contactID only when new organization is there
1138 // else retain the existing relationship
1139 else {
1140 // get the Employee relationship type id
1141 $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
b9dc56f5 1142
33260076 1143 // keep relationship params ready
1144 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1145 $relParams['is_permission_a_b'] = 1;
1146 $relParams['is_active'] = 1;
1147 $isNotCurrentEmployer = TRUE;
bb06e9ed 1148 }
6a488035 1149
75637f22
EM
1150 // formalities for creating / editing organization.
1151 $behalfOrganization['contact_type'] = 'Organization';
c8bde7ea 1152
75637f22
EM
1153 if (!$orgID) {
1154 // check if matching organization contact exists
1155 $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization');
1156 $dedupeParams['check_permission'] = FALSE;
1157 $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
6a488035 1158
75637f22
EM
1159 // CRM-6243 says to pick the first org even if more than one match
1160 if (count($dupeIDs) >= 1) {
1161 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1162 // don't allow name edit
1163 unset($behalfOrganization['organization_name']);
6a488035
TO
1164 }
1165 }
1166 else {
75637f22
EM
1167 // if found permissioned related organization, allow location edit
1168 $behalfOrganization['contact_id'] = $orgID;
1169 // don't allow name edit
1170 unset($behalfOrganization['organization_name']);
6a488035
TO
1171 }
1172
75637f22
EM
1173 // handling for image url
1174 if (!empty($behalfOrganization['image_URL'])) {
1175 CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
6a488035
TO
1176 }
1177
75637f22
EM
1178 // create organization, add location
1179 $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID,
1180 NULL, NULL, 'Organization'
1181 );
1182 // create relationship
33260076 1183 if ($isNotCurrentEmployer) {
1184 $relParams['contact_check'][$orgID] = 1;
1185 $cid = array('contact' => $contactID);
1186 CRM_Contact_BAO_Relationship::legacyCreateMultiple($relParams, $cid);
1187 }
1f1740fe 1188
75637f22
EM
1189 // if multiple match - send a duplicate alert
1190 if ($dupeIDs && (count($dupeIDs) > 1)) {
1191 $values['onbehalf_dupe_alert'] = 1;
1192 // required for IPN
1193 $params['onbehalf_dupe_alert'] = 1;
6a488035 1194 }
cde484fd 1195
75637f22
EM
1196 // make sure organization-contact-id is considered for recording
1197 // contribution/membership etc..
1198 if ($contactID != $orgID) {
1199 // take a note of contact-id, so we can send the
1200 // receipt to individual contact as well.
6a488035 1201
75637f22
EM
1202 // required for mailing/template display ..etc
1203 $values['related_contact'] = $contactID;
6a488035 1204
75637f22
EM
1205 //make this employee of relationship as current
1206 //employer / employee relationship, CRM-3532
33260076 1207 if ($isNotCurrentEmployer &&
75637f22
EM
1208 ($orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1209 ) {
33260076 1210 $isNotCurrentEmployer = FALSE;
6a488035 1211 }
6a488035 1212
33260076 1213 if (!$isNotCurrentEmployer && $orgID) {
75637f22
EM
1214 //build current employer params
1215 $currentEmpParams[$contactID] = $orgID;
1216 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
6a488035 1217 }
6a488035 1218
75637f22
EM
1219 // contribution / signup will be done using this
1220 // organization id.
1221 $contactID = $orgID;
6a488035 1222 }
75637f22
EM
1223 }
1224
6a488035 1225 /**
75637f22 1226 * Function used to send notification mail to pcp owner.
6a488035 1227 *
75637f22 1228 * This is used by contribution and also event PCPs.
03110609 1229 *
75637f22
EM
1230 * @param object $contribution
1231 * @param object $contributionSoft
1232 * Contribution object.
12f92dbd 1233 */
12f92dbd 1234 public static function pcpNotifyOwner($contribution, $contributionSoft) {
5fe87df6
N
1235 $params = array('id' => $contributionSoft->pcp_id);
1236 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1237 $ownerNotifyID = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1238
1239 if ($ownerNotifyID != CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1240 (($ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1241 CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id, 'is_notify')) ||
1242 $ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1243 $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info',
1244 "reset=1&id={$contributionSoft->pcp_id}",
1245 TRUE, NULL, FALSE, TRUE
1246 );
12f92dbd 1247 // set email in the template here
5fe87df6 1248
b576d770 1249 if (CRM_Core_BAO_LocationType::getBilling()) {
1250 list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id,
1251 FALSE, CRM_Core_BAO_LocationType::getBilling());
5fe87df6
N
1252 }
1253 // get primary location email if no email exist( for billing location).
1254 if (!$email) {
1255 list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id);
1256 }
1257 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contributionSoft->contact_id);
12f92dbd 1258 $tplParams = array(
5fe87df6 1259 'page_title' => $pcpInfo['title'],
12f92dbd
N
1260 'receive_date' => $contribution->receive_date,
1261 'total_amount' => $contributionSoft->amount,
1262 'donors_display_name' => $donorName,
5fe87df6
N
1263 'donors_email' => $email,
1264 'pcpInfoURL' => $pcpInfoURL,
12f92dbd 1265 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll,
dd55005c 1266 'currency' => $contributionSoft->currency,
12f92dbd
N
1267 );
1268 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
1269 $sendTemplateParams = array(
1270 'groupName' => 'msg_tpl_workflow_contribution',
1271 'valueName' => 'pcp_owner_notify',
1272 'contactId' => $contributionSoft->contact_id,
5fe87df6
N
1273 'toEmail' => $ownerEmail,
1274 'toName' => $ownerName,
12f92dbd
N
1275 'from' => "$domainValues[0] <$domainValues[1]>",
1276 'tplParams' => $tplParams,
1277 'PDFFilename' => 'receipt.pdf',
1278 );
1279 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
1280 }
1281 }
1282
1283 /**
5e4f7f74
EM
1284 * Function used to se pcp related defaults / params.
1285 *
1286 * This is used by contribution and also event PCPs
6a488035 1287 *
014c4014
TO
1288 * @param CRM_Core_Form $page
1289 * Form object.
1290 * @param array $params
6a488035 1291 *
cd6994fc 1292 * @return array
6a488035 1293 */
00be9182 1294 public static function processPcp(&$page, $params) {
547206bc 1295 $params['pcp_made_through_id'] = $page->_pcpId;
6a488035 1296 $page->assign('pcpBlock', TRUE);
8cc574cf 1297 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
6a488035
TO
1298 $params['pcp_roll_nickname'] = ts('Anonymous');
1299 $params['pcp_is_anonymous'] = 1;
1300 }
1301 else {
1302 $params['pcp_is_anonymous'] = 0;
1303 }
1304 foreach (array(
547206bc 1305 'pcp_display_in_roll',
1306 'pcp_is_anonymous',
1307 'pcp_roll_nickname',
21dfd5f5 1308 'pcp_personal_note',
547206bc 1309 ) as $val) {
a7488080 1310 if (!empty($params[$val])) {
6a488035
TO
1311 $page->assign($val, $params[$val]);
1312 }
1313 }
1314
1315 return $params;
1316 }
705b4205
EM
1317
1318 /**
5e4f7f74
EM
1319 * Process membership.
1320 *
5624f515 1321 * @param array $membershipParams
014c4014 1322 * @param int $contactID
5624f515
EM
1323 * @param array $customFieldsFormatted
1324 * @param array $fieldTypes
1325 * @param array $premiumParams
014c4014
TO
1326 * @param array $membershipLineItems
1327 * Line items specifically relating to memberships.
ab8fe4ef 1328 * @param bool $isPayLater
705b4205 1329 */
4b6c8c1e 1330 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1331 $membershipLineItems, $isPayLater) {
8bc79dfc 1332
4b6c8c1e 1333 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1334 $membershipTypes = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIDs);
1335 $membershipType = empty($membershipTypes) ? array() : reset($membershipTypes);
1336 $isPending = $this->getIsPending();
5624f515 1337
4b6c8c1e 1338 $this->assign('membership_name', CRM_Utils_Array::value('name', $membershipType));
1fc22ffa 1339 $this->_values['membership_name'] = CRM_Utils_Array::value('name', $membershipType);
7c113627 1340
4b6c8c1e 1341 $isPaidMembership = FALSE;
1342 if ($this->_amount >= 0.0 && isset($membershipParams['amount'])) {
1343 //amount must be greater than zero for
1344 //adding contribution record to contribution table.
1345 //this condition arises when separate membership payment is
1346 //enabled and contribution amount is not selected. fix for CRM-3010
1347 $isPaidMembership = TRUE;
1348 }
1349 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id, $this->_values['amount_block_is_active']);
7c113627 1350
4b6c8c1e 1351 if ($this->_values['amount_block_is_active']) {
1352 $financialTypeID = $this->_values['financial_type_id'];
705b4205 1353 }
4b6c8c1e 1354 else {
1355 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $membershipType, CRM_Utils_Array::value('financial_type_id', $membershipParams));
705b4205 1356 }
4b6c8c1e 1357
1358 if (CRM_Utils_Array::value('membership_source', $this->_params)) {
1359 $membershipParams['contribution_source'] = $this->_params['membership_source'];
1360 }
1361
1362 $this->postProcessMembership($membershipParams, $contactID,
1363 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId, $isProcessSeparateMembershipTransaction, $financialTypeID,
1364 $membershipLineItems, $isPayLater, $isPending);
1365
1366 $this->assign('membership_assign', TRUE);
1367 $this->set('membershipTypeID', $membershipParams['selectMembership']);
705b4205 1368 }
fb49fa48 1369
8bc79dfc 1370 /**
668ddfc2
EM
1371 * Process the Memberships.
1372 *
1373 * @param array $membershipParams
1374 * Array of membership fields.
1375 * @param int $contactID
1376 * Contact id.
1377 * @param CRM_Contribute_Form_Contribution_Confirm $form
1378 * Confirmation form object.
1379 *
1380 * @param array $premiumParams
1381 * @param null $customFieldsFormatted
1382 * @param null $includeFieldTypes
1383 *
1384 * @param array $membershipDetails
1385 *
1386 * @param array $membershipTypeIDs
1387 *
1388 * @param bool $isPaidMembership
1389 * @param array $membershipID
1390 *
1391 * @param bool $isProcessSeparateMembershipTransaction
1392 *
1393 * @param int $financialTypeID
1394 * @param array $membershipLineItems
1395 * Line items specific to membership payment that is separate to contribution.
1396 * @param bool $isPayLater
1397 * @param bool $isPending
1398 *
1399 * @throws \CRM_Core_Exception
1400 */
1401 protected function postProcessMembership(
1402 $membershipParams, $contactID, &$form, $premiumParams,
1403 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1404 $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending) {
82583880 1405 $membershipContribution = NULL;
668ddfc2 1406 $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE);
63137f3a 1407 $errors = $createdMemberships = $paymentResults = array();
858f7096 1408 $form->_values['isMembership'] = TRUE;
449f4c90 1409 $isRecurForFirstTransaction = CRM_Utils_Array::value('is_recur', $form->_values, CRM_Utils_Array::value('is_recur', $membershipParams));
858f7096 1410 $totalAmount = $membershipParams['amount'];
449f4c90 1411
668ddfc2
EM
1412 if ($isPaidMembership) {
1413 if ($isProcessSeparateMembershipTransaction) {
1414 // If we have 2 transactions only one can use the invoice id.
1415 $membershipParams['invoiceID'] .= '-2';
449f4c90 1416 if (!empty($membershipParams['auto_renew'])) {
1417 $isRecurForFirstTransaction = FALSE;
1418 }
668ddfc2
EM
1419 }
1420
1421 $paymentResult = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams,
5fb28746 1422 $contactID,
668ddfc2
EM
1423 $financialTypeID,
1424 'membership',
449f4c90 1425 $isTest,
1426 $isRecurForFirstTransaction
668ddfc2 1427 );
668ddfc2 1428
82583880 1429 if (!empty($paymentResult['contribution'])) {
5fb28746 1430 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
668ddfc2
EM
1431 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1432 $membershipContribution = $paymentResult['contribution'];
1433 // Save the contribution ID so that I can be used in email receipts
1434 // For example, if you need to generate a tax receipt for the donation only.
1435 $form->_values['contribution_other_id'] = $membershipContribution->id;
1436 }
1437 }
1438
1439 if ($isProcessSeparateMembershipTransaction) {
1440 try {
1441 $form->_lineItem = $membershipLineItems;
1442 if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) {
1443 unset($membershipParams['is_recur']);
1444 }
63137f3a 1445 list($membershipContribution, $secondPaymentResult) = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams,
668ddfc2 1446 $isTest, $membershipLineItems, CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array::value('financial_type_id', $membershipDetails));
63137f3a 1447 $paymentResults[] = array('contribution_id' => $membershipContribution->id, 'result' => $secondPaymentResult);
668ddfc2
EM
1448 }
1449 catch (CRM_Core_Exception $e) {
1450 $errors[2] = $e->getMessage();
1451 $membershipContribution = NULL;
1452 }
1453 }
1454
1455 $membership = NULL;
1456 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1457 $membershipContributionID = $membershipContribution->id;
1458 }
1459
1460 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1461 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1462 $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1463 }
1464 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1465 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1466 $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
1467 foreach ($membershipTypeIDs as $memType) {
1468 $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
1469 if (!empty($membershipContribution)) {
1470 $pendingStatus = CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name');
1471 $pending = ($membershipContribution->contribution_status_id == $pendingStatus) ? TRUE : FALSE;
1472 }
1473 else {
1474 $pending = $isPending;
1475 }
1476 $contributionRecurID = isset($form->_params['contributionRecurID']) ? $form->_params['contributionRecurID'] : NULL;
1477
1478 $membershipSource = NULL;
1479 if (!empty($form->_params['membership_source'])) {
1480 $membershipSource = $form->_params['membership_source'];
1481 }
1482 elseif (isset($form->_values['title']) && !empty($form->_values['title'])) {
1483 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values['title'];
1484 }
1485 $isPayLater = NULL;
1486 if (isset($form->_params)) {
1487 $isPayLater = CRM_Utils_Array::value('is_pay_later', $form->_params);
1488 }
1489 $campaignId = NULL;
1490 if (isset($form->_values) && is_array($form->_values) && !empty($form->_values)) {
1491 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_params);
1492 if (!array_key_exists('campaign_id', $form->_params)) {
1493 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1494 }
1495 }
1496
1497 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership::renewMembership(
1498 $contactID, $memType, $isTest,
1499 date('YmdHis'), CRM_Utils_Array::value('cms_contactID', $membershipParams),
1500 $customFieldsFormatted,
1501 $numTerms, $membershipID, $pending,
1502 $contributionRecurID, $membershipSource, $isPayLater, $campaignId
1503 );
1504 $form->set('renewal_mode', $renewalMode);
1505 if (!empty($dates)) {
1fc22ffa 1506 $form->assign('mem_start_date', CRM_Utils_Date::customFormat($dates['start_date'], '%Y%m%d'));
1507 $form->assign('mem_end_date', CRM_Utils_Date::customFormat($dates['end_date'], '%Y%m%d'));
668ddfc2
EM
1508 }
1509
1510 if (!empty($membershipContribution)) {
1511 // update recurring id for membership record
1512 CRM_Member_BAO_Membership::updateRecurMembership($membership, $membershipContribution);
1513 CRM_Member_BAO_Membership::linkMembershipPayment($membership, $membershipContribution);
1514 }
1515 }
1516 if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
1517 foreach ($form->_lineItem[$form->_priceSetId] as & $priceFieldOp) {
1518 if (!empty($priceFieldOp['membership_type_id']) &&
1519 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1520 ) {
1521 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1522 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%B %E%f, %Y') : '-';
1523 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%B %E%f, %Y') : '-';
1524 }
1525 else {
1526 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1527 }
1528 }
1529 $form->_values['lineItem'] = $form->_lineItem;
1530 $form->assign('lineItem', $form->_lineItem);
1531 }
1532 }
1533
1534 if (!empty($errors)) {
1535 $message = $this->compileErrorMessage($errors);
1536 throw new CRM_Core_Exception($message);
1537 }
1538 $form->_params['createdMembershipIDs'] = array();
1539
1540 // CRM-7851 - Moved after processing Payment Errors
1541 //@todo - the reasoning for this being here seems a little outdated
1542 foreach ($createdMemberships as $createdMembership) {
1543 CRM_Core_BAO_CustomValueTable::postProcess(
1544 $form->_params,
1545 'civicrm_membership',
1546 $createdMembership->id,
1547 'Membership'
1548 );
1549 $form->_params['createdMembershipIDs'][] = $createdMembership->id;
1550 }
1551 if (count($createdMemberships) == 1) {
1552 //presumably this is only relevant for exactly 1 membership
1553 $form->_params['membershipID'] = $createdMembership->id;
1554 }
1555
1556 //CRM-15232: Check if membership is created and on the basis of it use
1557 //membership receipt template to send payment receipt
1558 if (count($createdMemberships)) {
1559 $form->_values['isMembership'] = TRUE;
1560 }
82583880
EM
1561 if (isset($membershipContributionID)) {
1562 $form->_values['contribution_id'] = $membershipContributionID;
1563 }
a506739a 1564
1fc22ffa 1565 if (empty($form->_params['is_pay_later']) && $form->_paymentProcessor) {
a506739a 1566 // the is_monetary concept probably should be deprecated as it can be calculated from
1567 // the existence of 'amount' & seems fragile.
668ddfc2
EM
1568 if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
1569 // call postProcess hook before leaving
1570 $form->postProcessHook();
668ddfc2 1571 }
a506739a 1572
82583880 1573 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
fe3dbce1 1574 // The contribution_other_id is effectively the ID for the only contribution or the non-membership contribution.
1575 // Since we have called the membership contribution (in a 2 contribution scenario) this is out
1576 // primary-contribution compared to that - but let's face it - it's all just too hard & confusing at the moment!
1577 $paymentParams = array_merge($form->_params, array('contributionID' => $form->_values['contribution_other_id']));
1578 $paymentActionResult = $payment->doPayment($paymentParams, 'contribute');
63137f3a 1579 $paymentResults[] = array('contribution_id' => $paymentResult['contribution']->id, 'result' => $paymentActionResult);
668ddfc2
EM
1580 // Do not send an email if Recurring transaction is done via Direct Mode
1581 // Email will we sent when the IPN is received.
63137f3a 1582 foreach ($paymentResults as $result) {
7c864699
TL
1583 //CRM-18211: Fix situation where second contribution doesn't exist because it is optional.
1584 if ($result['contribution_id']) {
1585 $this->completeTransaction($result['result'], $result['contribution_id']);
1586 }
63137f3a 1587 }
668ddfc2
EM
1588 return;
1589 }
1590
1fc22ffa 1591 $emailValues = array_merge($membershipParams, $form->_values);
1592 $emailValues['membership_assign'] = 1;
858f7096 1593 // Finally send an email receipt for pay-later scenario (although it might sometimes be caught above!)
1594 if ($totalAmount == 0) {
1595 // This feels like a bizarre hack as the variable name doesn't seem to be directly connected to it's use in the template.
1596 $emailValues['useForMember'] = 0;
858f7096 1597 $emailValues['amount'] = 0;
036c6315 1598
1599 //CRM-18071, where on selecting $0 free membership payment section got hidden and
1600 // also it reset any payment processor selection result into pending free membership
1601 // so its a kind of hack to complete free membership at this point since there is no $form->_paymentProcessor info
1602 if (empty($form->_params['is_pay_later']) && !empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1603 $paymentProcessorIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('payment_processor', $this->_values));
1604 if (empty($form->_paymentProcessor) && !empty($paymentProcessorIDs)) {
1605 $this->_paymentProcessor['id'] = $paymentProcessorIDs[0];
1606 }
1607 $result = array('payment_status_id' => 1, 'contribution' => $membershipContribution);
1608 $this->completeTransaction($result, $result['contribution']->id);
1609 }
858f7096 1610 }
1fc22ffa 1611
668ddfc2 1612 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
858f7096 1613 $emailValues,
668ddfc2
EM
1614 $isTest, FALSE,
1615 $includeFieldTypes
1616 );
1617 }
1618
1619 /**
1620 * Turn array of errors into message string.
1621 *
1622 * @param array $errors
1623 *
1624 * @return string
1625 */
1626 protected function compileErrorMessage($errors) {
1627 foreach ($errors as $error) {
1628 if (is_string($error)) {
1629 $message[] = $error;
1630 }
1631 }
1632 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1633 }
1634
1635 /**
1636 * Where a second separate financial transaction is supported we will process it here.
1637 *
1638 * @param int $contactID
1639 * @param CRM_Contribute_Form_Contribution_Confirm $form
1640 * @param array $tempParams
1641 * @param bool $isTest
1642 * @param array $lineItems
1643 * @param $minimumFee
1644 * @param int $financialTypeID
1645 *
1646 * @throws CRM_Core_Exception
1647 * @throws Exception
1648 * @return CRM_Contribute_BAO_Contribution
1649 */
1650 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1651 $financialTypeID) {
1652 $financialType = new CRM_Financial_DAO_FinancialType();
1653 $financialType->id = $financialTypeID;
1654 $financialType->find(TRUE);
1655 $tempParams['amount'] = $minimumFee;
1656 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
449f4c90 1657 $isRecur = CRM_Utils_Array::value('is_recur', $tempParams);
668ddfc2 1658
668ddfc2
EM
1659 //assign receive date when separate membership payment
1660 //and contribution amount not selected.
1661 if ($form->_amount == 0) {
1662 $now = date('YmdHis');
1663 $form->_params['receive_date'] = $now;
1664 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
1665 $form->set('params', $form->_params);
1666 $form->assign('receive_date', $receiveDate);
1667 }
1668
668ddfc2 1669 $form->set('membership_amount', $minimumFee);
668ddfc2
EM
1670 $form->assign('membership_amount', $minimumFee);
1671
1672 // we don't need to create the user twice, so lets disable cms_create_account
1673 // irrespective of the value, CRM-2888
1674 $tempParams['cms_create_account'] = 0;
1675
668ddfc2
EM
1676 //set this variable as we are not creating pledge for
1677 //separate membership payment contribution.
1678 //so for differentiating membership contribution from
1679 //main contribution.
1680 $form->_params['separate_membership_payment'] = 1;
3febe800 1681 $contributionParams = array(
1682 'contact_id' => $contactID,
1683 'line_item' => $lineItems,
1684 'is_test' => $isTest,
1685 'campaign_id' => CRM_Utils_Array::value('campaign_id', $tempParams, CRM_Utils_Array::value('campaign_id',
1686 $form->_values)),
1687 'contribution_page_id' => $form->_id,
1688 'source' => CRM_Utils_Array::value('source', $tempParams, CRM_Utils_Array::value('description', $tempParams)),
1689 );
1690 $isMonetary = !empty($form->_values['is_monetary']);
1691 if ($isMonetary) {
1692 if (empty($paymentParams['is_pay_later'])) {
f3a63d1e 1693 $contributionParams['payment_instrument_id'] = $form->_paymentProcessor['payment_instrument_id'];
3febe800 1694 }
1695 }
668ddfc2
EM
1696 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($form,
1697 $tempParams,
0193ebdb 1698 $tempParams,
3febe800 1699 $contributionParams,
668ddfc2 1700 $financialType,
668ddfc2 1701 TRUE,
449f4c90 1702 $form->_bltID,
1703 $isRecur
668ddfc2 1704 );
0193ebdb 1705
4ae9c8ac 1706 $result = array();
0193ebdb 1707 if ($form->_values['is_monetary'] && !$form->_params['is_pay_later'] && $minimumFee > 0.0) {
1708 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1709 // now we compensate here.
1710 if (empty($form->_paymentProcessor['object'])) {
1711 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1712 }
1713 else {
1714 $payment = $form->_paymentProcessor['object'];
1715 }
1716 $result = $payment->doPayment($tempParams, 'contribute');
1717 $form->set('membership_trx_id', $result['trxn_id']);
1718 $form->assign('membership_trx_id', $result['trxn_id']);
0193ebdb 1719 }
1720
63137f3a 1721 return array($membershipContribution, $result);
668ddfc2
EM
1722 }
1723
1724 /**
8bc79dfc
EM
1725 * Is the payment a pending payment.
1726 *
1727 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1728 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1729 *
8bc79dfc
EM
1730 * @return bool
1731 */
1732 protected function getIsPending() {
0f2b049e 1733 // The concept of contributeMode is deprecated.
1734 // the is_monetary concept probably should be too as it can be calculated from
1735 // the existence of 'amount' & seems fragile.
8bc79dfc
EM
1736 if (((isset($this->_contributeMode)) || !empty
1737 ($this->_params['is_pay_later'])
1738 ) &&
1739 (($this->_values['is_monetary'] && $this->_amount > 0.0))
1740 ) {
1741 return TRUE;
1742 }
1743 return FALSE;
1744 }
1745
fb49fa48 1746 /**
5e4f7f74 1747 * Are we going to do 2 financial transactions.
fb49fa48 1748 *
5e4f7f74
EM
1749 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1750 * contribution
1751 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
fb49fa48 1752 *
014c4014 1753 * @param int $formID
fb49fa48
EM
1754 * @param bool $amountBlockActiveOnForm
1755 *
1756 * @return bool
1757 */
1758 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1759 $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($formID);
1760 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1761 return TRUE;
1762 }
1763 return FALSE;
1764 }
df6c4f28
EM
1765
1766 /**
5e4f7f74
EM
1767 * This function sets the fields.
1768 *
df6c4f28
EM
1769 * - $this->_params['amount_level']
1770 * - $this->_params['selectMembership']
1771 * And under certain circumstances sets
1772 * $this->_params['amount'] = null;
1773 *
100fef9d 1774 * @param int $priceSetID
df6c4f28
EM
1775 */
1776 public function setFormAmountFields($priceSetID) {
1777 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config');
1778 $priceField = new CRM_Price_DAO_PriceField();
1779 $priceField->price_set_id = $priceSetID;
1780 $priceField->orderBy('weight');
1781 $priceField->find();
06b4ee3e 1782 $paramWeDoNotUnderstand = NULL;
df6c4f28
EM
1783
1784 while ($priceField->fetch()) {
df6c4f28
EM
1785 if ($priceField->name == "contribution_amount") {
1786 $paramWeDoNotUnderstand = $priceField->id;
1787 }
1788 if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) {
1789 if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') {
c039f658 1790 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1791 // function to get correct amount level consistently. Remove setting of the amount level in
1792 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1793 // to cover all variants.
df6c4f28
EM
1794 $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1795 $this->_params["price_{$priceField->id}"], 'label');
1796 }
1797 if ($priceField->name == "membership_amount") {
1798 $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1799 $this->_params["price_{$priceField->id}"], 'membership_type_id');
1800 }
5e4f7f74
EM
1801 }
1802 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1803 // as membership amount.
df6c4f28
EM
1804 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1805 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1806 // so we should merge them together
1807 // the quick config seems like a red-herring - if this is about a separate membership payment then there
f64a217a 1808 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
df6c4f28
EM
1809 elseif (
1810 CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock)
1811 && !empty($this->_values['fee'][$priceField->id])
1812 && ($this->_values['fee'][$priceField->id]['name'] == "other_amount")
1813 && CRM_Utils_Array::value("price_{$paramWeDoNotUnderstand}", $this->_params) < 1
1814 && empty($this->_params["price_{$priceField->id}"])
1815 ) {
a13f3d8c 1816 $this->_params['amount'] = NULL;
df6c4f28
EM
1817 }
1818
1819 // Fix for CRM-14375 - If we are using separate payments and "no
1820 // thank you" is selected for the additional contribution, set
1821 // contribution amount to be null, so that it will not show
1822 // contribution amount same as membership amount.
1823 //@todo - merge with section above
1824 if ($this->_membershipBlock['is_separate_payment']
3c0201c9 1825 && !empty($this->_values['fee'][$priceField->id])
df6c4f28
EM
1826 && CRM_Utils_Array::value('name', $this->_values['fee'][$priceField->id]) == 'contribution_amount'
1827 && CRM_Utils_Array::value("price_{$priceField->id}", $this->_params) == '-1'
1828 ) {
a13f3d8c 1829 $this->_params['amount'] = NULL;
df6c4f28
EM
1830 }
1831 }
1832 }
be26f3e0 1833
03110609 1834 /**
5e4f7f74
EM
1835 * Submit function.
1836 *
03110609
EM
1837 * @param array $params
1838 *
1839 * @throws CiviCRM_API3_Exception
1840 */
00be9182 1841 public static function submit($params) {
be26f3e0
EM
1842 $form = new CRM_Contribute_Form_Contribution_Confirm();
1843 $form->_id = $params['id'];
75637f22 1844
f64a217a
EM
1845 CRM_Contribute_BAO_ContributionPage::setValues($form->_id, $form->_values);
1846 $form->_separateMembershipPayment = CRM_Contribute_BAO_ContributionPage::getIsMembershipPayment($form->_id);
be26f3e0
EM
1847 //this way the mocked up controller ignores the session stuff
1848 $_SERVER['REQUEST_METHOD'] = 'GET';
1849 $form->controller = new CRM_Contribute_Controller_Contribution();
1850 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1851 $paramsProcessedForForm = $form->_params = self::getFormParams($params['id'], $params);
f64a217a 1852 $form->_amount = $params['amount'];
870156d6 1853 // hack these in for test support.
1854 $form->_fields['billing_first_name'] = 1;
1855 $form->_fields['billing_last_name'] = 1;
be26f3e0
EM
1856 $priceSetID = $form->_params['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1857 $priceFields = CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
f64a217a
EM
1858 $priceSetFields = reset($priceFields);
1859 $form->_values['fee'] = $priceSetFields['fields'];
5624f515 1860 $form->_priceSetId = $priceSetID;
be26f3e0 1861 $form->setFormAmountFields($priceSetID);
e02d7e96
EM
1862 if (!empty($params['payment_processor_id'])) {
1863 $form->_paymentProcessor = civicrm_api3('payment_processor', 'getsingle', array(
1864 'id' => $params['payment_processor_id'],
1865 ));
0f2b049e 1866 // The concept of contributeMode is deprecated as is the billing_mode concept.
a13f3d8c 1867 if ($form->_paymentProcessor['billing_mode'] == 1) {
e6fa4056
EM
1868 $form->_contributeMode = 'direct';
1869 }
1870 else {
1871 $form->_contributeMode = 'notify';
1872 }
d25e4224 1873 }
07102c2c 1874 else {
e02d7e96 1875 $form->_params['payment_processor_id'] = 0;
07102c2c 1876 }
be26f3e0
EM
1877 $priceFields = $priceFields[$priceSetID]['fields'];
1878 CRM_Price_BAO_PriceSet::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1879 $form->_lineItem = array($priceSetID => $lineItems);
75637f22 1880 $form->processFormSubmission(CRM_Utils_Array::value('contact_id', $params));
be26f3e0
EM
1881 }
1882
1883 /**
ceb9fecb
EM
1884 * Helper function for static submit function.
1885 *
1886 * Set relevant params - help us to build up an array that we can pass in.
5e4f7f74 1887 *
100fef9d 1888 * @param int $id
be26f3e0
EM
1889 * @param array $params
1890 *
1891 * @return array
1892 * @throws CiviCRM_API3_Exception
1893 */
00be9182 1894 public static function getFormParams($id, array $params) {
a13f3d8c 1895 if (!isset($params['is_pay_later'])) {
e02d7e96 1896 if (!empty($params['payment_processor_id'])) {
d25e4224
DG
1897 $params['is_pay_later'] = 0;
1898 }
1899 else {
1900 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
a13f3d8c 1901 'id' => $id,
21dfd5f5 1902 'return' => 'is_pay_later',
a13f3d8c 1903 ));
d25e4224 1904 }
be26f3e0 1905 }
a13f3d8c 1906 if (empty($params['price_set_id'])) {
be26f3e0
EM
1907 $params['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id']);
1908 }
1909 return $params;
1910 }
96025800 1911
75637f22
EM
1912 /**
1913 * Post form submission handling.
1914 *
1915 * This is also called from the test suite.
1916 *
1917 * @param int $contactID
1918 *
1919 * @return array
1920 */
1921 protected function processFormSubmission($contactID) {
1922 $isPayLater = $this->_params['is_pay_later'];
858f7096 1923 if (!isset($this->_params['payment_processor_id'])) {
1924 // If there is no processor we are using the pay-later manual pseudo-processor.
1925 // (note it might make sense to make this a row in the processor table in the db).
1926 $this->_params['payment_processor_id'] = 0;
1927 }
036c6315 1928 if (isset($this->_params['payment_processor_id']) && $this->_params['payment_processor_id'] === 0) {
75637f22
EM
1929 $this->_params['is_pay_later'] = $isPayLater = TRUE;
1930 }
1931 // add a description field at the very beginning
1932 $this->_params['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
1933
1934 $this->_params['accountingCode'] = CRM_Utils_Array::value('accountingCode', $this->_values);
1935
1936 // fix currency ID
1937 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
1938
1939 //carry payment processor id.
1940 if (CRM_Utils_Array::value('id', $this->_paymentProcessor)) {
1941 $this->_params['payment_processor_id'] = $this->_paymentProcessor['id'];
1942 }
f85b8063
KJ
1943
1944 $premiumParams = $membershipParams = $params = $this->_params;
75637f22
EM
1945 if (!empty($params['image_URL'])) {
1946 CRM_Contact_BAO_Contact::processImageParams($params);
1947 }
f85b8063 1948
75637f22
EM
1949 $fields = array('email-Primary' => 1);
1950
1951 // get the add to groups
1952 $addToGroups = array();
1953
1954 // now set the values for the billing location.
1955 foreach ($this->_fields as $name => $value) {
1956 $fields[$name] = 1;
1957
1958 // get the add to groups for uf fields
1959 if (!empty($value['add_to_group_id'])) {
1960 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
1961 }
1962 }
1963
bddc8a28 1964 $fields = $this->formatParamsForPaymentProcessor($fields);
75637f22
EM
1965
1966 // billing email address
1967 $fields["email-{$this->_bltID}"] = 1;
1968
75637f22
EM
1969 // if onbehalf-of-organization contribution, take out
1970 // organization params in a separate variable, to make sure
1971 // normal behavior is continued. And use that variable to
1972 // process on-behalf-of functionality.
4779abb3 1973 if (!empty($this->_values['onbehalf_profile_id'])) {
75637f22
EM
1974 $behalfOrganization = array();
1975 $orgFields = array('organization_name', 'organization_id', 'org_option');
1976 foreach ($orgFields as $fld) {
1977 if (array_key_exists($fld, $params)) {
1978 $behalfOrganization[$fld] = $params[$fld];
1979 unset($params[$fld]);
1980 }
1981 }
1982
1983 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
1984 foreach ($params['onbehalf'] as $fld => $values) {
1985 if (strstr($fld, 'custom_')) {
1986 $behalfOrganization[$fld] = $values;
1987 }
1988 elseif (!(strstr($fld, '-'))) {
1989 if (in_array($fld, array(
1990 'contribution_campaign_id',
1991 'member_campaign_id',
1992 ))) {
1993 $fld = 'campaign_id';
1994 }
1995 else {
1996 $behalfOrganization[$fld] = $values;
1997 }
1998 $this->_params[$fld] = $values;
1999 }
2000 }
2001 }
2002
2003 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2004 foreach ($params['onbehalf_location'] as $block => $vals) {
2005 //fix for custom data (of type checkbox, multi-select)
2006 if (substr($block, 0, 7) == 'custom_') {
2007 continue;
2008 }
2009 // fix the index of block elements
2010 if (is_array($vals)) {
2011 foreach ($vals as $key => $val) {
2012 //dont adjust the index of address block as
2013 //it's index is WRT to location type
2014 $newKey = ($block == 'address') ? $key : ++$key;
2015 $behalfOrganization[$block][$newKey] = $val;
2016 }
2017 }
2018 }
2019 unset($params['onbehalf_location']);
2020 }
2021 if (!empty($params['onbehalf[image_URL]'])) {
2022 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2023 }
2024 }
2025
2026 // check for profile double opt-in and get groups to be subscribed
2027 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
2028
2029 // since we are directly adding contact to group lets unset it from mailing
2030 if (!empty($addToGroups)) {
2031 foreach ($addToGroups as $groupId) {
2032 if (isset($subscribeGroupIds[$groupId])) {
2033 unset($subscribeGroupIds[$groupId]);
2034 }
2035 }
2036 }
2037
2038 foreach ($addToGroups as $k) {
2039 if (array_key_exists($k, $subscribeGroupIds)) {
2040 unset($addToGroups[$k]);
2041 }
2042 }
2043
2044 if (empty($contactID)) {
2045 $dupeParams = $params;
2046 if (!empty($dupeParams['onbehalf'])) {
2047 unset($dupeParams['onbehalf']);
2048 }
2049 if (!empty($dupeParams['honor'])) {
2050 unset($dupeParams['honor']);
2051 }
2052
2053 $dedupeParams = CRM_Dedupe_Finder::formatParams($dupeParams, 'Individual');
2054 $dedupeParams['check_permission'] = FALSE;
2055 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
2056
2057 // if we find more than one contact, use the first one
2058 $contactID = CRM_Utils_Array::value(0, $ids);
2059
2060 // Fetch default greeting id's if creating a contact
2061 if (!$contactID) {
2062 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
2063 if (!isset($params[$greeting])) {
2064 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
2065 }
2066 }
2067 }
2068 $contactType = NULL;
2069 }
2070 else {
2071 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2072 }
2073 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
2074 $params,
2075 $fields,
2076 $contactID,
2077 $addToGroups,
2078 NULL,
2079 $contactType,
2080 TRUE
2081 );
2082
2083 // Make the contact ID associated with the contribution available at the Class level.
2084 // Also make available to the session.
2085 //@todo consider handling this in $this->getContactID();
2086 $this->set('contactID', $contactID);
2087 $this->_contactID = $contactID;
2088
2089 //get email primary first if exist
2090 $subscriptionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
2091 if (!$subscriptionEmail['email']) {
2092 $subscriptionEmail['email'] = CRM_Utils_Array::value("email-{$this->_bltID}", $params);
2093 }
2094 // subscribing contact to groups
2095 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2096 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2097 }
2098
2099 // If onbehalf-of-organization contribution / signup, add organization
2100 // and it's location.
a9653117 2101 if (isset($this->_values['onbehalf_profile_id']) &&
2102 isset($behalfOrganization['organization_name']) &&
2103 ($this->_values['is_for_organization'] == 2 ||
2104 !empty($this->_params['is_for_organization'])
2105 )
2106 ) {
75637f22
EM
2107 $ufFields = array();
2108 foreach ($this->_fields['onbehalf'] as $name => $value) {
2109 $ufFields[$name] = 1;
2110 }
2111 self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values,
2112 $this->_params, $ufFields
2113 );
2114 }
2115 elseif (!empty($this->_membershipContactID) && $contactID != $this->_membershipContactID) {
2116 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2117 // store current user id as related contact for later use for mailing / activity..
2118 $this->_values['related_contact'] = $contactID;
2119 $this->_params['related_contact'] = $contactID;
2120 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2121 $contactID = $this->_membershipContactID;
2122 }
2123
2124 // lets store the contactID in the session
2125 // for things like tell a friend
2126 $session = CRM_Core_Session::singleton();
2127 if (!$session->get('userID')) {
2128 $session->set('transaction.userID', $contactID);
2129 }
2130 else {
2131 $session->set('transaction.userID', NULL);
2132 }
2133
2134 $this->_useForMember = $this->get('useForMember');
2135
2136 // store the fact that this is a membership and membership type is selected
75637f22
EM
2137 if ((!empty($membershipParams['selectMembership']) &&
2138 $membershipParams['selectMembership'] != 'no_thanks'
2139 ) ||
2140 $this->_useForMember
2141 ) {
75637f22
EM
2142 if (!$this->_useForMember) {
2143 $this->assign('membership_assign', TRUE);
2144 $this->set('membershipTypeID', $this->_params['selectMembership']);
2145 }
2146
2147 if ($this->_action & CRM_Core_Action::PREVIEW) {
2148 $membershipParams['is_test'] = 1;
2149 }
2150 if ($this->_params['is_pay_later']) {
2151 $membershipParams['is_pay_later'] = 1;
2152 }
75637f22
EM
2153
2154 //inherit campaign from contribution page.
2155 if (!array_key_exists('campaign_id', $membershipParams)) {
2156 $membershipParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
2157 }
2158
7dd9ca37
EM
2159 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE);
2160 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater);
75637f22
EM
2161 }
2162 else {
2163 // at this point we've created a contact and stored its address etc
2164 // all the payment processors expect the name and address to be in the
2165 // so we copy stuff over to first_name etc.
2166 $paymentParams = $this->_params;
75637f22 2167
75637f22
EM
2168 if (!empty($paymentParams['onbehalf']) &&
2169 is_array($paymentParams['onbehalf'])
2170 ) {
2171 foreach ($paymentParams['onbehalf'] as $key => $value) {
2172 if (strstr($key, 'custom_')) {
2173 $this->_params[$key] = $value;
2174 }
2175 }
75637f22 2176 }
10490499 2177
a8a4259e 2178 $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($this, $paymentParams,
5fb28746 2179 $contactID,
46763692 2180 $this->wrangleFinancialTypeID($this->_values['financial_type_id']),
75637f22 2181 'contribution',
449f4c90 2182 ($this->_mode == 'test') ? 1 : 0,
10490499 2183 CRM_Utils_Array::value('is_recur', $paymentParams)
75637f22 2184 );
82583880 2185
0193ebdb 2186 if (empty($result['is_payment_failure'])) {
2187 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2188 $this->postProcessPremium($premiumParams, $result['contribution']);
2189 }
2190 if (!empty($result['contribution'])) {
2191 // Not quite sure why it would be empty at this stage but tests show it can be ... at least in tests.
2192 $this->completeTransaction($result, $result['contribution']->id);
a8a4259e
EM
2193 }
2194 return $result;
75637f22
EM
2195 }
2196 }
2197
7dd9ca37
EM
2198 /**
2199 * Membership processing section.
2200 *
2201 * This is in a separate function as part of a move towards refactoring.
2202 *
2203 * @param int $contactID
2204 * @param array $membershipParams
2205 * @param array $premiumParams
2206 * @param bool $isPayLater
2207 */
2208 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater) {
0d9ff2d4 2209 // This could be set by a hook.
2210 if (!empty($this->_params['installments'])) {
2211 $membershipParams['installments'] = $this->_params['installments'];
2212 }
7dd9ca37
EM
2213 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2214 if (isset($this->_params['related_contact'])) {
2215 $membershipParams['cms_contactID'] = $this->_params['related_contact'];
2216 }
2217 else {
2218 $membershipParams['cms_contactID'] = $contactID;
2219 }
2220
2221 if (!empty($membershipParams['onbehalf']) &&
2222 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2223 ) {
2224 $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2225 }
2226
2227 $customFieldsFormatted = $fieldTypes = array();
2228 if (!empty($membershipParams['onbehalf']) &&
2229 is_array($membershipParams['onbehalf'])
2230 ) {
2231 foreach ($membershipParams['onbehalf'] as $key => $value) {
2232 if (strstr($key, 'custom_')) {
2233 $customFieldId = explode('_', $key);
2234 CRM_Core_BAO_CustomField::formatCustomField(
2235 $customFieldId[1],
2236 $customFieldsFormatted,
2237 $value,
2238 'Membership',
2239 NULL,
2240 $contactID
2241 );
2242 }
2243 }
2244 $fieldTypes = array('Contact', 'Organization', 'Membership');
2245 }
2246
2247 $priceFieldIds = $this->get('memberPriceFieldIDS');
2248
2249 if (!empty($priceFieldIds)) {
2250 $contributionTypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2251 unset($priceFieldIds['id']);
2252 $membershipTypeIds = array();
2253 $membershipTypeTerms = array();
2254 foreach ($priceFieldIds as $priceFieldId) {
2255 if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
2256 $membershipTypeIds[] = $id;
2257 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
2258 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
2259 $term = 1;
2260 if ($term = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
2261 $membershipTypeTerms[$id] = ($term > 1) ? $term : 1;
2262 }
2263 else {
2264 $membershipTypeTerms[$id] = 1;
2265 }
2266 }
2267 }
2268 $membershipParams['selectMembership'] = $membershipTypeIds;
2269 $membershipParams['financial_type_id'] = $contributionTypeID;
2270 $membershipParams['types_terms'] = $membershipTypeTerms;
2271 }
2272 if (!empty($membershipParams['selectMembership'])) {
2273 // CRM-12233
2274 $membershipLineItems = array();
2275 if ($this->_separateMembershipPayment && $this->_values['amount_block_is_active']) {
2276 foreach ($this->_values['fee'] as $key => $feeValues) {
2277 if ($feeValues['name'] == 'membership_amount') {
2278 $fieldId = $this->_params['price_' . $key];
2279 $membershipLineItems[$this->_priceSetId][$fieldId] = $this->_lineItem[$this->_priceSetId][$fieldId];
2280 unset($this->_lineItem[$this->_priceSetId][$fieldId]);
2281 break;
2282 }
2283 }
2284 }
4b6c8c1e 2285 try {
2286 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
2287 }
2288 catch (CRM_Core_Exception $e) {
2289 CRM_Core_Session::singleton()->setStatus($e->getMessage());
2290 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2291 }
7dd9ca37
EM
2292 if (!$this->_amount > 0.0 || !$membershipParams['amount']) {
2293 // we need to explicitly create a CMS user in case of free memberships
2294 // since it is done under processConfirm for paid memberships
2295 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams,
2296 $membershipParams['cms_contactID'],
2297 'email-' . $this->_bltID
2298 );
2299 }
2300 }
2301 }
2302
0193ebdb 2303 /**
2304 * Complete transaction if payment has been processed.
2305 *
2306 * Check the result for a success outcome & if paid then complete the transaction.
2307 *
2308 * Completing will trigger update of related entities and emails.
2309 *
2310 * @param array $result
2311 * @param int $contributionID
2312 *
2313 * @throws \CRM_Core_Exception
2314 */
2315 protected function completeTransaction($result, $contributionID) {
2316 if (CRM_Utils_Array::value('payment_status_id', $result) == 1) {
2317 try {
2318 civicrm_api3('contribution', 'completetransaction', array(
2319 'id' => $contributionID,
2320 'trxn_id' => CRM_Utils_Array::value('trxn_id', $result),
2321 'payment_processor_id' => $this->_paymentProcessor['id'],
2322 'is_transactional' => FALSE,
2323 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
2324 )
2325 );
2326 }
2327 catch (CiviCRM_API3_Exception $e) {
2328 if ($e->getErrorCode() != 'contribution_completed') {
2329 throw new CRM_Core_Exception('Failed to update contribution in database');
2330 }
2331 }
2332 }
2333 }
2334
6a488035 2335}