3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * form to process actions on the group aspect of Custom Data
37 class CRM_Contribute_Form_Contribution_Confirm
extends CRM_Contribute_Form_ContributionBase
{
40 * The id of the contact associated with this contribution.
48 * The id of the contribution object that is created when the form is submitted.
52 public $_contributionID;
57 * @param $contributionParams
59 * @param $contribution
60 * @param $isEmailReceipt
63 public static function handlePledge(&$form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt) {
65 //when user doing pledge payments.
66 //update the schedule when payment(s) are made
67 $amount = $params['amount'];
68 $pledgePaymentParams = array();
69 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
70 $scheduledAmount = CRM_Core_DAO
::getFieldValue(
71 'CRM_Pledge_DAO_PledgePayment',
77 $pledgePayment = ($amount >= $scheduledAmount) ?
$scheduledAmount : $amount;
78 if ($pledgePayment > 0) {
79 $pledgePaymentParams[] = array(
81 'contribution_id' => $contribution->id
,
82 'status_id' => $contribution->contribution_status_id
,
83 'actual_amount' => $pledgePayment,
85 $amount -= $pledgePayment;
88 if ($amount > 0 && count($pledgePaymentParams)) {
89 $pledgePaymentParams[count($pledgePaymentParams) - 1]['actual_amount'] +
= $amount;
91 foreach ($pledgePaymentParams as $p) {
92 CRM_Pledge_BAO_PledgePayment
::add($p);
95 //update pledge status according to the new payment statuses
96 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID);
100 //when user creating pledge record.
101 $pledgeParams = array();
102 $pledgeParams['contact_id'] = $contribution->contact_id
;
103 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount
;
104 $pledgeParams['contribution_id'] = $contribution->id
;
105 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id
;
106 $pledgeParams['financial_type_id'] = $contribution->financial_type_id
;
107 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
108 $pledgeParams['installments'] = $params['pledge_installments'];
109 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
110 if ($pledgeParams['frequency_unit'] == 'month') {
111 $pledgeParams['frequency_day'] = intval(date("d"));
114 $pledgeParams['frequency_day'] = 1;
116 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
117 if (CRM_Utils_Array
::value('start_date', $params)) {
118 $pledgeParams['frequency_day'] = intval(date("d", strtotime(CRM_Utils_Array
::value('start_date', $params))));
119 $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date('Ymd', strtotime(CRM_Utils_Array
::value('start_date', $params)));
121 $pledgeParams['status_id'] = $contribution->contribution_status_id
;
122 $pledgeParams['max_reminders'] = $form->_values
['max_reminders'];
123 $pledgeParams['initial_reminder_day'] = $form->_values
['initial_reminder_day'];
124 $pledgeParams['additional_reminder_day'] = $form->_values
['additional_reminder_day'];
125 $pledgeParams['is_test'] = $contribution->is_test
;
126 $pledgeParams['acknowledge_date'] = date('Ymd');
127 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
129 //inherit campaign from contirb page.
130 $pledgeParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $contributionParams);
132 $pledge = CRM_Pledge_BAO_Pledge
::create($pledgeParams);
134 $form->_params
['pledge_id'] = $pledge->id
;
136 //send acknowledgment email. only when pledge is created
137 if ($pledge->id
&& $isEmailReceipt) {
138 //build params to send acknowledgment.
139 $pledgeParams['id'] = $pledge->id
;
140 $pledgeParams['receipt_from_name'] = $form->_values
['receipt_from_name'];
141 $pledgeParams['receipt_from_email'] = $form->_values
['receipt_from_email'];
143 //scheduled amount will be same as installment_amount.
144 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
146 //get total pledge amount.
147 $pledgeParams['total_pledge_amount'] = $pledge->amount
;
149 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($form, $pledgeParams);
157 * Set the parameters to be passed to contribution create function.
159 * @param array $params
160 * @param int $financialTypeID
161 * @param bool $pending
162 * @param array $paymentProcessorOutcome
163 * @param string $receiptDate
164 * @param int $recurringContributionID
168 public static function getContributionParams(
169 $params, $financialTypeID, $pending,
170 $paymentProcessorOutcome, $receiptDate, $recurringContributionID) {
171 $contributionParams = array(
172 'financial_type_id' => $financialTypeID,
173 'receive_date' => (CRM_Utils_Array
::value('receive_date', $params)) ? CRM_Utils_Date
::processDate($params['receive_date']) : date('YmdHis'),
174 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $params),
175 'amount_level' => CRM_Utils_Array
::value('amount_level', $params),
176 'invoice_id' => $params['invoiceID'],
177 'currency' => $params['currencyID'],
178 'is_pay_later' => CRM_Utils_Array
::value('is_pay_later', $params, 0),
179 //configure cancel reason, cancel date and thankyou date
180 //from 'contribution' type profile if included
181 'cancel_reason' => CRM_Utils_Array
::value('cancel_reason', $params, 0),
182 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date
::format($params['cancel_date']) : NULL,
183 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date
::format($params['thankyou_date']) : NULL,
184 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
185 'skipLineItem' => CRM_Utils_Array
::value('skipLineItem', $params, 0),
188 if ($paymentProcessorOutcome) {
189 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor', $paymentProcessorOutcome);
191 if (!empty($params["is_email_receipt"])) {
192 $contributionParams +
= array(
193 'receipt_date' => $receiptDate,
196 if (!$pending && $paymentProcessorOutcome) {
197 $contributionParams +
= array(
198 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $paymentProcessorOutcome),
199 'net_amount' => CRM_Utils_Array
::value('net_amount', $paymentProcessorOutcome, $params['amount']),
200 'trxn_id' => $paymentProcessorOutcome['trxn_id'],
201 'receipt_date' => $receiptDate,
202 // also add financial_trxn details as part of fix for CRM-4724
203 'trxn_result_code' => CRM_Utils_Array
::value('trxn_result_code', $paymentProcessorOutcome),
207 if ($recurringContributionID) {
208 $contributionParams['contribution_recur_id'] = $recurringContributionID;
211 $contributionParams['contribution_status_id'] = $pending ?
2 : 1;
212 if (isset($contributionParams['invoice_id'])) {
213 $contributionParams['id'] = CRM_Core_DAO
::getFieldValue(
214 'CRM_Contribute_DAO_Contribution',
215 $contributionParams['invoice_id'],
221 return $contributionParams;
225 * Get non-deductible amount.
227 * This is a bit too much about wierd form interpretation to be this deep.
230 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
233 * @param array $params
234 * @param CRM_Financial_BAO_FinancialType $financialType
235 * @param bool $online
236 * @param CRM_Contribute_Form_Contribution_Confirm $form
240 protected static function getNonDeductibleAmount($params, $financialType, $online, $form) {
241 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
242 return $params['non_deductible_amount'];
244 $priceSetId = CRM_Utils_Array
::value('priceSetId', $params);
245 // return non-deductible amount if it is set at the price field option level
246 if ($priceSetId && !empty($form->_lineItem
)) {
247 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $form->_lineItem
);
250 if (!empty($nonDeductibleAmount)) {
251 return $nonDeductibleAmount;
254 if ($financialType->is_deductible
) {
255 if ($online && isset($params['selectProduct'])) {
256 $selectProduct = CRM_Utils_Array
::value('selectProduct', $params);
258 if (!$online && isset($params['product_name'][0])) {
259 $selectProduct = $params['product_name'][0];
261 // if there is a product - compare the value to the contribution amount
262 if (isset($selectProduct) &&
263 $selectProduct != 'no_thanks'
265 $productDAO = new CRM_Contribute_DAO_Product();
266 $productDAO->id
= $selectProduct;
267 $productDAO->find(TRUE);
268 // product value exceeds contribution amount
269 if ($params['amount'] < $productDAO->price
) {
270 $nonDeductibleAmount = $params['amount'];
271 return $nonDeductibleAmount;
273 // product value does NOT exceed contribution amount
275 return $productDAO->price
;
278 // contribution is deductible - but there is no product
283 // contribution is NOT deductible
285 return $params['amount'];
291 * Set variables up before form is built.
293 public function preProcess() {
294 $config = CRM_Core_Config
::singleton();
295 parent
::preProcess();
297 // lineItem isn't set until Register postProcess
298 $this->_lineItem
= $this->get('lineItem');
299 $this->_ccid
= $this->get('ccid');
301 $this->_params
= $this->controller
->exportValues('Main');
302 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
303 $this->_params
['amount'] = $this->get('amount');
304 if (isset($this->_params
['amount'])) {
305 $this->setFormAmountFields($this->_params
['priceSetId']);
308 $this->_params
['tax_amount'] = $this->get('tax_amount');
309 $this->_useForMember
= $this->get('useForMember');
311 if (isset($this->_params
['credit_card_exp_date'])) {
312 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
313 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
316 $this->_params
['currencyID'] = $config->defaultCurrency
;
318 if (!empty($this->_membershipBlock
)) {
319 $this->_params
['selectMembership'] = $this->get('selectMembership');
321 if (!empty($this->_paymentProcessor
) && $this->_paymentProcessor
['object']->supports('preApproval')) {
322 $preApprovalParams = $this->_paymentProcessor
['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
323 $this->_params
= array_merge($this->_params
, $preApprovalParams);
325 // We may have fetched some billing details from the getPreApprovalDetails function so we
326 // want to ensure we set this after that function has been called.
327 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $preApprovalParams, $this->_params
, FALSE);
330 $this->_params
['is_pay_later'] = $this->get('is_pay_later');
331 $this->assign('is_pay_later', $this->_params
['is_pay_later']);
332 if ($this->_params
['is_pay_later']) {
333 $this->assign('pay_later_receipt', CRM_Utils_Array
::value('pay_later_receipt', $this->_values
));
335 // if onbehalf-of-organization
336 if (!empty($this->_values
['onbehalf_profile_id']) && !empty($this->_params
['onbehalf']['organization_name'])) {
337 if (empty($this->_params
['org_option']) && empty($this->_params
['organization_id'])) {
338 $this->_params
['organization_id'] = CRM_Utils_Array
::value('onbehalfof_id', $this->_params
);
340 $this->_params
['organization_name'] = $this->_params
['onbehalf']['organization_name'];
341 $addressBlocks = array(
347 'supplemental_address_1',
348 'supplemental_address_2',
349 'supplemental_address_3',
350 'postal_code_suffix',
356 $blocks = array('email', 'phone', 'im', 'url', 'openid');
357 foreach ($this->_params
['onbehalf'] as $loc => $value) {
358 $field = $typeId = NULL;
359 if (strstr($loc, '-')) {
360 list($field, $locType) = explode('-', $loc);
363 if (in_array($field, $addressBlocks)) {
364 if ($locType == 'Primary') {
365 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
366 $locType = $defaultLocationType->id
;
369 if ($field == 'country') {
370 $value = CRM_Core_PseudoConstant
::countryIsoCode($value);
372 elseif ($field == 'state_province') {
373 $value = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
377 if (isset($this->_params
['onbehalf_location']['address'])
378 && count($this->_params
['onbehalf_location']['address']) > 0
383 $this->_params
['onbehalf_location']['address'][$locType][$field] = $value;
384 if (empty($this->_params
['onbehalf_location']['address'][$locType]['is_primary'])) {
385 $this->_params
['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
387 $this->_params
['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
389 elseif (in_array($field, $blocks)) {
390 if (!$typeId ||
is_numeric($typeId)) {
391 $blockName = $fieldName = $field;
392 $locationType = 'location_type_id';
393 if ($locType == 'Primary') {
394 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
395 $locationValue = $defaultLocationType->id
;
398 $locationValue = $locType;
401 $phoneExtField = array();
403 if ($field == 'url') {
404 $blockName = 'website';
405 $locationType = 'website_type_id';
406 list($field, $locationValue) = explode('-', $loc);
408 elseif ($field == 'im') {
410 $locTypeId = 'provider_id';
411 $typeId = $this->_params
['onbehalf']["{$loc}-provider_id"];
413 elseif ($field == 'phone') {
414 list($field, $locType, $typeId) = explode('-', $loc);
415 $locTypeId = 'phone_type_id';
417 //check if extension field exists
418 $extField = str_replace('phone', 'phone_ext', $loc);
419 if (isset($this->_params
['onbehalf'][$extField])) {
420 $phoneExtField = array('phone_ext' => $this->_params
['onbehalf'][$extField]);
425 if (isset ($this->_params
['onbehalf_location'][$blockName])
426 && count($this->_params
['onbehalf_location'][$blockName]) > 0
430 if ($locationValue) {
431 $blockValues = array(
432 $fieldName => $value,
433 $locationType => $locationValue,
434 'is_primary' => $isPrimary,
438 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
440 if (!empty($phoneExtField)) {
441 $blockValues = array_merge($blockValues, $phoneExtField);
444 $this->_params
['onbehalf_location'][$blockName][] = $blockValues;
448 elseif (strstr($loc, 'custom')) {
449 if ($value && isset($this->_params
['onbehalf']["{$loc}_id"])) {
450 $value = $this->_params
['onbehalf']["{$loc}_id"];
452 $this->_params
['onbehalf_location']["{$loc}"] = $value;
455 if ($loc == 'contact_sub_type') {
456 $this->_params
['onbehalf_location'][$loc] = $value;
459 $this->_params
['onbehalf_location'][$field] = $value;
464 elseif (!empty($this->_values
['is_for_organization'])) {
465 // no on behalf of an organization, CRM-5519
466 // so reset loc blocks from main params.
472 if (isset($this->_params
[$blk])) {
473 unset($this->_params
[$blk]);
477 $this->setRecurringMembershipParams();
480 $params = $this->processPcp($this, $this->_params
);
481 $this->_params
= $params;
483 $this->_params
['invoiceID'] = $this->get('invoiceID');
485 //carry campaign from profile.
486 if (array_key_exists('contribution_campaign_id', $this->_params
)) {
487 $this->_params
['campaign_id'] = $this->_params
['contribution_campaign_id'];
490 // assign contribution page id to the template so we can add css class for it
491 $this->assign('contributionPageID', $this->_id
);
492 $this->assign('is_for_organization', CRM_Utils_Array
::value('is_for_organization', $this->_params
));
494 $this->set('params', $this->_params
);
498 * Build the form object.
500 public function buildQuickForm() {
501 // FIXME: Some of this code is identical to Thankyou.php and should be broken out into a shared function
502 $this->assignToTemplate();
504 $params = $this->_params
;
505 // make sure we have values for it
506 if (!empty($this->_values
['honoree_profile_id']) && !empty($params['soft_credit_type_id']) && empty($this->_ccid
)) {
508 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
510 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
511 CRM_Contribute_BAO_ContributionSoft
::formatHonoreeProfileFields($this, $params['honor']);
513 $fieldTypes = array('Contact');
514 $fieldTypes[] = CRM_Core_BAO_UFGroup
::getContactType($this->_values
['honoree_profile_id']);
515 $this->buildCustom($this->_values
['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
517 $this->assign('receiptFromEmail', CRM_Utils_Array
::value('receipt_from_email', $this->_values
));
518 $amount_block_is_active = $this->get('amount_block_is_active');
519 $this->assign('amount_block_is_active', $amount_block_is_active);
521 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
522 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
523 // Make a copy of line items array to use for display only
524 $tplLineItems = $this->_lineItem
;
526 $getTaxDetails = FALSE;
527 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
528 foreach ($this->_lineItem
as $key => $value) {
529 foreach ($value as $k => $v) {
530 if (isset($v['tax_rate'])) {
531 if ($v['tax_rate'] != '') {
532 $getTaxDetails = TRUE;
533 // Cast to float to display without trailing zero decimals
534 $tplLineItems[$key][$k]['tax_rate'] = (float) $v['tax_rate'];
539 $this->assign('getTaxDetails', $getTaxDetails);
540 $this->assign('taxTerm', $taxTerm);
541 $this->assign('totalTaxAmount', $params['tax_amount']);
543 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
544 $option = CRM_Utils_Array
::value('options_' . $params['selectProduct'], $params);
545 $productID = $params['selectProduct'];
546 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, FALSE,
549 $this->set('productID', $productID);
550 $this->set('option', $option);
552 $config = CRM_Core_Config
::singleton();
553 if (in_array('CiviMember', $config->enableComponents
) && empty($this->_ccid
)) {
554 if (isset($params['selectMembership']) &&
555 $params['selectMembership'] != 'no_thanks'
557 $this->buildMembershipBlock(
558 $this->_membershipContactID
,
560 $params['selectMembership'],
563 if (!empty($params['auto_renew'])) {
564 $this->assign('auto_renew', TRUE);
568 $this->assign('membershipBlock', FALSE);
571 if (empty($this->_ccid
)) {
572 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
573 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
576 if (!empty($this->_values
['onbehalf_profile_id']) &&
577 !empty($params['onbehalf']) &&
578 ($this->_values
['is_for_organization'] == 2 ||
579 !empty($params['is_for_organization'])
580 ) && empty($this->_ccid
)
582 $fieldTypes = array('Contact', 'Organization');
583 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
584 $fieldTypes = array_merge($fieldTypes, $contactSubType);
585 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
586 $fieldTypes = array_merge($fieldTypes, array('Membership'));
589 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
592 $this->buildCustom($this->_values
['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
595 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
596 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
597 if ($this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
598 $this->assign('lineItem', $tplLineItems);
601 $this->assign('is_quick_config', 1);
602 $this->_params
['is_quick_config'] = 1;
604 $this->assign('priceSetID', $this->_priceSetId
);
606 // The concept of contributeMode is deprecated.
607 // the is_monetary concept probably should be too as it can be calculated from
608 // the existence of 'amount' & seems fragile.
609 if ($this->_contributeMode
== 'notify' ||
610 $this->_amount
< 0.0 ||
$this->_params
['is_pay_later'] ||
611 ($this->_separateMembershipPayment
&& $this->_amount
<= 0.0)
613 $contribButton = ts('Continue');
614 $this->assign('button', ts('Continue'));
616 elseif (!empty($this->_ccid
)) {
617 $contribButton = ts('Make Payment');
618 $this->assign('button', ts('Make Payment'));
621 $contribButton = ts('Make Contribution');
622 $this->assign('button', ts('Make Contribution'));
624 $this->addButtons(array(
627 'name' => $contribButton,
628 'spacing' => ' ',
630 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name
. "','" . ts('Processing') . "');"),
634 'name' => ts('Go Back'),
640 $fields = array_fill_keys(array_keys($this->_fields
), 1);
641 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
643 $contact = $this->_params
;
644 foreach ($fields as $name => $dontCare) {
645 // Recursively set defaults for nested fields
646 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' ||
$name == 'honor')) {
647 foreach ($contact[$name] as $fieldName => $fieldValue) {
648 if (is_array($fieldValue) && !in_array($this->_fields
[$name][$fieldName]['html_type'], array(
653 foreach ($fieldValue as $key => $value) {
654 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
658 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
662 elseif (isset($contact[$name])) {
663 $defaults[$name] = $contact[$name];
664 if (substr($name, 0, 7) == 'custom_') {
665 $timeField = "{$name}_time";
666 if (isset($contact[$timeField])) {
667 $defaults[$timeField] = $contact[$timeField];
669 if (isset($contact["{$name}_id"])) {
670 $defaults["{$name}_id"] = $contact["{$name}_id"];
673 elseif (in_array($name, array(
677 )) && !empty($contact[$name . '_custom'])
679 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
684 $this->assign('useForMember', $this->get('useForMember'));
686 $this->setDefaults($defaults);
694 * Since we are only showing elements in frozen mode no help display needed.
698 public function getAction() {
699 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
700 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
703 return CRM_Core_Action
::VIEW
;
708 * Set default values for the form.
710 * Note that in edit/view mode
711 * the default values are retrieved from the database
713 public function setDefaultValues() {
719 public function postProcess() {
720 $contactID = $this->getContactID();
722 $result = $this->processFormSubmission($contactID);
724 catch (CRM_Core_Exception
$e) {
725 $this->bounceOnError($e->getMessage());
728 if (is_array($result) && !empty($result['is_payment_failure'])) {
729 $this->bounceOnError($result['error']->getMessage());
731 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
732 $this->set('params', $this->_params
);
736 * Wrangle financial type ID.
738 * 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
739 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
741 * Comments from previous refactor indicate doubt as to what was going on.
743 * @param int $financialTypeID
745 * @return null|string
747 public function wrangleFinancialTypeID($financialTypeID) {
748 if (empty($financialTypeID) && !empty($this->_values
['pledge_id'])) {
749 $financialTypeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
750 $this->_values
['pledge_id'],
754 return $financialTypeID;
760 * @param array $premiumParams
761 * @param CRM_Contribute_BAO_Contribution $contribution
763 protected function postProcessPremium($premiumParams, $contribution) {
764 $hour = $minute = $second = 0;
765 // assigning Premium information to receipt tpl
766 $selectProduct = CRM_Utils_Array
::value('selectProduct', $premiumParams);
767 if ($selectProduct &&
768 $selectProduct != 'no_thanks'
770 $startDate = $endDate = "";
771 $this->assign('selectPremium', TRUE);
772 $productDAO = new CRM_Contribute_DAO_Product();
773 $productDAO->id
= $selectProduct;
774 $productDAO->find(TRUE);
775 $this->assign('product_name', $productDAO->name
);
776 $this->assign('price', $productDAO->price
);
777 $this->assign('sku', $productDAO->sku
);
778 $this->assign('option', CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams));
780 $periodType = $productDAO->period_type
;
783 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
784 $duration_unit = $productDAO->duration_unit
;
785 $duration_interval = $productDAO->duration_interval
;
786 if ($periodType == 'rolling') {
787 $startDate = date('Y-m-d');
789 elseif ($periodType == 'fixed') {
790 if ($fixed_period_start_day) {
791 $date = explode('-', date('Y-m-d'));
792 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
793 $day = substr($fixed_period_start_day, -2) . "<br/>";
795 $startDate = $year . '-' . $month . '-' . $day;
798 $startDate = date('Y-m-d');
802 $date = explode('-', $startDate);
807 switch ($duration_unit) {
809 $year = $year +
$duration_interval;
813 $month = $month +
$duration_interval;
817 $day = $day +
$duration_interval;
821 $day = $day +
($duration_interval * 7);
823 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
824 $this->assign('start_date', $startDate);
825 $this->assign('end_date', $endDate);
828 $dao = new CRM_Contribute_DAO_Premium();
829 $dao->entity_table
= 'civicrm_contribution_page';
830 $dao->entity_id
= $this->_id
;
832 $this->assign('contact_phone', $dao->premiums_contact_phone
);
833 $this->assign('contact_email', $dao->premiums_contact_email
);
835 //create Premium record
837 'product_id' => $premiumParams['selectProduct'],
838 'contribution_id' => $contribution->id
,
839 'product_option' => CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams),
841 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
842 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
844 if (!empty($premiumParams['selectProduct'])) {
845 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
846 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
847 $daoPremiumsProduct->premiums_id
= $dao->id
;
848 $daoPremiumsProduct->find(TRUE);
849 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
852 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
853 $daoContrProd->contribution_id
= $contribution->id
;
854 if ($daoContrProd->find(TRUE)) {
855 $params['id'] = $daoContrProd->id
;
858 CRM_Contribute_BAO_Contribution
::addPremium($params);
859 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
861 'cost' => $productDAO->cost
,
862 'currency' => $productDAO->currency
,
863 'financial_type_id' => $params['financial_type_id'],
864 'contributionId' => $contribution->id
,
866 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
869 elseif ($selectProduct == 'no_thanks') {
871 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
872 $daoContrProd->contribution_id
= $contribution->id
;
873 if ($daoContrProd->find(TRUE)) {
874 $daoContrProd->delete();
880 * Process the contribution.
882 * @param CRM_Core_Form $form
883 * @param array $params
884 * @param array $result
885 * @param array $contributionParams
886 * Parameters to be passed to contribution create action.
887 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
888 * passed consistently & 2) documenting them here.
893 * - contribution_page_id
896 * - thankyou_date (not all forms will set this)
898 * @param CRM_Financial_DAO_FinancialType $financialType
899 * @param bool $online
900 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
902 * @param int $billingLocationID
903 * ID of billing location type.
904 * @param bool $isRecur
907 * @return \CRM_Contribute_DAO_Contribution
910 public static function processFormContribution(
920 $transaction = new CRM_Core_Transaction();
921 $contactID = $contributionParams['contact_id'];
923 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
924 $isSeparateMembershipPayment = empty($params['separate_membership_payment']) ?
FALSE : TRUE;
925 $pledgeID = !empty($params['pledge_id']) ?
$params['pledge_id'] : CRM_Utils_Array
::value('pledge_id', $form->_values
);
926 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
927 (!empty($params['is_pledge']) ||
$pledgeID)) {
934 // add these values for the recurringContrib function ,CRM-10188
935 $params['financial_type_id'] = $financialType->id
;
937 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
939 //@todo - this is being set from the form to resolve CRM-10188 - an
940 // eNotice caused by it not being set @ the front end
941 // however, we then get it being over-written with null for backend contributions
942 // a better fix would be to set the values in the respective forms rather than require
943 // a function being shared by two forms to deal with their respective values
944 // moving it to the BAO & not taking the $form as a param would make sense here.
945 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
946 $params['is_email_receipt'] = $isEmailReceipt;
948 $params['is_recur'] = $isRecur;
949 $params['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $contributionParams);
950 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType);
952 $now = date('YmdHis');
953 $receiptDate = CRM_Utils_Array
::value('receipt_date', $params);
954 if ($isEmailReceipt) {
958 if (isset($params['amount'])) {
959 $contributionParams = array_merge(self
::getContributionParams(
960 $params, $financialType->id
, TRUE,
961 $result, $receiptDate,
962 $recurringContributionID), $contributionParams
964 $contributionParams['non_deductible_amount'] = self
::getNonDeductibleAmount($params, $financialType, $online, $form);
965 $contributionParams['skipCleanMoney'] = TRUE;
966 // @todo this is the wrong place for this - it should be done as close to form submission
968 $contributionParams['total_amount'] = $params['amount'];
970 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
972 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
973 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
975 $dataArray = array();
976 // @todo - interrogate the line items passed in on the params array.
977 // No reason to assume line items will be set on the form.
978 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
979 foreach ($lineItemValue as $key => $value) {
980 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
981 if (isset($dataArray[$value['tax_rate']])) {
982 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
985 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
990 $smarty = CRM_Core_Smarty
::singleton();
991 $smarty->assign('dataArray', $dataArray);
992 $smarty->assign('totalTaxAmount', $params['tax_amount']);
995 // lets store it in the form variable so postProcess hook can get to this and use it
996 $form->_contributionID
= $contribution->id
;
999 // process soft credit / pcp params first
1000 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
1002 //CRM-13981, processing honor contact into soft-credit contribution
1003 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
1006 $form = self
::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
1009 if ($online && $contribution) {
1010 CRM_Core_BAO_CustomValueTable
::postProcess($params,
1011 'civicrm_contribution',
1016 elseif ($contribution) {
1017 //handle custom data.
1018 $params['contribution_id'] = $contribution->id
;
1019 if (!empty($params['custom']) &&
1020 is_array($params['custom'])
1022 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
1026 if ($contribution && !empty($params['contribution_note'])) {
1027 $noteParams = array(
1028 'entity_table' => 'civicrm_contribution',
1029 'note' => $params['contribution_note'],
1030 'entity_id' => $contribution->id
,
1031 'contact_id' => $contribution->contact_id
,
1032 'modified_date' => date('Ymd'),
1035 CRM_Core_BAO_Note
::add($noteParams, array());
1038 if (isset($params['related_contact'])) {
1039 $contactID = $params['related_contact'];
1041 elseif (isset($params['cms_contactID'])) {
1042 $contactID = $params['cms_contactID'];
1045 //create contribution activity w/ individual and target
1046 //activity w/ organisation contact id when onbelf, CRM-4027
1047 $targetContactID = NULL;
1048 if (!empty($params['hidden_onbehalf_profile'])) {
1049 $targetContactID = $contribution->contact_id
;
1050 $contribution->contact_id
= $contactID;
1053 // create an activity record
1054 if ($contribution) {
1055 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
1058 $transaction->commit();
1059 // CRM-13074 - create the CMSUser after the transaction is completed as it
1060 // is not appropriate to delete a valid contribution if a user create problem occurs
1061 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($params,
1063 'email-' . $billingLocationID
1065 return $contribution;
1069 * Create the recurring contribution record.
1071 * @param CRM_Core_Form $form
1072 * @param array $params
1073 * @param int $contactID
1074 * @param string $contributionType
1078 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType) {
1080 if (empty($params['is_recur'])) {
1084 $recurParams = array('contact_id' => $contactID);
1085 $recurParams['amount'] = CRM_Utils_Array
::value('amount', $params);
1086 $recurParams['auto_renew'] = CRM_Utils_Array
::value('auto_renew', $params);
1087 $recurParams['frequency_unit'] = CRM_Utils_Array
::value('frequency_unit', $params);
1088 $recurParams['frequency_interval'] = CRM_Utils_Array
::value('frequency_interval', $params);
1089 $recurParams['installments'] = CRM_Utils_Array
::value('installments', $params);
1090 $recurParams['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $params);
1091 $recurParams['currency'] = CRM_Utils_Array
::value('currency', $params);
1092 $recurParams['payment_instrument_id'] = $params['payment_instrument_id'];
1094 // CRM-14354: For an auto-renewing membership with an additional contribution,
1095 // if separate payments is not enabled, make sure only the membership fee recurs
1096 if (!empty($form->_membershipBlock
)
1097 && $form->_membershipBlock
['is_separate_payment'] === '0'
1098 && isset($params['selectMembership'])
1099 && $form->_values
['is_allow_other_amount'] == '1'
1101 && !empty($form->_membershipTypeValues
)
1102 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1104 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1107 $recurParams['is_test'] = 0;
1108 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1109 (isset($form->_mode
) && ($form->_mode
== 'test'))
1111 $recurParams['is_test'] = 1;
1114 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1115 if (!empty($params['receive_date'])) {
1116 $recurParams['start_date'] = date('YmdHis', strtotime($params['receive_date']));
1118 $recurParams['invoice_id'] = CRM_Utils_Array
::value('invoiceID', $params);
1119 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1120 $recurParams['payment_processor_id'] = CRM_Utils_Array
::value('payment_processor_id', $params);
1121 $recurParams['is_email_receipt'] = CRM_Utils_Array
::value('is_email_receipt', $params);
1122 // we need to add a unique trxn_id to avoid a unique key error
1123 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1124 $recurParams['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params, $params['invoiceID']);
1125 $recurParams['financial_type_id'] = $contributionType->id
;
1127 $campaignId = CRM_Utils_Array
::value('campaign_id', $params, CRM_Utils_Array
::value('campaign_id', $form->_values
));
1128 $recurParams['campaign_id'] = $campaignId;
1129 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1130 if (is_a($recurring, 'CRM_Core_Error')) {
1131 CRM_Core_Error
::displaySessionError($recurring);
1132 $urlString = 'civicrm/contribute/transact';
1133 $urlParams = '_qf_Main_display=true';
1134 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1135 $urlString = 'civicrm/contact/view/contribution';
1136 $urlParams = "action=add&cid={$form->_contactID}";
1138 $urlParams .= "&mode={$form->_mode}";
1141 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1143 // Only set contribution recur ID for contributions since offline membership recur payments are handled somewhere else.
1144 if (!is_a($form, "CRM_Member_Form_Membership")) {
1145 $form->_params
['contributionRecurID'] = $recurring->id
;
1148 return $recurring->id
;
1152 * Add on behalf of organization and it's location.
1154 * This situation occurs when on behalf of is enabled for the contribution page and the person
1155 * signing up does so on behalf of an organization.
1157 * @param array $behalfOrganization
1158 * array of organization info.
1159 * @param int $contactID
1160 * individual contact id. One.
1161 * who is doing the process of signup / contribution.
1163 * @param array $values
1164 * form values array.
1165 * @param array $params
1166 * @param array $fields
1167 * Array of fields from the onbehalf profile relevant to the organization.
1169 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1170 $isNotCurrentEmployer = FALSE;
1173 if (!empty($behalfOrganization['organization_id'])) {
1174 $orgID = $behalfOrganization['organization_id'];
1175 unset($behalfOrganization['organization_id']);
1177 // create employer relationship with $contactID only when new organization is there
1178 // else retain the existing relationship
1180 // get the Employee relationship type id
1181 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
1183 // keep relationship params ready
1184 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1185 $relParams['is_permission_a_b'] = 1;
1186 $relParams['is_active'] = 1;
1187 $isNotCurrentEmployer = TRUE;
1190 // formalities for creating / editing organization.
1191 $behalfOrganization['contact_type'] = 'Organization';
1194 // check if matching organization contact exists
1195 $dupeIDs = CRM_Contact_BAO_Contact
::getDuplicateContacts($behalfOrganization, 'Organization', 'Unsupervised', array(), FALSE);
1197 // CRM-6243 says to pick the first org even if more than one match
1198 if (count($dupeIDs) >= 1) {
1199 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1200 // don't allow name edit
1201 unset($behalfOrganization['organization_name']);
1205 // if found permissioned related organization, allow location edit
1206 $behalfOrganization['contact_id'] = $orgID;
1207 // don't allow name edit
1208 unset($behalfOrganization['organization_name']);
1211 // handling for image url
1212 if (!empty($behalfOrganization['image_URL'])) {
1213 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1216 // create organization, add location
1217 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1218 NULL, NULL, 'Organization'
1220 // create relationship
1221 if ($isNotCurrentEmployer) {
1222 $relParams['contact_check'][$orgID] = 1;
1223 $cid = array('contact' => $contactID);
1224 CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relParams, $cid);
1227 // if multiple match - send a duplicate alert
1228 if ($dupeIDs && (count($dupeIDs) > 1)) {
1229 $values['onbehalf_dupe_alert'] = 1;
1231 $params['onbehalf_dupe_alert'] = 1;
1234 // make sure organization-contact-id is considered for recording
1235 // contribution/membership etc..
1236 if ($contactID != $orgID) {
1237 // take a note of contact-id, so we can send the
1238 // receipt to individual contact as well.
1240 // required for mailing/template display ..etc
1241 $values['related_contact'] = $contactID;
1243 //CRM-19172: Create CMS user for individual on whose behalf organization is doing contribution
1244 $params['onbehalf_contact_id'] = $contactID;
1246 //make this employee of relationship as current
1247 //employer / employee relationship, CRM-3532
1248 if ($isNotCurrentEmployer &&
1249 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1251 $isNotCurrentEmployer = FALSE;
1254 if (!$isNotCurrentEmployer && $orgID) {
1255 //build current employer params
1256 $currentEmpParams[$contactID] = $orgID;
1257 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1260 // contribution / signup will be done using this
1262 $contactID = $orgID;
1267 * Function used to send notification mail to pcp owner.
1269 * This is used by contribution and also event PCPs.
1271 * @param object $contribution
1272 * @param object $contributionSoft
1273 * Contribution object.
1275 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1276 $params = array('id' => $contributionSoft->pcp_id
);
1277 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1278 $ownerNotifyID = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1279 $ownerNotifyOption = CRM_Core_PseudoConstant
::getName('CRM_PCP_DAO_PCPBlock', 'owner_notify_id', $ownerNotifyID);
1281 if ($ownerNotifyOption != 'no_notifications' &&
1282 (($ownerNotifyOption == 'owner_chooses' &&
1283 CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id
, 'is_notify')) ||
1284 $ownerNotifyOption == 'all_owners')) {
1285 $pcpInfoURL = CRM_Utils_System
::url('civicrm/pcp/info',
1286 "reset=1&id={$contributionSoft->pcp_id}",
1287 TRUE, NULL, FALSE, TRUE
1289 // set email in the template here
1291 if (CRM_Core_BAO_LocationType
::getBilling()) {
1292 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
,
1293 FALSE, CRM_Core_BAO_LocationType
::getBilling());
1295 // get primary location email if no email exist( for billing location).
1297 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
);
1299 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft->contact_id
);
1301 'page_title' => $pcpInfo['title'],
1302 'receive_date' => $contribution->receive_date
,
1303 'total_amount' => $contributionSoft->amount
,
1304 'donors_display_name' => $donorName,
1305 'donors_email' => $email,
1306 'pcpInfoURL' => $pcpInfoURL,
1307 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll
,
1308 'currency' => $contributionSoft->currency
,
1310 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1311 $sendTemplateParams = array(
1312 'groupName' => 'msg_tpl_workflow_contribution',
1313 'valueName' => 'pcp_owner_notify',
1314 'contactId' => $contributionSoft->contact_id
,
1315 'toEmail' => $ownerEmail,
1316 'toName' => $ownerName,
1317 'from' => "$domainValues[0] <$domainValues[1]>",
1318 'tplParams' => $tplParams,
1319 'PDFFilename' => 'receipt.pdf',
1321 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1326 * Function used to se pcp related defaults / params.
1328 * This is used by contribution and also event PCPs
1330 * @param CRM_Core_Form $page
1332 * @param array $params
1336 public static function processPcp(&$page, $params) {
1337 $params['pcp_made_through_id'] = $page->_pcpId
;
1338 $page->assign('pcpBlock', TRUE);
1339 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1340 $params['pcp_roll_nickname'] = ts('Anonymous');
1341 $params['pcp_is_anonymous'] = 1;
1344 $params['pcp_is_anonymous'] = 0;
1347 'pcp_display_in_roll',
1349 'pcp_roll_nickname',
1350 'pcp_personal_note',
1352 if (!empty($params[$val])) {
1353 $page->assign($val, $params[$val]);
1361 * Process membership.
1363 * @param array $membershipParams
1364 * @param int $contactID
1365 * @param array $customFieldsFormatted
1366 * @param array $fieldTypes
1367 * @param array $premiumParams
1368 * @param array $membershipLineItems
1369 * Line items specifically relating to memberships.
1371 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1372 $membershipLineItems) {
1374 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1375 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1376 $membershipType = empty($membershipTypes) ?
array() : reset($membershipTypes);
1377 $isPending = $this->getIsPending();
1379 $this->assign('membership_name', CRM_Utils_Array
::value('name', $membershipType));
1380 $this->_values
['membership_name'] = CRM_Utils_Array
::value('name', $membershipType);
1382 $isPaidMembership = FALSE;
1383 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1384 //amount must be greater than zero for
1385 //adding contribution record to contribution table.
1386 //this condition arises when separate membership payment is
1387 //enabled and contribution amount is not selected. fix for CRM-3010
1388 $isPaidMembership = TRUE;
1390 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1392 if ($this->_values
['amount_block_is_active']) {
1393 $financialTypeID = $this->_values
['financial_type_id'];
1396 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $membershipType, CRM_Utils_Array
::value('financial_type_id', $membershipParams));
1399 if (CRM_Utils_Array
::value('membership_source', $this->_params
)) {
1400 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1403 $this->postProcessMembership($membershipParams, $contactID,
1404 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1405 $membershipLineItems, $isPending);
1407 $this->assign('membership_assign', TRUE);
1408 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1412 * Process the Memberships.
1414 * @param array $membershipParams
1415 * Array of membership fields.
1416 * @param int $contactID
1418 * @param CRM_Contribute_Form_Contribution_Confirm $form
1419 * Confirmation form object.
1421 * @param array $premiumParams
1422 * @param null $customFieldsFormatted
1423 * @param null $includeFieldTypes
1425 * @param array $membershipDetails
1427 * @param array $membershipTypeIDs
1429 * @param bool $isPaidMembership
1430 * @param array $membershipID
1432 * @param bool $isProcessSeparateMembershipTransaction
1434 * @param int $financialTypeID
1435 * @param array $unprocessedLineItems
1436 * Line items for payment options chosen on the form.
1437 * @param bool $isPending
1439 * @throws \CRM_Core_Exception
1441 protected function postProcessMembership(
1442 $membershipParams, $contactID, &$form, $premiumParams,
1443 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1444 $isProcessSeparateMembershipTransaction, $financialTypeID, $unprocessedLineItems, $isPending) {
1446 $membershipContribution = NULL;
1447 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1448 $errors = $paymentResults = array();
1449 $form->_values
['isMembership'] = TRUE;
1450 $isRecurForFirstTransaction = CRM_Utils_Array
::value('is_recur', $form->_params
, CRM_Utils_Array
::value('is_recur', $membershipParams));
1452 $totalAmount = $membershipParams['amount'];
1454 if ($isPaidMembership) {
1455 if ($isProcessSeparateMembershipTransaction) {
1456 // If we have 2 transactions only one can use the invoice id.
1457 $membershipParams['invoiceID'] .= '-2';
1458 if (!empty($membershipParams['auto_renew'])) {
1459 $isRecurForFirstTransaction = FALSE;
1463 if (!$isProcessSeparateMembershipTransaction) {
1464 // Skip line items in the contribution processing transaction.
1465 // We will create them with the membership for proper linking.
1466 $membershipParams['skipLineItem'] = 1;
1469 $membershipParams['total_amount'] = $totalAmount;
1470 $membershipParams['skipLineItem'] = 0;
1471 CRM_Price_BAO_LineItem
::getLineItemArray($membershipParams);
1474 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm(
1480 $isRecurForFirstTransaction
1482 if (!empty($paymentResult['contribution'])) {
1483 $paymentResults[] = array('contribution_id' => $paymentResult['contribution']->id
, 'result' => $paymentResult);
1484 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1485 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1486 $membershipContribution = $paymentResult['contribution'];
1487 // Save the contribution ID so that I can be used in email receipts
1488 // For example, if you need to generate a tax receipt for the donation only.
1489 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1493 if ($isProcessSeparateMembershipTransaction) {
1495 $form->_lineItem
= $unprocessedLineItems;
1496 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1497 unset($membershipParams['is_recur']);
1499 list($membershipContribution, $secondPaymentResult) = $this->processSecondaryFinancialTransaction($contactID, $form, array_merge($membershipParams, array('skipLineItem' => 1)),
1500 $isTest, $unprocessedLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1501 $paymentResults[] = array('contribution_id' => $membershipContribution->id
, 'result' => $secondPaymentResult);
1502 $totalAmount = $membershipContribution->total_amount
;
1504 catch (CRM_Core_Exception
$e) {
1505 $errors[2] = $e->getMessage();
1506 $membershipContribution = NULL;
1511 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1512 $membershipContributionID = $membershipContribution->id
;
1515 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1516 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1517 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1519 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1520 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1521 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1523 $membershipLines = $nonMembershipLines = array();
1524 foreach ($unprocessedLineItems as $priceSetID => $lines) {
1525 foreach ($lines as $line) {
1526 if (!empty($line['membership_type_id'])) {
1527 $membershipLines[$line['membership_type_id']] = $line['price_field_value_id'];
1533 $form->_params
['createdMembershipIDs'] = array();
1534 foreach ($membershipTypeIDs as $memType) {
1535 $membershipLineItems = array();
1536 if ($i < count($membershipTypeIDs)) {
1537 $membershipLineItems[$priceSetID][$membershipLines[$memType]] = $unprocessedLineItems[$priceSetID][$membershipLines[$memType]];
1538 unset($unprocessedLineItems[$priceSetID][$membershipLines[$memType]]);
1541 $membershipLineItems = $unprocessedLineItems;
1544 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1545 if (!empty($membershipContribution)) {
1546 $pendingStatus = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1547 $pending = ($membershipContribution->contribution_status_id
== $pendingStatus) ?
TRUE : FALSE;
1550 $pending = $isPending;
1552 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
1554 $membershipSource = NULL;
1555 if (!empty($form->_params
['membership_source'])) {
1556 $membershipSource = $form->_params
['membership_source'];
1558 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
1559 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
1562 if (isset($form->_params
)) {
1563 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
1566 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
1567 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
1568 if (!array_key_exists('campaign_id', $form->_params
)) {
1569 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1573 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership
::processMembership(
1574 $contactID, $memType, $isTest,
1575 date('YmdHis'), CRM_Utils_Array
::value('cms_contactID', $membershipParams),
1576 $customFieldsFormatted,
1577 $numTerms, $membershipID, $pending,
1578 $contributionRecurID, $membershipSource, $isPayLater, $campaignId, array(), $membershipContribution,
1579 $membershipLineItems
1582 $form->set('renewal_mode', $renewalMode);
1583 if (!empty($dates)) {
1584 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d'));
1585 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d'));
1588 if (!empty($membershipContribution)) {
1589 // update recurring id for membership record
1590 CRM_Member_BAO_Membership
::updateRecurMembership($membership, $membershipContribution);
1591 // Next line is probably redundant. Checksprevent it happening twice.
1592 CRM_Member_BAO_Membership
::linkMembershipPayment($membership, $membershipContribution);
1595 CRM_Core_BAO_CustomValueTable
::postProcess($form->_params
, 'civicrm_membership', $membership->id
, 'Membership');
1596 $form->_params
['createdMembershipIDs'][] = $membership->id
;
1597 $form->_params
['membershipID'] = $membership->id
;
1599 //CRM-15232: Check if membership is created and on the basis of it use
1600 //membership receipt template to send payment receipt
1601 $form->_values
['isMembership'] = TRUE;
1604 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1605 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1606 if (!empty($priceFieldOp['membership_type_id']) && $membership->membership_type_id
== $priceFieldOp['membership_type_id']) {
1607 $membershipOb = $membership;
1608 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1609 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1612 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1615 $form->_values
['lineItem'] = $form->_lineItem
;
1616 $form->assign('lineItem', $form->_lineItem
);
1620 if (!empty($errors)) {
1621 $message = $this->compileErrorMessage($errors);
1622 throw new CRM_Core_Exception($message);
1625 if (isset($membershipContributionID)) {
1626 $form->_values
['contribution_id'] = $membershipContributionID;
1629 if (empty($form->_params
['is_pay_later']) && $form->_paymentProcessor
) {
1630 // the is_monetary concept probably should be deprecated as it can be calculated from
1631 // the existence of 'amount' & seems fragile.
1632 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1633 // call postProcess hook before leaving
1634 $form->postProcessHook();
1637 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1638 // The contribution_other_id is effectively the ID for the only contribution or the non-membership contribution.
1639 // Since we have called the membership contribution (in a 2 contribution scenario) this is out
1640 // primary-contribution compared to that - but let's face it - it's all just too hard & confusing at the moment!
1641 $paymentParams = array_merge($form->_params
, array('contributionID' => $form->_values
['contribution_other_id']));
1643 // CRM-19792 : set necessary fields for payment processor
1644 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $paymentParams, $paymentParams, TRUE);
1646 // If this is a single membership-related contribution, it won't have
1647 // be performed yet, so do it now.
1648 if ($isPaidMembership && !$isProcessSeparateMembershipTransaction) {
1649 $paymentActionResult = $payment->doPayment($paymentParams, 'contribute');
1650 $paymentResults[] = array('contribution_id' => $paymentResult['contribution']->id
, 'result' => $paymentActionResult);
1652 // Do not send an email if Recurring transaction is done via Direct Mode
1653 // Email will we sent when the IPN is received.
1654 foreach ($paymentResults as $result) {
1655 //CRM-18211: Fix situation where second contribution doesn't exist because it is optional.
1656 if ($result['contribution_id']) {
1657 $this->completeTransaction($result['result'], $result['contribution_id']);
1663 $emailValues = array_merge($membershipParams, $form->_values
);
1664 $emailValues['membership_assign'] = 1;
1665 $emailValues['useForMember'] = !empty($form->_useForMember
);
1667 // Finally send an email receipt for pay-later scenario (although it might sometimes be caught above!)
1668 if ($totalAmount == 0) {
1669 // This feels like a bizarre hack as the variable name doesn't seem to be directly connected to it's use in the template.
1670 $emailValues['useForMember'] = 0;
1671 $emailValues['amount'] = 0;
1673 //CRM-18071, where on selecting $0 free membership payment section got hidden and
1674 // also it reset any payment processor selection result into pending free membership
1675 // so its a kind of hack to complete free membership at this point since there is no $form->_paymentProcessor info
1676 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1677 if (empty($form->_paymentProcessor
)) {
1678 // @todo this can maybe go now we are setting payment_processor_id = 0 more reliably.
1679 $paymentProcessorIDs = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, CRM_Utils_Array
::value('payment_processor', $this->_values
));
1680 $this->_paymentProcessor
['id'] = $paymentProcessorIDs[0];
1682 $result = array('payment_status_id' => 1, 'contribution' => $membershipContribution);
1683 $this->completeTransaction($result, $result['contribution']->id
);
1685 // return as completeTransaction() already sends the receipt mail.
1689 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1697 * Turn array of errors into message string.
1699 * @param array $errors
1703 protected function compileErrorMessage($errors) {
1704 foreach ($errors as $error) {
1705 if (is_string($error)) {
1706 $message[] = $error;
1709 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1713 * Where a second separate financial transaction is supported we will process it here.
1715 * @param int $contactID
1716 * @param CRM_Contribute_Form_Contribution_Confirm $form
1717 * @param array $tempParams
1718 * @param bool $isTest
1719 * @param array $lineItems
1720 * @param $minimumFee
1721 * @param int $financialTypeID
1723 * @throws CRM_Core_Exception
1725 * @return CRM_Contribute_BAO_Contribution
1727 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1729 $financialType = new CRM_Financial_DAO_FinancialType();
1730 $financialType->id
= $financialTypeID;
1731 $financialType->find(TRUE);
1732 $tempParams['amount'] = $minimumFee;
1733 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1734 $isRecur = CRM_Utils_Array
::value('is_recur', $tempParams);
1736 //assign receive date when separate membership payment
1737 //and contribution amount not selected.
1738 if ($form->_amount
== 0) {
1739 $now = date('YmdHis');
1740 $form->_params
['receive_date'] = $now;
1741 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1742 $form->set('params', $form->_params
);
1743 $form->assign('receive_date', $receiveDate);
1746 $form->set('membership_amount', $minimumFee);
1747 $form->assign('membership_amount', $minimumFee);
1749 // we don't need to create the user twice, so lets disable cms_create_account
1750 // irrespective of the value, CRM-2888
1751 $tempParams['cms_create_account'] = 0;
1753 //set this variable as we are not creating pledge for
1754 //separate membership payment contribution.
1755 //so for differentiating membership contribution from
1756 //main contribution.
1757 $form->_params
['separate_membership_payment'] = 1;
1758 $contributionParams = array(
1759 'contact_id' => $contactID,
1760 'line_item' => $lineItems,
1761 'is_test' => $isTest,
1762 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $tempParams, CRM_Utils_Array
::value('campaign_id',
1764 'contribution_page_id' => $form->_id
,
1765 'source' => CRM_Utils_Array
::value('source', $tempParams, CRM_Utils_Array
::value('description', $tempParams)),
1767 $isMonetary = !empty($form->_values
['is_monetary']);
1769 if (empty($paymentParams['is_pay_later'])) {
1770 $contributionParams['payment_instrument_id'] = $form->_paymentProcessor
['payment_instrument_id'];
1774 // CRM-19792 : set necessary fields for payment processor
1775 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $form->_params
, $tempParams, TRUE);
1777 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
1780 $contributionParams,
1789 // We're not processing the line item here because we are processing a membership.
1790 // To ensure processing of the correct parameters, replace relevant parameters
1791 // in $tempParams with those in $membershipContribution.
1792 $tempParams['amount_level'] = $membershipContribution->amount_level
;
1793 $tempParams['total_amount'] = $membershipContribution->total_amount
;
1794 $tempParams['tax_amount'] = $membershipContribution->tax_amount
;
1795 $tempParams['contactID'] = $membershipContribution->contact_id
;
1796 $tempParams['financialTypeID'] = $membershipContribution->financial_type_id
;
1797 $tempParams['invoiceID'] = $membershipContribution->invoice_id
;
1798 $tempParams['trxn_id'] = $membershipContribution->trxn_id
;
1799 $tempParams['contributionID'] = $membershipContribution->id
;
1801 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
1802 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1803 // now we compensate here.
1804 if (empty($form->_paymentProcessor
['object'])) {
1805 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1808 $payment = $form->_paymentProcessor
['object'];
1810 $result = $payment->doPayment($tempParams, 'contribute');
1811 $form->set('membership_trx_id', $result['trxn_id']);
1812 $form->assign('membership_trx_id', $result['trxn_id']);
1815 return array($membershipContribution, $result);
1819 * Is the payment a pending payment.
1821 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1822 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1826 protected function getIsPending() {
1827 // The concept of contributeMode is deprecated.
1828 // the is_monetary concept probably should be too as it can be calculated from
1829 // the existence of 'amount' & seems fragile.
1830 if (((isset($this->_contributeMode
)) ||
!empty
1831 ($this->_params
['is_pay_later'])
1833 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1841 * Are we going to do 2 financial transactions.
1843 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1845 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferCheckout style)
1847 * @param int $formID
1848 * @param bool $amountBlockActiveOnForm
1852 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1853 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1854 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1861 * This function sets the fields.
1863 * - $this->_params['amount_level']
1864 * - $this->_params['selectMembership']
1865 * And under certain circumstances sets
1866 * $this->_params['amount'] = null;
1868 * @param int $priceSetID
1870 public function setFormAmountFields($priceSetID) {
1871 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1872 $priceField = new CRM_Price_DAO_PriceField();
1873 $priceField->price_set_id
= $priceSetID;
1874 $priceField->orderBy('weight');
1875 $priceField->find();
1876 $paramWeDoNotUnderstand = NULL;
1878 while ($priceField->fetch()) {
1879 if ($priceField->name
== "contribution_amount") {
1880 $paramWeDoNotUnderstand = $priceField->id
;
1882 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1883 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1884 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1885 // function to get correct amount level consistently. Remove setting of the amount level in
1886 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1887 // to cover all variants.
1888 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1889 $this->_params
["price_{$priceField->id}"], 'label');
1891 if ($priceField->name
== "membership_amount") {
1892 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1893 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1896 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1897 // as membership amount.
1898 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1899 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1900 // so we should merge them together
1901 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1902 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1904 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
)
1905 && !empty($this->_values
['fee'][$priceField->id
])
1906 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1907 && CRM_Utils_Array
::value("price_{$paramWeDoNotUnderstand}", $this->_params
) < 1
1908 && empty($this->_params
["price_{$priceField->id}"])
1910 $this->_params
['amount'] = NULL;
1913 // Fix for CRM-14375 - If we are using separate payments and "no
1914 // thank you" is selected for the additional contribution, set
1915 // contribution amount to be null, so that it will not show
1916 // contribution amount same as membership amount.
1917 //@todo - merge with section above
1918 if ($this->_membershipBlock
['is_separate_payment']
1919 && !empty($this->_values
['fee'][$priceField->id
])
1920 && CRM_Utils_Array
::value('name', $this->_values
['fee'][$priceField->id
]) == 'contribution_amount'
1921 && CRM_Utils_Array
::value("price_{$priceField->id}", $this->_params
) == '-1'
1923 $this->_params
['amount'] = NULL;
1931 * @param array $params
1933 * @throws CiviCRM_API3_Exception
1935 public static function submit($params) {
1936 $form = new CRM_Contribute_Form_Contribution_Confirm();
1937 $form->_id
= $params['id'];
1939 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1940 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1941 //this way the mocked up controller ignores the session stuff
1942 $_SERVER['REQUEST_METHOD'] = 'GET';
1943 $form->controller
= new CRM_Contribute_Controller_Contribution();
1944 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1945 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1946 $form->_amount
= $params['amount'];
1947 // hack these in for test support.
1948 $form->_fields
['billing_first_name'] = 1;
1949 $form->_fields
['billing_last_name'] = 1;
1950 // CRM-18854 - Set form values to allow pledge to be created for api test.
1951 if (CRM_Utils_Array
::value('pledge_block_id', $params)) {
1952 $form->_values
['pledge_id'] = CRM_Utils_Array
::value('pledge_id', $params, NULL);
1953 $form->_values
['pledge_block_id'] = $params['pledge_block_id'];
1954 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($params['id']);
1955 $form->_values
['max_reminders'] = $pledgeBlock['max_reminders'];
1956 $form->_values
['initial_reminder_day'] = $pledgeBlock['initial_reminder_day'];
1957 $form->_values
['additional_reminder_day'] = $pledgeBlock['additional_reminder_day'];
1958 $form->_values
['is_email_receipt'] = FALSE;
1960 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1961 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1962 $priceSetFields = reset($priceFields);
1963 $form->_values
['fee'] = $priceSetFields['fields'];
1964 $form->_priceSetId
= $priceSetID;
1965 $form->setFormAmountFields($priceSetID);
1966 $capabilities = array();
1968 $capabilities[] = (ucfirst($form->_mode
) . 'Mode');
1970 $form->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors($capabilities);
1971 $form->_params
['payment_processor_id'] = isset($params['payment_processor_id']) ?
$params['payment_processor_id'] : 0;
1972 if ($form->_params
['payment_processor_id'] !== '') {
1973 // It can be blank with a $0 transaction - then no processor needs to be selected
1974 $form->_paymentProcessor
= $form->_paymentProcessors
[$form->_params
['payment_processor_id']];
1976 if (!empty($params['payment_processor_id'])) {
1977 // The concept of contributeMode is deprecated as is the billing_mode concept.
1978 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1979 $form->_contributeMode
= 'direct';
1982 $form->_contributeMode
= 'notify';
1986 $priceFields = $priceFields[$priceSetID]['fields'];
1987 $lineItems = array();
1988 CRM_Price_BAO_PriceSet
::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution', $priceSetID);
1989 $form->_lineItem
= array($priceSetID => $lineItems);
1990 $membershipPriceFieldIDs = array();
1991 foreach ((array) $lineItems as $lineItem) {
1992 if (!empty($lineItem['membership_type_id'])) {
1993 $form->set('useForMember', 1);
1994 $form->_useForMember
= 1;
1995 $membershipPriceFieldIDs['id'] = $priceSetID;
1996 $membershipPriceFieldIDs[] = $lineItem['price_field_value_id'];
1999 $form->set('memberPriceFieldIDS', $membershipPriceFieldIDs);
2000 $form->setRecurringMembershipParams();
2001 $form->processFormSubmission(CRM_Utils_Array
::value('contact_id', $params));
2005 * Helper function for static submit function.
2007 * Set relevant params - help us to build up an array that we can pass in.
2010 * @param array $params
2013 * @throws CiviCRM_API3_Exception
2015 public static function getFormParams($id, array $params) {
2016 if (!isset($params['is_pay_later'])) {
2017 if (!empty($params['payment_processor_id'])) {
2018 $params['is_pay_later'] = 0;
2020 elseif ($params['amount'] !== 0) {
2021 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
2023 'return' => 'is_pay_later',
2027 if (empty($params['price_set_id'])) {
2028 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
2034 * Post form submission handling.
2036 * This is also called from the test suite.
2038 * @param int $contactID
2042 protected function processFormSubmission($contactID) {
2043 if (!isset($this->_params
['payment_processor_id'])) {
2044 // If there is no processor we are using the pay-later manual pseudo-processor.
2045 // (note it might make sense to make this a row in the processor table in the db).
2046 $this->_params
['payment_processor_id'] = 0;
2048 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] === 0) {
2049 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
2052 if (!empty($this->_ccid
)) {
2053 $this->_params
['contribution_id'] = $this->_ccid
;
2055 //Set email-bltID if pre/post profile contains an email.
2056 if ($this->_emailExists
== TRUE) {
2057 foreach ($this->_params
as $key => $val) {
2058 if (substr($key, 0, 6) == 'email-' && empty($this->_params
["email-{$this->_bltID}"])) {
2059 $this->_params
["email-{$this->_bltID}"] = $this->_params
[$key];
2063 // add a description field at the very beginning
2064 $this->_params
['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $this->_values
['title']);
2066 $this->_params
['accountingCode'] = CRM_Utils_Array
::value('accountingCode', $this->_values
);
2069 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
2071 CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($this->_params
);
2074 if (CRM_Utils_Array
::value('is_pledge', $this->_params
) && !CRM_Utils_Array
::value('pledge_id', $this->_values
) && CRM_Utils_Array
::value('adjust_recur_start_date', $this->_values
)) {
2075 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($this->_id
);
2076 if (CRM_Utils_Array
::value('start_date', $this->_params
) ||
!CRM_Utils_Array
::value('is_pledge_start_date_visible', $pledgeBlock)
2077 ||
!CRM_Utils_Array
::value('is_pledge_start_date_editable', $pledgeBlock)) {
2078 $pledgeStartDate = CRM_Utils_Array
::value('start_date', $this->_params
, NULL);
2079 $this->_params
['receive_date'] = CRM_Pledge_BAO_Pledge
::getPledgeStartDate($pledgeStartDate, $pledgeBlock);
2080 $recurParams = CRM_Pledge_BAO_Pledge
::buildRecurParams($this->_params
);
2081 $this->_params
= array_merge($this->_params
, $recurParams);
2085 //carry payment processor id.
2086 if (CRM_Utils_Array
::value('id', $this->_paymentProcessor
)) {
2087 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
2090 $premiumParams = $membershipParams = $params = $this->_params
;
2091 if (!empty($params['image_URL'])) {
2092 CRM_Contact_BAO_Contact
::processImageParams($params);
2095 $fields = array('email-Primary' => 1);
2097 // get the add to groups
2098 $addToGroups = array();
2100 // now set the values for the billing location.
2101 foreach ($this->_fields
as $name => $value) {
2104 // get the add to groups for uf fields
2105 if (!empty($value['add_to_group_id'])) {
2106 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2110 $fields = $this->formatParamsForPaymentProcessor($fields);
2112 // billing email address
2113 $fields["email-{$this->_bltID}"] = 1;
2115 // if onbehalf-of-organization contribution, take out
2116 // organization params in a separate variable, to make sure
2117 // normal behavior is continued. And use that variable to
2118 // process on-behalf-of functionality.
2119 if (!empty($this->_values
['onbehalf_profile_id']) && empty($this->_ccid
)) {
2120 $behalfOrganization = array();
2121 $orgFields = array('organization_name', 'organization_id', 'org_option');
2122 foreach ($orgFields as $fld) {
2123 if (array_key_exists($fld, $params)) {
2124 $behalfOrganization[$fld] = $params[$fld];
2125 unset($params[$fld]);
2129 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2130 foreach ($params['onbehalf'] as $fld => $values) {
2131 if (strstr($fld, 'custom_')) {
2132 $behalfOrganization[$fld] = $values;
2134 elseif (!(strstr($fld, '-'))) {
2135 if (in_array($fld, array(
2136 'contribution_campaign_id',
2137 'member_campaign_id',
2139 $fld = 'campaign_id';
2142 $behalfOrganization[$fld] = $values;
2144 $this->_params
[$fld] = $values;
2149 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2150 foreach ($params['onbehalf_location'] as $block => $vals) {
2151 //fix for custom data (of type checkbox, multi-select)
2152 if (substr($block, 0, 7) == 'custom_') {
2155 // fix the index of block elements
2156 if (is_array($vals)) {
2157 foreach ($vals as $key => $val) {
2158 //dont adjust the index of address block as
2159 //it's index is WRT to location type
2160 $newKey = ($block == 'address') ?
$key : ++
$key;
2161 $behalfOrganization[$block][$newKey] = $val;
2165 unset($params['onbehalf_location']);
2167 if (!empty($params['onbehalf[image_URL]'])) {
2168 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2172 // check for profile double opt-in and get groups to be subscribed
2173 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2175 // since we are directly adding contact to group lets unset it from mailing
2176 if (!empty($addToGroups)) {
2177 foreach ($addToGroups as $groupId) {
2178 if (isset($subscribeGroupIds[$groupId])) {
2179 unset($subscribeGroupIds[$groupId]);
2184 foreach ($addToGroups as $k) {
2185 if (array_key_exists($k, $subscribeGroupIds)) {
2186 unset($addToGroups[$k]);
2190 if (empty($contactID)) {
2191 $dupeParams = $params;
2192 if (!empty($dupeParams['onbehalf'])) {
2193 unset($dupeParams['onbehalf']);
2195 if (!empty($dupeParams['honor'])) {
2196 unset($dupeParams['honor']);
2199 $contactID = CRM_Contact_BAO_Contact
::getFirstDuplicateContact($dupeParams, 'Individual', 'Unsupervised', array(), FALSE);
2201 // Fetch default greeting id's if creating a contact
2203 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2204 if (!isset($params[$greeting])) {
2205 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2209 $contactType = NULL;
2212 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2214 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2224 // Make the contact ID associated with the contribution available at the Class level.
2225 // Also make available to the session.
2226 //@todo consider handling this in $this->getContactID();
2227 $this->set('contactID', $contactID);
2228 $this->_contactID
= $contactID;
2230 //get email primary first if exist
2231 $subscriptionEmail = array('email' => CRM_Utils_Array
::value('email-Primary', $params));
2232 if (!$subscriptionEmail['email']) {
2233 $subscriptionEmail['email'] = CRM_Utils_Array
::value("email-{$this->_bltID}", $params);
2235 // subscribing contact to groups
2236 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2237 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2240 // If onbehalf-of-organization contribution / signup, add organization
2241 // and it's location.
2242 if (isset($this->_values
['onbehalf_profile_id']) &&
2243 isset($behalfOrganization['organization_name']) &&
2244 ($this->_values
['is_for_organization'] == 2 ||
2245 !empty($this->_params
['is_for_organization'])
2248 $ufFields = array();
2249 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2250 $ufFields[$name] = 1;
2252 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2253 $this->_params
, $ufFields
2256 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2257 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2258 // store current user id as related contact for later use for mailing / activity..
2259 $this->_values
['related_contact'] = $contactID;
2260 $this->_params
['related_contact'] = $contactID;
2261 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2262 $contactID = $this->_membershipContactID
;
2265 // lets store the contactID in the session
2266 // for things like tell a friend
2267 $session = CRM_Core_Session
::singleton();
2268 if (!$session->get('userID')) {
2269 $session->set('transaction.userID', $contactID);
2272 $session->set('transaction.userID', NULL);
2275 $this->_useForMember
= $this->get('useForMember');
2277 // store the fact that this is a membership and membership type is selected
2278 if ((!empty($membershipParams['selectMembership']) &&
2279 $membershipParams['selectMembership'] != 'no_thanks'
2281 $this->_useForMember
2283 if (!$this->_useForMember
) {
2284 $this->assign('membership_assign', TRUE);
2285 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2288 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2289 $membershipParams['is_test'] = 1;
2291 if ($this->_params
['is_pay_later']) {
2292 $membershipParams['is_pay_later'] = 1;
2295 if (isset($this->_params
['onbehalf_contact_id'])) {
2296 $membershipParams['onbehalf_contact_id'] = $this->_params
['onbehalf_contact_id'];
2298 //inherit campaign from contribution page.
2299 if (!array_key_exists('campaign_id', $membershipParams)) {
2300 $membershipParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
);
2303 $this->_params
= CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2304 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $this->_lineItem
);
2307 // at this point we've created a contact and stored its address etc
2308 // all the payment processors expect the name and address to be in the
2309 // so we copy stuff over to first_name etc.
2310 $paymentParams = $this->_params
;
2311 // Make it explict that we are letting the processConfirm function figure out the line items.
2312 $paymentParams['skipLineItem'] = 0;
2314 if (!isset($paymentParams['line_item'])) {
2315 $paymentParams['line_item'] = $this->_lineItem
;
2318 if (!empty($paymentParams['onbehalf']) &&
2319 is_array($paymentParams['onbehalf'])
2321 foreach ($paymentParams['onbehalf'] as $key => $value) {
2322 if (strstr($key, 'custom_')) {
2323 $this->_params
[$key] = $value;
2328 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2330 $this->wrangleFinancialTypeID($this->_values
['financial_type_id']),
2331 ($this->_mode
== 'test') ?
1 : 0,
2332 CRM_Utils_Array
::value('is_recur', $paymentParams)
2335 if (empty($result['is_payment_failure'])) {
2336 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2337 $this->postProcessPremium($premiumParams, $result['contribution']);
2339 if (!empty($result['contribution'])) {
2340 // It seems this line is hit when there is a zero dollar transaction & in tests, not sure when else.
2341 $this->completeTransaction($result, $result['contribution']->id
);
2348 * Membership processing section.
2350 * This is in a separate function as part of a move towards refactoring.
2352 * @param int $contactID
2353 * @param array $membershipParams
2354 * @param array $premiumParams
2355 * @param array $formLineItems
2357 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $formLineItems) {
2358 // This could be set by a hook.
2359 if (!empty($this->_params
['installments'])) {
2360 $membershipParams['installments'] = $this->_params
['installments'];
2362 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2363 if (isset($this->_params
['related_contact'])) {
2364 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2367 $membershipParams['cms_contactID'] = $contactID;
2370 if (!empty($membershipParams['onbehalf']) &&
2371 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2373 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2376 $customFieldsFormatted = $fieldTypes = array();
2377 if (!empty($membershipParams['onbehalf']) &&
2378 is_array($membershipParams['onbehalf'])
2380 foreach ($membershipParams['onbehalf'] as $key => $value) {
2381 if (strstr($key, 'custom_')) {
2382 $customFieldId = explode('_', $key);
2383 CRM_Core_BAO_CustomField
::formatCustomField(
2385 $customFieldsFormatted,
2393 $fieldTypes = array('Contact', 'Organization', 'Membership');
2396 $priceFieldIds = $this->get('memberPriceFieldIDS');
2398 if (!empty($priceFieldIds)) {
2399 $membershipParams['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2400 unset($priceFieldIds['id']);
2401 $membershipTypeIds = array();
2402 $membershipTypeTerms = array();
2403 foreach ($priceFieldIds as $priceFieldId) {
2404 $membershipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id');
2405 if ($membershipTypeId) {
2406 $membershipTypeIds[] = $membershipTypeId;
2407 $term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms') ?
: 1;
2408 $membershipTypeTerms[$membershipTypeId] = ($term > 1) ?
$term : 1;
2411 $membershipParams['selectMembership'] = $membershipTypeIds;
2412 $membershipParams['types_terms'] = $membershipTypeTerms;
2414 if (!empty($membershipParams['selectMembership'])) {
2416 $membershipLineItems = $formLineItems;
2417 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2418 $membershipLineItems = array();
2419 foreach ($this->_values
['fee'] as $key => $feeValues) {
2420 if ($feeValues['name'] == 'membership_amount') {
2421 $fieldId = $this->_params
['price_' . $key];
2422 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2423 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2429 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems);
2431 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
2432 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2433 if (!empty($this->_contributionID
)) {
2434 CRM_Contribute_BAO_Contribution
::failPayment($this->_contributionID
,
2435 $contactID, $e->getMessage());
2437 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2439 catch (CRM_Core_Exception
$e) {
2440 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2441 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2443 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2444 // we need to explicitly create a CMS user in case of free memberships
2445 // since it is done under processConfirm for paid memberships
2446 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2447 $membershipParams['cms_contactID'],
2448 'email-' . $this->_bltID
2455 * Complete transaction if payment has been processed.
2457 * Check the result for a success outcome & if paid then complete the transaction.
2459 * Completing will trigger update of related entities and emails.
2461 * @param array $result
2462 * @param int $contributionID
2464 * @throws \CiviCRM_API3_Exception
2465 * @throws \Exception
2467 protected function completeTransaction($result, $contributionID) {
2468 if (CRM_Utils_Array
::value('payment_status_id', $result) == 1) {
2470 civicrm_api3('contribution', 'completetransaction', array(
2471 'id' => $contributionID,
2472 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $result),
2473 'payment_processor_id' => CRM_Utils_Array
::value('payment_processor_id', $result, $this->_paymentProcessor
['id']),
2474 'is_transactional' => FALSE,
2475 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
2476 'receive_date' => CRM_Utils_Array
::value('receive_date', $result),
2477 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $result),
2478 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $result),
2481 catch (CiviCRM_API3_Exception
$e) {
2482 if ($e->getErrorCode() != 'contribution_completed') {
2483 throw new CRM_Core_Exception('Failed to update contribution in database');
2490 * Bounce the user back to retry when an error occurs.
2492 * @param string $message
2494 protected function bounceOnError($message) {
2495 CRM_Core_Session
::singleton()
2496 ->setStatus(ts("Payment Processor Error message :") .
2498 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
2499 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"