3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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;
55 * Set the parameters to be passed to contribution create function.
57 * @param array $params
58 * @param int $contactID
59 * @param int $financialTypeID
61 * @param int $contributionPageId
62 * @param float $nonDeductibleAmount
63 * @param int $campaignId
64 * @param bool $isMonetary
65 * @param bool $pending
66 * @param array $paymentProcessorOutcome
67 * @param string $receiptDate
68 * @param int $recurringContributionID
70 * @param int $addressID
71 * @param int $softCreditToID
72 * @param array $lineItems
76 public static function getContributionParams(
77 $params, $contactID, $financialTypeID, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending,
78 $paymentProcessorOutcome, $receiptDate, $recurringContributionID, $isTest, $addressID, $softCreditToID, $lineItems) {
79 $contributionParams = array(
80 'contact_id' => $contactID,
81 'financial_type_id' => $financialTypeID,
82 'contribution_page_id' => $contributionPageId,
83 'receive_date' => (CRM_Utils_Array
::value('receive_date', $params)) ? CRM_Utils_Date
::processDate($params['receive_date']) : date('YmdHis'),
84 'non_deductible_amount' => $nonDeductibleAmount,
85 'total_amount' => $params['amount'],
86 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $params),
87 'amount_level' => CRM_Utils_Array
::value('amount_level', $params),
88 'invoice_id' => $params['invoiceID'],
89 'currency' => $params['currencyID'],
90 'source' => (!$online ||
!empty($params['source'])) ? CRM_Utils_Array
::value('source', $params) : CRM_Utils_Array
::value('description', $params),
91 'is_pay_later' => CRM_Utils_Array
::value('is_pay_later', $params, 0),
92 //configure cancel reason, cancel date and thankyou date
93 //from 'contribution' type profile if included
94 'cancel_reason' => CRM_Utils_Array
::value('cancel_reason', $params, 0),
95 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date
::format($params['cancel_date']) : NULL,
96 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date
::format($params['thankyou_date']) : NULL,
97 'campaign_id' => $campaignId,
99 'address_id' => $addressID,
100 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
101 'soft_credit_to' => $softCreditToID,
102 'line_item' => $lineItems,
103 'skipLineItem' => CRM_Utils_Array
::value('skipLineItem', $params, 0),
105 if (!$online && isset($params['thankyou_date'])) {
106 $contributionParam['thankyou_date'] = $params['thankyou_date'];
108 if (!$online ||
$isMonetary) {
109 if (empty($params['is_pay_later'])) {
110 $contributionParams['payment_instrument_id'] = 1;
113 if ($paymentProcessorOutcome) {
114 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor', $paymentProcessorOutcome);
116 if (!$pending && $paymentProcessorOutcome) {
117 $contributionParams +
= array(
118 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $paymentProcessorOutcome),
119 'net_amount' => CRM_Utils_Array
::value('net_amount', $paymentProcessorOutcome, $params['amount']),
120 'trxn_id' => $paymentProcessorOutcome['trxn_id'],
121 'receipt_date' => $receiptDate,
122 // also add financial_trxn details as part of fix for CRM-4724
123 'trxn_result_code' => CRM_Utils_Array
::value('trxn_result_code', $paymentProcessorOutcome),
127 // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
128 $contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money
::format($contributionParams['non_deductible_amount'], ' '));
129 $contributionParams['total_amount'] = trim(CRM_Utils_Money
::format($contributionParams['total_amount'], ' '));
131 if ($recurringContributionID) {
132 $contributionParams['contribution_recur_id'] = $recurringContributionID;
135 $contributionParams['contribution_status_id'] = $pending ?
2 : 1;
136 if (isset($contributionParams['invoice_id'])) {
137 $contributionParams['id'] = CRM_Core_DAO
::getFieldValue(
138 'CRM_Contribute_DAO_Contribution',
139 $contributionParams['invoice_id'],
145 return $contributionParams;
149 * Get non-deductible amount.
151 * This is a bit too much about wierd form interpretation to be this deep.
154 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
157 * @param array $params
158 * @param CRM_Financial_BAO_FinancialType $financialType
159 * @param bool $online
163 protected static function getNonDeductibleAmount($params, $financialType, $online) {
164 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
165 return $params['non_deductible_amount'];
168 if ($financialType->is_deductible
) {
169 if ($online && isset($params['selectProduct'])) {
170 $selectProduct = CRM_Utils_Array
::value('selectProduct', $params);
172 if (!$online && isset($params['product_name'][0])) {
173 $selectProduct = $params['product_name'][0];
175 // if there is a product - compare the value to the contribution amount
176 if (isset($selectProduct) &&
177 $selectProduct != 'no_thanks'
179 $productDAO = new CRM_Contribute_DAO_Product();
180 $productDAO->id
= $selectProduct;
181 $productDAO->find(TRUE);
182 // product value exceeds contribution amount
183 if ($params['amount'] < $productDAO->price
) {
184 $nonDeductibleAmount = $params['amount'];
185 return $nonDeductibleAmount;
187 // product value does NOT exceed contribution amount
189 return $productDAO->price
;
192 // contribution is deductible - but there is no product
197 // contribution is NOT deductible
199 return $params['amount'];
205 * Set variables up before form is built.
207 public function preProcess() {
208 $config = CRM_Core_Config
::singleton();
209 parent
::preProcess();
211 // lineItem isn't set until Register postProcess
212 $this->_lineItem
= $this->get('lineItem');
213 $this->_paymentProcessor
= $this->get('paymentProcessor');
214 $this->_params
= $this->controller
->exportValues('Main');
215 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
216 $this->_params
['amount'] = $this->get('amount');
217 if (isset($this->_params
['amount'])) {
218 $this->setFormAmountFields($this->_params
['priceSetId']);
221 $this->_params
['tax_amount'] = $this->get('tax_amount');
222 $this->_useForMember
= $this->get('useForMember');
224 if (isset($this->_params
['credit_card_exp_date'])) {
225 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
226 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
229 $this->_params
['currencyID'] = $config->defaultCurrency
;
231 if (!empty($this->_membershipBlock
)) {
232 $this->_params
['selectMembership'] = $this->get('selectMembership');
234 if (!empty($this->_paymentProcessor
) && $this->_paymentProcessor
['object']->supports('preApproval')) {
235 $preApprovalParams = $this->_paymentProcessor
['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
236 $this->_params
= array_merge($this->_params
, $preApprovalParams);
239 // We may have fetched some billing details from the getPreApprovalDetails function so we
240 // want to ensure we set this after that function has been called.
241 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $this->_params
, FALSE);
242 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
243 $this->_params
["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($this->_params
["billing_state_province_id-{$this->_bltID}"]);
245 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
246 $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
249 $this->_params
['is_pay_later'] = $this->get('is_pay_later');
250 $this->assign('is_pay_later', $this->_params
['is_pay_later']);
251 if ($this->_params
['is_pay_later']) {
252 $this->assign('pay_later_receipt', $this->_values
['pay_later_receipt']);
254 // if onbehalf-of-organization
255 if (!empty($this->_params
['hidden_onbehalf_profile'])) {
257 if (empty($this->_params
['org_option']) && empty($this->_params
['organization_id'])) {
258 if (!empty($this->_params
['onbehalfof_id'])) {
259 $this->_params
['organization_id'] = $this->_params
['onbehalfof_id'];
262 $this->_params
['organization_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_params
['onbehalf']['organization_name'], 'id', 'display_name');
266 $this->_params
['organization_name'] = $this->_params
['onbehalf']['organization_name'];
267 $addressBlocks = array(
273 'supplemental_address_1',
274 'supplemental_address_2',
275 'supplemental_address_3',
276 'postal_code_suffix',
282 $blocks = array('email', 'phone', 'im', 'url', 'openid');
283 foreach ($this->_params
['onbehalf'] as $loc => $value) {
284 $field = $typeId = NULL;
285 if (strstr($loc, '-')) {
286 list($field, $locType) = explode('-', $loc);
289 if (in_array($field, $addressBlocks)) {
290 if ($locType == 'Primary') {
291 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
292 $locType = $defaultLocationType->id
;
295 if ($field == 'country') {
296 $value = CRM_Core_PseudoConstant
::countryIsoCode($value);
298 elseif ($field == 'state_province') {
299 $value = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
303 if (isset($this->_params
['onbehalf_location']['address'])
304 && count($this->_params
['onbehalf_location']['address']) > 0
309 $this->_params
['onbehalf_location']['address'][$locType][$field] = $value;
310 if (empty($this->_params
['onbehalf_location']['address'][$locType]['is_primary'])) {
311 $this->_params
['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
313 $this->_params
['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
315 elseif (in_array($field, $blocks)) {
316 if (!$typeId ||
is_numeric($typeId)) {
317 $blockName = $fieldName = $field;
318 $locationType = 'location_type_id';
319 if ($locType == 'Primary') {
320 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
321 $locationValue = $defaultLocationType->id
;
324 $locationValue = $locType;
327 $phoneExtField = array();
329 if ($field == 'url') {
330 $blockName = 'website';
331 $locationType = 'website_type_id';
332 list($field, $locationValue) = explode('-', $loc);
334 elseif ($field == 'im') {
336 $locTypeId = 'provider_id';
337 $typeId = $this->_params
['onbehalf']["{$loc}-provider_id"];
339 elseif ($field == 'phone') {
340 list($field, $locType, $typeId) = explode('-', $loc);
341 $locTypeId = 'phone_type_id';
343 //check if extension field exists
344 $extField = str_replace('phone', 'phone_ext', $loc);
345 if (isset($this->_params
['onbehalf'][$extField])) {
346 $phoneExtField = array('phone_ext' => $this->_params
['onbehalf'][$extField]);
351 if (isset ($this->_params
['onbehalf_location'][$blockName])
352 && count($this->_params
['onbehalf_location'][$blockName]) > 0
356 if ($locationValue) {
357 $blockValues = array(
358 $fieldName => $value,
359 $locationType => $locationValue,
360 'is_primary' => $isPrimary,
364 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
366 if (!empty($phoneExtField)) {
367 $blockValues = array_merge($blockValues, $phoneExtField);
370 $this->_params
['onbehalf_location'][$blockName][] = $blockValues;
374 elseif (strstr($loc, 'custom')) {
375 if ($value && isset($this->_params
['onbehalf']["{$loc}_id"])) {
376 $value = $this->_params
['onbehalf']["{$loc}_id"];
378 $this->_params
['onbehalf_location']["{$loc}"] = $value;
381 if ($loc == 'contact_sub_type') {
382 $this->_params
['onbehalf_location'][$loc] = $value;
385 $this->_params
['onbehalf_location'][$field] = $value;
390 elseif (!empty($this->_values
['is_for_organization'])) {
391 // no on behalf of an organization, CRM-5519
392 // so reset loc blocks from main params.
398 if (isset($this->_params
[$blk])) {
399 unset($this->_params
[$blk]);
403 $this->setRecurringMembershipParams();
406 $params = $this->processPcp($this, $this->_params
);
407 $this->_params
= $params;
409 $this->_params
['invoiceID'] = $this->get('invoiceID');
411 //carry campaign from profile.
412 if (array_key_exists('contribution_campaign_id', $this->_params
)) {
413 $this->_params
['campaign_id'] = $this->_params
['contribution_campaign_id'];
416 // assign contribution page id to the template so we can add css class for it
417 $this->assign('contributionPageID', $this->_id
);
419 $this->set('params', $this->_params
);
423 * Build the form object.
425 public function buildQuickForm() {
426 $this->assignToTemplate();
428 $params = $this->_params
;
429 // make sure we have values for it
430 if ($this->_honor_block_is_active
&& !empty($params['soft_credit_type_id'])) {
432 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
434 $this->assign('honor_block_is_active', $this->_honor_block_is_active
);
435 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
436 CRM_Contribute_BAO_ContributionSoft
::formatHonoreeProfileFields($this, $params['honor'], $params['honoree_profile_id']);
438 $fieldTypes = array('Contact');
439 $fieldTypes[] = CRM_Core_BAO_UFGroup
::getContactType($params['honoree_profile_id']);
440 $this->buildCustom($params['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
442 $this->assign('receiptFromEmail', CRM_Utils_Array
::value('receipt_from_email', $this->_values
));
443 $amount_block_is_active = $this->get('amount_block_is_active');
444 $this->assign('amount_block_is_active', $amount_block_is_active);
446 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
447 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
449 $getTaxDetails = FALSE;
450 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
451 foreach ($this->_lineItem
as $key => $value) {
452 foreach ($value as $v) {
453 if (isset($v['tax_rate'])) {
454 if ($v['tax_rate'] != '') {
455 $getTaxDetails = TRUE;
460 $this->assign('getTaxDetails', $getTaxDetails);
461 $this->assign('taxTerm', $taxTerm);
462 $this->assign('totalTaxAmount', $params['tax_amount']);
464 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
465 $option = CRM_Utils_Array
::value('options_' . $params['selectProduct'], $params);
466 $productID = $params['selectProduct'];
467 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, FALSE,
470 $this->set('productID', $productID);
471 $this->set('option', $option);
473 $config = CRM_Core_Config
::singleton();
474 if (in_array('CiviMember', $config->enableComponents
)) {
475 if (isset($params['selectMembership']) &&
476 $params['selectMembership'] != 'no_thanks'
478 $this->buildMembershipBlock(
479 $this->_membershipContactID
,
481 $params['selectMembership'],
484 if (!empty($params['auto_renew'])) {
485 $this->assign('auto_renew', TRUE);
489 $this->assign('membershipBlock', FALSE);
492 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
493 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
495 if (!empty($params['hidden_onbehalf_profile'])) {
496 $ufJoinParams = array(
497 'module' => 'onBehalf',
498 'entity_table' => 'civicrm_contribution_page',
499 'entity_id' => $this->_id
,
501 $OnBehalfProfile = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
502 $profileId = $OnBehalfProfile[0];
504 $fieldTypes = array('Contact', 'Organization');
505 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
506 $fieldTypes = array_merge($fieldTypes, $contactSubType);
507 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
508 $fieldTypes = array_merge($fieldTypes, array('Membership'));
511 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
514 $this->buildCustom($profileId, 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
517 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
518 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
519 if ($this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
520 $this->assign('lineItem', $this->_lineItem
);
523 $this->assign('is_quick_config', 1);
524 $this->_params
['is_quick_config'] = 1;
526 $this->assign('priceSetID', $this->_priceSetId
);
527 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
528 if ($this->_paymentProcessor
&&
529 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('Google_Checkout', $paymentProcessorType)
530 && !$this->_params
['is_pay_later'] && !($this->_amount
== 0)
532 $this->_checkoutButtonName
= $this->getButtonName('next', 'checkout');
534 $this->_checkoutButtonName
,
535 $this->_paymentProcessor
['url_button'],
536 array('class' => 'crm-form-submit')
539 $this->addButtons(array(
542 'name' => ts('Go Back'),
548 if ($this->_contributeMode
== 'notify' ||
!$this->_values
['is_monetary'] ||
549 $this->_amount
<= 0.0 ||
$this->_params
['is_pay_later'] ||
550 ($this->_separateMembershipPayment
&& $this->_amount
<= 0.0)
552 $contribButton = ts('Continue');
553 $this->assign('button', ts('Continue'));
556 $contribButton = ts('Make Contribution');
557 $this->assign('button', ts('Make Contribution'));
559 $this->addButtons(array(
562 'name' => $contribButton,
563 'spacing' => ' ',
565 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name
. "','" . ts('Processing') . "');"),
569 'name' => ts('Go Back'),
576 $fields = array_fill_keys(array_keys($this->_fields
), 1);
577 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
579 $contact = $this->_params
;
580 foreach ($fields as $name => $dontCare) {
581 // Recursively set defaults for nested fields
582 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' ||
$name == 'honor')) {
583 foreach ($contact[$name] as $fieldName => $fieldValue) {
584 if (is_array($fieldValue) && !in_array($this->_fields
[$name][$fieldName]['html_type'], array(
589 foreach ($fieldValue as $key => $value) {
590 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
594 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
598 elseif (isset($contact[$name])) {
599 $defaults[$name] = $contact[$name];
600 if (substr($name, 0, 7) == 'custom_') {
601 $timeField = "{$name}_time";
602 if (isset($contact[$timeField])) {
603 $defaults[$timeField] = $contact[$timeField];
605 if (isset($contact["{$name}_id"])) {
606 $defaults["{$name}_id"] = $contact["{$name}_id"];
609 elseif (in_array($name, array(
613 )) && !empty($contact[$name . '_custom'])
615 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
620 $this->assign('useForMember', $this->get('useForMember'));
622 $this->setDefaults($defaults);
630 * Since we are only showing elements in frozen mode no help display needed.
634 public function getAction() {
635 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
636 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
639 return CRM_Core_Action
::VIEW
;
644 * Set default values for the form.
646 * Note that in edit/view mode
647 * the default values are retrieved from the database
649 public function setDefaultValues() {
655 public function postProcess() {
656 $contactID = $this->getContactID();
657 $result = $this->processFormSubmission($contactID);
658 if (is_array($result) && !empty($result['is_payment_failure'])) {
659 // We will probably have the function that gets this error throw an exception on the next round of refactoring.
660 CRM_Core_Session
::singleton()->setStatus(ts("Payment Processor Error message :") .
661 $result['error']->getMessage());
662 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
663 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
666 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
667 $this->set('params', $this->_params
);
671 * Wrangle financial type ID.
673 * 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
674 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
676 * Comments from previous refactor indicate doubt as to what was going on.
678 * @param int $contributionTypeId
680 * @return null|string
682 public function wrangleFinancialTypeID($contributionTypeId) {
683 if (isset($paymentParams['financial_type'])) {
684 $contributionTypeId = $paymentParams['financial_type'];
686 elseif (!empty($this->_values
['pledge_id'])) {
687 $contributionTypeId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
688 $this->_values
['pledge_id'],
692 return $contributionTypeId;
698 * @param array $premiumParams
699 * @param CRM_Contribute_BAO_Contribution $contribution
701 protected function postProcessPremium($premiumParams, $contribution) {
702 $hour = $minute = $second = 0;
703 // assigning Premium information to receipt tpl
704 $selectProduct = CRM_Utils_Array
::value('selectProduct', $premiumParams);
705 if ($selectProduct &&
706 $selectProduct != 'no_thanks'
708 $startDate = $endDate = "";
709 $this->assign('selectPremium', TRUE);
710 $productDAO = new CRM_Contribute_DAO_Product();
711 $productDAO->id
= $selectProduct;
712 $productDAO->find(TRUE);
713 $this->assign('product_name', $productDAO->name
);
714 $this->assign('price', $productDAO->price
);
715 $this->assign('sku', $productDAO->sku
);
716 $this->assign('option', CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams));
718 $periodType = $productDAO->period_type
;
721 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
722 $duration_unit = $productDAO->duration_unit
;
723 $duration_interval = $productDAO->duration_interval
;
724 if ($periodType == 'rolling') {
725 $startDate = date('Y-m-d');
727 elseif ($periodType == 'fixed') {
728 if ($fixed_period_start_day) {
729 $date = explode('-', date('Y-m-d'));
730 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
731 $day = substr($fixed_period_start_day, -2) . "<br/>";
733 $startDate = $year . '-' . $month . '-' . $day;
736 $startDate = date('Y-m-d');
740 $date = explode('-', $startDate);
745 switch ($duration_unit) {
747 $year = $year +
$duration_interval;
751 $month = $month +
$duration_interval;
755 $day = $day +
$duration_interval;
759 $day = $day +
($duration_interval * 7);
761 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
762 $this->assign('start_date', $startDate);
763 $this->assign('end_date', $endDate);
766 $dao = new CRM_Contribute_DAO_Premium();
767 $dao->entity_table
= 'civicrm_contribution_page';
768 $dao->entity_id
= $this->_id
;
770 $this->assign('contact_phone', $dao->premiums_contact_phone
);
771 $this->assign('contact_email', $dao->premiums_contact_email
);
773 //create Premium record
775 'product_id' => $premiumParams['selectProduct'],
776 'contribution_id' => $contribution->id
,
777 'product_option' => CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams),
779 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
780 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
782 if (!empty($premiumParams['selectProduct'])) {
783 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
784 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
785 $daoPremiumsProduct->premiums_id
= $dao->id
;
786 $daoPremiumsProduct->find(TRUE);
787 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
790 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
791 $daoContrProd->contribution_id
= $contribution->id
;
792 if ($daoContrProd->find(TRUE)) {
793 $params['id'] = $daoContrProd->id
;
796 CRM_Contribute_BAO_Contribution
::addPremium($params);
797 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
799 'cost' => $productDAO->cost
,
800 'currency' => $productDAO->currency
,
801 'financial_type_id' => $params['financial_type_id'],
802 'contributionId' => $contribution->id
,
804 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
807 elseif ($selectProduct == 'no_thanks') {
809 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
810 $daoContrProd->contribution_id
= $contribution->id
;
811 if ($daoContrProd->find(TRUE)) {
812 $daoContrProd->delete();
818 * Process the contribution.
820 * @param CRM_Core_Form $form
821 * @param array $params
822 * @param array $result
823 * @param int $contactID
824 * @param CRM_Financial_DAO_FinancialType $financialType
825 * @param bool $pending
826 * @param bool $online
828 * @param bool $isTest
829 * @param array $lineItems
831 * @param int $billingLocationID
832 * ID of billing location type.
834 * @return \CRM_Contribute_DAO_Contribution
837 public static function processFormContribution(
849 $transaction = new CRM_Core_Transaction();
850 $contribSoftContactId = $addressID = NULL;
851 $isMonetary = !empty($form->_values
['is_monetary']);
852 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
853 // How do these vary from params? These are currently passed to
854 // - custom data function....
855 $formParams = $form->_params
;
856 $isSeparateMembershipPayment = empty($formParams['separate_membership_payment']) ?
FALSE : TRUE;
857 $pledgeID = empty($formParams['pledge_id']) ?
NULL : $formParams['pledge_id'];
858 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
859 (!empty($formParams['is_pledge']) ||
$pledgeID)) {
866 // add these values for the recurringContrib function ,CRM-10188
867 $params['financial_type_id'] = $financialType->id
;
869 $addressID = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
871 //@todo - this is being set from the form to resolve CRM-10188 - an
872 // eNotice caused by it not being set @ the front end
873 // however, we then get it being over-written with null for backend contributions
874 // a better fix would be to set the values in the respective forms rather than require
875 // a function being shared by two forms to deal with their respective values
876 // moving it to the BAO & not taking the $form as a param would make sense here.
877 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
878 $params['is_email_receipt'] = $isEmailReceipt;
880 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType, $online);
881 $nonDeductibleAmount = self
::getNonDeductibleAmount($params, $financialType, $online);
883 $now = date('YmdHis');
884 $receiptDate = CRM_Utils_Array
::value('receipt_date', $params);
885 if ($isEmailReceipt) {
889 //get the contrib page id.
890 $contributionPageId = NULL;
892 $contributionPageId = $form->_id
;
893 $campaignId = CRM_Utils_Array
::value('campaign_id', $params);
894 if (!array_key_exists('campaign_id', $params)) {
895 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
899 //also for offline we do support - CRM-7290
900 $contributionPageId = CRM_Utils_Array
::value('contribution_page_id', $params);
901 $campaignId = CRM_Utils_Array
::value('campaign_id', $params);
904 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
905 if (!empty($params['pcp_made_through_id']) ||
!empty($params['soft_credit_to'])) {
907 if (!empty($params['pcp_made_through_id'])) {
908 $contribSoftContactId = CRM_Core_DAO
::getFieldValue(
910 $params['pcp_made_through_id'],
915 $contribSoftContactId = CRM_Utils_Array
::value('soft_credit_to', $params);
918 // Pass these details onto with the contribution to make them
919 // available at hook_post_process, CRM-8908
920 $params['soft_credit_to'] = $contribSoftContactId;
923 if (isset($params['amount'])) {
924 $contribParams = self
::getContributionParams(
925 $params, $contactID, $financialType->id
, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending, $result, $receiptDate,
926 $recurringContributionID, $isTest, $addressID, $contribSoftContactId, $lineItems
928 $contribution = CRM_Contribute_BAO_Contribution
::add($contribParams);
930 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
931 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
933 $dataArray = array();
934 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
935 foreach ($lineItemValue as $key => $value) {
936 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
937 if (isset($dataArray[$value['tax_rate']])) {
938 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
941 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
946 $smarty = CRM_Core_Smarty
::singleton();
947 $smarty->assign('dataArray', $dataArray);
948 $smarty->assign('totalTaxAmount', $params['tax_amount']);
950 if (is_a($contribution, 'CRM_Core_Error')) {
951 $message = CRM_Core_Error
::getMessages($contribution);
952 CRM_Core_Error
::fatal($message);
955 // lets store it in the form variable so postProcess hook can get to this and use it
956 $form->_contributionID
= $contribution->id
;
959 //CRM-13981, processing honor contact into soft-credit contribution
960 CRM_Contact_Form_ProfileContact
::postProcess($form);
962 // process soft credit / pcp pages
963 CRM_Contribute_Form_Contribution_Confirm
::processPcpSoft($params, $contribution);
965 //handle pledge stuff.
968 //when user doing pledge payments.
969 //update the schedule when payment(s) are made
970 foreach ($form->_params
['pledge_amount'] as $paymentId => $dontCare) {
971 $scheduledAmount = CRM_Core_DAO
::getFieldValue(
972 'CRM_Pledge_DAO_PledgePayment',
978 $pledgePaymentParams = array(
980 'contribution_id' => $contribution->id
,
981 'status_id' => $contribution->contribution_status_id
,
982 'actual_amount' => $scheduledAmount,
985 CRM_Pledge_BAO_PledgePayment
::add($pledgePaymentParams);
988 //update pledge status according to the new payment statuses
989 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID);
992 //when user creating pledge record.
993 $pledgeParams = array();
994 $pledgeParams['contact_id'] = $contribution->contact_id
;
995 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount
;
996 $pledgeParams['contribution_id'] = $contribution->id
;
997 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id
;
998 $pledgeParams['financial_type_id'] = $contribution->financial_type_id
;
999 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
1000 $pledgeParams['installments'] = $params['pledge_installments'];
1001 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
1002 if ($pledgeParams['frequency_unit'] == 'month') {
1003 $pledgeParams['frequency_day'] = intval(date("d"));
1006 $pledgeParams['frequency_day'] = 1;
1008 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
1009 $pledgeParams['status_id'] = $contribution->contribution_status_id
;
1010 $pledgeParams['max_reminders'] = $form->_values
['max_reminders'];
1011 $pledgeParams['initial_reminder_day'] = $form->_values
['initial_reminder_day'];
1012 $pledgeParams['additional_reminder_day'] = $form->_values
['additional_reminder_day'];
1013 $pledgeParams['is_test'] = $contribution->is_test
;
1014 $pledgeParams['acknowledge_date'] = date('Ymd');
1015 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
1017 //inherit campaign from contirb page.
1018 $pledgeParams['campaign_id'] = $campaignId;
1020 $pledge = CRM_Pledge_BAO_Pledge
::create($pledgeParams);
1022 $form->_params
['pledge_id'] = $pledge->id
;
1024 //send acknowledgment email. only when pledge is created
1026 //build params to send acknowledgment.
1027 $pledgeParams['id'] = $pledge->id
;
1028 $pledgeParams['receipt_from_name'] = $form->_values
['receipt_from_name'];
1029 $pledgeParams['receipt_from_email'] = $form->_values
['receipt_from_email'];
1031 //scheduled amount will be same as installment_amount.
1032 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
1034 //get total pledge amount.
1035 $pledgeParams['total_pledge_amount'] = $pledge->amount
;
1037 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($form, $pledgeParams);
1042 if ($online && $contribution) {
1043 CRM_Core_BAO_CustomValueTable
::postProcess($form->_params
,
1044 'civicrm_contribution',
1049 elseif ($contribution) {
1050 //handle custom data.
1051 $params['contribution_id'] = $contribution->id
;
1052 if (!empty($params['custom']) &&
1053 is_array($params['custom']) &&
1054 !is_a($contribution, 'CRM_Core_Error')
1056 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
1060 if ($contribution && !empty($params['contribution_note'])) {
1061 $noteParams = array(
1062 'entity_table' => 'civicrm_contribution',
1063 'note' => $params['contribution_note'],
1064 'entity_id' => $contribution->id
,
1065 'contact_id' => $contribution->contact_id
,
1066 'modified_date' => date('Ymd'),
1069 CRM_Core_BAO_Note
::add($noteParams, array());
1072 if (isset($params['related_contact'])) {
1073 $contactID = $params['related_contact'];
1075 elseif (isset($params['cms_contactID'])) {
1076 $contactID = $params['cms_contactID'];
1079 //create contribution activity w/ individual and target
1080 //activity w/ organisation contact id when onbelf, CRM-4027
1081 $targetContactID = NULL;
1082 if (!empty($params['hidden_onbehalf_profile'])) {
1083 $targetContactID = $contribution->contact_id
;
1084 $contribution->contact_id
= $contactID;
1087 // create an activity record
1088 if ($contribution) {
1089 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
1092 $transaction->commit();
1093 // CRM-13074 - create the CMSUser after the transaction is completed as it
1094 // is not appropriate to delete a valid contribution if a user create problem occurs
1095 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($params,
1097 'email-' . $billingLocationID
1099 return $contribution;
1103 * Create the recurring contribution record.
1105 * @param CRM_Core_Form $form
1106 * @param array $params
1107 * @param int $contactID
1108 * @param string $contributionType
1109 * @param bool $online
1113 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1114 // return if this page is not set for recurring
1115 // or the user has not chosen the recurring option
1117 //this is online case validation.
1118 if ((empty($form->_values
['is_recur']) && $online) ||
empty($params['is_recur'])) {
1122 $recurParams = array('contact_id' => $contactID);
1123 $recurParams['amount'] = CRM_Utils_Array
::value('amount', $params);
1124 $recurParams['auto_renew'] = CRM_Utils_Array
::value('auto_renew', $params);
1125 $recurParams['frequency_unit'] = CRM_Utils_Array
::value('frequency_unit', $params);
1126 $recurParams['frequency_interval'] = CRM_Utils_Array
::value('frequency_interval', $params);
1127 $recurParams['installments'] = CRM_Utils_Array
::value('installments', $params);
1128 $recurParams['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $params);
1129 $recurParams['currency'] = CRM_Utils_Array
::value('currency', $params);
1131 // CRM-14354: For an auto-renewing membership with an additional contribution,
1132 // if separate payments is not enabled, make sure only the membership fee recurs
1133 if (!empty($form->_membershipBlock
)
1134 && $form->_membershipBlock
['is_separate_payment'] === '0'
1135 && isset($params['selectMembership'])
1136 && $form->_values
['is_allow_other_amount'] == '1'
1138 && !empty($form->_membershipTypeValues
)
1139 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1141 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1144 $recurParams['is_test'] = 0;
1145 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1146 (isset($form->_mode
) && ($form->_mode
== 'test'))
1148 $recurParams['is_test'] = 1;
1151 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1152 if (!empty($params['receive_date'])) {
1153 $recurParams['start_date'] = $params['receive_date'];
1155 $recurParams['invoice_id'] = CRM_Utils_Array
::value('invoiceID', $params);
1156 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1157 $recurParams['payment_processor_id'] = CRM_Utils_Array
::value('payment_processor_id', $params);
1158 $recurParams['is_email_receipt'] = CRM_Utils_Array
::value('is_email_receipt', $params);
1159 // we need to add a unique trxn_id to avoid a unique key error
1160 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1161 $recurParams['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params, $params['invoiceID']);
1162 $recurParams['financial_type_id'] = $contributionType->id
;
1164 if (!$online ||
$form->_values
['is_monetary']) {
1165 $recurParams['payment_instrument_id'] = 1;
1168 $campaignId = CRM_Utils_Array
::value('campaign_id', $params);
1170 if (!array_key_exists('campaign_id', $params)) {
1171 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1174 $recurParams['campaign_id'] = $campaignId;
1176 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1177 if (is_a($recurring, 'CRM_Core_Error')) {
1178 CRM_Core_Error
::displaySessionError($recurring);
1179 $urlString = 'civicrm/contribute/transact';
1180 $urlParams = '_qf_Main_display=true';
1181 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1182 $urlString = 'civicrm/contact/view/contribution';
1183 $urlParams = "action=add&cid={$form->_contactID}";
1185 $urlParams .= "&mode={$form->_mode}";
1188 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1191 return $recurring->id
;
1195 * Add on behalf of organization and it's location.
1197 * This situation occurs when on behalf of is enabled for the contribution page and the person
1198 * signing up does so on behalf of an organization.
1200 * @param array $behalfOrganization
1201 * array of organization info.
1202 * @param int $contactID
1203 * individual contact id. One.
1204 * who is doing the process of signup / contribution.
1206 * @param array $values
1207 * form values array.
1208 * @param array $params
1209 * @param array $fields
1210 * Array of fields from the onbehalf profile relevant to the organization.
1212 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1213 $isCurrentEmployer = FALSE;
1216 if (!empty($behalfOrganization['organization_id']) && empty($behalfOrganization['org_option'])) {
1217 $orgID = $behalfOrganization['organization_id'];
1218 unset($behalfOrganization['organization_id']);
1219 $isCurrentEmployer = TRUE;
1222 // formalities for creating / editing organization.
1223 $behalfOrganization['contact_type'] = 'Organization';
1225 // get the relationship type id
1226 $relType = new CRM_Contact_DAO_RelationshipType();
1227 $relType->name_a_b
= 'Employee of';
1228 $relType->find(TRUE);
1229 $relTypeId = $relType->id
;
1231 // keep relationship params ready
1232 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1233 $relParams['is_permission_a_b'] = 1;
1234 $relParams['is_active'] = 1;
1237 // check if matching organization contact exists
1238 $dedupeParams = CRM_Dedupe_Finder
::formatParams($behalfOrganization, 'Organization');
1239 $dedupeParams['check_permission'] = FALSE;
1240 $dupeIDs = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1242 // CRM-6243 says to pick the first org even if more than one match
1243 if (count($dupeIDs) >= 1) {
1244 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1245 // don't allow name edit
1246 unset($behalfOrganization['organization_name']);
1250 // if found permissioned related organization, allow location edit
1251 $behalfOrganization['contact_id'] = $orgID;
1252 // don't allow name edit
1253 unset($behalfOrganization['organization_name']);
1256 // handling for image url
1257 if (!empty($behalfOrganization['image_URL'])) {
1258 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1261 // create organization, add location
1262 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1263 NULL, NULL, 'Organization'
1265 // create relationship
1266 $relParams['contact_check'][$orgID] = 1;
1267 $cid = array('contact' => $contactID);
1268 CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relParams, $cid);
1270 // if multiple match - send a duplicate alert
1271 if ($dupeIDs && (count($dupeIDs) > 1)) {
1272 $values['onbehalf_dupe_alert'] = 1;
1274 $params['onbehalf_dupe_alert'] = 1;
1277 // make sure organization-contact-id is considered for recording
1278 // contribution/membership etc..
1279 if ($contactID != $orgID) {
1280 // take a note of contact-id, so we can send the
1281 // receipt to individual contact as well.
1283 // required for mailing/template display ..etc
1284 $values['related_contact'] = $contactID;
1286 $params['related_contact'] = $contactID;
1288 //make this employee of relationship as current
1289 //employer / employee relationship, CRM-3532
1290 if ($isCurrentEmployer &&
1291 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1293 $isCurrentEmployer = FALSE;
1296 if (!$isCurrentEmployer && $orgID) {
1297 //build current employer params
1298 $currentEmpParams[$contactID] = $orgID;
1299 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1302 // contribution / signup will be done using this
1304 $contactID = $orgID;
1309 * Function used to save pcp / soft credit entry.
1311 * This is used by contribution and also event pcps
1313 * @param array $params
1314 * @param object $contribution
1315 * Contribution object.
1317 public static function processPcpSoft(&$params, &$contribution) {
1318 // Add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1319 if (!empty($params['soft_credit_to'])) {
1320 $contributionSoftParams = array();
1322 'pcp_display_in_roll',
1323 'pcp_roll_nickname',
1324 'pcp_personal_note',
1327 if (!empty($params[$val])) {
1328 $contributionSoftParams[$val] = $params[$val];
1332 $contributionSoftParams['contact_id'] = $params['soft_credit_to'];
1333 // add contribution id
1334 $contributionSoftParams['contribution_id'] = $contribution->id
;
1336 $contributionSoftParams['pcp_id'] = $params['pcp_made_through_id'];
1338 $contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
1340 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
1342 //Send notification to owner for PCP
1343 if ($contributionSoft->id
&& $contributionSoft->pcp_id
) {
1344 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
1350 * Function used to send notification mail to pcp owner.
1352 * This is used by contribution and also event PCPs.
1354 * @param object $contribution
1355 * @param object $contributionSoft
1356 * Contribution object.
1358 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1359 $params = array('id' => $contributionSoft->pcp_id
);
1360 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1361 $ownerNotifyID = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1363 if ($ownerNotifyID != CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1364 (($ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1365 CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id
, 'is_notify')) ||
1366 $ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1367 $pcpInfoURL = CRM_Utils_System
::url('civicrm/pcp/info',
1368 "reset=1&id={$contributionSoft->pcp_id}",
1369 TRUE, NULL, FALSE, TRUE
1371 // set email in the template here
1372 // get the billing location type
1373 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1374 $billingLocationTypeId = array_search('Billing', $locationTypes);
1376 if ($billingLocationTypeId) {
1377 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
, FALSE, $billingLocationTypeId);
1379 // get primary location email if no email exist( for billing location).
1381 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
);
1383 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft->contact_id
);
1385 'page_title' => $pcpInfo['title'],
1386 'receive_date' => $contribution->receive_date
,
1387 'total_amount' => $contributionSoft->amount
,
1388 'donors_display_name' => $donorName,
1389 'donors_email' => $email,
1390 'pcpInfoURL' => $pcpInfoURL,
1391 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll
,
1392 'currency' => $contributionSoft->currency
,
1394 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1395 $sendTemplateParams = array(
1396 'groupName' => 'msg_tpl_workflow_contribution',
1397 'valueName' => 'pcp_owner_notify',
1398 'contactId' => $contributionSoft->contact_id
,
1399 'toEmail' => $ownerEmail,
1400 'toName' => $ownerName,
1401 'from' => "$domainValues[0] <$domainValues[1]>",
1402 'tplParams' => $tplParams,
1403 'PDFFilename' => 'receipt.pdf',
1405 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1410 * Function used to se pcp related defaults / params.
1412 * This is used by contribution and also event PCPs
1414 * @param CRM_Core_Form $page
1416 * @param array $params
1420 public static function processPcp(&$page, $params) {
1421 $params['pcp_made_through_id'] = $page->_pcpId
;
1422 $page->assign('pcpBlock', TRUE);
1423 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1424 $params['pcp_roll_nickname'] = ts('Anonymous');
1425 $params['pcp_is_anonymous'] = 1;
1428 $params['pcp_is_anonymous'] = 0;
1431 'pcp_display_in_roll',
1433 'pcp_roll_nickname',
1434 'pcp_personal_note',
1436 if (!empty($params[$val])) {
1437 $page->assign($val, $params[$val]);
1445 * Process membership.
1447 * @param array $membershipParams
1448 * @param int $contactID
1449 * @param array $customFieldsFormatted
1450 * @param array $fieldTypes
1451 * @param array $premiumParams
1452 * @param array $membershipLineItems
1453 * Line items specifically relating to memberships.
1454 * @param bool $isPayLater
1456 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1457 $membershipLineItems, $isPayLater) {
1459 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1460 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1461 $membershipType = empty($membershipTypes) ?
array() : reset($membershipTypes);
1462 $isPending = $this->getIsPending();
1464 $this->assign('membership_name', CRM_Utils_Array
::value('name', $membershipType));
1466 $isPaidMembership = FALSE;
1467 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1468 //amount must be greater than zero for
1469 //adding contribution record to contribution table.
1470 //this condition arises when separate membership payment is
1471 //enabled and contribution amount is not selected. fix for CRM-3010
1472 $isPaidMembership = TRUE;
1474 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1476 if ($this->_values
['amount_block_is_active']) {
1477 $financialTypeID = $this->_values
['financial_type_id'];
1480 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $membershipType, CRM_Utils_Array
::value('financial_type_id', $membershipParams));
1483 if (CRM_Utils_Array
::value('membership_source', $this->_params
)) {
1484 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1487 $this->postProcessMembership($membershipParams, $contactID,
1488 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1489 $membershipLineItems, $isPayLater, $isPending);
1491 $this->assign('membership_assign', TRUE);
1492 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1496 * Process the Memberships.
1498 * @param array $membershipParams
1499 * Array of membership fields.
1500 * @param int $contactID
1502 * @param CRM_Contribute_Form_Contribution_Confirm $form
1503 * Confirmation form object.
1505 * @param array $premiumParams
1506 * @param null $customFieldsFormatted
1507 * @param null $includeFieldTypes
1509 * @param array $membershipDetails
1511 * @param array $membershipTypeIDs
1513 * @param bool $isPaidMembership
1514 * @param array $membershipID
1516 * @param bool $isProcessSeparateMembershipTransaction
1518 * @param int $financialTypeID
1519 * @param array $membershipLineItems
1520 * Line items specific to membership payment that is separate to contribution.
1521 * @param bool $isPayLater
1522 * @param bool $isPending
1524 * @throws \CRM_Core_Exception
1526 protected function postProcessMembership(
1527 $membershipParams, $contactID, &$form, $premiumParams,
1528 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1529 $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending) {
1530 $membershipContribution = NULL;
1531 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1532 $errors = $createdMemberships = $paymentResult = array();
1534 if ($isPaidMembership) {
1535 if ($isProcessSeparateMembershipTransaction) {
1536 // If we have 2 transactions only one can use the invoice id.
1537 $membershipParams['invoiceID'] .= '-2';
1540 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1549 if (!empty($paymentResult['contribution'])) {
1550 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1551 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1552 $membershipContribution = $paymentResult['contribution'];
1553 // Save the contribution ID so that I can be used in email receipts
1554 // For example, if you need to generate a tax receipt for the donation only.
1555 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1559 if ($isProcessSeparateMembershipTransaction) {
1561 $form->_lineItem
= $membershipLineItems;
1562 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1563 unset($membershipParams['is_recur']);
1565 $membershipContribution = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams,
1566 $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1568 catch (CRM_Core_Exception
$e) {
1569 $errors[2] = $e->getMessage();
1570 $membershipContribution = NULL;
1575 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1576 $membershipContributionID = $membershipContribution->id
;
1579 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1580 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1581 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1583 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1584 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1585 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1586 foreach ($membershipTypeIDs as $memType) {
1587 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1588 if (!empty($membershipContribution)) {
1589 $pendingStatus = CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name');
1590 $pending = ($membershipContribution->contribution_status_id
== $pendingStatus) ?
TRUE : FALSE;
1593 $pending = $isPending;
1595 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
1597 $membershipSource = NULL;
1598 if (!empty($form->_params
['membership_source'])) {
1599 $membershipSource = $form->_params
['membership_source'];
1601 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
1602 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
1605 if (isset($form->_params
)) {
1606 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
1609 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
1610 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
1611 if (!array_key_exists('campaign_id', $form->_params
)) {
1612 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1616 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership
::renewMembership(
1617 $contactID, $memType, $isTest,
1618 date('YmdHis'), CRM_Utils_Array
::value('cms_contactID', $membershipParams),
1619 $customFieldsFormatted,
1620 $numTerms, $membershipID, $pending,
1621 $contributionRecurID, $membershipSource, $isPayLater, $campaignId
1623 $form->set('renewal_mode', $renewalMode);
1624 if (!empty($dates)) {
1625 $form->assign('mem_start_date',
1626 CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d')
1628 $form->assign('mem_end_date',
1629 CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d')
1633 if (!empty($membershipContribution)) {
1634 // update recurring id for membership record
1635 CRM_Member_BAO_Membership
::updateRecurMembership($membership, $membershipContribution);
1636 CRM_Member_BAO_Membership
::linkMembershipPayment($membership, $membershipContribution);
1639 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1640 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1641 if (!empty($priceFieldOp['membership_type_id']) &&
1642 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1644 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1645 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1646 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1649 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1652 $form->_values
['lineItem'] = $form->_lineItem
;
1653 $form->assign('lineItem', $form->_lineItem
);
1657 if (!empty($errors)) {
1658 $message = $this->compileErrorMessage($errors);
1659 throw new CRM_Core_Exception($message);
1661 $form->_params
['createdMembershipIDs'] = array();
1663 // CRM-7851 - Moved after processing Payment Errors
1664 //@todo - the reasoning for this being here seems a little outdated
1665 foreach ($createdMemberships as $createdMembership) {
1666 CRM_Core_BAO_CustomValueTable
::postProcess(
1668 'civicrm_membership',
1669 $createdMembership->id
,
1672 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1674 if (count($createdMemberships) == 1) {
1675 //presumably this is only relevant for exactly 1 membership
1676 $form->_params
['membershipID'] = $createdMembership->id
;
1679 //CRM-15232: Check if membership is created and on the basis of it use
1680 //membership receipt template to send payment receipt
1681 if (count($createdMemberships)) {
1682 $form->_values
['isMembership'] = TRUE;
1684 if (isset($membershipContributionID)) {
1685 $form->_values
['contribution_id'] = $membershipContributionID;
1687 if ($form->_contributeMode
) {
1688 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1689 // call postProcess hook before leaving
1690 $form->postProcessHook();
1692 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1693 $paymentActionResult = $payment->doPayment($form->_params
, 'contribute');
1695 if (CRM_Utils_Array
::value('payment_status_id', $paymentActionResult) == 1) {
1696 // Refer to CRM-16737. Payment processors 'should' return payment_status_id
1697 // to denote the outcome of the transaction.
1699 civicrm_api3('contribution', 'completetransaction', array(
1700 'id' => $paymentResult['contribution']->id
,
1701 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $paymentActionResult, $paymentResult['contribution']->trxn_id
),
1702 'is_transactional' => FALSE,
1703 'payment_processor_id' => $form->_paymentProcessor
['id'],
1706 catch (CiviCRM_API3_Exception
$e) {
1707 if ($e->getErrorCode() != 'contribution_completed') {
1708 throw new CRM_Core_Exception('Failed to update contribution in database');
1712 // Do not send an email if Recurring transaction is done via Direct Mode
1713 // Email will we sent when the IPN is received.
1717 //finally send an email receipt
1718 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1726 * Turn array of errors into message string.
1728 * @param array $errors
1732 protected function compileErrorMessage($errors) {
1733 foreach ($errors as $error) {
1734 if (is_string($error)) {
1735 $message[] = $error;
1738 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1742 * Where a second separate financial transaction is supported we will process it here.
1744 * @param int $contactID
1745 * @param CRM_Contribute_Form_Contribution_Confirm $form
1746 * @param array $tempParams
1747 * @param bool $isTest
1748 * @param array $lineItems
1749 * @param $minimumFee
1750 * @param int $financialTypeID
1752 * @throws CRM_Core_Exception
1754 * @return CRM_Contribute_BAO_Contribution
1756 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1758 $financialType = new CRM_Financial_DAO_FinancialType();
1759 $financialType->id
= $financialTypeID;
1760 $financialType->find(TRUE);
1761 $tempParams['amount'] = $minimumFee;
1762 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1765 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
1766 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1767 // now we compensate here.
1768 if (empty($form->_paymentProcessor
['object'])) {
1769 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1772 $payment = $form->_paymentProcessor
['object'];
1774 $result = $payment->doPayment($tempParams, 'contribute');
1777 //assign receive date when separate membership payment
1778 //and contribution amount not selected.
1779 if ($form->_amount
== 0) {
1780 $now = date('YmdHis');
1781 $form->_params
['receive_date'] = $now;
1782 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1783 $form->set('params', $form->_params
);
1784 $form->assign('receive_date', $receiveDate);
1787 $form->set('membership_trx_id', $result['trxn_id']);
1788 $form->set('membership_amount', $minimumFee);
1790 $form->assign('membership_trx_id', $result['trxn_id']);
1791 $form->assign('membership_amount', $minimumFee);
1793 // we don't need to create the user twice, so lets disable cms_create_account
1794 // irrespective of the value, CRM-2888
1795 $tempParams['cms_create_account'] = 0;
1797 //CRM-16165, scenarios are
1798 // 1) If contribution is_pay_later and if contribution amount is > 0.0 we set pending = TRUE, vice-versa FALSE
1799 // 2) If not pay later but auto-renewal membership is chosen then pending = TRUE as it later triggers
1800 // pending recurring contribution, vice-versa FALSE
1801 $pending = $form->_params
['is_pay_later'] ?
(($minimumFee > 0.0) ?
TRUE : FALSE) : (!empty($form->_params
['auto_renew']) ?
TRUE : FALSE);
1803 //set this variable as we are not creating pledge for
1804 //separate membership payment contribution.
1805 //so for differentiating membership contribution from
1806 //main contribution.
1807 $form->_params
['separate_membership_payment'] = 1;
1808 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
1819 return $membershipContribution;
1823 * Is the payment a pending payment.
1825 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1826 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1831 protected function getIsPending() {
1832 if (((isset($this->_contributeMode
)) ||
!empty
1833 ($this->_params
['is_pay_later'])
1835 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1843 * Are we going to do 2 financial transactions.
1845 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1847 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1849 * @param int $formID
1850 * @param bool $amountBlockActiveOnForm
1854 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1855 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1856 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1863 * This function sets the fields.
1865 * - $this->_params['amount_level']
1866 * - $this->_params['selectMembership']
1867 * And under certain circumstances sets
1868 * $this->_params['amount'] = null;
1870 * @param int $priceSetID
1872 public function setFormAmountFields($priceSetID) {
1873 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1874 $priceField = new CRM_Price_DAO_PriceField();
1875 $priceField->price_set_id
= $priceSetID;
1876 $priceField->orderBy('weight');
1877 $priceField->find();
1878 $paramWeDoNotUnderstand = NULL;
1880 while ($priceField->fetch()) {
1881 if ($priceField->name
== "contribution_amount") {
1882 $paramWeDoNotUnderstand = $priceField->id
;
1884 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1885 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1886 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1887 $this->_params
["price_{$priceField->id}"], 'label');
1889 if ($priceField->name
== "membership_amount") {
1890 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1891 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1894 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1895 // as membership amount.
1896 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1897 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1898 // so we should merge them together
1899 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1900 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1902 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
)
1903 && !empty($this->_values
['fee'][$priceField->id
])
1904 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1905 && CRM_Utils_Array
::value("price_{$paramWeDoNotUnderstand}", $this->_params
) < 1
1906 && empty($this->_params
["price_{$priceField->id}"])
1908 $this->_params
['amount'] = NULL;
1911 // Fix for CRM-14375 - If we are using separate payments and "no
1912 // thank you" is selected for the additional contribution, set
1913 // contribution amount to be null, so that it will not show
1914 // contribution amount same as membership amount.
1915 //@todo - merge with section above
1916 if ($this->_membershipBlock
['is_separate_payment']
1917 && !empty($this->_values
['fee'][$priceField->id
])
1918 && CRM_Utils_Array
::value('name', $this->_values
['fee'][$priceField->id
]) == 'contribution_amount'
1919 && CRM_Utils_Array
::value("price_{$priceField->id}", $this->_params
) == '-1'
1921 $this->_params
['amount'] = NULL;
1929 * @param array $params
1931 * @throws CiviCRM_API3_Exception
1933 public static function submit($params) {
1934 $form = new CRM_Contribute_Form_Contribution_Confirm();
1935 $form->_id
= $params['id'];
1937 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1938 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1939 //this way the mocked up controller ignores the session stuff
1940 $_SERVER['REQUEST_METHOD'] = 'GET';
1941 $form->controller
= new CRM_Contribute_Controller_Contribution();
1942 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1943 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1944 $form->_amount
= $params['amount'];
1945 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1946 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1947 $priceSetFields = reset($priceFields);
1948 $form->_values
['fee'] = $priceSetFields['fields'];
1949 $form->_priceSetId
= $priceSetID;
1950 $form->setFormAmountFields($priceSetID);
1951 if (!empty($params['payment_processor_id'])) {
1952 $form->_paymentProcessor
= civicrm_api3('payment_processor', 'getsingle', array(
1953 'id' => $params['payment_processor_id'],
1955 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1956 $form->_contributeMode
= 'direct';
1959 $form->_contributeMode
= 'notify';
1963 $form->_params
['payment_processor_id'] = 0;
1965 $priceFields = $priceFields[$priceSetID]['fields'];
1966 CRM_Price_BAO_PriceSet
::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1967 $form->_lineItem
= array($priceSetID => $lineItems);
1968 $form->processFormSubmission(CRM_Utils_Array
::value('contact_id', $params));
1972 * Helper function for static submit function.
1974 * Set relevant params - help us to build up an array that we can pass in.
1977 * @param array $params
1980 * @throws CiviCRM_API3_Exception
1982 public static function getFormParams($id, array $params) {
1983 if (!isset($params['is_pay_later'])) {
1984 if (!empty($params['payment_processor_id'])) {
1985 $params['is_pay_later'] = 0;
1988 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1990 'return' => 'is_pay_later',
1994 if (empty($params['price_set_id'])) {
1995 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
2001 * Post form submission handling.
2003 * This is also called from the test suite.
2005 * @param int $contactID
2009 protected function processFormSubmission($contactID) {
2010 $isPayLater = $this->_params
['is_pay_later'];
2011 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] == 0) {
2012 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
2014 // add a description field at the very beginning
2015 $this->_params
['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $this->_values
['title']);
2017 $this->_params
['accountingCode'] = CRM_Utils_Array
::value('accountingCode', $this->_values
);
2020 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
2022 //carry payment processor id.
2023 if (CRM_Utils_Array
::value('id', $this->_paymentProcessor
)) {
2024 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
2027 $premiumParams = $membershipParams = $params = $this->_params
;
2028 if (!empty($params['image_URL'])) {
2029 CRM_Contact_BAO_Contact
::processImageParams($params);
2032 $fields = array('email-Primary' => 1);
2034 // get the add to groups
2035 $addToGroups = array();
2037 // now set the values for the billing location.
2038 foreach ($this->_fields
as $name => $value) {
2041 // get the add to groups for uf fields
2042 if (!empty($value['add_to_group_id'])) {
2043 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2047 if (!array_key_exists('first_name', $fields)) {
2048 $nameFields = array('first_name', 'middle_name', 'last_name');
2049 foreach ($nameFields as $name) {
2051 if (array_key_exists("billing_$name", $params)) {
2052 $params[$name] = $params["billing_{$name}"];
2053 $params['preserveDBName'] = TRUE;
2058 // billing email address
2059 $fields["email-{$this->_bltID}"] = 1;
2061 //unset the billing parameters if it is pay later mode
2062 //to avoid creation of billing location
2063 if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater
) {
2064 $billingFields = array(
2065 'billing_first_name',
2066 'billing_middle_name',
2067 'billing_last_name',
2068 "billing_street_address-{$this->_bltID}",
2069 "billing_city-{$this->_bltID}",
2070 "billing_state_province-{$this->_bltID}",
2071 "billing_state_province_id-{$this->_bltID}",
2072 "billing_postal_code-{$this->_bltID}",
2073 "billing_country-{$this->_bltID}",
2074 "billing_country_id-{$this->_bltID}",
2077 foreach ($billingFields as $value) {
2078 unset($params[$value]);
2079 unset($fields[$value]);
2083 // if onbehalf-of-organization contribution, take out
2084 // organization params in a separate variable, to make sure
2085 // normal behavior is continued. And use that variable to
2086 // process on-behalf-of functionality.
2087 if (!empty($this->_params
['hidden_onbehalf_profile'])) {
2088 $behalfOrganization = array();
2089 $orgFields = array('organization_name', 'organization_id', 'org_option');
2090 foreach ($orgFields as $fld) {
2091 if (array_key_exists($fld, $params)) {
2092 $behalfOrganization[$fld] = $params[$fld];
2093 unset($params[$fld]);
2097 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2098 foreach ($params['onbehalf'] as $fld => $values) {
2099 if (strstr($fld, 'custom_')) {
2100 $behalfOrganization[$fld] = $values;
2102 elseif (!(strstr($fld, '-'))) {
2103 if (in_array($fld, array(
2104 'contribution_campaign_id',
2105 'member_campaign_id',
2107 $fld = 'campaign_id';
2110 $behalfOrganization[$fld] = $values;
2112 $this->_params
[$fld] = $values;
2117 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2118 foreach ($params['onbehalf_location'] as $block => $vals) {
2119 //fix for custom data (of type checkbox, multi-select)
2120 if (substr($block, 0, 7) == 'custom_') {
2123 // fix the index of block elements
2124 if (is_array($vals)) {
2125 foreach ($vals as $key => $val) {
2126 //dont adjust the index of address block as
2127 //it's index is WRT to location type
2128 $newKey = ($block == 'address') ?
$key : ++
$key;
2129 $behalfOrganization[$block][$newKey] = $val;
2133 unset($params['onbehalf_location']);
2135 if (!empty($params['onbehalf[image_URL]'])) {
2136 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2140 // check for profile double opt-in and get groups to be subscribed
2141 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2143 // since we are directly adding contact to group lets unset it from mailing
2144 if (!empty($addToGroups)) {
2145 foreach ($addToGroups as $groupId) {
2146 if (isset($subscribeGroupIds[$groupId])) {
2147 unset($subscribeGroupIds[$groupId]);
2152 foreach ($addToGroups as $k) {
2153 if (array_key_exists($k, $subscribeGroupIds)) {
2154 unset($addToGroups[$k]);
2158 if (empty($contactID)) {
2159 $dupeParams = $params;
2160 if (!empty($dupeParams['onbehalf'])) {
2161 unset($dupeParams['onbehalf']);
2163 if (!empty($dupeParams['honor'])) {
2164 unset($dupeParams['honor']);
2167 $dedupeParams = CRM_Dedupe_Finder
::formatParams($dupeParams, 'Individual');
2168 $dedupeParams['check_permission'] = FALSE;
2169 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
2171 // if we find more than one contact, use the first one
2172 $contactID = CRM_Utils_Array
::value(0, $ids);
2174 // Fetch default greeting id's if creating a contact
2176 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2177 if (!isset($params[$greeting])) {
2178 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2182 $contactType = NULL;
2185 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2187 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2197 // Make the contact ID associated with the contribution available at the Class level.
2198 // Also make available to the session.
2199 //@todo consider handling this in $this->getContactID();
2200 $this->set('contactID', $contactID);
2201 $this->_contactID
= $contactID;
2203 //get email primary first if exist
2204 $subscriptionEmail = array('email' => CRM_Utils_Array
::value('email-Primary', $params));
2205 if (!$subscriptionEmail['email']) {
2206 $subscriptionEmail['email'] = CRM_Utils_Array
::value("email-{$this->_bltID}", $params);
2208 // subscribing contact to groups
2209 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2210 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2213 // If onbehalf-of-organization contribution / signup, add organization
2214 // and it's location.
2215 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
2216 $ufFields = array();
2217 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2218 $ufFields[$name] = 1;
2220 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2221 $this->_params
, $ufFields
2224 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2225 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2226 // store current user id as related contact for later use for mailing / activity..
2227 $this->_values
['related_contact'] = $contactID;
2228 $this->_params
['related_contact'] = $contactID;
2229 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2230 $contactID = $this->_membershipContactID
;
2233 // lets store the contactID in the session
2234 // for things like tell a friend
2235 $session = CRM_Core_Session
::singleton();
2236 if (!$session->get('userID')) {
2237 $session->set('transaction.userID', $contactID);
2240 $session->set('transaction.userID', NULL);
2243 $this->_useForMember
= $this->get('useForMember');
2245 // store the fact that this is a membership and membership type is selected
2246 if ((!empty($membershipParams['selectMembership']) &&
2247 $membershipParams['selectMembership'] != 'no_thanks'
2249 $this->_useForMember
2251 if (!$this->_useForMember
) {
2252 $this->assign('membership_assign', TRUE);
2253 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2256 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2257 $membershipParams['is_test'] = 1;
2259 if ($this->_params
['is_pay_later']) {
2260 $membershipParams['is_pay_later'] = 1;
2263 //inherit campaign from contribution page.
2264 if (!array_key_exists('campaign_id', $membershipParams)) {
2265 $membershipParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
);
2268 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2269 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater);
2272 // at this point we've created a contact and stored its address etc
2273 // all the payment processors expect the name and address to be in the
2274 // so we copy stuff over to first_name etc.
2275 $paymentParams = $this->_params
;
2276 $contributionTypeId = $this->_values
['financial_type_id'];
2278 $fieldTypes = array();
2279 if (!empty($paymentParams['onbehalf']) &&
2280 is_array($paymentParams['onbehalf'])
2282 foreach ($paymentParams['onbehalf'] as $key => $value) {
2283 if (strstr($key, 'custom_')) {
2284 $this->_params
[$key] = $value;
2287 $fieldTypes = array('Contact', 'Organization', 'Contribution');
2289 $financialTypeID = $this->wrangleFinancialTypeID($contributionTypeId);
2291 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2296 ($this->_mode
== 'test') ?
1 : 0,
2300 if (!empty($result['is_payment_failure'])) {
2303 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2304 $this->postProcessPremium($premiumParams, $result['contribution']);
2305 if (CRM_Utils_Array
::value('payment_status_id', $result) == 1) {
2307 civicrm_api3('contribution', 'completetransaction', array(
2308 'id' => $result['contribution']->id
,
2309 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $result),
2310 'payment_processor_id' => $this->_paymentProcessor
['id'],
2311 'is_transactional' => FALSE,
2315 catch (CiviCRM_API3_Exception
$e) {
2316 if ($e->getErrorCode() != 'contribution_completed') {
2317 throw new CRM_Core_Exception('Failed to update contribution in database');
2327 * Membership processing section.
2329 * This is in a separate function as part of a move towards refactoring.
2331 * @param int $contactID
2332 * @param array $membershipParams
2333 * @param array $premiumParams
2334 * @param bool $isPayLater
2336 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater) {
2338 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2339 if (isset($this->_params
['related_contact'])) {
2340 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2343 $membershipParams['cms_contactID'] = $contactID;
2346 if (!empty($membershipParams['onbehalf']) &&
2347 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2349 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2352 $customFieldsFormatted = $fieldTypes = array();
2353 if (!empty($membershipParams['onbehalf']) &&
2354 is_array($membershipParams['onbehalf'])
2356 foreach ($membershipParams['onbehalf'] as $key => $value) {
2357 if (strstr($key, 'custom_')) {
2358 $customFieldId = explode('_', $key);
2359 CRM_Core_BAO_CustomField
::formatCustomField(
2361 $customFieldsFormatted,
2369 $fieldTypes = array('Contact', 'Organization', 'Membership');
2372 $priceFieldIds = $this->get('memberPriceFieldIDS');
2374 if (!empty($priceFieldIds)) {
2375 $contributionTypeID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2376 unset($priceFieldIds['id']);
2377 $membershipTypeIds = array();
2378 $membershipTypeTerms = array();
2379 foreach ($priceFieldIds as $priceFieldId) {
2380 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
2381 $membershipTypeIds[] = $id;
2382 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
2383 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
2385 if ($term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
2386 $membershipTypeTerms[$id] = ($term > 1) ?
$term : 1;
2389 $membershipTypeTerms[$id] = 1;
2393 $membershipParams['selectMembership'] = $membershipTypeIds;
2394 $membershipParams['financial_type_id'] = $contributionTypeID;
2395 $membershipParams['types_terms'] = $membershipTypeTerms;
2397 if (!empty($membershipParams['selectMembership'])) {
2399 $membershipLineItems = array();
2400 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2401 foreach ($this->_values
['fee'] as $key => $feeValues) {
2402 if ($feeValues['name'] == 'membership_amount') {
2403 $fieldId = $this->_params
['price_' . $key];
2404 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2405 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2411 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
2413 catch (CRM_Core_Exception
$e) {
2414 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2415 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2417 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2418 // we need to explicitly create a CMS user in case of free memberships
2419 // since it is done under processConfirm for paid memberships
2420 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2421 $membershipParams['cms_contactID'],
2422 'email-' . $this->_bltID