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 public function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater) {
1458 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1459 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1460 $membershipType = empty($membershipTypes) ?
array() : reset($membershipTypes);
1461 $isPending = $this->getIsPending();
1463 $this->assign('membership_name', CRM_Utils_Array
::value('name', $membershipType));
1465 $isPaidMembership = FALSE;
1466 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1467 //amount must be greater than zero for
1468 //adding contribution record to contribution table.
1469 //this condition arises when separate membership payment is
1470 //enabled and contribution amount is not selected. fix for CRM-3010
1471 $isPaidMembership = TRUE;
1473 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1475 if ($this->_values
['amount_block_is_active']) {
1476 $financialTypeID = $this->_values
['financial_type_id'];
1479 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $membershipType, CRM_Utils_Array
::value('financial_type_id', $membershipParams));
1482 if (CRM_Utils_Array
::value('membership_source', $this->_params
)) {
1483 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1486 $this->postProcessMembership($membershipParams, $contactID,
1487 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1488 $membershipLineItems, $isPayLater, $isPending);
1490 $this->assign('membership_assign', TRUE);
1491 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1493 catch (CRM_Core_Exception
$e) {
1494 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
1495 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
1500 * Process the Memberships.
1502 * @param array $membershipParams
1503 * Array of membership fields.
1504 * @param int $contactID
1506 * @param CRM_Contribute_Form_Contribution_Confirm $form
1507 * Confirmation form object.
1509 * @param array $premiumParams
1510 * @param null $customFieldsFormatted
1511 * @param null $includeFieldTypes
1513 * @param array $membershipDetails
1515 * @param array $membershipTypeIDs
1517 * @param bool $isPaidMembership
1518 * @param array $membershipID
1520 * @param bool $isProcessSeparateMembershipTransaction
1522 * @param int $financialTypeID
1523 * @param array $membershipLineItems
1524 * Line items specific to membership payment that is separate to contribution.
1525 * @param bool $isPayLater
1526 * @param bool $isPending
1528 * @throws \CRM_Core_Exception
1530 protected function postProcessMembership(
1531 $membershipParams, $contactID, &$form, $premiumParams,
1532 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1533 $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending) {
1534 $membershipContribution = NULL;
1535 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1536 $errors = $createdMemberships = $paymentResult = array();
1538 if ($isPaidMembership) {
1539 if ($isProcessSeparateMembershipTransaction) {
1540 // If we have 2 transactions only one can use the invoice id.
1541 $membershipParams['invoiceID'] .= '-2';
1544 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1553 if (!empty($paymentResult['contribution'])) {
1554 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1555 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1556 $membershipContribution = $paymentResult['contribution'];
1557 // Save the contribution ID so that I can be used in email receipts
1558 // For example, if you need to generate a tax receipt for the donation only.
1559 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1563 if ($isProcessSeparateMembershipTransaction) {
1565 $form->_lineItem
= $membershipLineItems;
1566 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1567 unset($membershipParams['is_recur']);
1569 $membershipContribution = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams,
1570 $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1572 catch (CRM_Core_Exception
$e) {
1573 $errors[2] = $e->getMessage();
1574 $membershipContribution = NULL;
1579 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1580 $membershipContributionID = $membershipContribution->id
;
1583 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1584 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1585 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1587 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1588 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1589 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1590 foreach ($membershipTypeIDs as $memType) {
1591 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1592 if (!empty($membershipContribution)) {
1593 $pendingStatus = CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name');
1594 $pending = ($membershipContribution->contribution_status_id
== $pendingStatus) ?
TRUE : FALSE;
1597 $pending = $isPending;
1599 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
1601 $membershipSource = NULL;
1602 if (!empty($form->_params
['membership_source'])) {
1603 $membershipSource = $form->_params
['membership_source'];
1605 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
1606 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
1609 if (isset($form->_params
)) {
1610 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
1613 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
1614 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
1615 if (!array_key_exists('campaign_id', $form->_params
)) {
1616 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1620 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership
::renewMembership(
1621 $contactID, $memType, $isTest,
1622 date('YmdHis'), CRM_Utils_Array
::value('cms_contactID', $membershipParams),
1623 $customFieldsFormatted,
1624 $numTerms, $membershipID, $pending,
1625 $contributionRecurID, $membershipSource, $isPayLater, $campaignId
1627 $form->set('renewal_mode', $renewalMode);
1628 if (!empty($dates)) {
1629 $form->assign('mem_start_date',
1630 CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d')
1632 $form->assign('mem_end_date',
1633 CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d')
1637 if (!empty($membershipContribution)) {
1638 // update recurring id for membership record
1639 CRM_Member_BAO_Membership
::updateRecurMembership($membership, $membershipContribution);
1640 CRM_Member_BAO_Membership
::linkMembershipPayment($membership, $membershipContribution);
1643 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1644 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1645 if (!empty($priceFieldOp['membership_type_id']) &&
1646 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1648 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1649 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1650 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1653 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1656 $form->_values
['lineItem'] = $form->_lineItem
;
1657 $form->assign('lineItem', $form->_lineItem
);
1661 if (!empty($errors)) {
1662 $message = $this->compileErrorMessage($errors);
1663 throw new CRM_Core_Exception($message);
1665 $form->_params
['createdMembershipIDs'] = array();
1667 // CRM-7851 - Moved after processing Payment Errors
1668 //@todo - the reasoning for this being here seems a little outdated
1669 foreach ($createdMemberships as $createdMembership) {
1670 CRM_Core_BAO_CustomValueTable
::postProcess(
1672 'civicrm_membership',
1673 $createdMembership->id
,
1676 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1678 if (count($createdMemberships) == 1) {
1679 //presumably this is only relevant for exactly 1 membership
1680 $form->_params
['membershipID'] = $createdMembership->id
;
1683 //CRM-15232: Check if membership is created and on the basis of it use
1684 //membership receipt template to send payment receipt
1685 if (count($createdMemberships)) {
1686 $form->_values
['isMembership'] = TRUE;
1688 if (isset($membershipContributionID)) {
1689 $form->_values
['contribution_id'] = $membershipContributionID;
1691 if ($form->_contributeMode
) {
1692 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1693 // call postProcess hook before leaving
1694 $form->postProcessHook();
1696 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1697 $result = $payment->doPayment($form->_params
, 'contribute');
1699 if (CRM_Utils_Array
::value('payment_status_id', $result) == 1) {
1700 // Refer to CRM-16737. Payment processors 'should' return payment_status_id
1701 // to denote the outcome of the transaction.
1703 civicrm_api3('contribution', 'completetransaction', array(
1704 'id' => $paymentResult['contribution']->id
,
1705 'trxn_id' => $paymentResult['contribution']->trxn_id
,
1706 'is_transactional' => FALSE,
1709 catch (CiviCRM_API3_Exception
$e) {
1710 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
1711 // so let's be gentle here
1712 CRM_Core_Error
::debug_log_message('contribution ' . $membershipContribution->id
. ' not completed with trxn_id ' . $membershipContribution->trxn_id
. ' and message ' . $e->getMessage());
1715 // Do not send an email if Recurring transaction is done via Direct Mode
1716 // Email will we sent when the IPN is received.
1720 //finally send an email receipt
1721 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1729 * Turn array of errors into message string.
1731 * @param array $errors
1735 protected function compileErrorMessage($errors) {
1736 foreach ($errors as $error) {
1737 if (is_string($error)) {
1738 $message[] = $error;
1741 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1745 * Where a second separate financial transaction is supported we will process it here.
1747 * @param int $contactID
1748 * @param CRM_Contribute_Form_Contribution_Confirm $form
1749 * @param array $tempParams
1750 * @param bool $isTest
1751 * @param array $lineItems
1752 * @param $minimumFee
1753 * @param int $financialTypeID
1755 * @throws CRM_Core_Exception
1757 * @return CRM_Contribute_BAO_Contribution
1759 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1761 $financialType = new CRM_Financial_DAO_FinancialType();
1762 $financialType->id
= $financialTypeID;
1763 $financialType->find(TRUE);
1764 $tempParams['amount'] = $minimumFee;
1765 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1768 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
1769 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1770 // now we compensate here.
1771 if (empty($form->_paymentProcessor
['object'])) {
1772 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1775 $payment = $form->_paymentProcessor
['object'];
1777 $result = $payment->doPayment($tempParams, 'contribute');
1780 //assign receive date when separate membership payment
1781 //and contribution amount not selected.
1782 if ($form->_amount
== 0) {
1783 $now = date('YmdHis');
1784 $form->_params
['receive_date'] = $now;
1785 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1786 $form->set('params', $form->_params
);
1787 $form->assign('receive_date', $receiveDate);
1790 $form->set('membership_trx_id', $result['trxn_id']);
1791 $form->set('membership_amount', $minimumFee);
1793 $form->assign('membership_trx_id', $result['trxn_id']);
1794 $form->assign('membership_amount', $minimumFee);
1796 // we don't need to create the user twice, so lets disable cms_create_account
1797 // irrespective of the value, CRM-2888
1798 $tempParams['cms_create_account'] = 0;
1800 //CRM-16165, scenarios are
1801 // 1) If contribution is_pay_later and if contribution amount is > 0.0 we set pending = TRUE, vice-versa FALSE
1802 // 2) If not pay later but auto-renewal membership is chosen then pending = TRUE as it later triggers
1803 // pending recurring contribution, vice-versa FALSE
1804 $pending = $form->_params
['is_pay_later'] ?
(($minimumFee > 0.0) ?
TRUE : FALSE) : (!empty($form->_params
['auto_renew']) ?
TRUE : FALSE);
1806 //set this variable as we are not creating pledge for
1807 //separate membership payment contribution.
1808 //so for differentiating membership contribution from
1809 //main contribution.
1810 $form->_params
['separate_membership_payment'] = 1;
1811 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
1822 return $membershipContribution;
1826 * Is the payment a pending payment.
1828 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1829 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1834 protected function getIsPending() {
1835 if (((isset($this->_contributeMode
)) ||
!empty
1836 ($this->_params
['is_pay_later'])
1838 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1846 * Are we going to do 2 financial transactions.
1848 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1850 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1852 * @param int $formID
1853 * @param bool $amountBlockActiveOnForm
1857 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1858 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1859 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1866 * This function sets the fields.
1868 * - $this->_params['amount_level']
1869 * - $this->_params['selectMembership']
1870 * And under certain circumstances sets
1871 * $this->_params['amount'] = null;
1873 * @param int $priceSetID
1875 public function setFormAmountFields($priceSetID) {
1876 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1877 $priceField = new CRM_Price_DAO_PriceField();
1878 $priceField->price_set_id
= $priceSetID;
1879 $priceField->orderBy('weight');
1880 $priceField->find();
1881 $paramWeDoNotUnderstand = NULL;
1883 while ($priceField->fetch()) {
1884 if ($priceField->name
== "contribution_amount") {
1885 $paramWeDoNotUnderstand = $priceField->id
;
1887 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1888 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1889 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1890 $this->_params
["price_{$priceField->id}"], 'label');
1892 if ($priceField->name
== "membership_amount") {
1893 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1894 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1897 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1898 // as membership amount.
1899 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1900 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1901 // so we should merge them together
1902 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1903 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1905 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
)
1906 && !empty($this->_values
['fee'][$priceField->id
])
1907 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1908 && CRM_Utils_Array
::value("price_{$paramWeDoNotUnderstand}", $this->_params
) < 1
1909 && empty($this->_params
["price_{$priceField->id}"])
1911 $this->_params
['amount'] = NULL;
1914 // Fix for CRM-14375 - If we are using separate payments and "no
1915 // thank you" is selected for the additional contribution, set
1916 // contribution amount to be null, so that it will not show
1917 // contribution amount same as membership amount.
1918 //@todo - merge with section above
1919 if ($this->_membershipBlock
['is_separate_payment']
1920 && !empty($this->_values
['fee'][$priceField->id
])
1921 && CRM_Utils_Array
::value('name', $this->_values
['fee'][$priceField->id
]) == 'contribution_amount'
1922 && CRM_Utils_Array
::value("price_{$priceField->id}", $this->_params
) == '-1'
1924 $this->_params
['amount'] = NULL;
1932 * @param array $params
1934 * @throws CiviCRM_API3_Exception
1936 public static function submit($params) {
1937 $form = new CRM_Contribute_Form_Contribution_Confirm();
1938 $form->_id
= $params['id'];
1940 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1941 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1942 //this way the mocked up controller ignores the session stuff
1943 $_SERVER['REQUEST_METHOD'] = 'GET';
1944 $form->controller
= new CRM_Contribute_Controller_Contribution();
1945 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1946 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1947 $form->_amount
= $params['amount'];
1948 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1949 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1950 $priceSetFields = reset($priceFields);
1951 $form->_values
['fee'] = $priceSetFields['fields'];
1952 $form->_priceSetId
= $priceSetID;
1953 $form->setFormAmountFields($priceSetID);
1954 if (!empty($params['payment_processor_id'])) {
1955 $form->_paymentProcessor
= civicrm_api3('payment_processor', 'getsingle', array(
1956 'id' => $params['payment_processor_id'],
1958 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1959 $form->_contributeMode
= 'direct';
1962 $form->_contributeMode
= 'notify';
1966 $form->_params
['payment_processor_id'] = 0;
1968 $priceFields = $priceFields[$priceSetID]['fields'];
1969 CRM_Price_BAO_PriceSet
::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1970 $form->_lineItem
= array($priceSetID => $lineItems);
1971 $form->processFormSubmission(CRM_Utils_Array
::value('contact_id', $params));
1975 * Helper function for static submit function.
1977 * Set relevant params - help us to build up an array that we can pass in.
1980 * @param array $params
1983 * @throws CiviCRM_API3_Exception
1985 public static function getFormParams($id, array $params) {
1986 if (!isset($params['is_pay_later'])) {
1987 if (!empty($params['payment_processor_id'])) {
1988 $params['is_pay_later'] = 0;
1991 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1993 'return' => 'is_pay_later',
1997 if (empty($params['price_set_id'])) {
1998 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
2004 * Post form submission handling.
2006 * This is also called from the test suite.
2008 * @param int $contactID
2012 protected function processFormSubmission($contactID) {
2013 $isPayLater = $this->_params
['is_pay_later'];
2014 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] == 0) {
2015 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
2017 // add a description field at the very beginning
2018 $this->_params
['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $this->_values
['title']);
2020 $this->_params
['accountingCode'] = CRM_Utils_Array
::value('accountingCode', $this->_values
);
2023 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
2025 //carry payment processor id.
2026 if (CRM_Utils_Array
::value('id', $this->_paymentProcessor
)) {
2027 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
2030 $premiumParams = $membershipParams = $params = $this->_params
;
2031 if (!empty($params['image_URL'])) {
2032 CRM_Contact_BAO_Contact
::processImageParams($params);
2035 $fields = array('email-Primary' => 1);
2037 // get the add to groups
2038 $addToGroups = array();
2040 // now set the values for the billing location.
2041 foreach ($this->_fields
as $name => $value) {
2044 // get the add to groups for uf fields
2045 if (!empty($value['add_to_group_id'])) {
2046 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2050 if (!array_key_exists('first_name', $fields)) {
2051 $nameFields = array('first_name', 'middle_name', 'last_name');
2052 foreach ($nameFields as $name) {
2054 if (array_key_exists("billing_$name", $params)) {
2055 $params[$name] = $params["billing_{$name}"];
2056 $params['preserveDBName'] = TRUE;
2061 // billing email address
2062 $fields["email-{$this->_bltID}"] = 1;
2064 //unset the billing parameters if it is pay later mode
2065 //to avoid creation of billing location
2066 if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater
) {
2067 $billingFields = array(
2068 'billing_first_name',
2069 'billing_middle_name',
2070 'billing_last_name',
2071 "billing_street_address-{$this->_bltID}",
2072 "billing_city-{$this->_bltID}",
2073 "billing_state_province-{$this->_bltID}",
2074 "billing_state_province_id-{$this->_bltID}",
2075 "billing_postal_code-{$this->_bltID}",
2076 "billing_country-{$this->_bltID}",
2077 "billing_country_id-{$this->_bltID}",
2080 foreach ($billingFields as $value) {
2081 unset($params[$value]);
2082 unset($fields[$value]);
2086 // if onbehalf-of-organization contribution, take out
2087 // organization params in a separate variable, to make sure
2088 // normal behavior is continued. And use that variable to
2089 // process on-behalf-of functionality.
2090 if (!empty($this->_params
['hidden_onbehalf_profile'])) {
2091 $behalfOrganization = array();
2092 $orgFields = array('organization_name', 'organization_id', 'org_option');
2093 foreach ($orgFields as $fld) {
2094 if (array_key_exists($fld, $params)) {
2095 $behalfOrganization[$fld] = $params[$fld];
2096 unset($params[$fld]);
2100 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2101 foreach ($params['onbehalf'] as $fld => $values) {
2102 if (strstr($fld, 'custom_')) {
2103 $behalfOrganization[$fld] = $values;
2105 elseif (!(strstr($fld, '-'))) {
2106 if (in_array($fld, array(
2107 'contribution_campaign_id',
2108 'member_campaign_id',
2110 $fld = 'campaign_id';
2113 $behalfOrganization[$fld] = $values;
2115 $this->_params
[$fld] = $values;
2120 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2121 foreach ($params['onbehalf_location'] as $block => $vals) {
2122 //fix for custom data (of type checkbox, multi-select)
2123 if (substr($block, 0, 7) == 'custom_') {
2126 // fix the index of block elements
2127 if (is_array($vals)) {
2128 foreach ($vals as $key => $val) {
2129 //dont adjust the index of address block as
2130 //it's index is WRT to location type
2131 $newKey = ($block == 'address') ?
$key : ++
$key;
2132 $behalfOrganization[$block][$newKey] = $val;
2136 unset($params['onbehalf_location']);
2138 if (!empty($params['onbehalf[image_URL]'])) {
2139 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2143 // check for profile double opt-in and get groups to be subscribed
2144 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2146 // since we are directly adding contact to group lets unset it from mailing
2147 if (!empty($addToGroups)) {
2148 foreach ($addToGroups as $groupId) {
2149 if (isset($subscribeGroupIds[$groupId])) {
2150 unset($subscribeGroupIds[$groupId]);
2155 foreach ($addToGroups as $k) {
2156 if (array_key_exists($k, $subscribeGroupIds)) {
2157 unset($addToGroups[$k]);
2161 if (empty($contactID)) {
2162 $dupeParams = $params;
2163 if (!empty($dupeParams['onbehalf'])) {
2164 unset($dupeParams['onbehalf']);
2166 if (!empty($dupeParams['honor'])) {
2167 unset($dupeParams['honor']);
2170 $dedupeParams = CRM_Dedupe_Finder
::formatParams($dupeParams, 'Individual');
2171 $dedupeParams['check_permission'] = FALSE;
2172 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
2174 // if we find more than one contact, use the first one
2175 $contactID = CRM_Utils_Array
::value(0, $ids);
2177 // Fetch default greeting id's if creating a contact
2179 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2180 if (!isset($params[$greeting])) {
2181 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2185 $contactType = NULL;
2188 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2190 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2200 // Make the contact ID associated with the contribution available at the Class level.
2201 // Also make available to the session.
2202 //@todo consider handling this in $this->getContactID();
2203 $this->set('contactID', $contactID);
2204 $this->_contactID
= $contactID;
2206 //get email primary first if exist
2207 $subscriptionEmail = array('email' => CRM_Utils_Array
::value('email-Primary', $params));
2208 if (!$subscriptionEmail['email']) {
2209 $subscriptionEmail['email'] = CRM_Utils_Array
::value("email-{$this->_bltID}", $params);
2211 // subscribing contact to groups
2212 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2213 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2216 // If onbehalf-of-organization contribution / signup, add organization
2217 // and it's location.
2218 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
2219 $ufFields = array();
2220 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2221 $ufFields[$name] = 1;
2223 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2224 $this->_params
, $ufFields
2227 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2228 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2229 // store current user id as related contact for later use for mailing / activity..
2230 $this->_values
['related_contact'] = $contactID;
2231 $this->_params
['related_contact'] = $contactID;
2232 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2233 $contactID = $this->_membershipContactID
;
2236 // lets store the contactID in the session
2237 // for things like tell a friend
2238 $session = CRM_Core_Session
::singleton();
2239 if (!$session->get('userID')) {
2240 $session->set('transaction.userID', $contactID);
2243 $session->set('transaction.userID', NULL);
2246 $this->_useForMember
= $this->get('useForMember');
2248 // store the fact that this is a membership and membership type is selected
2249 if ((!empty($membershipParams['selectMembership']) &&
2250 $membershipParams['selectMembership'] != 'no_thanks'
2252 $this->_useForMember
2254 if (!$this->_useForMember
) {
2255 $this->assign('membership_assign', TRUE);
2256 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2259 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2260 $membershipParams['is_test'] = 1;
2262 if ($this->_params
['is_pay_later']) {
2263 $membershipParams['is_pay_later'] = 1;
2266 //inherit campaign from contribution page.
2267 if (!array_key_exists('campaign_id', $membershipParams)) {
2268 $membershipParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
);
2271 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2272 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater);
2275 // at this point we've created a contact and stored its address etc
2276 // all the payment processors expect the name and address to be in the
2277 // so we copy stuff over to first_name etc.
2278 $paymentParams = $this->_params
;
2279 $contributionTypeId = $this->_values
['financial_type_id'];
2281 $fieldTypes = array();
2282 if (!empty($paymentParams['onbehalf']) &&
2283 is_array($paymentParams['onbehalf'])
2285 foreach ($paymentParams['onbehalf'] as $key => $value) {
2286 if (strstr($key, 'custom_')) {
2287 $this->_params
[$key] = $value;
2290 $fieldTypes = array('Contact', 'Organization', 'Contribution');
2292 $financialTypeID = $this->wrangleFinancialTypeID($contributionTypeId);
2294 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2299 ($this->_mode
== 'test') ?
1 : 0,
2303 if (!empty($result['is_payment_failure'])) {
2306 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2307 $this->postProcessPremium($premiumParams, $result['contribution']);
2308 if (CRM_Utils_Array
::value('payment_status_id', $result) == 1) {
2309 civicrm_api3('contribution', 'completetransaction', array(
2310 'id' => $result['contribution']->id
,
2311 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $result),
2320 * Membership processing section.
2322 * This is in a separate function as part of a move towards refactoring.
2324 * @param int $contactID
2325 * @param array $membershipParams
2326 * @param array $premiumParams
2327 * @param bool $isPayLater
2329 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater) {
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 $contributionTypeID = 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'] = $contributionTypeID;
2388 $membershipParams['types_terms'] = $membershipTypeTerms;
2390 if (!empty($membershipParams['selectMembership'])) {
2392 $membershipLineItems = array();
2393 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2394 foreach ($this->_values
['fee'] as $key => $feeValues) {
2395 if ($feeValues['name'] == 'membership_amount') {
2396 $fieldId = $this->_params
['price_' . $key];
2397 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2398 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2403 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
2404 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2405 // we need to explicitly create a CMS user in case of free memberships
2406 // since it is done under processConfirm for paid memberships
2407 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2408 $membershipParams['cms_contactID'],
2409 'email-' . $this->_bltID