3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 float $nonDeductibleAmount
162 * @param bool $pending
163 * @param array $paymentProcessorOutcome
164 * @param string $receiptDate
165 * @param int $recurringContributionID
169 public static function getContributionParams(
170 $params, $financialTypeID, $nonDeductibleAmount, $pending,
171 $paymentProcessorOutcome, $receiptDate, $recurringContributionID) {
172 $contributionParams = array(
173 'financial_type_id' => $financialTypeID,
174 'receive_date' => (CRM_Utils_Array
::value('receive_date', $params)) ? CRM_Utils_Date
::processDate($params['receive_date']) : date('YmdHis'),
175 'non_deductible_amount' => $nonDeductibleAmount,
176 'total_amount' => $params['amount'],
177 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $params),
178 'amount_level' => CRM_Utils_Array
::value('amount_level', $params),
179 'invoice_id' => $params['invoiceID'],
180 'currency' => $params['currencyID'],
181 'is_pay_later' => CRM_Utils_Array
::value('is_pay_later', $params, 0),
182 //configure cancel reason, cancel date and thankyou date
183 //from 'contribution' type profile if included
184 'cancel_reason' => CRM_Utils_Array
::value('cancel_reason', $params, 0),
185 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date
::format($params['cancel_date']) : NULL,
186 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date
::format($params['thankyou_date']) : NULL,
187 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
188 'skipLineItem' => CRM_Utils_Array
::value('skipLineItem', $params, 0),
191 if ($paymentProcessorOutcome) {
192 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor', $paymentProcessorOutcome);
194 if (!$pending && $paymentProcessorOutcome) {
195 $contributionParams +
= array(
196 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $paymentProcessorOutcome),
197 'net_amount' => CRM_Utils_Array
::value('net_amount', $paymentProcessorOutcome, $params['amount']),
198 'trxn_id' => $paymentProcessorOutcome['trxn_id'],
199 'receipt_date' => $receiptDate,
200 // also add financial_trxn details as part of fix for CRM-4724
201 'trxn_result_code' => CRM_Utils_Array
::value('trxn_result_code', $paymentProcessorOutcome),
205 // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
206 $contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money
::format($contributionParams['non_deductible_amount'], ' '));
207 $contributionParams['total_amount'] = trim(CRM_Utils_Money
::format($contributionParams['total_amount'], ' '));
209 if ($recurringContributionID) {
210 $contributionParams['contribution_recur_id'] = $recurringContributionID;
213 $contributionParams['contribution_status_id'] = $pending ?
2 : 1;
214 if (isset($contributionParams['invoice_id'])) {
215 $contributionParams['id'] = CRM_Core_DAO
::getFieldValue(
216 'CRM_Contribute_DAO_Contribution',
217 $contributionParams['invoice_id'],
223 return $contributionParams;
227 * Get non-deductible amount.
229 * This is a bit too much about wierd form interpretation to be this deep.
232 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
235 * @param array $params
236 * @param CRM_Financial_BAO_FinancialType $financialType
237 * @param bool $online
238 * @param CRM_Contribute_Form_Contribution_Confirm $form
242 protected static function getNonDeductibleAmount($params, $financialType, $online, $form) {
243 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
244 return $params['non_deductible_amount'];
246 $priceSetId = CRM_Utils_Array
::value('priceSetId', $params);
247 // return non-deductible amount if it is set at the price field option level
248 if ($priceSetId && !empty($form->_lineItem
)) {
249 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $form->_lineItem
);
252 if (!empty($nonDeductibleAmount)) {
253 return $nonDeductibleAmount;
256 if ($financialType->is_deductible
) {
257 if ($online && isset($params['selectProduct'])) {
258 $selectProduct = CRM_Utils_Array
::value('selectProduct', $params);
260 if (!$online && isset($params['product_name'][0])) {
261 $selectProduct = $params['product_name'][0];
263 // if there is a product - compare the value to the contribution amount
264 if (isset($selectProduct) &&
265 $selectProduct != 'no_thanks'
267 $productDAO = new CRM_Contribute_DAO_Product();
268 $productDAO->id
= $selectProduct;
269 $productDAO->find(TRUE);
270 // product value exceeds contribution amount
271 if ($params['amount'] < $productDAO->price
) {
272 $nonDeductibleAmount = $params['amount'];
273 return $nonDeductibleAmount;
275 // product value does NOT exceed contribution amount
277 return $productDAO->price
;
280 // contribution is deductible - but there is no product
285 // contribution is NOT deductible
287 return $params['amount'];
293 * Set variables up before form is built.
295 public function preProcess() {
296 $config = CRM_Core_Config
::singleton();
297 parent
::preProcess();
299 // lineItem isn't set until Register postProcess
300 $this->_lineItem
= $this->get('lineItem');
301 $this->_ccid
= $this->get('ccid');
302 $this->_paymentProcessor
= $this->get('paymentProcessor');
303 $this->_params
= $this->controller
->exportValues('Main');
304 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
305 $this->_params
['amount'] = $this->get('amount');
306 if (isset($this->_params
['amount'])) {
307 $this->setFormAmountFields($this->_params
['priceSetId']);
310 $this->_params
['tax_amount'] = $this->get('tax_amount');
311 $this->_useForMember
= $this->get('useForMember');
313 if (isset($this->_params
['credit_card_exp_date'])) {
314 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
315 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
318 $this->_params
['currencyID'] = $config->defaultCurrency
;
320 if (!empty($this->_membershipBlock
)) {
321 $this->_params
['selectMembership'] = $this->get('selectMembership');
323 if (!empty($this->_paymentProcessor
) && $this->_paymentProcessor
['object']->supports('preApproval')) {
324 $preApprovalParams = $this->_paymentProcessor
['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
325 $this->_params
= array_merge($this->_params
, $preApprovalParams);
327 // We may have fetched some billing details from the getPreApprovalDetails function so we
328 // want to ensure we set this after that function has been called.
329 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $preApprovalParams, $this->_params
, FALSE);
332 $this->_params
['is_pay_later'] = $this->get('is_pay_later');
333 $this->assign('is_pay_later', $this->_params
['is_pay_later']);
334 if ($this->_params
['is_pay_later']) {
335 $this->assign('pay_later_receipt', CRM_Utils_Array
::value('pay_later_receipt', $this->_values
));
337 // if onbehalf-of-organization
338 if (!empty($this->_values
['onbehalf_profile_id']) && !empty($this->_params
['onbehalf']['organization_name'])) {
339 $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 $this->assignToTemplate();
503 $params = $this->_params
;
504 // make sure we have values for it
505 if (!empty($this->_values
['honoree_profile_id']) && !empty($params['soft_credit_type_id']) && empty($this->_ccid
)) {
507 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
509 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
510 CRM_Contribute_BAO_ContributionSoft
::formatHonoreeProfileFields($this, $params['honor']);
512 $fieldTypes = array('Contact');
513 $fieldTypes[] = CRM_Core_BAO_UFGroup
::getContactType($this->_values
['honoree_profile_id']);
514 $this->buildCustom($this->_values
['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
516 $this->assign('receiptFromEmail', CRM_Utils_Array
::value('receipt_from_email', $this->_values
));
517 $amount_block_is_active = $this->get('amount_block_is_active');
518 $this->assign('amount_block_is_active', $amount_block_is_active);
520 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
521 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
523 $getTaxDetails = FALSE;
524 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
525 foreach ($this->_lineItem
as $key => $value) {
526 foreach ($value as $v) {
527 if (isset($v['tax_rate'])) {
528 if ($v['tax_rate'] != '') {
529 $getTaxDetails = TRUE;
534 $this->assign('getTaxDetails', $getTaxDetails);
535 $this->assign('taxTerm', $taxTerm);
536 $this->assign('totalTaxAmount', $params['tax_amount']);
538 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
539 $option = CRM_Utils_Array
::value('options_' . $params['selectProduct'], $params);
540 $productID = $params['selectProduct'];
541 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, FALSE,
544 $this->set('productID', $productID);
545 $this->set('option', $option);
547 $config = CRM_Core_Config
::singleton();
548 if (in_array('CiviMember', $config->enableComponents
) && empty($this->_ccid
)) {
549 if (isset($params['selectMembership']) &&
550 $params['selectMembership'] != 'no_thanks'
552 $this->buildMembershipBlock(
553 $this->_membershipContactID
,
555 $params['selectMembership'],
558 if (!empty($params['auto_renew'])) {
559 $this->assign('auto_renew', TRUE);
563 $this->assign('membershipBlock', FALSE);
566 if (empty($this->_ccid
)) {
567 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
568 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
571 if (!empty($this->_values
['onbehalf_profile_id']) &&
572 !empty($params['onbehalf']) &&
573 ($this->_values
['is_for_organization'] == 2 ||
574 !empty($params['is_for_organization'])
575 ) && empty($this->_ccid
)
577 $fieldTypes = array('Contact', 'Organization');
578 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
579 $fieldTypes = array_merge($fieldTypes, $contactSubType);
580 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
581 $fieldTypes = array_merge($fieldTypes, array('Membership'));
584 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
587 $this->buildCustom($this->_values
['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
590 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
591 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
592 if ($this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
593 $this->assign('lineItem', $this->_lineItem
);
596 $this->assign('is_quick_config', 1);
597 $this->_params
['is_quick_config'] = 1;
599 $this->assign('priceSetID', $this->_priceSetId
);
601 // The concept of contributeMode is deprecated.
602 // the is_monetary concept probably should be too as it can be calculated from
603 // the existence of 'amount' & seems fragile.
604 if ($this->_contributeMode
== 'notify' ||
605 $this->_amount
< 0.0 ||
$this->_params
['is_pay_later'] ||
606 ($this->_separateMembershipPayment
&& $this->_amount
<= 0.0)
608 $contribButton = ts('Continue');
609 $this->assign('button', ts('Continue'));
611 elseif (!empty($this->_ccid
)) {
612 $contribButton = ts('Make Payment');
613 $this->assign('button', ts('Make Payment'));
616 $contribButton = ts('Make Contribution');
617 $this->assign('button', ts('Make Contribution'));
619 $this->addButtons(array(
622 'name' => $contribButton,
623 'spacing' => ' ',
625 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name
. "','" . ts('Processing') . "');"),
629 'name' => ts('Go Back'),
635 $fields = array_fill_keys(array_keys($this->_fields
), 1);
636 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
638 $contact = $this->_params
;
639 foreach ($fields as $name => $dontCare) {
640 // Recursively set defaults for nested fields
641 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' ||
$name == 'honor')) {
642 foreach ($contact[$name] as $fieldName => $fieldValue) {
643 if (is_array($fieldValue) && !in_array($this->_fields
[$name][$fieldName]['html_type'], array(
648 foreach ($fieldValue as $key => $value) {
649 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
653 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
657 elseif (isset($contact[$name])) {
658 $defaults[$name] = $contact[$name];
659 if (substr($name, 0, 7) == 'custom_') {
660 $timeField = "{$name}_time";
661 if (isset($contact[$timeField])) {
662 $defaults[$timeField] = $contact[$timeField];
664 if (isset($contact["{$name}_id"])) {
665 $defaults["{$name}_id"] = $contact["{$name}_id"];
668 elseif (in_array($name, array(
672 )) && !empty($contact[$name . '_custom'])
674 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
679 $this->assign('useForMember', $this->get('useForMember'));
681 $this->setDefaults($defaults);
689 * Since we are only showing elements in frozen mode no help display needed.
693 public function getAction() {
694 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
695 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
698 return CRM_Core_Action
::VIEW
;
703 * Set default values for the form.
705 * Note that in edit/view mode
706 * the default values are retrieved from the database
708 public function setDefaultValues() {
714 public function postProcess() {
715 $contactID = $this->getContactID();
716 $result = $this->processFormSubmission($contactID);
717 if (is_array($result) && !empty($result['is_payment_failure'])) {
718 // We will probably have the function that gets this error throw an exception on the next round of refactoring.
719 CRM_Core_Session
::singleton()->setStatus(ts("Payment Processor Error message :") .
720 $result['error']->getMessage());
721 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
722 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
725 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
726 $this->set('params', $this->_params
);
730 * Wrangle financial type ID.
732 * 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
733 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
735 * Comments from previous refactor indicate doubt as to what was going on.
737 * @param int $contributionTypeId
739 * @return null|string
741 public function wrangleFinancialTypeID($contributionTypeId) {
742 if (isset($paymentParams['financial_type'])) {
743 $contributionTypeId = $paymentParams['financial_type'];
745 elseif (!empty($this->_values
['pledge_id'])) {
746 $contributionTypeId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
747 $this->_values
['pledge_id'],
751 return $contributionTypeId;
757 * @param array $premiumParams
758 * @param CRM_Contribute_BAO_Contribution $contribution
760 protected function postProcessPremium($premiumParams, $contribution) {
761 $hour = $minute = $second = 0;
762 // assigning Premium information to receipt tpl
763 $selectProduct = CRM_Utils_Array
::value('selectProduct', $premiumParams);
764 if ($selectProduct &&
765 $selectProduct != 'no_thanks'
767 $startDate = $endDate = "";
768 $this->assign('selectPremium', TRUE);
769 $productDAO = new CRM_Contribute_DAO_Product();
770 $productDAO->id
= $selectProduct;
771 $productDAO->find(TRUE);
772 $this->assign('product_name', $productDAO->name
);
773 $this->assign('price', $productDAO->price
);
774 $this->assign('sku', $productDAO->sku
);
775 $this->assign('option', CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams));
777 $periodType = $productDAO->period_type
;
780 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
781 $duration_unit = $productDAO->duration_unit
;
782 $duration_interval = $productDAO->duration_interval
;
783 if ($periodType == 'rolling') {
784 $startDate = date('Y-m-d');
786 elseif ($periodType == 'fixed') {
787 if ($fixed_period_start_day) {
788 $date = explode('-', date('Y-m-d'));
789 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
790 $day = substr($fixed_period_start_day, -2) . "<br/>";
792 $startDate = $year . '-' . $month . '-' . $day;
795 $startDate = date('Y-m-d');
799 $date = explode('-', $startDate);
804 switch ($duration_unit) {
806 $year = $year +
$duration_interval;
810 $month = $month +
$duration_interval;
814 $day = $day +
$duration_interval;
818 $day = $day +
($duration_interval * 7);
820 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
821 $this->assign('start_date', $startDate);
822 $this->assign('end_date', $endDate);
825 $dao = new CRM_Contribute_DAO_Premium();
826 $dao->entity_table
= 'civicrm_contribution_page';
827 $dao->entity_id
= $this->_id
;
829 $this->assign('contact_phone', $dao->premiums_contact_phone
);
830 $this->assign('contact_email', $dao->premiums_contact_email
);
832 //create Premium record
834 'product_id' => $premiumParams['selectProduct'],
835 'contribution_id' => $contribution->id
,
836 'product_option' => CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams),
838 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
839 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
841 if (!empty($premiumParams['selectProduct'])) {
842 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
843 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
844 $daoPremiumsProduct->premiums_id
= $dao->id
;
845 $daoPremiumsProduct->find(TRUE);
846 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
849 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
850 $daoContrProd->contribution_id
= $contribution->id
;
851 if ($daoContrProd->find(TRUE)) {
852 $params['id'] = $daoContrProd->id
;
855 CRM_Contribute_BAO_Contribution
::addPremium($params);
856 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
858 'cost' => $productDAO->cost
,
859 'currency' => $productDAO->currency
,
860 'financial_type_id' => $params['financial_type_id'],
861 'contributionId' => $contribution->id
,
863 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
866 elseif ($selectProduct == 'no_thanks') {
868 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
869 $daoContrProd->contribution_id
= $contribution->id
;
870 if ($daoContrProd->find(TRUE)) {
871 $daoContrProd->delete();
877 * Process the contribution.
879 * @param CRM_Core_Form $form
880 * @param array $params
881 * @param array $result
882 * @param array $contributionParams
883 * Parameters to be passed to contribution create action.
884 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
885 * passed consistently & 2) documenting them here.
890 * - contribution_page_id
893 * - thankyou_date (not all forms will set this)
895 * @param CRM_Financial_DAO_FinancialType $financialType
896 * @param bool $online
897 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
899 * @param int $billingLocationID
900 * ID of billing location type.
901 * @param bool $isRecur
904 * @return \CRM_Contribute_DAO_Contribution
907 public static function processFormContribution(
917 $transaction = new CRM_Core_Transaction();
918 $contactID = $contributionParams['contact_id'];
920 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
921 $isSeparateMembershipPayment = empty($params['separate_membership_payment']) ?
FALSE : TRUE;
922 $pledgeID = !empty($params['pledge_id']) ?
$params['pledge_id'] : CRM_Utils_Array
::value('pledge_id', $form->_values
);
923 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
924 (!empty($params['is_pledge']) ||
$pledgeID)) {
931 // add these values for the recurringContrib function ,CRM-10188
932 $params['financial_type_id'] = $financialType->id
;
934 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
936 //@todo - this is being set from the form to resolve CRM-10188 - an
937 // eNotice caused by it not being set @ the front end
938 // however, we then get it being over-written with null for backend contributions
939 // a better fix would be to set the values in the respective forms rather than require
940 // a function being shared by two forms to deal with their respective values
941 // moving it to the BAO & not taking the $form as a param would make sense here.
942 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
943 $params['is_email_receipt'] = $isEmailReceipt;
945 $params['is_recur'] = $isRecur;
946 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'];
947 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType);
948 $nonDeductibleAmount = self
::getNonDeductibleAmount($params, $financialType, $online, $form);
950 $now = date('YmdHis');
951 $receiptDate = CRM_Utils_Array
::value('receipt_date', $params);
952 if ($isEmailReceipt) {
956 if (isset($params['amount'])) {
957 $contributionParams = array_merge(self
::getContributionParams(
958 $params, $financialType->id
, $nonDeductibleAmount, TRUE,
959 $result, $receiptDate,
960 $recurringContributionID), $contributionParams
962 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
964 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
965 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
967 $dataArray = array();
968 // @todo - interrogate the line items passed in on the params array.
969 // No reason to assume line items will be set on the form.
970 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
971 foreach ($lineItemValue as $key => $value) {
972 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
973 if (isset($dataArray[$value['tax_rate']])) {
974 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
977 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
982 $smarty = CRM_Core_Smarty
::singleton();
983 $smarty->assign('dataArray', $dataArray);
984 $smarty->assign('totalTaxAmount', $params['tax_amount']);
986 if (is_a($contribution, 'CRM_Core_Error')) {
987 $message = CRM_Core_Error
::getMessages($contribution);
988 CRM_Core_Error
::fatal($message);
991 // lets store it in the form variable so postProcess hook can get to this and use it
992 $form->_contributionID
= $contribution->id
;
995 // process soft credit / pcp params first
996 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
998 //CRM-13981, processing honor contact into soft-credit contribution
999 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
1002 $form = self
::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
1005 if ($online && $contribution) {
1006 CRM_Core_BAO_CustomValueTable
::postProcess($params,
1007 'civicrm_contribution',
1012 elseif ($contribution) {
1013 //handle custom data.
1014 $params['contribution_id'] = $contribution->id
;
1015 if (!empty($params['custom']) &&
1016 is_array($params['custom']) &&
1017 !is_a($contribution, 'CRM_Core_Error')
1019 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
1023 if ($contribution && !empty($params['contribution_note'])) {
1024 $noteParams = array(
1025 'entity_table' => 'civicrm_contribution',
1026 'note' => $params['contribution_note'],
1027 'entity_id' => $contribution->id
,
1028 'contact_id' => $contribution->contact_id
,
1029 'modified_date' => date('Ymd'),
1032 CRM_Core_BAO_Note
::add($noteParams, array());
1035 if (isset($params['related_contact'])) {
1036 $contactID = $params['related_contact'];
1038 elseif (isset($params['cms_contactID'])) {
1039 $contactID = $params['cms_contactID'];
1042 //create contribution activity w/ individual and target
1043 //activity w/ organisation contact id when onbelf, CRM-4027
1044 $targetContactID = NULL;
1045 if (!empty($params['hidden_onbehalf_profile'])) {
1046 $targetContactID = $contribution->contact_id
;
1047 $contribution->contact_id
= $contactID;
1050 // create an activity record
1051 if ($contribution) {
1052 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
1055 $transaction->commit();
1056 // CRM-13074 - create the CMSUser after the transaction is completed as it
1057 // is not appropriate to delete a valid contribution if a user create problem occurs
1058 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($params,
1060 'email-' . $billingLocationID
1062 return $contribution;
1066 * Create the recurring contribution record.
1068 * @param CRM_Core_Form $form
1069 * @param array $params
1070 * @param int $contactID
1071 * @param string $contributionType
1075 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType) {
1077 if (empty($params['is_recur'])) {
1081 $recurParams = array('contact_id' => $contactID);
1082 $recurParams['amount'] = CRM_Utils_Array
::value('amount', $params);
1083 $recurParams['auto_renew'] = CRM_Utils_Array
::value('auto_renew', $params);
1084 $recurParams['frequency_unit'] = CRM_Utils_Array
::value('frequency_unit', $params);
1085 $recurParams['frequency_interval'] = CRM_Utils_Array
::value('frequency_interval', $params);
1086 $recurParams['installments'] = CRM_Utils_Array
::value('installments', $params);
1087 $recurParams['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $params);
1088 $recurParams['currency'] = CRM_Utils_Array
::value('currency', $params);
1089 $recurParams['payment_instrument_id'] = $params['payment_instrument_id'];
1091 // CRM-14354: For an auto-renewing membership with an additional contribution,
1092 // if separate payments is not enabled, make sure only the membership fee recurs
1093 if (!empty($form->_membershipBlock
)
1094 && $form->_membershipBlock
['is_separate_payment'] === '0'
1095 && isset($params['selectMembership'])
1096 && $form->_values
['is_allow_other_amount'] == '1'
1098 && !empty($form->_membershipTypeValues
)
1099 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1101 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1104 $recurParams['is_test'] = 0;
1105 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1106 (isset($form->_mode
) && ($form->_mode
== 'test'))
1108 $recurParams['is_test'] = 1;
1111 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1112 if (!empty($params['receive_date'])) {
1113 $recurParams['start_date'] = date('YmdHis', strtotime($params['receive_date']));
1115 $recurParams['invoice_id'] = CRM_Utils_Array
::value('invoiceID', $params);
1116 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1117 $recurParams['payment_processor_id'] = CRM_Utils_Array
::value('payment_processor_id', $params);
1118 $recurParams['is_email_receipt'] = CRM_Utils_Array
::value('is_email_receipt', $params);
1119 // we need to add a unique trxn_id to avoid a unique key error
1120 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1121 $recurParams['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params, $params['invoiceID']);
1122 $recurParams['financial_type_id'] = $contributionType->id
;
1124 $campaignId = CRM_Utils_Array
::value('campaign_id', $params, CRM_Utils_Array
::value('campaign_id', $form->_values
));
1125 $recurParams['campaign_id'] = $campaignId;
1126 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1127 if (is_a($recurring, 'CRM_Core_Error')) {
1128 CRM_Core_Error
::displaySessionError($recurring);
1129 $urlString = 'civicrm/contribute/transact';
1130 $urlParams = '_qf_Main_display=true';
1131 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1132 $urlString = 'civicrm/contact/view/contribution';
1133 $urlParams = "action=add&cid={$form->_contactID}";
1135 $urlParams .= "&mode={$form->_mode}";
1138 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1140 // Only set contribution recur ID for contributions since offline membership recur payments are handled somewhere else.
1141 if (!is_a($form, "CRM_Member_Form_Membership")) {
1142 $form->_params
['contributionRecurID'] = $recurring->id
;
1145 return $recurring->id
;
1149 * Add on behalf of organization and it's location.
1151 * This situation occurs when on behalf of is enabled for the contribution page and the person
1152 * signing up does so on behalf of an organization.
1154 * @param array $behalfOrganization
1155 * array of organization info.
1156 * @param int $contactID
1157 * individual contact id. One.
1158 * who is doing the process of signup / contribution.
1160 * @param array $values
1161 * form values array.
1162 * @param array $params
1163 * @param array $fields
1164 * Array of fields from the onbehalf profile relevant to the organization.
1166 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1167 $isNotCurrentEmployer = FALSE;
1170 if (!empty($behalfOrganization['organization_id'])) {
1171 $orgID = $behalfOrganization['organization_id'];
1172 unset($behalfOrganization['organization_id']);
1174 // create employer relationship with $contactID only when new organization is there
1175 // else retain the existing relationship
1177 // get the Employee relationship type id
1178 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
1180 // keep relationship params ready
1181 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1182 $relParams['is_permission_a_b'] = 1;
1183 $relParams['is_active'] = 1;
1184 $isNotCurrentEmployer = TRUE;
1187 // formalities for creating / editing organization.
1188 $behalfOrganization['contact_type'] = 'Organization';
1191 // check if matching organization contact exists
1192 $dupeID = CRM_Contact_BAO_Contact
::getFirstDuplicateContact($behalfOrganization, 'Organization', 'Unsupervised', array(), FALSE);
1194 // CRM-6243 says to pick the first org even if more than one match
1195 if (count($dupeIDs) >= 1) {
1196 $behalfOrganization['contact_id'] = $orgID = $dupeID;
1197 // don't allow name edit
1198 unset($behalfOrganization['organization_name']);
1202 // if found permissioned related organization, allow location edit
1203 $behalfOrganization['contact_id'] = $orgID;
1204 // don't allow name edit
1205 unset($behalfOrganization['organization_name']);
1208 // handling for image url
1209 if (!empty($behalfOrganization['image_URL'])) {
1210 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1213 // create organization, add location
1214 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1215 NULL, NULL, 'Organization'
1217 // create relationship
1218 if ($isNotCurrentEmployer) {
1219 $relParams['contact_check'][$orgID] = 1;
1220 $cid = array('contact' => $contactID);
1221 CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relParams, $cid);
1224 // if multiple match - send a duplicate alert
1225 if ($dupeIDs && (count($dupeIDs) > 1)) {
1226 $values['onbehalf_dupe_alert'] = 1;
1228 $params['onbehalf_dupe_alert'] = 1;
1231 // make sure organization-contact-id is considered for recording
1232 // contribution/membership etc..
1233 if ($contactID != $orgID) {
1234 // take a note of contact-id, so we can send the
1235 // receipt to individual contact as well.
1237 // required for mailing/template display ..etc
1238 $values['related_contact'] = $contactID;
1240 //CRM-19172: Create CMS user for individual on whose behalf organization is doing contribution
1241 $params['onbehalf_contact_id'] = $contactID;
1243 //make this employee of relationship as current
1244 //employer / employee relationship, CRM-3532
1245 if ($isNotCurrentEmployer &&
1246 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1248 $isNotCurrentEmployer = FALSE;
1251 if (!$isNotCurrentEmployer && $orgID) {
1252 //build current employer params
1253 $currentEmpParams[$contactID] = $orgID;
1254 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1257 // contribution / signup will be done using this
1259 $contactID = $orgID;
1264 * Function used to send notification mail to pcp owner.
1266 * This is used by contribution and also event PCPs.
1268 * @param object $contribution
1269 * @param object $contributionSoft
1270 * Contribution object.
1272 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1273 $params = array('id' => $contributionSoft->pcp_id
);
1274 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1275 $ownerNotifyID = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1277 if ($ownerNotifyID != CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1278 (($ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1279 CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id
, 'is_notify')) ||
1280 $ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1281 $pcpInfoURL = CRM_Utils_System
::url('civicrm/pcp/info',
1282 "reset=1&id={$contributionSoft->pcp_id}",
1283 TRUE, NULL, FALSE, TRUE
1285 // set email in the template here
1287 if (CRM_Core_BAO_LocationType
::getBilling()) {
1288 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
,
1289 FALSE, CRM_Core_BAO_LocationType
::getBilling());
1291 // get primary location email if no email exist( for billing location).
1293 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
);
1295 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft->contact_id
);
1297 'page_title' => $pcpInfo['title'],
1298 'receive_date' => $contribution->receive_date
,
1299 'total_amount' => $contributionSoft->amount
,
1300 'donors_display_name' => $donorName,
1301 'donors_email' => $email,
1302 'pcpInfoURL' => $pcpInfoURL,
1303 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll
,
1304 'currency' => $contributionSoft->currency
,
1306 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1307 $sendTemplateParams = array(
1308 'groupName' => 'msg_tpl_workflow_contribution',
1309 'valueName' => 'pcp_owner_notify',
1310 'contactId' => $contributionSoft->contact_id
,
1311 'toEmail' => $ownerEmail,
1312 'toName' => $ownerName,
1313 'from' => "$domainValues[0] <$domainValues[1]>",
1314 'tplParams' => $tplParams,
1315 'PDFFilename' => 'receipt.pdf',
1317 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1322 * Function used to se pcp related defaults / params.
1324 * This is used by contribution and also event PCPs
1326 * @param CRM_Core_Form $page
1328 * @param array $params
1332 public static function processPcp(&$page, $params) {
1333 $params['pcp_made_through_id'] = $page->_pcpId
;
1334 $page->assign('pcpBlock', TRUE);
1335 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1336 $params['pcp_roll_nickname'] = ts('Anonymous');
1337 $params['pcp_is_anonymous'] = 1;
1340 $params['pcp_is_anonymous'] = 0;
1343 'pcp_display_in_roll',
1345 'pcp_roll_nickname',
1346 'pcp_personal_note',
1348 if (!empty($params[$val])) {
1349 $page->assign($val, $params[$val]);
1357 * Process membership.
1359 * @param array $membershipParams
1360 * @param int $contactID
1361 * @param array $customFieldsFormatted
1362 * @param array $fieldTypes
1363 * @param array $premiumParams
1364 * @param array $membershipLineItems
1365 * Line items specifically relating to memberships.
1367 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1368 $membershipLineItems) {
1370 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1371 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1372 $membershipType = empty($membershipTypes) ?
array() : reset($membershipTypes);
1373 $isPending = $this->getIsPending();
1375 $this->assign('membership_name', CRM_Utils_Array
::value('name', $membershipType));
1376 $this->_values
['membership_name'] = CRM_Utils_Array
::value('name', $membershipType);
1378 $isPaidMembership = FALSE;
1379 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1380 //amount must be greater than zero for
1381 //adding contribution record to contribution table.
1382 //this condition arises when separate membership payment is
1383 //enabled and contribution amount is not selected. fix for CRM-3010
1384 $isPaidMembership = TRUE;
1386 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1388 if ($this->_values
['amount_block_is_active']) {
1389 $financialTypeID = $this->_values
['financial_type_id'];
1392 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $membershipType, CRM_Utils_Array
::value('financial_type_id', $membershipParams));
1395 if (CRM_Utils_Array
::value('membership_source', $this->_params
)) {
1396 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1399 $this->postProcessMembership($membershipParams, $contactID,
1400 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1401 $membershipLineItems, $isPending);
1403 $this->assign('membership_assign', TRUE);
1404 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1408 * Process the Memberships.
1410 * @param array $membershipParams
1411 * Array of membership fields.
1412 * @param int $contactID
1414 * @param CRM_Contribute_Form_Contribution_Confirm $form
1415 * Confirmation form object.
1417 * @param array $premiumParams
1418 * @param null $customFieldsFormatted
1419 * @param null $includeFieldTypes
1421 * @param array $membershipDetails
1423 * @param array $membershipTypeIDs
1425 * @param bool $isPaidMembership
1426 * @param array $membershipID
1428 * @param bool $isProcessSeparateMembershipTransaction
1430 * @param int $financialTypeID
1431 * @param array $unprocessedLineItems
1432 * Line items for payment options chosen on the form.
1433 * @param bool $isPending
1435 * @throws \CRM_Core_Exception
1437 protected function postProcessMembership(
1438 $membershipParams, $contactID, &$form, $premiumParams,
1439 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1440 $isProcessSeparateMembershipTransaction, $financialTypeID, $unprocessedLineItems, $isPending) {
1442 $membershipContribution = NULL;
1443 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1444 $errors = $paymentResults = array();
1445 $form->_values
['isMembership'] = TRUE;
1446 $isRecurForFirstTransaction = CRM_Utils_Array
::value('is_recur', $form->_values
, CRM_Utils_Array
::value('is_recur', $membershipParams));
1448 $totalAmount = $membershipParams['amount'];
1450 if ($isPaidMembership) {
1451 if ($isProcessSeparateMembershipTransaction) {
1452 // If we have 2 transactions only one can use the invoice id.
1453 $membershipParams['invoiceID'] .= '-2';
1454 if (!empty($membershipParams['auto_renew'])) {
1455 $isRecurForFirstTransaction = FALSE;
1459 if (!$isProcessSeparateMembershipTransaction) {
1460 // Skip line items in the contribution processing transaction.
1461 // We will create them with the membership for proper linking.
1462 $membershipParams['skipLineItem'] = 1;
1465 $membershipParams['total_amount'] = $totalAmount;
1466 $membershipParams['skipLineItem'] = 0;
1467 CRM_Price_BAO_LineItem
::getLineItemArray($membershipParams);
1470 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm(
1476 $isRecurForFirstTransaction
1479 if (!empty($paymentResult['contribution'])) {
1480 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1481 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1482 $membershipContribution = $paymentResult['contribution'];
1483 // Save the contribution ID so that I can be used in email receipts
1484 // For example, if you need to generate a tax receipt for the donation only.
1485 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1489 if ($isProcessSeparateMembershipTransaction) {
1491 $form->_lineItem
= $unprocessedLineItems;
1492 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1493 unset($membershipParams['is_recur']);
1495 list($membershipContribution, $secondPaymentResult) = $this->processSecondaryFinancialTransaction($contactID, $form, array_merge($membershipParams, array('skipLineItem' => 1)),
1496 $isTest, $unprocessedLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1497 $paymentResults[] = array('contribution_id' => $membershipContribution->id
, 'result' => $secondPaymentResult);
1499 catch (CRM_Core_Exception
$e) {
1500 $errors[2] = $e->getMessage();
1501 $membershipContribution = NULL;
1506 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1507 $membershipContributionID = $membershipContribution->id
;
1510 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1511 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1512 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1514 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1515 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1516 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1518 $membershipLines = $nonMembershipLines = array();
1519 foreach ($unprocessedLineItems as $priceSetID => $lines) {
1520 foreach ($lines as $line) {
1521 if (!empty($line['membership_type_id'])) {
1522 $membershipLines[$line['membership_type_id']] = $line['price_field_value_id'];
1528 foreach ($membershipTypeIDs as $memType) {
1529 $membershipLineItems = array();
1530 if ($i < count($membershipTypeIDs)) {
1531 $membershipLineItems[$priceSetID][$membershipLines[$memType]] = $unprocessedLineItems[$priceSetID][$membershipLines[$memType]];
1532 unset($unprocessedLineItems[$priceSetID][$membershipLines[$memType]]);
1535 $membershipLineItems = $unprocessedLineItems;
1538 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1539 if (!empty($membershipContribution)) {
1540 $pendingStatus = CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name');
1541 $pending = ($membershipContribution->contribution_status_id
== $pendingStatus) ?
TRUE : FALSE;
1544 $pending = $isPending;
1546 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
1548 $membershipSource = NULL;
1549 if (!empty($form->_params
['membership_source'])) {
1550 $membershipSource = $form->_params
['membership_source'];
1552 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
1553 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
1556 if (isset($form->_params
)) {
1557 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
1560 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
1561 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
1562 if (!array_key_exists('campaign_id', $form->_params
)) {
1563 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1567 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership
::processMembership(
1568 $contactID, $memType, $isTest,
1569 date('YmdHis'), CRM_Utils_Array
::value('cms_contactID', $membershipParams),
1570 $customFieldsFormatted,
1571 $numTerms, $membershipID, $pending,
1572 $contributionRecurID, $membershipSource, $isPayLater, $campaignId, array(), $membershipContribution,
1573 $membershipLineItems
1576 $form->set('renewal_mode', $renewalMode);
1577 if (!empty($dates)) {
1578 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d'));
1579 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d'));
1582 if (!empty($membershipContribution)) {
1583 // update recurring id for membership record
1584 CRM_Member_BAO_Membership
::updateRecurMembership($membership, $membershipContribution);
1585 // Next line is probably redundant. Checksprevent it happening twice.
1586 CRM_Member_BAO_Membership
::linkMembershipPayment($membership, $membershipContribution);
1589 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1590 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1591 if (!empty($priceFieldOp['membership_type_id']) && $membership->membership_type_id
== $priceFieldOp['membership_type_id']) {
1592 $membershipOb = $membership;
1593 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1594 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1597 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1600 $form->_values
['lineItem'] = $form->_lineItem
;
1601 $form->assign('lineItem', $form->_lineItem
);
1605 if (!empty($errors)) {
1606 $message = $this->compileErrorMessage($errors);
1607 throw new CRM_Core_Exception($message);
1609 $form->_params
['createdMembershipIDs'] = array();
1611 // CRM-7851 - Moved after processing Payment Errors
1612 //@todo - the reasoning for this being here seems a little outdated
1613 CRM_Core_BAO_CustomValueTable
::postProcess($form->_params
, 'civicrm_membership', $membership->id
, 'Membership');
1614 $form->_params
['createdMembershipIDs'][] = $membership->id
;
1617 //presumably this is only relevant for exactly 1 membership
1618 $form->_params
['membershipID'] = $membership->id
;
1621 //CRM-15232: Check if membership is created and on the basis of it use
1622 //membership receipt template to send payment receipt
1624 $form->_values
['isMembership'] = TRUE;
1626 if (isset($membershipContributionID)) {
1627 $form->_values
['contribution_id'] = $membershipContributionID;
1630 if (empty($form->_params
['is_pay_later']) && $form->_paymentProcessor
) {
1631 // the is_monetary concept probably should be deprecated as it can be calculated from
1632 // the existence of 'amount' & seems fragile.
1633 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1634 // call postProcess hook before leaving
1635 $form->postProcessHook();
1638 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1639 // The contribution_other_id is effectively the ID for the only contribution or the non-membership contribution.
1640 // Since we have called the membership contribution (in a 2 contribution scenario) this is out
1641 // primary-contribution compared to that - but let's face it - it's all just too hard & confusing at the moment!
1642 $paymentParams = array_merge($form->_params
, array('contributionID' => $form->_values
['contribution_other_id']));
1644 // CRM-19792 : set necessary fields for payment processor
1645 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $paymentParams, $paymentParams, TRUE);
1647 $paymentActionResult = $payment->doPayment($paymentParams, 'contribute');
1648 $paymentResults[] = array('contribution_id' => $paymentResult['contribution']->id
, 'result' => $paymentActionResult);
1649 // Do not send an email if Recurring transaction is done via Direct Mode
1650 // Email will we sent when the IPN is received.
1651 foreach ($paymentResults as $result) {
1652 //CRM-18211: Fix situation where second contribution doesn't exist because it is optional.
1653 if ($result['contribution_id']) {
1654 $this->completeTransaction($result['result'], $result['contribution_id']);
1660 $emailValues = array_merge($membershipParams, $form->_values
);
1661 $emailValues['membership_assign'] = 1;
1662 // Finally send an email receipt for pay-later scenario (although it might sometimes be caught above!)
1663 if ($totalAmount == 0) {
1664 // This feels like a bizarre hack as the variable name doesn't seem to be directly connected to it's use in the template.
1665 $emailValues['useForMember'] = 0;
1666 $emailValues['amount'] = 0;
1668 //CRM-18071, where on selecting $0 free membership payment section got hidden and
1669 // also it reset any payment processor selection result into pending free membership
1670 // so its a kind of hack to complete free membership at this point since there is no $form->_paymentProcessor info
1671 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1672 if (empty($form->_paymentProcessor
)) {
1673 // @todo this can maybe go now we are setting payment_processor_id = 0 more reliably.
1674 $paymentProcessorIDs = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, CRM_Utils_Array
::value('payment_processor', $this->_values
));
1675 $this->_paymentProcessor
['id'] = $paymentProcessorIDs[0];
1677 $result = array('payment_status_id' => 1, 'contribution' => $membershipContribution);
1678 $this->completeTransaction($result, $result['contribution']->id
);
1680 // return as completeTransaction() already sends the receipt mail.
1684 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1692 * Turn array of errors into message string.
1694 * @param array $errors
1698 protected function compileErrorMessage($errors) {
1699 foreach ($errors as $error) {
1700 if (is_string($error)) {
1701 $message[] = $error;
1704 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1708 * Where a second separate financial transaction is supported we will process it here.
1710 * @param int $contactID
1711 * @param CRM_Contribute_Form_Contribution_Confirm $form
1712 * @param array $tempParams
1713 * @param bool $isTest
1714 * @param array $lineItems
1715 * @param $minimumFee
1716 * @param int $financialTypeID
1718 * @throws CRM_Core_Exception
1720 * @return CRM_Contribute_BAO_Contribution
1722 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1724 $financialType = new CRM_Financial_DAO_FinancialType();
1725 $financialType->id
= $financialTypeID;
1726 $financialType->find(TRUE);
1727 $tempParams['amount'] = $minimumFee;
1728 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1729 $isRecur = CRM_Utils_Array
::value('is_recur', $tempParams);
1731 //assign receive date when separate membership payment
1732 //and contribution amount not selected.
1733 if ($form->_amount
== 0) {
1734 $now = date('YmdHis');
1735 $form->_params
['receive_date'] = $now;
1736 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1737 $form->set('params', $form->_params
);
1738 $form->assign('receive_date', $receiveDate);
1741 $form->set('membership_amount', $minimumFee);
1742 $form->assign('membership_amount', $minimumFee);
1744 // we don't need to create the user twice, so lets disable cms_create_account
1745 // irrespective of the value, CRM-2888
1746 $tempParams['cms_create_account'] = 0;
1748 //set this variable as we are not creating pledge for
1749 //separate membership payment contribution.
1750 //so for differentiating membership contribution from
1751 //main contribution.
1752 $form->_params
['separate_membership_payment'] = 1;
1753 $contributionParams = array(
1754 'contact_id' => $contactID,
1755 'line_item' => $lineItems,
1756 'is_test' => $isTest,
1757 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $tempParams, CRM_Utils_Array
::value('campaign_id',
1759 'contribution_page_id' => $form->_id
,
1760 'source' => CRM_Utils_Array
::value('source', $tempParams, CRM_Utils_Array
::value('description', $tempParams)),
1762 $isMonetary = !empty($form->_values
['is_monetary']);
1764 if (empty($paymentParams['is_pay_later'])) {
1765 $contributionParams['payment_instrument_id'] = $form->_paymentProcessor
['payment_instrument_id'];
1769 // CRM-19792 : set necessary fields for payment processor
1770 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $form->_params
, $tempParams, TRUE);
1772 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
1775 $contributionParams,
1783 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
1784 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1785 // now we compensate here.
1786 if (empty($form->_paymentProcessor
['object'])) {
1787 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1790 $payment = $form->_paymentProcessor
['object'];
1792 $result = $payment->doPayment($tempParams, 'contribute');
1793 $form->set('membership_trx_id', $result['trxn_id']);
1794 $form->assign('membership_trx_id', $result['trxn_id']);
1797 return array($membershipContribution, $result);
1801 * Is the payment a pending payment.
1803 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1804 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1808 protected function getIsPending() {
1809 // The concept of contributeMode is deprecated.
1810 // the is_monetary concept probably should be too as it can be calculated from
1811 // the existence of 'amount' & seems fragile.
1812 if (((isset($this->_contributeMode
)) ||
!empty
1813 ($this->_params
['is_pay_later'])
1815 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1823 * Are we going to do 2 financial transactions.
1825 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1827 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1829 * @param int $formID
1830 * @param bool $amountBlockActiveOnForm
1834 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1835 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1836 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1843 * This function sets the fields.
1845 * - $this->_params['amount_level']
1846 * - $this->_params['selectMembership']
1847 * And under certain circumstances sets
1848 * $this->_params['amount'] = null;
1850 * @param int $priceSetID
1852 public function setFormAmountFields($priceSetID) {
1853 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1854 $priceField = new CRM_Price_DAO_PriceField();
1855 $priceField->price_set_id
= $priceSetID;
1856 $priceField->orderBy('weight');
1857 $priceField->find();
1858 $paramWeDoNotUnderstand = NULL;
1860 while ($priceField->fetch()) {
1861 if ($priceField->name
== "contribution_amount") {
1862 $paramWeDoNotUnderstand = $priceField->id
;
1864 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1865 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1866 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1867 // function to get correct amount level consistently. Remove setting of the amount level in
1868 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1869 // to cover all variants.
1870 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1871 $this->_params
["price_{$priceField->id}"], 'label');
1873 if ($priceField->name
== "membership_amount") {
1874 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1875 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1878 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1879 // as membership amount.
1880 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1881 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1882 // so we should merge them together
1883 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1884 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1886 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
)
1887 && !empty($this->_values
['fee'][$priceField->id
])
1888 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1889 && CRM_Utils_Array
::value("price_{$paramWeDoNotUnderstand}", $this->_params
) < 1
1890 && empty($this->_params
["price_{$priceField->id}"])
1892 $this->_params
['amount'] = NULL;
1895 // Fix for CRM-14375 - If we are using separate payments and "no
1896 // thank you" is selected for the additional contribution, set
1897 // contribution amount to be null, so that it will not show
1898 // contribution amount same as membership amount.
1899 //@todo - merge with section above
1900 if ($this->_membershipBlock
['is_separate_payment']
1901 && !empty($this->_values
['fee'][$priceField->id
])
1902 && CRM_Utils_Array
::value('name', $this->_values
['fee'][$priceField->id
]) == 'contribution_amount'
1903 && CRM_Utils_Array
::value("price_{$priceField->id}", $this->_params
) == '-1'
1905 $this->_params
['amount'] = NULL;
1913 * @param array $params
1915 * @throws CiviCRM_API3_Exception
1917 public static function submit($params) {
1918 $form = new CRM_Contribute_Form_Contribution_Confirm();
1919 $form->_id
= $params['id'];
1921 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1922 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1923 //this way the mocked up controller ignores the session stuff
1924 $_SERVER['REQUEST_METHOD'] = 'GET';
1925 $form->controller
= new CRM_Contribute_Controller_Contribution();
1926 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1927 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1928 $form->_amount
= $params['amount'];
1929 // hack these in for test support.
1930 $form->_fields
['billing_first_name'] = 1;
1931 $form->_fields
['billing_last_name'] = 1;
1932 // CRM-18854 - Set form values to allow pledge to be created for api test.
1933 if (CRM_Utils_Array
::value('pledge_block_id', $params)) {
1934 $form->_values
['pledge_id'] = CRM_Utils_Array
::value('pledge_id', $params, NULL);
1935 $form->_values
['pledge_block_id'] = $params['pledge_block_id'];
1936 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($params['id']);
1937 $form->_values
['max_reminders'] = $pledgeBlock['max_reminders'];
1938 $form->_values
['initial_reminder_day'] = $pledgeBlock['initial_reminder_day'];
1939 $form->_values
['additional_reminder_day'] = $pledgeBlock['additional_reminder_day'];
1940 $form->_values
['is_email_receipt'] = FALSE;
1942 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1943 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1944 $priceSetFields = reset($priceFields);
1945 $form->_values
['fee'] = $priceSetFields['fields'];
1946 $form->_priceSetId
= $priceSetID;
1947 $form->setFormAmountFields($priceSetID);
1948 $capabilities = array();
1950 $capabilities[] = (ucfirst($form->_mode
) . 'Mode');
1952 $form->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors($capabilities);
1953 $form->_params
['payment_processor_id'] = !empty($params['payment_processor_id']) ?
$params['payment_processor_id'] : 0;
1954 $form->_paymentProcessor
= $form->_paymentProcessors
[$form->_params
['payment_processor_id']];
1955 if (!empty($params['payment_processor_id'])) {
1956 // The concept of contributeMode is deprecated as is the billing_mode concept.
1957 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1958 $form->_contributeMode
= 'direct';
1961 $form->_contributeMode
= 'notify';
1965 $priceFields = $priceFields[$priceSetID]['fields'];
1966 CRM_Price_BAO_PriceSet
::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1967 $form->_lineItem
= array($priceSetID => $lineItems);
1968 $membershipPriceFieldIDs = array();
1969 foreach ((array) $lineItems as $lineItem) {
1970 if (!empty($lineItem['membership_type_id'])) {
1971 $form->set('useForMember', 1);
1972 $form->_useForMember
= 1;
1973 $membershipPriceFieldIDs['id'] = $priceSetID;
1974 $membershipPriceFieldIDs[] = $lineItem['price_field_value_id'];
1977 $form->set('memberPriceFieldIDS', $membershipPriceFieldIDs);
1978 $form->processFormSubmission(CRM_Utils_Array
::value('contact_id', $params));
1982 * Helper function for static submit function.
1984 * Set relevant params - help us to build up an array that we can pass in.
1987 * @param array $params
1990 * @throws CiviCRM_API3_Exception
1992 public static function getFormParams($id, array $params) {
1993 if (!isset($params['is_pay_later'])) {
1994 if (!empty($params['payment_processor_id'])) {
1995 $params['is_pay_later'] = 0;
1998 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
2000 'return' => 'is_pay_later',
2004 if (empty($params['price_set_id'])) {
2005 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
2011 * Post form submission handling.
2013 * This is also called from the test suite.
2015 * @param int $contactID
2019 protected function processFormSubmission($contactID) {
2020 if (!isset($this->_params
['payment_processor_id'])) {
2021 // If there is no processor we are using the pay-later manual pseudo-processor.
2022 // (note it might make sense to make this a row in the processor table in the db).
2023 $this->_params
['payment_processor_id'] = 0;
2025 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] === 0) {
2026 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
2029 if (!empty($this->_ccid
)) {
2030 $this->_params
['contribution_id'] = $this->_ccid
;
2032 // add a description field at the very beginning
2033 $this->_params
['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $this->_values
['title']);
2035 $this->_params
['accountingCode'] = CRM_Utils_Array
::value('accountingCode', $this->_values
);
2038 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
2040 CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($this->_params
);
2043 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
)) {
2044 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($this->_id
);
2045 if (CRM_Utils_Array
::value('start_date', $this->_params
) ||
!CRM_Utils_Array
::value('is_pledge_start_date_visible', $pledgeBlock)
2046 ||
!CRM_Utils_Array
::value('is_pledge_start_date_editable', $pledgeBlock)) {
2047 $pledgeStartDate = CRM_Utils_Array
::value('start_date', $this->_params
, NULL);
2048 $this->_params
['receive_date'] = CRM_Pledge_BAO_Pledge
::getPledgeStartDate($pledgeStartDate, $pledgeBlock);
2049 $recurParams = CRM_Pledge_BAO_Pledge
::buildRecurParams($this->_params
);
2050 $this->_params
= array_merge($this->_params
, $recurParams);
2054 //carry payment processor id.
2055 if (CRM_Utils_Array
::value('id', $this->_paymentProcessor
)) {
2056 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
2059 $premiumParams = $membershipParams = $params = $this->_params
;
2060 if (!empty($params['image_URL'])) {
2061 CRM_Contact_BAO_Contact
::processImageParams($params);
2064 $fields = array('email-Primary' => 1);
2066 // get the add to groups
2067 $addToGroups = array();
2069 // now set the values for the billing location.
2070 foreach ($this->_fields
as $name => $value) {
2073 // get the add to groups for uf fields
2074 if (!empty($value['add_to_group_id'])) {
2075 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2079 $fields = $this->formatParamsForPaymentProcessor($fields);
2081 // billing email address
2082 $fields["email-{$this->_bltID}"] = 1;
2084 // if onbehalf-of-organization contribution, take out
2085 // organization params in a separate variable, to make sure
2086 // normal behavior is continued. And use that variable to
2087 // process on-behalf-of functionality.
2088 if (!empty($this->_values
['onbehalf_profile_id']) && empty($this->_ccid
)) {
2089 $behalfOrganization = array();
2090 $orgFields = array('organization_name', 'organization_id', 'org_option');
2091 foreach ($orgFields as $fld) {
2092 if (array_key_exists($fld, $params)) {
2093 $behalfOrganization[$fld] = $params[$fld];
2094 unset($params[$fld]);
2098 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2099 foreach ($params['onbehalf'] as $fld => $values) {
2100 if (strstr($fld, 'custom_')) {
2101 $behalfOrganization[$fld] = $values;
2103 elseif (!(strstr($fld, '-'))) {
2104 if (in_array($fld, array(
2105 'contribution_campaign_id',
2106 'member_campaign_id',
2108 $fld = 'campaign_id';
2111 $behalfOrganization[$fld] = $values;
2113 $this->_params
[$fld] = $values;
2118 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2119 foreach ($params['onbehalf_location'] as $block => $vals) {
2120 //fix for custom data (of type checkbox, multi-select)
2121 if (substr($block, 0, 7) == 'custom_') {
2124 // fix the index of block elements
2125 if (is_array($vals)) {
2126 foreach ($vals as $key => $val) {
2127 //dont adjust the index of address block as
2128 //it's index is WRT to location type
2129 $newKey = ($block == 'address') ?
$key : ++
$key;
2130 $behalfOrganization[$block][$newKey] = $val;
2134 unset($params['onbehalf_location']);
2136 if (!empty($params['onbehalf[image_URL]'])) {
2137 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2141 // check for profile double opt-in and get groups to be subscribed
2142 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2144 // since we are directly adding contact to group lets unset it from mailing
2145 if (!empty($addToGroups)) {
2146 foreach ($addToGroups as $groupId) {
2147 if (isset($subscribeGroupIds[$groupId])) {
2148 unset($subscribeGroupIds[$groupId]);
2153 foreach ($addToGroups as $k) {
2154 if (array_key_exists($k, $subscribeGroupIds)) {
2155 unset($addToGroups[$k]);
2159 if (empty($contactID)) {
2160 $dupeParams = $params;
2161 if (!empty($dupeParams['onbehalf'])) {
2162 unset($dupeParams['onbehalf']);
2164 if (!empty($dupeParams['honor'])) {
2165 unset($dupeParams['honor']);
2168 $contactID = CRM_Contact_BAO_Contact
::getFirstDuplicateContact($dupeParams, 'Individual', 'Unsupervised', array(), FALSE);
2170 // Fetch default greeting id's if creating a contact
2172 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2173 if (!isset($params[$greeting])) {
2174 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2178 $contactType = NULL;
2181 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2183 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2193 // Make the contact ID associated with the contribution available at the Class level.
2194 // Also make available to the session.
2195 //@todo consider handling this in $this->getContactID();
2196 $this->set('contactID', $contactID);
2197 $this->_contactID
= $contactID;
2199 //get email primary first if exist
2200 $subscriptionEmail = array('email' => CRM_Utils_Array
::value('email-Primary', $params));
2201 if (!$subscriptionEmail['email']) {
2202 $subscriptionEmail['email'] = CRM_Utils_Array
::value("email-{$this->_bltID}", $params);
2204 // subscribing contact to groups
2205 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2206 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2209 // If onbehalf-of-organization contribution / signup, add organization
2210 // and it's location.
2211 if (isset($this->_values
['onbehalf_profile_id']) &&
2212 isset($behalfOrganization['organization_name']) &&
2213 ($this->_values
['is_for_organization'] == 2 ||
2214 !empty($this->_params
['is_for_organization'])
2217 $ufFields = array();
2218 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2219 $ufFields[$name] = 1;
2221 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2222 $this->_params
, $ufFields
2225 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2226 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2227 // store current user id as related contact for later use for mailing / activity..
2228 $this->_values
['related_contact'] = $contactID;
2229 $this->_params
['related_contact'] = $contactID;
2230 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2231 $contactID = $this->_membershipContactID
;
2234 // lets store the contactID in the session
2235 // for things like tell a friend
2236 $session = CRM_Core_Session
::singleton();
2237 if (!$session->get('userID')) {
2238 $session->set('transaction.userID', $contactID);
2241 $session->set('transaction.userID', NULL);
2244 $this->_useForMember
= $this->get('useForMember');
2246 // store the fact that this is a membership and membership type is selected
2247 if ((!empty($membershipParams['selectMembership']) &&
2248 $membershipParams['selectMembership'] != 'no_thanks'
2250 $this->_useForMember
2252 if (!$this->_useForMember
) {
2253 $this->assign('membership_assign', TRUE);
2254 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2257 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2258 $membershipParams['is_test'] = 1;
2260 if ($this->_params
['is_pay_later']) {
2261 $membershipParams['is_pay_later'] = 1;
2264 if (isset($this->_params
['onbehalf_contact_id'])) {
2265 $membershipParams['onbehalf_contact_id'] = $this->_params
['onbehalf_contact_id'];
2267 //inherit campaign from contribution page.
2268 if (!array_key_exists('campaign_id', $membershipParams)) {
2269 $membershipParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
);
2272 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2273 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $this->_lineItem
);
2276 // at this point we've created a contact and stored its address etc
2277 // all the payment processors expect the name and address to be in the
2278 // so we copy stuff over to first_name etc.
2279 $paymentParams = $this->_params
;
2280 // Make it explict that we are letting the processConfirm function figure out the line items.
2281 $paymentParams['skipLineItem'] = 0;
2283 if (!isset($paymentParams['line_item'])) {
2284 $paymentParams['line_item'] = $this->_lineItem
;
2287 if (!empty($paymentParams['onbehalf']) &&
2288 is_array($paymentParams['onbehalf'])
2290 foreach ($paymentParams['onbehalf'] as $key => $value) {
2291 if (strstr($key, 'custom_')) {
2292 $this->_params
[$key] = $value;
2297 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2299 $this->wrangleFinancialTypeID($this->_values
['financial_type_id']),
2300 ($this->_mode
== 'test') ?
1 : 0,
2301 CRM_Utils_Array
::value('is_recur', $paymentParams)
2304 if (empty($result['is_payment_failure'])) {
2305 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2306 $this->postProcessPremium($premiumParams, $result['contribution']);
2308 if (!empty($result['contribution'])) {
2309 // Not quite sure why it would be empty at this stage but tests show it can be ... at least in tests.
2310 $this->completeTransaction($result, $result['contribution']->id
);
2317 * Membership processing section.
2319 * This is in a separate function as part of a move towards refactoring.
2321 * @param int $contactID
2322 * @param array $membershipParams
2323 * @param array $premiumParams
2324 * @param array $formLineItems
2326 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $formLineItems) {
2327 // This could be set by a hook.
2328 if (!empty($this->_params
['installments'])) {
2329 $membershipParams['installments'] = $this->_params
['installments'];
2331 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2332 if (isset($this->_params
['related_contact'])) {
2333 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2336 $membershipParams['cms_contactID'] = $contactID;
2339 if (!empty($membershipParams['onbehalf']) &&
2340 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2342 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2345 $customFieldsFormatted = $fieldTypes = array();
2346 if (!empty($membershipParams['onbehalf']) &&
2347 is_array($membershipParams['onbehalf'])
2349 foreach ($membershipParams['onbehalf'] as $key => $value) {
2350 if (strstr($key, 'custom_')) {
2351 $customFieldId = explode('_', $key);
2352 CRM_Core_BAO_CustomField
::formatCustomField(
2354 $customFieldsFormatted,
2362 $fieldTypes = array('Contact', 'Organization', 'Membership');
2365 $priceFieldIds = $this->get('memberPriceFieldIDS');
2367 if (!empty($priceFieldIds)) {
2368 $financialTypeID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2369 unset($priceFieldIds['id']);
2370 $membershipTypeIds = array();
2371 $membershipTypeTerms = array();
2372 foreach ($priceFieldIds as $priceFieldId) {
2373 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
2374 $membershipTypeIds[] = $id;
2375 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
2376 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
2378 if ($term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
2379 $membershipTypeTerms[$id] = ($term > 1) ?
$term : 1;
2382 $membershipTypeTerms[$id] = 1;
2386 $membershipParams['selectMembership'] = $membershipTypeIds;
2387 $membershipParams['financial_type_id'] = $financialTypeID;
2388 $membershipParams['types_terms'] = $membershipTypeTerms;
2390 if (!empty($membershipParams['selectMembership'])) {
2392 $membershipLineItems = $formLineItems;
2393 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2394 $membershipLineItems = array();
2395 foreach ($this->_values
['fee'] as $key => $feeValues) {
2396 if ($feeValues['name'] == 'membership_amount') {
2397 $fieldId = $this->_params
['price_' . $key];
2398 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2399 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2405 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems);
2407 catch (CRM_Core_Exception
$e) {
2408 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2409 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2411 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2412 // we need to explicitly create a CMS user in case of free memberships
2413 // since it is done under processConfirm for paid memberships
2414 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2415 $membershipParams['cms_contactID'],
2416 'email-' . $this->_bltID
2423 * Complete transaction if payment has been processed.
2425 * Check the result for a success outcome & if paid then complete the transaction.
2427 * Completing will trigger update of related entities and emails.
2429 * @param array $result
2430 * @param int $contributionID
2432 * @throws \CiviCRM_API3_Exception
2433 * @throws \Exception
2435 protected function completeTransaction($result, $contributionID) {
2436 if (CRM_Utils_Array
::value('payment_status_id', $result) == 1) {
2438 civicrm_api3('contribution', 'completetransaction', array(
2439 'id' => $contributionID,
2440 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $result),
2441 'payment_processor_id' => $this->_paymentProcessor
['id'],
2442 'is_transactional' => FALSE,
2443 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
2444 'receive_date' => CRM_Utils_Array
::value('receive_date', $result),
2445 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $result),
2446 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $result),
2449 catch (CiviCRM_API3_Exception
$e) {
2450 if ($e->getErrorCode() != 'contribution_completed') {
2451 throw new CRM_Core_Exception('Failed to update contribution in database');