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