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