3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
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 $financialTypeID
59 * @param float $nonDeductibleAmount
60 * @param bool $pending
61 * @param array $paymentProcessorOutcome
62 * @param string $receiptDate
63 * @param int $recurringContributionID
67 public static function getContributionParams(
68 $params, $financialTypeID, $nonDeductibleAmount, $pending,
69 $paymentProcessorOutcome, $receiptDate, $recurringContributionID) {
70 $contributionParams = array(
71 'financial_type_id' => $financialTypeID,
72 'receive_date' => (CRM_Utils_Array
::value('receive_date', $params)) ? CRM_Utils_Date
::processDate($params['receive_date']) : date('YmdHis'),
73 'non_deductible_amount' => $nonDeductibleAmount,
74 'total_amount' => $params['amount'],
75 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $params),
76 'amount_level' => CRM_Utils_Array
::value('amount_level', $params),
77 'invoice_id' => $params['invoiceID'],
78 'currency' => $params['currencyID'],
79 'is_pay_later' => CRM_Utils_Array
::value('is_pay_later', $params, 0),
80 //configure cancel reason, cancel date and thankyou date
81 //from 'contribution' type profile if included
82 'cancel_reason' => CRM_Utils_Array
::value('cancel_reason', $params, 0),
83 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date
::format($params['cancel_date']) : NULL,
84 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date
::format($params['thankyou_date']) : NULL,
85 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
86 'skipLineItem' => CRM_Utils_Array
::value('skipLineItem', $params, 0),
89 if ($paymentProcessorOutcome) {
90 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor', $paymentProcessorOutcome);
92 if (!$pending && $paymentProcessorOutcome) {
93 $contributionParams +
= array(
94 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $paymentProcessorOutcome),
95 'net_amount' => CRM_Utils_Array
::value('net_amount', $paymentProcessorOutcome, $params['amount']),
96 'trxn_id' => $paymentProcessorOutcome['trxn_id'],
97 'receipt_date' => $receiptDate,
98 // also add financial_trxn details as part of fix for CRM-4724
99 'trxn_result_code' => CRM_Utils_Array
::value('trxn_result_code', $paymentProcessorOutcome),
103 // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
104 $contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money
::format($contributionParams['non_deductible_amount'], ' '));
105 $contributionParams['total_amount'] = trim(CRM_Utils_Money
::format($contributionParams['total_amount'], ' '));
107 if ($recurringContributionID) {
108 $contributionParams['contribution_recur_id'] = $recurringContributionID;
111 $contributionParams['contribution_status_id'] = $pending ?
2 : 1;
112 if (isset($contributionParams['invoice_id'])) {
113 $contributionParams['id'] = CRM_Core_DAO
::getFieldValue(
114 'CRM_Contribute_DAO_Contribution',
115 $contributionParams['invoice_id'],
121 return $contributionParams;
125 * Get non-deductible amount.
127 * This is a bit too much about wierd form interpretation to be this deep.
130 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
133 * @param array $params
134 * @param CRM_Financial_BAO_FinancialType $financialType
135 * @param bool $online
139 protected static function getNonDeductibleAmount($params, $financialType, $online) {
140 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
141 return $params['non_deductible_amount'];
144 if ($financialType->is_deductible
) {
145 if ($online && isset($params['selectProduct'])) {
146 $selectProduct = CRM_Utils_Array
::value('selectProduct', $params);
148 if (!$online && isset($params['product_name'][0])) {
149 $selectProduct = $params['product_name'][0];
151 // if there is a product - compare the value to the contribution amount
152 if (isset($selectProduct) &&
153 $selectProduct != 'no_thanks'
155 $productDAO = new CRM_Contribute_DAO_Product();
156 $productDAO->id
= $selectProduct;
157 $productDAO->find(TRUE);
158 // product value exceeds contribution amount
159 if ($params['amount'] < $productDAO->price
) {
160 $nonDeductibleAmount = $params['amount'];
161 return $nonDeductibleAmount;
163 // product value does NOT exceed contribution amount
165 return $productDAO->price
;
168 // contribution is deductible - but there is no product
173 // contribution is NOT deductible
175 return $params['amount'];
181 * Set variables up before form is built.
183 public function preProcess() {
184 $config = CRM_Core_Config
::singleton();
185 parent
::preProcess();
187 // lineItem isn't set until Register postProcess
188 $this->_lineItem
= $this->get('lineItem');
189 $this->_paymentProcessor
= $this->get('paymentProcessor');
190 $this->_params
= $this->controller
->exportValues('Main');
191 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
192 $this->_params
['amount'] = $this->get('amount');
193 if (isset($this->_params
['amount'])) {
194 $this->setFormAmountFields($this->_params
['priceSetId']);
197 $this->_params
['tax_amount'] = $this->get('tax_amount');
198 $this->_useForMember
= $this->get('useForMember');
200 if (isset($this->_params
['credit_card_exp_date'])) {
201 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
202 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
205 $this->_params
['currencyID'] = $config->defaultCurrency
;
207 if (!empty($this->_membershipBlock
)) {
208 $this->_params
['selectMembership'] = $this->get('selectMembership');
210 if (!empty($this->_paymentProcessor
) && $this->_paymentProcessor
['object']->supports('preApproval')) {
211 $preApprovalParams = $this->_paymentProcessor
['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
212 $this->_params
= array_merge($this->_params
, $preApprovalParams);
215 // We may have fetched some billing details from the getPreApprovalDetails function so we
216 // want to ensure we set this after that function has been called.
217 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $this->_params
, FALSE);
218 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
219 $this->_params
["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($this->_params
["billing_state_province_id-{$this->_bltID}"]);
221 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
222 $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
225 $this->_params
['is_pay_later'] = $this->get('is_pay_later');
226 $this->assign('is_pay_later', $this->_params
['is_pay_later']);
227 if ($this->_params
['is_pay_later']) {
228 $this->assign('pay_later_receipt', $this->_values
['pay_later_receipt']);
230 // if onbehalf-of-organization
231 if (!empty($this->_params
['hidden_onbehalf_profile'])) {
233 if (empty($this->_params
['org_option']) && empty($this->_params
['organization_id'])) {
234 if (!empty($this->_params
['onbehalfof_id'])) {
235 $this->_params
['organization_id'] = $this->_params
['onbehalfof_id'];
238 $this->_params
['organization_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_params
['onbehalf']['organization_name'], 'id', 'display_name');
242 $this->_params
['organization_name'] = $this->_params
['onbehalf']['organization_name'];
243 $addressBlocks = array(
249 'supplemental_address_1',
250 'supplemental_address_2',
251 'supplemental_address_3',
252 'postal_code_suffix',
258 $blocks = array('email', 'phone', 'im', 'url', 'openid');
259 foreach ($this->_params
['onbehalf'] as $loc => $value) {
260 $field = $typeId = NULL;
261 if (strstr($loc, '-')) {
262 list($field, $locType) = explode('-', $loc);
265 if (in_array($field, $addressBlocks)) {
266 if ($locType == 'Primary') {
267 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
268 $locType = $defaultLocationType->id
;
271 if ($field == 'country') {
272 $value = CRM_Core_PseudoConstant
::countryIsoCode($value);
274 elseif ($field == 'state_province') {
275 $value = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
279 if (isset($this->_params
['onbehalf_location']['address'])
280 && count($this->_params
['onbehalf_location']['address']) > 0
285 $this->_params
['onbehalf_location']['address'][$locType][$field] = $value;
286 if (empty($this->_params
['onbehalf_location']['address'][$locType]['is_primary'])) {
287 $this->_params
['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
289 $this->_params
['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
291 elseif (in_array($field, $blocks)) {
292 if (!$typeId ||
is_numeric($typeId)) {
293 $blockName = $fieldName = $field;
294 $locationType = 'location_type_id';
295 if ($locType == 'Primary') {
296 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
297 $locationValue = $defaultLocationType->id
;
300 $locationValue = $locType;
303 $phoneExtField = array();
305 if ($field == 'url') {
306 $blockName = 'website';
307 $locationType = 'website_type_id';
308 list($field, $locationValue) = explode('-', $loc);
310 elseif ($field == 'im') {
312 $locTypeId = 'provider_id';
313 $typeId = $this->_params
['onbehalf']["{$loc}-provider_id"];
315 elseif ($field == 'phone') {
316 list($field, $locType, $typeId) = explode('-', $loc);
317 $locTypeId = 'phone_type_id';
319 //check if extension field exists
320 $extField = str_replace('phone', 'phone_ext', $loc);
321 if (isset($this->_params
['onbehalf'][$extField])) {
322 $phoneExtField = array('phone_ext' => $this->_params
['onbehalf'][$extField]);
327 if (isset ($this->_params
['onbehalf_location'][$blockName])
328 && count($this->_params
['onbehalf_location'][$blockName]) > 0
332 if ($locationValue) {
333 $blockValues = array(
334 $fieldName => $value,
335 $locationType => $locationValue,
336 'is_primary' => $isPrimary,
340 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
342 if (!empty($phoneExtField)) {
343 $blockValues = array_merge($blockValues, $phoneExtField);
346 $this->_params
['onbehalf_location'][$blockName][] = $blockValues;
350 elseif (strstr($loc, 'custom')) {
351 if ($value && isset($this->_params
['onbehalf']["{$loc}_id"])) {
352 $value = $this->_params
['onbehalf']["{$loc}_id"];
354 $this->_params
['onbehalf_location']["{$loc}"] = $value;
357 if ($loc == 'contact_sub_type') {
358 $this->_params
['onbehalf_location'][$loc] = $value;
361 $this->_params
['onbehalf_location'][$field] = $value;
366 elseif (!empty($this->_values
['is_for_organization'])) {
367 // no on behalf of an organization, CRM-5519
368 // so reset loc blocks from main params.
374 if (isset($this->_params
[$blk])) {
375 unset($this->_params
[$blk]);
379 $this->setRecurringMembershipParams();
382 $params = $this->processPcp($this, $this->_params
);
383 $this->_params
= $params;
385 $this->_params
['invoiceID'] = $this->get('invoiceID');
387 //carry campaign from profile.
388 if (array_key_exists('contribution_campaign_id', $this->_params
)) {
389 $this->_params
['campaign_id'] = $this->_params
['contribution_campaign_id'];
392 // assign contribution page id to the template so we can add css class for it
393 $this->assign('contributionPageID', $this->_id
);
395 $this->set('params', $this->_params
);
399 * Build the form object.
401 public function buildQuickForm() {
402 $this->assignToTemplate();
404 $params = $this->_params
;
405 // make sure we have values for it
406 if ($this->_honor_block_is_active
&& !empty($params['soft_credit_type_id'])) {
408 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
410 $this->assign('honor_block_is_active', $this->_honor_block_is_active
);
411 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
412 CRM_Contribute_BAO_ContributionSoft
::formatHonoreeProfileFields($this, $params['honor'], $params['honoree_profile_id']);
414 $fieldTypes = array('Contact');
415 $fieldTypes[] = CRM_Core_BAO_UFGroup
::getContactType($params['honoree_profile_id']);
416 $this->buildCustom($params['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
418 $this->assign('receiptFromEmail', CRM_Utils_Array
::value('receipt_from_email', $this->_values
));
419 $amount_block_is_active = $this->get('amount_block_is_active');
420 $this->assign('amount_block_is_active', $amount_block_is_active);
422 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
423 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
425 $getTaxDetails = FALSE;
426 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
427 foreach ($this->_lineItem
as $key => $value) {
428 foreach ($value as $v) {
429 if (isset($v['tax_rate'])) {
430 if ($v['tax_rate'] != '') {
431 $getTaxDetails = TRUE;
436 $this->assign('getTaxDetails', $getTaxDetails);
437 $this->assign('taxTerm', $taxTerm);
438 $this->assign('totalTaxAmount', $params['tax_amount']);
440 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
441 $option = CRM_Utils_Array
::value('options_' . $params['selectProduct'], $params);
442 $productID = $params['selectProduct'];
443 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, FALSE,
446 $this->set('productID', $productID);
447 $this->set('option', $option);
449 $config = CRM_Core_Config
::singleton();
450 if (in_array('CiviMember', $config->enableComponents
)) {
451 if (isset($params['selectMembership']) &&
452 $params['selectMembership'] != 'no_thanks'
454 $this->buildMembershipBlock(
455 $this->_membershipContactID
,
457 $params['selectMembership'],
460 if (!empty($params['auto_renew'])) {
461 $this->assign('auto_renew', TRUE);
465 $this->assign('membershipBlock', FALSE);
468 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
469 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
471 if (!empty($params['hidden_onbehalf_profile'])) {
472 $ufJoinParams = array(
473 'module' => 'onBehalf',
474 'entity_table' => 'civicrm_contribution_page',
475 'entity_id' => $this->_id
,
477 $OnBehalfProfile = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
478 $profileId = $OnBehalfProfile[0];
480 $fieldTypes = array('Contact', 'Organization');
481 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
482 $fieldTypes = array_merge($fieldTypes, $contactSubType);
483 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
484 $fieldTypes = array_merge($fieldTypes, array('Membership'));
487 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
490 $this->buildCustom($profileId, 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
493 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
494 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
495 if ($this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
496 $this->assign('lineItem', $this->_lineItem
);
499 $this->assign('is_quick_config', 1);
500 $this->_params
['is_quick_config'] = 1;
502 $this->assign('priceSetID', $this->_priceSetId
);
503 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
504 if ($this->_paymentProcessor
&&
505 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('Google_Checkout', $paymentProcessorType)
506 && !$this->_params
['is_pay_later'] && !($this->_amount
== 0)
508 $this->_checkoutButtonName
= $this->getButtonName('next', 'checkout');
510 $this->_checkoutButtonName
,
511 $this->_paymentProcessor
['url_button'],
512 array('class' => 'crm-form-submit')
515 $this->addButtons(array(
518 'name' => ts('Go Back'),
524 if ($this->_contributeMode
== 'notify' ||
!$this->_values
['is_monetary'] ||
525 $this->_amount
<= 0.0 ||
$this->_params
['is_pay_later'] ||
526 ($this->_separateMembershipPayment
&& $this->_amount
<= 0.0)
528 $contribButton = ts('Continue');
529 $this->assign('button', ts('Continue'));
532 $contribButton = ts('Make Contribution');
533 $this->assign('button', ts('Make Contribution'));
535 $this->addButtons(array(
538 'name' => $contribButton,
539 'spacing' => ' ',
541 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name
. "','" . ts('Processing') . "');"),
545 'name' => ts('Go Back'),
552 $fields = array_fill_keys(array_keys($this->_fields
), 1);
553 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
555 $contact = $this->_params
;
556 foreach ($fields as $name => $dontCare) {
557 // Recursively set defaults for nested fields
558 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' ||
$name == 'honor')) {
559 foreach ($contact[$name] as $fieldName => $fieldValue) {
560 if (is_array($fieldValue) && !in_array($this->_fields
[$name][$fieldName]['html_type'], array(
565 foreach ($fieldValue as $key => $value) {
566 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
570 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
574 elseif (isset($contact[$name])) {
575 $defaults[$name] = $contact[$name];
576 if (substr($name, 0, 7) == 'custom_') {
577 $timeField = "{$name}_time";
578 if (isset($contact[$timeField])) {
579 $defaults[$timeField] = $contact[$timeField];
581 if (isset($contact["{$name}_id"])) {
582 $defaults["{$name}_id"] = $contact["{$name}_id"];
585 elseif (in_array($name, array(
589 )) && !empty($contact[$name . '_custom'])
591 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
596 $this->assign('useForMember', $this->get('useForMember'));
598 $this->setDefaults($defaults);
606 * Since we are only showing elements in frozen mode no help display needed.
610 public function getAction() {
611 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
612 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
615 return CRM_Core_Action
::VIEW
;
620 * Set default values for the form.
622 * Note that in edit/view mode
623 * the default values are retrieved from the database
625 public function setDefaultValues() {
631 public function postProcess() {
632 $contactID = $this->getContactID();
633 $result = $this->processFormSubmission($contactID);
634 if (is_array($result) && !empty($result['is_payment_failure'])) {
635 // We will probably have the function that gets this error throw an exception on the next round of refactoring.
636 CRM_Core_Session
::singleton()->setStatus(ts("Payment Processor Error message :") .
637 $result['error']->getMessage());
638 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
639 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
642 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
643 $this->set('params', $this->_params
);
647 * Wrangle financial type ID.
649 * 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
650 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
652 * Comments from previous refactor indicate doubt as to what was going on.
654 * @param int $contributionTypeId
656 * @return null|string
658 public function wrangleFinancialTypeID($contributionTypeId) {
659 if (isset($paymentParams['financial_type'])) {
660 $contributionTypeId = $paymentParams['financial_type'];
662 elseif (!empty($this->_values
['pledge_id'])) {
663 $contributionTypeId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
664 $this->_values
['pledge_id'],
668 return $contributionTypeId;
674 * @param array $premiumParams
675 * @param CRM_Contribute_BAO_Contribution $contribution
677 protected function postProcessPremium($premiumParams, $contribution) {
678 $hour = $minute = $second = 0;
679 // assigning Premium information to receipt tpl
680 $selectProduct = CRM_Utils_Array
::value('selectProduct', $premiumParams);
681 if ($selectProduct &&
682 $selectProduct != 'no_thanks'
684 $startDate = $endDate = "";
685 $this->assign('selectPremium', TRUE);
686 $productDAO = new CRM_Contribute_DAO_Product();
687 $productDAO->id
= $selectProduct;
688 $productDAO->find(TRUE);
689 $this->assign('product_name', $productDAO->name
);
690 $this->assign('price', $productDAO->price
);
691 $this->assign('sku', $productDAO->sku
);
692 $this->assign('option', CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams));
694 $periodType = $productDAO->period_type
;
697 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
698 $duration_unit = $productDAO->duration_unit
;
699 $duration_interval = $productDAO->duration_interval
;
700 if ($periodType == 'rolling') {
701 $startDate = date('Y-m-d');
703 elseif ($periodType == 'fixed') {
704 if ($fixed_period_start_day) {
705 $date = explode('-', date('Y-m-d'));
706 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
707 $day = substr($fixed_period_start_day, -2) . "<br/>";
709 $startDate = $year . '-' . $month . '-' . $day;
712 $startDate = date('Y-m-d');
716 $date = explode('-', $startDate);
721 switch ($duration_unit) {
723 $year = $year +
$duration_interval;
727 $month = $month +
$duration_interval;
731 $day = $day +
$duration_interval;
735 $day = $day +
($duration_interval * 7);
737 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
738 $this->assign('start_date', $startDate);
739 $this->assign('end_date', $endDate);
742 $dao = new CRM_Contribute_DAO_Premium();
743 $dao->entity_table
= 'civicrm_contribution_page';
744 $dao->entity_id
= $this->_id
;
746 $this->assign('contact_phone', $dao->premiums_contact_phone
);
747 $this->assign('contact_email', $dao->premiums_contact_email
);
749 //create Premium record
751 'product_id' => $premiumParams['selectProduct'],
752 'contribution_id' => $contribution->id
,
753 'product_option' => CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams),
755 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
756 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
758 if (!empty($premiumParams['selectProduct'])) {
759 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
760 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
761 $daoPremiumsProduct->premiums_id
= $dao->id
;
762 $daoPremiumsProduct->find(TRUE);
763 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
766 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
767 $daoContrProd->contribution_id
= $contribution->id
;
768 if ($daoContrProd->find(TRUE)) {
769 $params['id'] = $daoContrProd->id
;
772 CRM_Contribute_BAO_Contribution
::addPremium($params);
773 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
775 'cost' => $productDAO->cost
,
776 'currency' => $productDAO->currency
,
777 'financial_type_id' => $params['financial_type_id'],
778 'contributionId' => $contribution->id
,
780 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
783 elseif ($selectProduct == 'no_thanks') {
785 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
786 $daoContrProd->contribution_id
= $contribution->id
;
787 if ($daoContrProd->find(TRUE)) {
788 $daoContrProd->delete();
794 * Process the contribution.
796 * @param CRM_Core_Form $form
797 * @param array $params
798 * @param array $result
799 * @param array $contributionParams
800 * Parameters to be passed to contribution create action.
801 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
802 * passed consistently & 2) documenting them here.
807 * - contribution_page_id
810 * - thankyou_date (not all forms will set this)
812 * @param CRM_Financial_DAO_FinancialType $financialType
813 * @param bool $pending
814 * The intention is this should always be TRUE and we are refactoring towards any completion happening elsewhere.
815 * @param bool $online
816 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
818 * @param int $billingLocationID
819 * ID of billing location type.
821 * @return \CRM_Contribute_DAO_Contribution
824 public static function processFormContribution(
834 $transaction = new CRM_Core_Transaction();
835 $contactID = $contributionParams['contact_id'];
837 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
838 // How do these vary from params? These are currently passed to
839 // - custom data function....
840 $formParams = $form->_params
;
841 $isSeparateMembershipPayment = empty($formParams['separate_membership_payment']) ?
FALSE : TRUE;
842 $pledgeID = empty($formParams['pledge_id']) ?
NULL : $formParams['pledge_id'];
843 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
844 (!empty($formParams['is_pledge']) ||
$pledgeID)) {
851 // add these values for the recurringContrib function ,CRM-10188
852 $params['financial_type_id'] = $financialType->id
;
854 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
856 //@todo - this is being set from the form to resolve CRM-10188 - an
857 // eNotice caused by it not being set @ the front end
858 // however, we then get it being over-written with null for backend contributions
859 // a better fix would be to set the values in the respective forms rather than require
860 // a function being shared by two forms to deal with their respective values
861 // moving it to the BAO & not taking the $form as a param would make sense here.
862 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
863 $params['is_email_receipt'] = $isEmailReceipt;
865 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType, $online);
866 $nonDeductibleAmount = self
::getNonDeductibleAmount($params, $financialType, $online);
868 $now = date('YmdHis');
869 $receiptDate = CRM_Utils_Array
::value('receipt_date', $params);
870 if ($isEmailReceipt) {
874 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
875 if (!empty($params['pcp_made_through_id']) ||
!empty($params['soft_credit_to'])) {
877 if (!empty($params['pcp_made_through_id'])) {
878 $contributionParams['soft_credit_to'] = CRM_Core_DAO
::getFieldValue(
880 $params['pcp_made_through_id'],
883 // Pass these details onto with the contribution to make them
884 // available at hook_post_process, CRM-8908
886 $params['soft_credit_to'] = $contributionParams['soft_credit_to'];
889 $contributionParams['soft_credit_to'] = CRM_Utils_Array
::value('soft_credit_to', $params);
893 if (isset($params['amount'])) {
894 $contributionParams = array_merge(self
::getContributionParams(
895 $params, $financialType->id
, $nonDeductibleAmount, $pending,
896 $result, $receiptDate,
897 $recurringContributionID), $contributionParams
899 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
901 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
902 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
904 $dataArray = array();
905 // @todo - interrogate the line items passed in on the params array.
906 // No reason to assume line items will be set on the form.
907 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
908 foreach ($lineItemValue as $key => $value) {
909 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
910 if (isset($dataArray[$value['tax_rate']])) {
911 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
914 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
919 $smarty = CRM_Core_Smarty
::singleton();
920 $smarty->assign('dataArray', $dataArray);
921 $smarty->assign('totalTaxAmount', $params['tax_amount']);
923 if (is_a($contribution, 'CRM_Core_Error')) {
924 $message = CRM_Core_Error
::getMessages($contribution);
925 CRM_Core_Error
::fatal($message);
928 // lets store it in the form variable so postProcess hook can get to this and use it
929 $form->_contributionID
= $contribution->id
;
932 //CRM-13981, processing honor contact into soft-credit contribution
933 CRM_Contact_Form_ProfileContact
::postProcess($form);
935 // process soft credit / pcp pages
936 CRM_Contribute_Form_Contribution_Confirm
::processPcpSoft($params, $contribution);
938 //handle pledge stuff.
941 //when user doing pledge payments.
942 //update the schedule when payment(s) are made
943 foreach ($form->_params
['pledge_amount'] as $paymentId => $dontCare) {
944 $scheduledAmount = CRM_Core_DAO
::getFieldValue(
945 'CRM_Pledge_DAO_PledgePayment',
951 $pledgePaymentParams = array(
953 'contribution_id' => $contribution->id
,
954 'status_id' => $contribution->contribution_status_id
,
955 'actual_amount' => $scheduledAmount,
958 CRM_Pledge_BAO_PledgePayment
::add($pledgePaymentParams);
961 //update pledge status according to the new payment statuses
962 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID);
965 //when user creating pledge record.
966 $pledgeParams = array();
967 $pledgeParams['contact_id'] = $contribution->contact_id
;
968 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount
;
969 $pledgeParams['contribution_id'] = $contribution->id
;
970 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id
;
971 $pledgeParams['financial_type_id'] = $contribution->financial_type_id
;
972 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
973 $pledgeParams['installments'] = $params['pledge_installments'];
974 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
975 if ($pledgeParams['frequency_unit'] == 'month') {
976 $pledgeParams['frequency_day'] = intval(date("d"));
979 $pledgeParams['frequency_day'] = 1;
981 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
982 $pledgeParams['status_id'] = $contribution->contribution_status_id
;
983 $pledgeParams['max_reminders'] = $form->_values
['max_reminders'];
984 $pledgeParams['initial_reminder_day'] = $form->_values
['initial_reminder_day'];
985 $pledgeParams['additional_reminder_day'] = $form->_values
['additional_reminder_day'];
986 $pledgeParams['is_test'] = $contribution->is_test
;
987 $pledgeParams['acknowledge_date'] = date('Ymd');
988 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
990 //inherit campaign from contirb page.
991 $pledgeParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $contributionParams);
993 $pledge = CRM_Pledge_BAO_Pledge
::create($pledgeParams);
995 $form->_params
['pledge_id'] = $pledge->id
;
997 //send acknowledgment email. only when pledge is created
999 //build params to send acknowledgment.
1000 $pledgeParams['id'] = $pledge->id
;
1001 $pledgeParams['receipt_from_name'] = $form->_values
['receipt_from_name'];
1002 $pledgeParams['receipt_from_email'] = $form->_values
['receipt_from_email'];
1004 //scheduled amount will be same as installment_amount.
1005 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
1007 //get total pledge amount.
1008 $pledgeParams['total_pledge_amount'] = $pledge->amount
;
1010 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($form, $pledgeParams);
1015 if ($online && $contribution) {
1016 CRM_Core_BAO_CustomValueTable
::postProcess($form->_params
,
1017 'civicrm_contribution',
1022 elseif ($contribution) {
1023 //handle custom data.
1024 $params['contribution_id'] = $contribution->id
;
1025 if (!empty($params['custom']) &&
1026 is_array($params['custom']) &&
1027 !is_a($contribution, 'CRM_Core_Error')
1029 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
1033 if ($contribution && !empty($params['contribution_note'])) {
1034 $noteParams = array(
1035 'entity_table' => 'civicrm_contribution',
1036 'note' => $params['contribution_note'],
1037 'entity_id' => $contribution->id
,
1038 'contact_id' => $contribution->contact_id
,
1039 'modified_date' => date('Ymd'),
1042 CRM_Core_BAO_Note
::add($noteParams, array());
1045 if (isset($params['related_contact'])) {
1046 $contactID = $params['related_contact'];
1048 elseif (isset($params['cms_contactID'])) {
1049 $contactID = $params['cms_contactID'];
1052 //create contribution activity w/ individual and target
1053 //activity w/ organisation contact id when onbelf, CRM-4027
1054 $targetContactID = NULL;
1055 if (!empty($params['hidden_onbehalf_profile'])) {
1056 $targetContactID = $contribution->contact_id
;
1057 $contribution->contact_id
= $contactID;
1060 // create an activity record
1061 if ($contribution) {
1062 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
1065 $transaction->commit();
1066 // CRM-13074 - create the CMSUser after the transaction is completed as it
1067 // is not appropriate to delete a valid contribution if a user create problem occurs
1068 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($params,
1070 'email-' . $billingLocationID
1072 return $contribution;
1076 * Create the recurring contribution record.
1078 * @param CRM_Core_Form $form
1079 * @param array $params
1080 * @param int $contactID
1081 * @param string $contributionType
1082 * @param bool $online
1086 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1087 // return if this page is not set for recurring
1088 // or the user has not chosen the recurring option
1090 //this is online case validation.
1091 if ((empty($form->_values
['is_recur']) && $online) ||
empty($params['is_recur'])) {
1095 $recurParams = array('contact_id' => $contactID);
1096 $recurParams['amount'] = CRM_Utils_Array
::value('amount', $params);
1097 $recurParams['auto_renew'] = CRM_Utils_Array
::value('auto_renew', $params);
1098 $recurParams['frequency_unit'] = CRM_Utils_Array
::value('frequency_unit', $params);
1099 $recurParams['frequency_interval'] = CRM_Utils_Array
::value('frequency_interval', $params);
1100 $recurParams['installments'] = CRM_Utils_Array
::value('installments', $params);
1101 $recurParams['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $params);
1102 $recurParams['currency'] = CRM_Utils_Array
::value('currency', $params);
1104 // CRM-14354: For an auto-renewing membership with an additional contribution,
1105 // if separate payments is not enabled, make sure only the membership fee recurs
1106 if (!empty($form->_membershipBlock
)
1107 && $form->_membershipBlock
['is_separate_payment'] === '0'
1108 && isset($params['selectMembership'])
1109 && $form->_values
['is_allow_other_amount'] == '1'
1111 && !empty($form->_membershipTypeValues
)
1112 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1114 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1117 $recurParams['is_test'] = 0;
1118 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1119 (isset($form->_mode
) && ($form->_mode
== 'test'))
1121 $recurParams['is_test'] = 1;
1124 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1125 if (!empty($params['receive_date'])) {
1126 $recurParams['start_date'] = $params['receive_date'];
1128 $recurParams['invoice_id'] = CRM_Utils_Array
::value('invoiceID', $params);
1129 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1130 $recurParams['payment_processor_id'] = CRM_Utils_Array
::value('payment_processor_id', $params);
1131 $recurParams['is_email_receipt'] = CRM_Utils_Array
::value('is_email_receipt', $params);
1132 // we need to add a unique trxn_id to avoid a unique key error
1133 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1134 $recurParams['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params, $params['invoiceID']);
1135 $recurParams['financial_type_id'] = $contributionType->id
;
1137 if (!$online ||
$form->_values
['is_monetary']) {
1138 $recurParams['payment_instrument_id'] = 1;
1141 $campaignId = CRM_Utils_Array
::value('campaign_id', $params);
1143 if (!array_key_exists('campaign_id', $params)) {
1144 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1147 $recurParams['campaign_id'] = $campaignId;
1149 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1150 if (is_a($recurring, 'CRM_Core_Error')) {
1151 CRM_Core_Error
::displaySessionError($recurring);
1152 $urlString = 'civicrm/contribute/transact';
1153 $urlParams = '_qf_Main_display=true';
1154 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1155 $urlString = 'civicrm/contact/view/contribution';
1156 $urlParams = "action=add&cid={$form->_contactID}";
1158 $urlParams .= "&mode={$form->_mode}";
1161 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1164 return $recurring->id
;
1168 * Add on behalf of organization and it's location.
1170 * This situation occurs when on behalf of is enabled for the contribution page and the person
1171 * signing up does so on behalf of an organization.
1173 * @param array $behalfOrganization
1174 * array of organization info.
1175 * @param int $contactID
1176 * individual contact id. One.
1177 * who is doing the process of signup / contribution.
1179 * @param array $values
1180 * form values array.
1181 * @param array $params
1182 * @param array $fields
1183 * Array of fields from the onbehalf profile relevant to the organization.
1185 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1186 $isCurrentEmployer = FALSE;
1189 if (!empty($behalfOrganization['organization_id']) && empty($behalfOrganization['org_option'])) {
1190 $orgID = $behalfOrganization['organization_id'];
1191 unset($behalfOrganization['organization_id']);
1192 $isCurrentEmployer = TRUE;
1195 // formalities for creating / editing organization.
1196 $behalfOrganization['contact_type'] = 'Organization';
1198 // get the relationship type id
1199 $relType = new CRM_Contact_DAO_RelationshipType();
1200 $relType->name_a_b
= 'Employee of';
1201 $relType->find(TRUE);
1202 $relTypeId = $relType->id
;
1204 // keep relationship params ready
1205 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1206 $relParams['is_permission_a_b'] = 1;
1207 $relParams['is_active'] = 1;
1210 // check if matching organization contact exists
1211 $dedupeParams = CRM_Dedupe_Finder
::formatParams($behalfOrganization, 'Organization');
1212 $dedupeParams['check_permission'] = FALSE;
1213 $dupeIDs = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1215 // CRM-6243 says to pick the first org even if more than one match
1216 if (count($dupeIDs) >= 1) {
1217 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1218 // don't allow name edit
1219 unset($behalfOrganization['organization_name']);
1223 // if found permissioned related organization, allow location edit
1224 $behalfOrganization['contact_id'] = $orgID;
1225 // don't allow name edit
1226 unset($behalfOrganization['organization_name']);
1229 // handling for image url
1230 if (!empty($behalfOrganization['image_URL'])) {
1231 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1234 // create organization, add location
1235 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1236 NULL, NULL, 'Organization'
1238 // create relationship
1239 $relParams['contact_check'][$orgID] = 1;
1240 $cid = array('contact' => $contactID);
1241 CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relParams, $cid);
1243 // if multiple match - send a duplicate alert
1244 if ($dupeIDs && (count($dupeIDs) > 1)) {
1245 $values['onbehalf_dupe_alert'] = 1;
1247 $params['onbehalf_dupe_alert'] = 1;
1250 // make sure organization-contact-id is considered for recording
1251 // contribution/membership etc..
1252 if ($contactID != $orgID) {
1253 // take a note of contact-id, so we can send the
1254 // receipt to individual contact as well.
1256 // required for mailing/template display ..etc
1257 $values['related_contact'] = $contactID;
1259 $params['related_contact'] = $contactID;
1261 //make this employee of relationship as current
1262 //employer / employee relationship, CRM-3532
1263 if ($isCurrentEmployer &&
1264 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1266 $isCurrentEmployer = FALSE;
1269 if (!$isCurrentEmployer && $orgID) {
1270 //build current employer params
1271 $currentEmpParams[$contactID] = $orgID;
1272 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1275 // contribution / signup will be done using this
1277 $contactID = $orgID;
1282 * Function used to save pcp / soft credit entry.
1284 * This is used by contribution and also event pcps
1286 * @param array $params
1287 * @param object $contribution
1288 * Contribution object.
1290 public static function processPcpSoft(&$params, &$contribution) {
1291 // Add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1292 if (!empty($params['soft_credit_to'])) {
1293 $contributionSoftParams = array();
1295 'pcp_display_in_roll',
1296 'pcp_roll_nickname',
1297 'pcp_personal_note',
1300 if (!empty($params[$val])) {
1301 $contributionSoftParams[$val] = $params[$val];
1305 $contributionSoftParams['contact_id'] = $params['soft_credit_to'];
1306 // add contribution id
1307 $contributionSoftParams['contribution_id'] = $contribution->id
;
1309 $contributionSoftParams['pcp_id'] = $params['pcp_made_through_id'];
1311 $contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
1313 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
1315 //Send notification to owner for PCP
1316 if ($contributionSoft->id
&& $contributionSoft->pcp_id
) {
1317 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
1323 * Function used to send notification mail to pcp owner.
1325 * This is used by contribution and also event PCPs.
1327 * @param object $contribution
1328 * @param object $contributionSoft
1329 * Contribution object.
1331 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1332 $params = array('id' => $contributionSoft->pcp_id
);
1333 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1334 $ownerNotifyID = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1336 if ($ownerNotifyID != CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1337 (($ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1338 CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id
, 'is_notify')) ||
1339 $ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1340 $pcpInfoURL = CRM_Utils_System
::url('civicrm/pcp/info',
1341 "reset=1&id={$contributionSoft->pcp_id}",
1342 TRUE, NULL, FALSE, TRUE
1344 // set email in the template here
1345 // get the billing location type
1346 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1347 $billingLocationTypeId = array_search('Billing', $locationTypes);
1349 if ($billingLocationTypeId) {
1350 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
, FALSE, $billingLocationTypeId);
1352 // get primary location email if no email exist( for billing location).
1354 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
);
1356 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft->contact_id
);
1358 'page_title' => $pcpInfo['title'],
1359 'receive_date' => $contribution->receive_date
,
1360 'total_amount' => $contributionSoft->amount
,
1361 'donors_display_name' => $donorName,
1362 'donors_email' => $email,
1363 'pcpInfoURL' => $pcpInfoURL,
1364 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll
,
1365 'currency' => $contributionSoft->currency
,
1367 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1368 $sendTemplateParams = array(
1369 'groupName' => 'msg_tpl_workflow_contribution',
1370 'valueName' => 'pcp_owner_notify',
1371 'contactId' => $contributionSoft->contact_id
,
1372 'toEmail' => $ownerEmail,
1373 'toName' => $ownerName,
1374 'from' => "$domainValues[0] <$domainValues[1]>",
1375 'tplParams' => $tplParams,
1376 'PDFFilename' => 'receipt.pdf',
1378 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1383 * Function used to se pcp related defaults / params.
1385 * This is used by contribution and also event PCPs
1387 * @param CRM_Core_Form $page
1389 * @param array $params
1393 public static function processPcp(&$page, $params) {
1394 $params['pcp_made_through_id'] = $page->_pcpId
;
1395 $page->assign('pcpBlock', TRUE);
1396 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1397 $params['pcp_roll_nickname'] = ts('Anonymous');
1398 $params['pcp_is_anonymous'] = 1;
1401 $params['pcp_is_anonymous'] = 0;
1404 'pcp_display_in_roll',
1406 'pcp_roll_nickname',
1407 'pcp_personal_note',
1409 if (!empty($params[$val])) {
1410 $page->assign($val, $params[$val]);
1418 * Process membership.
1420 * @param array $membershipParams
1421 * @param int $contactID
1422 * @param array $customFieldsFormatted
1423 * @param array $fieldTypes
1424 * @param array $premiumParams
1425 * @param array $membershipLineItems
1426 * Line items specifically relating to memberships.
1427 * @param bool $isPayLater
1429 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1430 $membershipLineItems, $isPayLater) {
1432 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1433 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1434 $membershipType = empty($membershipTypes) ?
array() : reset($membershipTypes);
1435 $isPending = $this->getIsPending();
1437 $this->assign('membership_name', CRM_Utils_Array
::value('name', $membershipType));
1439 $isPaidMembership = FALSE;
1440 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1441 //amount must be greater than zero for
1442 //adding contribution record to contribution table.
1443 //this condition arises when separate membership payment is
1444 //enabled and contribution amount is not selected. fix for CRM-3010
1445 $isPaidMembership = TRUE;
1447 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1449 if ($this->_values
['amount_block_is_active']) {
1450 $financialTypeID = $this->_values
['financial_type_id'];
1453 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $membershipType, CRM_Utils_Array
::value('financial_type_id', $membershipParams));
1456 if (CRM_Utils_Array
::value('membership_source', $this->_params
)) {
1457 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1460 $this->postProcessMembership($membershipParams, $contactID,
1461 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1462 $membershipLineItems, $isPayLater, $isPending);
1464 $this->assign('membership_assign', TRUE);
1465 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1469 * Process the Memberships.
1471 * @param array $membershipParams
1472 * Array of membership fields.
1473 * @param int $contactID
1475 * @param CRM_Contribute_Form_Contribution_Confirm $form
1476 * Confirmation form object.
1478 * @param array $premiumParams
1479 * @param null $customFieldsFormatted
1480 * @param null $includeFieldTypes
1482 * @param array $membershipDetails
1484 * @param array $membershipTypeIDs
1486 * @param bool $isPaidMembership
1487 * @param array $membershipID
1489 * @param bool $isProcessSeparateMembershipTransaction
1491 * @param int $financialTypeID
1492 * @param array $membershipLineItems
1493 * Line items specific to membership payment that is separate to contribution.
1494 * @param bool $isPayLater
1495 * @param bool $isPending
1497 * @throws \CRM_Core_Exception
1499 protected function postProcessMembership(
1500 $membershipParams, $contactID, &$form, $premiumParams,
1501 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1502 $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending) {
1503 $membershipContribution = NULL;
1504 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1505 $errors = $createdMemberships = $paymentResult = array();
1507 if ($isPaidMembership) {
1508 if ($isProcessSeparateMembershipTransaction) {
1509 // If we have 2 transactions only one can use the invoice id.
1510 $membershipParams['invoiceID'] .= '-2';
1513 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1520 if (!empty($paymentResult['contribution'])) {
1521 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1522 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1523 $membershipContribution = $paymentResult['contribution'];
1524 // Save the contribution ID so that I can be used in email receipts
1525 // For example, if you need to generate a tax receipt for the donation only.
1526 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1530 if ($isProcessSeparateMembershipTransaction) {
1532 $form->_lineItem
= $membershipLineItems;
1533 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1534 unset($membershipParams['is_recur']);
1536 $membershipContribution = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams,
1537 $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1539 catch (CRM_Core_Exception
$e) {
1540 $errors[2] = $e->getMessage();
1541 $membershipContribution = NULL;
1546 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1547 $membershipContributionID = $membershipContribution->id
;
1550 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1551 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1552 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1554 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1555 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1556 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1557 foreach ($membershipTypeIDs as $memType) {
1558 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1559 if (!empty($membershipContribution)) {
1560 $pendingStatus = CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name');
1561 $pending = ($membershipContribution->contribution_status_id
== $pendingStatus) ?
TRUE : FALSE;
1564 $pending = $isPending;
1566 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
1568 $membershipSource = NULL;
1569 if (!empty($form->_params
['membership_source'])) {
1570 $membershipSource = $form->_params
['membership_source'];
1572 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
1573 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
1576 if (isset($form->_params
)) {
1577 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
1580 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
1581 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
1582 if (!array_key_exists('campaign_id', $form->_params
)) {
1583 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1587 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership
::renewMembership(
1588 $contactID, $memType, $isTest,
1589 date('YmdHis'), CRM_Utils_Array
::value('cms_contactID', $membershipParams),
1590 $customFieldsFormatted,
1591 $numTerms, $membershipID, $pending,
1592 $contributionRecurID, $membershipSource, $isPayLater, $campaignId
1594 $form->set('renewal_mode', $renewalMode);
1595 if (!empty($dates)) {
1596 $form->assign('mem_start_date',
1597 CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d')
1599 $form->assign('mem_end_date',
1600 CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d')
1604 if (!empty($membershipContribution)) {
1605 // update recurring id for membership record
1606 CRM_Member_BAO_Membership
::updateRecurMembership($membership, $membershipContribution);
1607 CRM_Member_BAO_Membership
::linkMembershipPayment($membership, $membershipContribution);
1610 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1611 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1612 if (!empty($priceFieldOp['membership_type_id']) &&
1613 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1615 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1616 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1617 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1620 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1623 $form->_values
['lineItem'] = $form->_lineItem
;
1624 $form->assign('lineItem', $form->_lineItem
);
1628 if (!empty($errors)) {
1629 $message = $this->compileErrorMessage($errors);
1630 throw new CRM_Core_Exception($message);
1632 $form->_params
['createdMembershipIDs'] = array();
1634 // CRM-7851 - Moved after processing Payment Errors
1635 //@todo - the reasoning for this being here seems a little outdated
1636 foreach ($createdMemberships as $createdMembership) {
1637 CRM_Core_BAO_CustomValueTable
::postProcess(
1639 'civicrm_membership',
1640 $createdMembership->id
,
1643 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1645 if (count($createdMemberships) == 1) {
1646 //presumably this is only relevant for exactly 1 membership
1647 $form->_params
['membershipID'] = $createdMembership->id
;
1650 //CRM-15232: Check if membership is created and on the basis of it use
1651 //membership receipt template to send payment receipt
1652 if (count($createdMemberships)) {
1653 $form->_values
['isMembership'] = TRUE;
1655 if (isset($membershipContributionID)) {
1656 $form->_values
['contribution_id'] = $membershipContributionID;
1658 if ($form->_contributeMode
) {
1659 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1660 // call postProcess hook before leaving
1661 $form->postProcessHook();
1663 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1664 $paymentActionResult = $payment->doPayment($form->_params
, 'contribute');
1666 if (CRM_Utils_Array
::value('payment_status_id', $paymentActionResult) == 1) {
1667 // Refer to CRM-16737. Payment processors 'should' return payment_status_id
1668 // to denote the outcome of the transaction.
1670 civicrm_api3('contribution', 'completetransaction', array(
1671 'id' => $paymentResult['contribution']->id
,
1672 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $paymentActionResult, $paymentResult['contribution']->trxn_id
),
1673 'is_transactional' => FALSE,
1674 'payment_processor_id' => $form->_paymentProcessor
['id'],
1677 catch (CiviCRM_API3_Exception
$e) {
1678 if ($e->getErrorCode() != 'contribution_completed') {
1679 throw new CRM_Core_Exception('Failed to update contribution in database');
1683 // Do not send an email if Recurring transaction is done via Direct Mode
1684 // Email will we sent when the IPN is received.
1688 //finally send an email receipt
1689 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1697 * Turn array of errors into message string.
1699 * @param array $errors
1703 protected function compileErrorMessage($errors) {
1704 foreach ($errors as $error) {
1705 if (is_string($error)) {
1706 $message[] = $error;
1709 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1713 * Where a second separate financial transaction is supported we will process it here.
1715 * @param int $contactID
1716 * @param CRM_Contribute_Form_Contribution_Confirm $form
1717 * @param array $tempParams
1718 * @param bool $isTest
1719 * @param array $lineItems
1720 * @param $minimumFee
1721 * @param int $financialTypeID
1723 * @throws CRM_Core_Exception
1725 * @return CRM_Contribute_BAO_Contribution
1727 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1729 $financialType = new CRM_Financial_DAO_FinancialType();
1730 $financialType->id
= $financialTypeID;
1731 $financialType->find(TRUE);
1732 $tempParams['amount'] = $minimumFee;
1733 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1736 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
1737 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1738 // now we compensate here.
1739 if (empty($form->_paymentProcessor
['object'])) {
1740 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1743 $payment = $form->_paymentProcessor
['object'];
1745 $result = $payment->doPayment($tempParams, 'contribute');
1748 //assign receive date when separate membership payment
1749 //and contribution amount not selected.
1750 if ($form->_amount
== 0) {
1751 $now = date('YmdHis');
1752 $form->_params
['receive_date'] = $now;
1753 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1754 $form->set('params', $form->_params
);
1755 $form->assign('receive_date', $receiveDate);
1758 $form->set('membership_trx_id', $result['trxn_id']);
1759 $form->set('membership_amount', $minimumFee);
1761 $form->assign('membership_trx_id', $result['trxn_id']);
1762 $form->assign('membership_amount', $minimumFee);
1764 // we don't need to create the user twice, so lets disable cms_create_account
1765 // irrespective of the value, CRM-2888
1766 $tempParams['cms_create_account'] = 0;
1768 //CRM-16165, scenarios are
1769 // 1) If contribution is_pay_later and if contribution amount is > 0.0 we set pending = TRUE, vice-versa FALSE
1770 // 2) If not pay later but auto-renewal membership is chosen then pending = TRUE as it later triggers
1771 // pending recurring contribution, vice-versa FALSE
1772 $pending = $form->_params
['is_pay_later'] ?
(($minimumFee > 0.0) ?
TRUE : FALSE) : (!empty($form->_params
['auto_renew']) ?
TRUE : FALSE);
1774 //set this variable as we are not creating pledge for
1775 //separate membership payment contribution.
1776 //so for differentiating membership contribution from
1777 //main contribution.
1778 $form->_params
['separate_membership_payment'] = 1;
1779 $contributionParams = array(
1780 'contact_id' => $contactID,
1781 'line_item' => $lineItems,
1782 'is_test' => $isTest,
1783 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $tempParams, CRM_Utils_Array
::value('campaign_id',
1785 'contribution_page_id' => $form->_id
,
1786 'source' => CRM_Utils_Array
::value('source', $tempParams, CRM_Utils_Array
::value('description', $tempParams)),
1788 $isMonetary = !empty($form->_values
['is_monetary']);
1790 if (empty($paymentParams['is_pay_later'])) {
1791 // @todo look up payment_instrument_id on payment processor table.
1792 $contributionParams['payment_instrument_id'] = 1;
1795 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
1798 $contributionParams,
1804 return $membershipContribution;
1808 * Is the payment a pending payment.
1810 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1811 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1816 protected function getIsPending() {
1817 if (((isset($this->_contributeMode
)) ||
!empty
1818 ($this->_params
['is_pay_later'])
1820 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1828 * Are we going to do 2 financial transactions.
1830 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1832 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1834 * @param int $formID
1835 * @param bool $amountBlockActiveOnForm
1839 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1840 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1841 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1848 * This function sets the fields.
1850 * - $this->_params['amount_level']
1851 * - $this->_params['selectMembership']
1852 * And under certain circumstances sets
1853 * $this->_params['amount'] = null;
1855 * @param int $priceSetID
1857 public function setFormAmountFields($priceSetID) {
1858 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1859 $priceField = new CRM_Price_DAO_PriceField();
1860 $priceField->price_set_id
= $priceSetID;
1861 $priceField->orderBy('weight');
1862 $priceField->find();
1863 $paramWeDoNotUnderstand = NULL;
1865 while ($priceField->fetch()) {
1866 if ($priceField->name
== "contribution_amount") {
1867 $paramWeDoNotUnderstand = $priceField->id
;
1869 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1870 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1871 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1872 $this->_params
["price_{$priceField->id}"], 'label');
1874 if ($priceField->name
== "membership_amount") {
1875 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1876 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1879 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1880 // as membership amount.
1881 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1882 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1883 // so we should merge them together
1884 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1885 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1887 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
)
1888 && !empty($this->_values
['fee'][$priceField->id
])
1889 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1890 && CRM_Utils_Array
::value("price_{$paramWeDoNotUnderstand}", $this->_params
) < 1
1891 && empty($this->_params
["price_{$priceField->id}"])
1893 $this->_params
['amount'] = NULL;
1896 // Fix for CRM-14375 - If we are using separate payments and "no
1897 // thank you" is selected for the additional contribution, set
1898 // contribution amount to be null, so that it will not show
1899 // contribution amount same as membership amount.
1900 //@todo - merge with section above
1901 if ($this->_membershipBlock
['is_separate_payment']
1902 && !empty($this->_values
['fee'][$priceField->id
])
1903 && CRM_Utils_Array
::value('name', $this->_values
['fee'][$priceField->id
]) == 'contribution_amount'
1904 && CRM_Utils_Array
::value("price_{$priceField->id}", $this->_params
) == '-1'
1906 $this->_params
['amount'] = NULL;
1914 * @param array $params
1916 * @throws CiviCRM_API3_Exception
1918 public static function submit($params) {
1919 $form = new CRM_Contribute_Form_Contribution_Confirm();
1920 $form->_id
= $params['id'];
1922 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1923 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1924 //this way the mocked up controller ignores the session stuff
1925 $_SERVER['REQUEST_METHOD'] = 'GET';
1926 $form->controller
= new CRM_Contribute_Controller_Contribution();
1927 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1928 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1929 $form->_amount
= $params['amount'];
1930 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1931 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1932 $priceSetFields = reset($priceFields);
1933 $form->_values
['fee'] = $priceSetFields['fields'];
1934 $form->_priceSetId
= $priceSetID;
1935 $form->setFormAmountFields($priceSetID);
1936 if (!empty($params['payment_processor_id'])) {
1937 $form->_paymentProcessor
= civicrm_api3('payment_processor', 'getsingle', array(
1938 'id' => $params['payment_processor_id'],
1940 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1941 $form->_contributeMode
= 'direct';
1944 $form->_contributeMode
= 'notify';
1948 $form->_params
['payment_processor_id'] = 0;
1950 $priceFields = $priceFields[$priceSetID]['fields'];
1951 CRM_Price_BAO_PriceSet
::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1952 $form->_lineItem
= array($priceSetID => $lineItems);
1953 $form->processFormSubmission(CRM_Utils_Array
::value('contact_id', $params));
1957 * Helper function for static submit function.
1959 * Set relevant params - help us to build up an array that we can pass in.
1962 * @param array $params
1965 * @throws CiviCRM_API3_Exception
1967 public static function getFormParams($id, array $params) {
1968 if (!isset($params['is_pay_later'])) {
1969 if (!empty($params['payment_processor_id'])) {
1970 $params['is_pay_later'] = 0;
1973 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1975 'return' => 'is_pay_later',
1979 if (empty($params['price_set_id'])) {
1980 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
1986 * Post form submission handling.
1988 * This is also called from the test suite.
1990 * @param int $contactID
1994 protected function processFormSubmission($contactID) {
1995 $isPayLater = $this->_params
['is_pay_later'];
1996 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] == 0) {
1997 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
1999 // add a description field at the very beginning
2000 $this->_params
['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $this->_values
['title']);
2002 $this->_params
['accountingCode'] = CRM_Utils_Array
::value('accountingCode', $this->_values
);
2005 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
2007 //carry payment processor id.
2008 if (CRM_Utils_Array
::value('id', $this->_paymentProcessor
)) {
2009 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
2012 $premiumParams = $membershipParams = $params = $this->_params
;
2013 if (!empty($params['image_URL'])) {
2014 CRM_Contact_BAO_Contact
::processImageParams($params);
2017 $fields = array('email-Primary' => 1);
2019 // get the add to groups
2020 $addToGroups = array();
2022 // now set the values for the billing location.
2023 foreach ($this->_fields
as $name => $value) {
2026 // get the add to groups for uf fields
2027 if (!empty($value['add_to_group_id'])) {
2028 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2032 if (!array_key_exists('first_name', $fields)) {
2033 $nameFields = array('first_name', 'middle_name', 'last_name');
2034 foreach ($nameFields as $name) {
2036 if (array_key_exists("billing_$name", $params)) {
2037 $params[$name] = $params["billing_{$name}"];
2038 $params['preserveDBName'] = TRUE;
2043 // billing email address
2044 $fields["email-{$this->_bltID}"] = 1;
2046 //unset the billing parameters if it is pay later mode
2047 //to avoid creation of billing location
2048 if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater
) {
2049 $billingFields = array(
2050 'billing_first_name',
2051 'billing_middle_name',
2052 'billing_last_name',
2053 "billing_street_address-{$this->_bltID}",
2054 "billing_city-{$this->_bltID}",
2055 "billing_state_province-{$this->_bltID}",
2056 "billing_state_province_id-{$this->_bltID}",
2057 "billing_postal_code-{$this->_bltID}",
2058 "billing_country-{$this->_bltID}",
2059 "billing_country_id-{$this->_bltID}",
2062 foreach ($billingFields as $value) {
2063 unset($params[$value]);
2064 unset($fields[$value]);
2068 // if onbehalf-of-organization contribution, take out
2069 // organization params in a separate variable, to make sure
2070 // normal behavior is continued. And use that variable to
2071 // process on-behalf-of functionality.
2072 if (!empty($this->_params
['hidden_onbehalf_profile'])) {
2073 $behalfOrganization = array();
2074 $orgFields = array('organization_name', 'organization_id', 'org_option');
2075 foreach ($orgFields as $fld) {
2076 if (array_key_exists($fld, $params)) {
2077 $behalfOrganization[$fld] = $params[$fld];
2078 unset($params[$fld]);
2082 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2083 foreach ($params['onbehalf'] as $fld => $values) {
2084 if (strstr($fld, 'custom_')) {
2085 $behalfOrganization[$fld] = $values;
2087 elseif (!(strstr($fld, '-'))) {
2088 if (in_array($fld, array(
2089 'contribution_campaign_id',
2090 'member_campaign_id',
2092 $fld = 'campaign_id';
2095 $behalfOrganization[$fld] = $values;
2097 $this->_params
[$fld] = $values;
2102 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2103 foreach ($params['onbehalf_location'] as $block => $vals) {
2104 //fix for custom data (of type checkbox, multi-select)
2105 if (substr($block, 0, 7) == 'custom_') {
2108 // fix the index of block elements
2109 if (is_array($vals)) {
2110 foreach ($vals as $key => $val) {
2111 //dont adjust the index of address block as
2112 //it's index is WRT to location type
2113 $newKey = ($block == 'address') ?
$key : ++
$key;
2114 $behalfOrganization[$block][$newKey] = $val;
2118 unset($params['onbehalf_location']);
2120 if (!empty($params['onbehalf[image_URL]'])) {
2121 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2125 // check for profile double opt-in and get groups to be subscribed
2126 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2128 // since we are directly adding contact to group lets unset it from mailing
2129 if (!empty($addToGroups)) {
2130 foreach ($addToGroups as $groupId) {
2131 if (isset($subscribeGroupIds[$groupId])) {
2132 unset($subscribeGroupIds[$groupId]);
2137 foreach ($addToGroups as $k) {
2138 if (array_key_exists($k, $subscribeGroupIds)) {
2139 unset($addToGroups[$k]);
2143 if (empty($contactID)) {
2144 $dupeParams = $params;
2145 if (!empty($dupeParams['onbehalf'])) {
2146 unset($dupeParams['onbehalf']);
2148 if (!empty($dupeParams['honor'])) {
2149 unset($dupeParams['honor']);
2152 $dedupeParams = CRM_Dedupe_Finder
::formatParams($dupeParams, 'Individual');
2153 $dedupeParams['check_permission'] = FALSE;
2154 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
2156 // if we find more than one contact, use the first one
2157 $contactID = CRM_Utils_Array
::value(0, $ids);
2159 // Fetch default greeting id's if creating a contact
2161 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2162 if (!isset($params[$greeting])) {
2163 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2167 $contactType = NULL;
2170 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2172 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2182 // Make the contact ID associated with the contribution available at the Class level.
2183 // Also make available to the session.
2184 //@todo consider handling this in $this->getContactID();
2185 $this->set('contactID', $contactID);
2186 $this->_contactID
= $contactID;
2188 //get email primary first if exist
2189 $subscriptionEmail = array('email' => CRM_Utils_Array
::value('email-Primary', $params));
2190 if (!$subscriptionEmail['email']) {
2191 $subscriptionEmail['email'] = CRM_Utils_Array
::value("email-{$this->_bltID}", $params);
2193 // subscribing contact to groups
2194 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2195 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2198 // If onbehalf-of-organization contribution / signup, add organization
2199 // and it's location.
2200 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
2201 $ufFields = array();
2202 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2203 $ufFields[$name] = 1;
2205 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2206 $this->_params
, $ufFields
2209 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2210 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2211 // store current user id as related contact for later use for mailing / activity..
2212 $this->_values
['related_contact'] = $contactID;
2213 $this->_params
['related_contact'] = $contactID;
2214 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2215 $contactID = $this->_membershipContactID
;
2218 // lets store the contactID in the session
2219 // for things like tell a friend
2220 $session = CRM_Core_Session
::singleton();
2221 if (!$session->get('userID')) {
2222 $session->set('transaction.userID', $contactID);
2225 $session->set('transaction.userID', NULL);
2228 $this->_useForMember
= $this->get('useForMember');
2230 // store the fact that this is a membership and membership type is selected
2231 if ((!empty($membershipParams['selectMembership']) &&
2232 $membershipParams['selectMembership'] != 'no_thanks'
2234 $this->_useForMember
2236 if (!$this->_useForMember
) {
2237 $this->assign('membership_assign', TRUE);
2238 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2241 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2242 $membershipParams['is_test'] = 1;
2244 if ($this->_params
['is_pay_later']) {
2245 $membershipParams['is_pay_later'] = 1;
2248 //inherit campaign from contribution page.
2249 if (!array_key_exists('campaign_id', $membershipParams)) {
2250 $membershipParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
);
2253 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2254 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater);
2257 // at this point we've created a contact and stored its address etc
2258 // all the payment processors expect the name and address to be in the
2259 // so we copy stuff over to first_name etc.
2260 $paymentParams = $this->_params
;
2262 if (!empty($paymentParams['onbehalf']) &&
2263 is_array($paymentParams['onbehalf'])
2265 foreach ($paymentParams['onbehalf'] as $key => $value) {
2266 if (strstr($key, 'custom_')) {
2267 $this->_params
[$key] = $value;
2272 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2274 $this->wrangleFinancialTypeID($this->_values
['financial_type_id']),
2276 ($this->_mode
== 'test') ?
1 : 0
2279 if (!empty($result['is_payment_failure'])) {
2282 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2283 $this->postProcessPremium($premiumParams, $result['contribution']);
2284 if (CRM_Utils_Array
::value('payment_status_id', $result) == 1) {
2286 civicrm_api3('contribution', 'completetransaction', array(
2287 'id' => $result['contribution']->id
,
2288 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $result),
2289 'payment_processor_id' => $this->_paymentProcessor
['id'],
2290 'is_transactional' => FALSE,
2294 catch (CiviCRM_API3_Exception
$e) {
2295 if ($e->getErrorCode() != 'contribution_completed') {
2296 throw new CRM_Core_Exception('Failed to update contribution in database');
2306 * Membership processing section.
2308 * This is in a separate function as part of a move towards refactoring.
2310 * @param int $contactID
2311 * @param array $membershipParams
2312 * @param array $premiumParams
2313 * @param bool $isPayLater
2315 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater) {
2317 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2318 if (isset($this->_params
['related_contact'])) {
2319 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2322 $membershipParams['cms_contactID'] = $contactID;
2325 if (!empty($membershipParams['onbehalf']) &&
2326 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2328 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2331 $customFieldsFormatted = $fieldTypes = array();
2332 if (!empty($membershipParams['onbehalf']) &&
2333 is_array($membershipParams['onbehalf'])
2335 foreach ($membershipParams['onbehalf'] as $key => $value) {
2336 if (strstr($key, 'custom_')) {
2337 $customFieldId = explode('_', $key);
2338 CRM_Core_BAO_CustomField
::formatCustomField(
2340 $customFieldsFormatted,
2348 $fieldTypes = array('Contact', 'Organization', 'Membership');
2351 $priceFieldIds = $this->get('memberPriceFieldIDS');
2353 if (!empty($priceFieldIds)) {
2354 $contributionTypeID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2355 unset($priceFieldIds['id']);
2356 $membershipTypeIds = array();
2357 $membershipTypeTerms = array();
2358 foreach ($priceFieldIds as $priceFieldId) {
2359 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
2360 $membershipTypeIds[] = $id;
2361 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
2362 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
2364 if ($term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
2365 $membershipTypeTerms[$id] = ($term > 1) ?
$term : 1;
2368 $membershipTypeTerms[$id] = 1;
2372 $membershipParams['selectMembership'] = $membershipTypeIds;
2373 $membershipParams['financial_type_id'] = $contributionTypeID;
2374 $membershipParams['types_terms'] = $membershipTypeTerms;
2376 if (!empty($membershipParams['selectMembership'])) {
2378 $membershipLineItems = array();
2379 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2380 foreach ($this->_values
['fee'] as $key => $feeValues) {
2381 if ($feeValues['name'] == 'membership_amount') {
2382 $fieldId = $this->_params
['price_' . $key];
2383 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2384 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2390 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
2392 catch (CRM_Core_Exception
$e) {
2393 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2394 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2396 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2397 // we need to explicitly create a CMS user in case of free memberships
2398 // since it is done under processConfirm for paid memberships
2399 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2400 $membershipParams['cms_contactID'],
2401 'email-' . $this->_bltID