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