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
['onbehalf_profile_id'])) {
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);
470 CRM_Core_Error
::debug( '$params', $params );
472 if (!empty($params['onbehalf_profile_id'])) {
474 $fieldTypes = array('Contact', 'Organization');
475 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
476 $fieldTypes = array_merge($fieldTypes, $contactSubType);
477 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
478 $fieldTypes = array_merge($fieldTypes, array('Membership'));
481 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
484 $this->buildCustom($params['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
487 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
488 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
489 if ($this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
490 $this->assign('lineItem', $this->_lineItem
);
493 $this->assign('is_quick_config', 1);
494 $this->_params
['is_quick_config'] = 1;
496 $this->assign('priceSetID', $this->_priceSetId
);
497 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
498 if ($this->_paymentProcessor
&&
499 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('Google_Checkout', $paymentProcessorType)
500 && !$this->_params
['is_pay_later'] && !($this->_amount
== 0)
502 $this->_checkoutButtonName
= $this->getButtonName('next', 'checkout');
504 $this->_checkoutButtonName
,
505 $this->_paymentProcessor
['url_button'],
506 array('class' => 'crm-form-submit')
509 $this->addButtons(array(
512 'name' => ts('Go Back'),
518 if ($this->_contributeMode
== 'notify' ||
!$this->_values
['is_monetary'] ||
519 $this->_amount
<= 0.0 ||
$this->_params
['is_pay_later'] ||
520 ($this->_separateMembershipPayment
&& $this->_amount
<= 0.0)
522 $contribButton = ts('Continue');
523 $this->assign('button', ts('Continue'));
526 $contribButton = ts('Make Contribution');
527 $this->assign('button', ts('Make Contribution'));
529 $this->addButtons(array(
532 'name' => $contribButton,
533 'spacing' => ' ',
535 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name
. "','" . ts('Processing') . "');"),
539 'name' => ts('Go Back'),
546 $fields = array_fill_keys(array_keys($this->_fields
), 1);
547 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
549 $contact = $this->_params
;
550 foreach ($fields as $name => $dontCare) {
551 // Recursively set defaults for nested fields
552 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' ||
$name == 'honor')) {
553 foreach ($contact[$name] as $fieldName => $fieldValue) {
554 if (is_array($fieldValue) && !in_array($this->_fields
[$name][$fieldName]['html_type'], array(
559 foreach ($fieldValue as $key => $value) {
560 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
564 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
568 elseif (isset($contact[$name])) {
569 $defaults[$name] = $contact[$name];
570 if (substr($name, 0, 7) == 'custom_') {
571 $timeField = "{$name}_time";
572 if (isset($contact[$timeField])) {
573 $defaults[$timeField] = $contact[$timeField];
575 if (isset($contact["{$name}_id"])) {
576 $defaults["{$name}_id"] = $contact["{$name}_id"];
579 elseif (in_array($name, array(
583 )) && !empty($contact[$name . '_custom'])
585 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
590 $this->assign('useForMember', $this->get('useForMember'));
592 $this->setDefaults($defaults);
600 * Since we are only showing elements in frozen mode no help display needed.
604 public function getAction() {
605 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
606 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
609 return CRM_Core_Action
::VIEW
;
614 * Set default values for the form.
616 * Note that in edit/view mode
617 * the default values are retrieved from the database
619 public function setDefaultValues() {
625 public function postProcess() {
626 $contactID = $this->getContactID();
627 $result = $this->processFormSubmission($contactID);
628 if (is_array($result) && !empty($result['is_payment_failure'])) {
629 // We will probably have the function that gets this error throw an exception on the next round of refactoring.
630 CRM_Core_Session
::singleton()->setStatus(ts("Payment Processor Error message :") .
631 $result['error']->getMessage());
632 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
633 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
636 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
637 $this->set('params', $this->_params
);
641 * Wrangle financial type ID.
643 * 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
644 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
646 * Comments from previous refactor indicate doubt as to what was going on.
648 * @param int $contributionTypeId
650 * @return null|string
652 public function wrangleFinancialTypeID($contributionTypeId) {
653 if (isset($paymentParams['financial_type'])) {
654 $contributionTypeId = $paymentParams['financial_type'];
656 elseif (!empty($this->_values
['pledge_id'])) {
657 $contributionTypeId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
658 $this->_values
['pledge_id'],
662 return $contributionTypeId;
668 * @param array $premiumParams
669 * @param CRM_Contribute_BAO_Contribution $contribution
671 protected function postProcessPremium($premiumParams, $contribution) {
672 $hour = $minute = $second = 0;
673 // assigning Premium information to receipt tpl
674 $selectProduct = CRM_Utils_Array
::value('selectProduct', $premiumParams);
675 if ($selectProduct &&
676 $selectProduct != 'no_thanks'
678 $startDate = $endDate = "";
679 $this->assign('selectPremium', TRUE);
680 $productDAO = new CRM_Contribute_DAO_Product();
681 $productDAO->id
= $selectProduct;
682 $productDAO->find(TRUE);
683 $this->assign('product_name', $productDAO->name
);
684 $this->assign('price', $productDAO->price
);
685 $this->assign('sku', $productDAO->sku
);
686 $this->assign('option', CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams));
688 $periodType = $productDAO->period_type
;
691 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
692 $duration_unit = $productDAO->duration_unit
;
693 $duration_interval = $productDAO->duration_interval
;
694 if ($periodType == 'rolling') {
695 $startDate = date('Y-m-d');
697 elseif ($periodType == 'fixed') {
698 if ($fixed_period_start_day) {
699 $date = explode('-', date('Y-m-d'));
700 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
701 $day = substr($fixed_period_start_day, -2) . "<br/>";
703 $startDate = $year . '-' . $month . '-' . $day;
706 $startDate = date('Y-m-d');
710 $date = explode('-', $startDate);
715 switch ($duration_unit) {
717 $year = $year +
$duration_interval;
721 $month = $month +
$duration_interval;
725 $day = $day +
$duration_interval;
729 $day = $day +
($duration_interval * 7);
731 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
732 $this->assign('start_date', $startDate);
733 $this->assign('end_date', $endDate);
736 $dao = new CRM_Contribute_DAO_Premium();
737 $dao->entity_table
= 'civicrm_contribution_page';
738 $dao->entity_id
= $this->_id
;
740 $this->assign('contact_phone', $dao->premiums_contact_phone
);
741 $this->assign('contact_email', $dao->premiums_contact_email
);
743 //create Premium record
745 'product_id' => $premiumParams['selectProduct'],
746 'contribution_id' => $contribution->id
,
747 'product_option' => CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams),
749 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
750 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
752 if (!empty($premiumParams['selectProduct'])) {
753 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
754 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
755 $daoPremiumsProduct->premiums_id
= $dao->id
;
756 $daoPremiumsProduct->find(TRUE);
757 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
760 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
761 $daoContrProd->contribution_id
= $contribution->id
;
762 if ($daoContrProd->find(TRUE)) {
763 $params['id'] = $daoContrProd->id
;
766 CRM_Contribute_BAO_Contribution
::addPremium($params);
767 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
769 'cost' => $productDAO->cost
,
770 'currency' => $productDAO->currency
,
771 'financial_type_id' => $params['financial_type_id'],
772 'contributionId' => $contribution->id
,
774 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
777 elseif ($selectProduct == 'no_thanks') {
779 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
780 $daoContrProd->contribution_id
= $contribution->id
;
781 if ($daoContrProd->find(TRUE)) {
782 $daoContrProd->delete();
788 * Process the contribution.
790 * @param CRM_Core_Form $form
791 * @param array $params
792 * @param array $result
793 * @param array $contributionParams
794 * Parameters to be passed to contribution create action.
795 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
796 * passed consistently & 2) documenting them here.
801 * - contribution_page_id
804 * - thankyou_date (not all forms will set this)
806 * @param CRM_Financial_DAO_FinancialType $financialType
807 * @param bool $online
808 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
810 * @param int $billingLocationID
811 * ID of billing location type.
813 * @return \CRM_Contribute_DAO_Contribution
816 public static function processFormContribution(
825 $transaction = new CRM_Core_Transaction();
826 $contactID = $contributionParams['contact_id'];
828 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
829 $isSeparateMembershipPayment = empty($params['separate_membership_payment']) ?
FALSE : TRUE;
830 $pledgeID = empty($params['pledge_id']) ?
NULL : $params['pledge_id'];
831 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
832 (!empty($params['is_pledge']) ||
$pledgeID)) {
839 // add these values for the recurringContrib function ,CRM-10188
840 $params['financial_type_id'] = $financialType->id
;
842 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
844 //@todo - this is being set from the form to resolve CRM-10188 - an
845 // eNotice caused by it not being set @ the front end
846 // however, we then get it being over-written with null for backend contributions
847 // a better fix would be to set the values in the respective forms rather than require
848 // a function being shared by two forms to deal with their respective values
849 // moving it to the BAO & not taking the $form as a param would make sense here.
850 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
851 $params['is_email_receipt'] = $isEmailReceipt;
853 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType, $online);
854 $nonDeductibleAmount = self
::getNonDeductibleAmount($params, $financialType, $online);
856 $now = date('YmdHis');
857 $receiptDate = CRM_Utils_Array
::value('receipt_date', $params);
858 if ($isEmailReceipt) {
862 if (isset($params['amount'])) {
863 $contributionParams = array_merge(self
::getContributionParams(
864 $params, $financialType->id
, $nonDeductibleAmount, TRUE,
865 $result, $receiptDate,
866 $recurringContributionID), $contributionParams
868 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
870 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
871 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
873 $dataArray = array();
874 // @todo - interrogate the line items passed in on the params array.
875 // No reason to assume line items will be set on the form.
876 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
877 foreach ($lineItemValue as $key => $value) {
878 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
879 if (isset($dataArray[$value['tax_rate']])) {
880 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
883 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
888 $smarty = CRM_Core_Smarty
::singleton();
889 $smarty->assign('dataArray', $dataArray);
890 $smarty->assign('totalTaxAmount', $params['tax_amount']);
892 if (is_a($contribution, 'CRM_Core_Error')) {
893 $message = CRM_Core_Error
::getMessages($contribution);
894 CRM_Core_Error
::fatal($message);
897 // lets store it in the form variable so postProcess hook can get to this and use it
898 $form->_contributionID
= $contribution->id
;
901 // process soft credit / pcp params first
902 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
904 //CRM-13981, processing honor contact into soft-credit contribution
905 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
907 //handle pledge stuff.
910 //when user doing pledge payments.
911 //update the schedule when payment(s) are made
912 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
913 $scheduledAmount = CRM_Core_DAO
::getFieldValue(
914 'CRM_Pledge_DAO_PledgePayment',
920 $pledgePaymentParams = array(
922 'contribution_id' => $contribution->id
,
923 'status_id' => $contribution->contribution_status_id
,
924 'actual_amount' => $scheduledAmount,
927 CRM_Pledge_BAO_PledgePayment
::add($pledgePaymentParams);
930 //update pledge status according to the new payment statuses
931 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID);
934 //when user creating pledge record.
935 $pledgeParams = array();
936 $pledgeParams['contact_id'] = $contribution->contact_id
;
937 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount
;
938 $pledgeParams['contribution_id'] = $contribution->id
;
939 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id
;
940 $pledgeParams['financial_type_id'] = $contribution->financial_type_id
;
941 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
942 $pledgeParams['installments'] = $params['pledge_installments'];
943 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
944 if ($pledgeParams['frequency_unit'] == 'month') {
945 $pledgeParams['frequency_day'] = intval(date("d"));
948 $pledgeParams['frequency_day'] = 1;
950 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
951 $pledgeParams['status_id'] = $contribution->contribution_status_id
;
952 $pledgeParams['max_reminders'] = $form->_values
['max_reminders'];
953 $pledgeParams['initial_reminder_day'] = $form->_values
['initial_reminder_day'];
954 $pledgeParams['additional_reminder_day'] = $form->_values
['additional_reminder_day'];
955 $pledgeParams['is_test'] = $contribution->is_test
;
956 $pledgeParams['acknowledge_date'] = date('Ymd');
957 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
959 //inherit campaign from contirb page.
960 $pledgeParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $contributionParams);
962 $pledge = CRM_Pledge_BAO_Pledge
::create($pledgeParams);
964 $form->_params
['pledge_id'] = $pledge->id
;
966 //send acknowledgment email. only when pledge is created
968 //build params to send acknowledgment.
969 $pledgeParams['id'] = $pledge->id
;
970 $pledgeParams['receipt_from_name'] = $form->_values
['receipt_from_name'];
971 $pledgeParams['receipt_from_email'] = $form->_values
['receipt_from_email'];
973 //scheduled amount will be same as installment_amount.
974 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
976 //get total pledge amount.
977 $pledgeParams['total_pledge_amount'] = $pledge->amount
;
979 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($form, $pledgeParams);
984 if ($online && $contribution) {
985 CRM_Core_BAO_CustomValueTable
::postProcess($params,
986 'civicrm_contribution',
991 elseif ($contribution) {
992 //handle custom data.
993 $params['contribution_id'] = $contribution->id
;
994 if (!empty($params['custom']) &&
995 is_array($params['custom']) &&
996 !is_a($contribution, 'CRM_Core_Error')
998 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
1002 if ($contribution && !empty($params['contribution_note'])) {
1003 $noteParams = array(
1004 'entity_table' => 'civicrm_contribution',
1005 'note' => $params['contribution_note'],
1006 'entity_id' => $contribution->id
,
1007 'contact_id' => $contribution->contact_id
,
1008 'modified_date' => date('Ymd'),
1011 CRM_Core_BAO_Note
::add($noteParams, array());
1014 if (isset($params['related_contact'])) {
1015 $contactID = $params['related_contact'];
1017 elseif (isset($params['cms_contactID'])) {
1018 $contactID = $params['cms_contactID'];
1021 //create contribution activity w/ individual and target
1022 //activity w/ organisation contact id when onbelf, CRM-4027
1023 $targetContactID = NULL;
1024 if (!empty($params['hidden_onbehalf_profile'])) {
1025 $targetContactID = $contribution->contact_id
;
1026 $contribution->contact_id
= $contactID;
1029 // create an activity record
1030 if ($contribution) {
1031 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
1034 $transaction->commit();
1035 // CRM-13074 - create the CMSUser after the transaction is completed as it
1036 // is not appropriate to delete a valid contribution if a user create problem occurs
1037 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($params,
1039 'email-' . $billingLocationID
1041 return $contribution;
1045 * Create the recurring contribution record.
1047 * @param CRM_Core_Form $form
1048 * @param array $params
1049 * @param int $contactID
1050 * @param string $contributionType
1051 * @param bool $online
1055 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1056 // return if this page is not set for recurring
1057 // or the user has not chosen the recurring option
1059 //this is online case validation.
1060 if ((empty($form->_values
['is_recur']) && $online) ||
empty($params['is_recur'])) {
1064 $recurParams = array('contact_id' => $contactID);
1065 $recurParams['amount'] = CRM_Utils_Array
::value('amount', $params);
1066 $recurParams['auto_renew'] = CRM_Utils_Array
::value('auto_renew', $params);
1067 $recurParams['frequency_unit'] = CRM_Utils_Array
::value('frequency_unit', $params);
1068 $recurParams['frequency_interval'] = CRM_Utils_Array
::value('frequency_interval', $params);
1069 $recurParams['installments'] = CRM_Utils_Array
::value('installments', $params);
1070 $recurParams['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $params);
1071 $recurParams['currency'] = CRM_Utils_Array
::value('currency', $params);
1073 // CRM-14354: For an auto-renewing membership with an additional contribution,
1074 // if separate payments is not enabled, make sure only the membership fee recurs
1075 if (!empty($form->_membershipBlock
)
1076 && $form->_membershipBlock
['is_separate_payment'] === '0'
1077 && isset($params['selectMembership'])
1078 && $form->_values
['is_allow_other_amount'] == '1'
1080 && !empty($form->_membershipTypeValues
)
1081 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1083 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1086 $recurParams['is_test'] = 0;
1087 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1088 (isset($form->_mode
) && ($form->_mode
== 'test'))
1090 $recurParams['is_test'] = 1;
1093 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1094 if (!empty($params['receive_date'])) {
1095 $recurParams['start_date'] = $params['receive_date'];
1097 $recurParams['invoice_id'] = CRM_Utils_Array
::value('invoiceID', $params);
1098 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1099 $recurParams['payment_processor_id'] = CRM_Utils_Array
::value('payment_processor_id', $params);
1100 $recurParams['is_email_receipt'] = CRM_Utils_Array
::value('is_email_receipt', $params);
1101 // we need to add a unique trxn_id to avoid a unique key error
1102 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1103 $recurParams['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params, $params['invoiceID']);
1104 $recurParams['financial_type_id'] = $contributionType->id
;
1106 if (!$online ||
$form->_values
['is_monetary']) {
1107 $recurParams['payment_instrument_id'] = 1;
1110 $campaignId = CRM_Utils_Array
::value('campaign_id', $params);
1112 if (!array_key_exists('campaign_id', $params)) {
1113 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1116 $recurParams['campaign_id'] = $campaignId;
1118 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1119 if (is_a($recurring, 'CRM_Core_Error')) {
1120 CRM_Core_Error
::displaySessionError($recurring);
1121 $urlString = 'civicrm/contribute/transact';
1122 $urlParams = '_qf_Main_display=true';
1123 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1124 $urlString = 'civicrm/contact/view/contribution';
1125 $urlParams = "action=add&cid={$form->_contactID}";
1127 $urlParams .= "&mode={$form->_mode}";
1130 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1133 return $recurring->id
;
1137 * Add on behalf of organization and it's location.
1139 * This situation occurs when on behalf of is enabled for the contribution page and the person
1140 * signing up does so on behalf of an organization.
1142 * @param array $behalfOrganization
1143 * array of organization info.
1144 * @param int $contactID
1145 * individual contact id. One.
1146 * who is doing the process of signup / contribution.
1148 * @param array $values
1149 * form values array.
1150 * @param array $params
1151 * @param array $fields
1152 * Array of fields from the onbehalf profile relevant to the organization.
1154 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1155 $isCurrentEmployer = FALSE;
1158 if (!empty($behalfOrganization['organization_id']) && empty($behalfOrganization['org_option'])) {
1159 $orgID = $behalfOrganization['organization_id'];
1160 unset($behalfOrganization['organization_id']);
1161 $isCurrentEmployer = TRUE;
1164 // formalities for creating / editing organization.
1165 $behalfOrganization['contact_type'] = 'Organization';
1167 // get the relationship type id
1168 $relType = new CRM_Contact_DAO_RelationshipType();
1169 $relType->name_a_b
= 'Employee of';
1170 $relType->find(TRUE);
1171 $relTypeId = $relType->id
;
1173 // keep relationship params ready
1174 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1175 $relParams['is_permission_a_b'] = 1;
1176 $relParams['is_active'] = 1;
1179 // check if matching organization contact exists
1180 $dedupeParams = CRM_Dedupe_Finder
::formatParams($behalfOrganization, 'Organization');
1181 $dedupeParams['check_permission'] = FALSE;
1182 $dupeIDs = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1184 // CRM-6243 says to pick the first org even if more than one match
1185 if (count($dupeIDs) >= 1) {
1186 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1187 // don't allow name edit
1188 unset($behalfOrganization['organization_name']);
1192 // if found permissioned related organization, allow location edit
1193 $behalfOrganization['contact_id'] = $orgID;
1194 // don't allow name edit
1195 unset($behalfOrganization['organization_name']);
1198 // handling for image url
1199 if (!empty($behalfOrganization['image_URL'])) {
1200 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1203 // create organization, add location
1204 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1205 NULL, NULL, 'Organization'
1207 // create relationship
1208 $relParams['contact_check'][$orgID] = 1;
1209 $cid = array('contact' => $contactID);
1210 CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relParams, $cid);
1212 // if multiple match - send a duplicate alert
1213 if ($dupeIDs && (count($dupeIDs) > 1)) {
1214 $values['onbehalf_dupe_alert'] = 1;
1216 $params['onbehalf_dupe_alert'] = 1;
1219 // make sure organization-contact-id is considered for recording
1220 // contribution/membership etc..
1221 if ($contactID != $orgID) {
1222 // take a note of contact-id, so we can send the
1223 // receipt to individual contact as well.
1225 // required for mailing/template display ..etc
1226 $values['related_contact'] = $contactID;
1228 $params['related_contact'] = $contactID;
1230 //make this employee of relationship as current
1231 //employer / employee relationship, CRM-3532
1232 if ($isCurrentEmployer &&
1233 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1235 $isCurrentEmployer = FALSE;
1238 if (!$isCurrentEmployer && $orgID) {
1239 //build current employer params
1240 $currentEmpParams[$contactID] = $orgID;
1241 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1244 // contribution / signup will be done using this
1246 $contactID = $orgID;
1251 * Function used to send notification mail to pcp owner.
1253 * This is used by contribution and also event PCPs.
1255 * @param object $contribution
1256 * @param object $contributionSoft
1257 * Contribution object.
1259 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1260 $params = array('id' => $contributionSoft->pcp_id
);
1261 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1262 $ownerNotifyID = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1264 if ($ownerNotifyID != CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1265 (($ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1266 CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id
, 'is_notify')) ||
1267 $ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1268 $pcpInfoURL = CRM_Utils_System
::url('civicrm/pcp/info',
1269 "reset=1&id={$contributionSoft->pcp_id}",
1270 TRUE, NULL, FALSE, TRUE
1272 // set email in the template here
1273 // get the billing location type
1274 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1275 $billingLocationTypeId = array_search('Billing', $locationTypes);
1277 if ($billingLocationTypeId) {
1278 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
, FALSE, $billingLocationTypeId);
1280 // get primary location email if no email exist( for billing location).
1282 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
);
1284 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft->contact_id
);
1286 'page_title' => $pcpInfo['title'],
1287 'receive_date' => $contribution->receive_date
,
1288 'total_amount' => $contributionSoft->amount
,
1289 'donors_display_name' => $donorName,
1290 'donors_email' => $email,
1291 'pcpInfoURL' => $pcpInfoURL,
1292 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll
,
1293 'currency' => $contributionSoft->currency
,
1295 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1296 $sendTemplateParams = array(
1297 'groupName' => 'msg_tpl_workflow_contribution',
1298 'valueName' => 'pcp_owner_notify',
1299 'contactId' => $contributionSoft->contact_id
,
1300 'toEmail' => $ownerEmail,
1301 'toName' => $ownerName,
1302 'from' => "$domainValues[0] <$domainValues[1]>",
1303 'tplParams' => $tplParams,
1304 'PDFFilename' => 'receipt.pdf',
1306 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1311 * Function used to se pcp related defaults / params.
1313 * This is used by contribution and also event PCPs
1315 * @param CRM_Core_Form $page
1317 * @param array $params
1321 public static function processPcp(&$page, $params) {
1322 $params['pcp_made_through_id'] = $page->_pcpId
;
1323 $page->assign('pcpBlock', TRUE);
1324 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1325 $params['pcp_roll_nickname'] = ts('Anonymous');
1326 $params['pcp_is_anonymous'] = 1;
1329 $params['pcp_is_anonymous'] = 0;
1332 'pcp_display_in_roll',
1334 'pcp_roll_nickname',
1335 'pcp_personal_note',
1337 if (!empty($params[$val])) {
1338 $page->assign($val, $params[$val]);
1346 * Process membership.
1348 * @param array $membershipParams
1349 * @param int $contactID
1350 * @param array $customFieldsFormatted
1351 * @param array $fieldTypes
1352 * @param array $premiumParams
1353 * @param array $membershipLineItems
1354 * Line items specifically relating to memberships.
1355 * @param bool $isPayLater
1357 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1358 $membershipLineItems, $isPayLater) {
1360 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1361 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1362 $membershipType = empty($membershipTypes) ?
array() : reset($membershipTypes);
1363 $isPending = $this->getIsPending();
1365 $this->assign('membership_name', CRM_Utils_Array
::value('name', $membershipType));
1367 $isPaidMembership = FALSE;
1368 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1369 //amount must be greater than zero for
1370 //adding contribution record to contribution table.
1371 //this condition arises when separate membership payment is
1372 //enabled and contribution amount is not selected. fix for CRM-3010
1373 $isPaidMembership = TRUE;
1375 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1377 if ($this->_values
['amount_block_is_active']) {
1378 $financialTypeID = $this->_values
['financial_type_id'];
1381 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $membershipType, CRM_Utils_Array
::value('financial_type_id', $membershipParams));
1384 if (CRM_Utils_Array
::value('membership_source', $this->_params
)) {
1385 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1388 $this->postProcessMembership($membershipParams, $contactID,
1389 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1390 $membershipLineItems, $isPayLater, $isPending);
1392 $this->assign('membership_assign', TRUE);
1393 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1397 * Process the Memberships.
1399 * @param array $membershipParams
1400 * Array of membership fields.
1401 * @param int $contactID
1403 * @param CRM_Contribute_Form_Contribution_Confirm $form
1404 * Confirmation form object.
1406 * @param array $premiumParams
1407 * @param null $customFieldsFormatted
1408 * @param null $includeFieldTypes
1410 * @param array $membershipDetails
1412 * @param array $membershipTypeIDs
1414 * @param bool $isPaidMembership
1415 * @param array $membershipID
1417 * @param bool $isProcessSeparateMembershipTransaction
1419 * @param int $financialTypeID
1420 * @param array $membershipLineItems
1421 * Line items specific to membership payment that is separate to contribution.
1422 * @param bool $isPayLater
1423 * @param bool $isPending
1425 * @throws \CRM_Core_Exception
1427 protected function postProcessMembership(
1428 $membershipParams, $contactID, &$form, $premiumParams,
1429 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1430 $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending) {
1431 $membershipContribution = NULL;
1432 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1433 $errors = $createdMemberships = $paymentResult = array();
1435 if ($isPaidMembership) {
1436 if ($isProcessSeparateMembershipTransaction) {
1437 // If we have 2 transactions only one can use the invoice id.
1438 $membershipParams['invoiceID'] .= '-2';
1441 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1448 if (!empty($paymentResult['contribution'])) {
1449 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1450 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1451 $membershipContribution = $paymentResult['contribution'];
1452 // Save the contribution ID so that I can be used in email receipts
1453 // For example, if you need to generate a tax receipt for the donation only.
1454 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1458 if ($isProcessSeparateMembershipTransaction) {
1460 $form->_lineItem
= $membershipLineItems;
1461 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1462 unset($membershipParams['is_recur']);
1464 $membershipContribution = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams,
1465 $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1467 catch (CRM_Core_Exception
$e) {
1468 $errors[2] = $e->getMessage();
1469 $membershipContribution = NULL;
1474 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1475 $membershipContributionID = $membershipContribution->id
;
1478 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1479 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1480 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1482 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1483 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1484 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1485 foreach ($membershipTypeIDs as $memType) {
1486 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1487 if (!empty($membershipContribution)) {
1488 $pendingStatus = CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name');
1489 $pending = ($membershipContribution->contribution_status_id
== $pendingStatus) ?
TRUE : FALSE;
1492 $pending = $isPending;
1494 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
1496 $membershipSource = NULL;
1497 if (!empty($form->_params
['membership_source'])) {
1498 $membershipSource = $form->_params
['membership_source'];
1500 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
1501 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
1504 if (isset($form->_params
)) {
1505 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
1508 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
1509 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
1510 if (!array_key_exists('campaign_id', $form->_params
)) {
1511 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1515 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership
::renewMembership(
1516 $contactID, $memType, $isTest,
1517 date('YmdHis'), CRM_Utils_Array
::value('cms_contactID', $membershipParams),
1518 $customFieldsFormatted,
1519 $numTerms, $membershipID, $pending,
1520 $contributionRecurID, $membershipSource, $isPayLater, $campaignId
1522 $form->set('renewal_mode', $renewalMode);
1523 if (!empty($dates)) {
1524 $form->assign('mem_start_date',
1525 CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d')
1527 $form->assign('mem_end_date',
1528 CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d')
1532 if (!empty($membershipContribution)) {
1533 // update recurring id for membership record
1534 CRM_Member_BAO_Membership
::updateRecurMembership($membership, $membershipContribution);
1535 CRM_Member_BAO_Membership
::linkMembershipPayment($membership, $membershipContribution);
1538 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1539 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1540 if (!empty($priceFieldOp['membership_type_id']) &&
1541 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1543 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1544 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1545 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1548 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1551 $form->_values
['lineItem'] = $form->_lineItem
;
1552 $form->assign('lineItem', $form->_lineItem
);
1556 if (!empty($errors)) {
1557 $message = $this->compileErrorMessage($errors);
1558 throw new CRM_Core_Exception($message);
1560 $form->_params
['createdMembershipIDs'] = array();
1562 // CRM-7851 - Moved after processing Payment Errors
1563 //@todo - the reasoning for this being here seems a little outdated
1564 foreach ($createdMemberships as $createdMembership) {
1565 CRM_Core_BAO_CustomValueTable
::postProcess(
1567 'civicrm_membership',
1568 $createdMembership->id
,
1571 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1573 if (count($createdMemberships) == 1) {
1574 //presumably this is only relevant for exactly 1 membership
1575 $form->_params
['membershipID'] = $createdMembership->id
;
1578 //CRM-15232: Check if membership is created and on the basis of it use
1579 //membership receipt template to send payment receipt
1580 if (count($createdMemberships)) {
1581 $form->_values
['isMembership'] = TRUE;
1583 if (isset($membershipContributionID)) {
1584 $form->_values
['contribution_id'] = $membershipContributionID;
1586 if ($form->_contributeMode
) {
1587 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1588 // call postProcess hook before leaving
1589 $form->postProcessHook();
1591 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1592 $paymentActionResult = $payment->doPayment($form->_params
, 'contribute');
1593 $this->completeTransaction($paymentActionResult, $paymentResult['contribution']->id
);
1594 // Do not send an email if Recurring transaction is done via Direct Mode
1595 // Email will we sent when the IPN is received.
1599 //finally send an email receipt
1600 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1608 * Turn array of errors into message string.
1610 * @param array $errors
1614 protected function compileErrorMessage($errors) {
1615 foreach ($errors as $error) {
1616 if (is_string($error)) {
1617 $message[] = $error;
1620 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1624 * Where a second separate financial transaction is supported we will process it here.
1626 * @param int $contactID
1627 * @param CRM_Contribute_Form_Contribution_Confirm $form
1628 * @param array $tempParams
1629 * @param bool $isTest
1630 * @param array $lineItems
1631 * @param $minimumFee
1632 * @param int $financialTypeID
1634 * @throws CRM_Core_Exception
1636 * @return CRM_Contribute_BAO_Contribution
1638 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1640 $financialType = new CRM_Financial_DAO_FinancialType();
1641 $financialType->id
= $financialTypeID;
1642 $financialType->find(TRUE);
1643 $tempParams['amount'] = $minimumFee;
1644 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1646 //assign receive date when separate membership payment
1647 //and contribution amount not selected.
1648 if ($form->_amount
== 0) {
1649 $now = date('YmdHis');
1650 $form->_params
['receive_date'] = $now;
1651 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1652 $form->set('params', $form->_params
);
1653 $form->assign('receive_date', $receiveDate);
1656 $form->set('membership_amount', $minimumFee);
1657 $form->assign('membership_amount', $minimumFee);
1659 // we don't need to create the user twice, so lets disable cms_create_account
1660 // irrespective of the value, CRM-2888
1661 $tempParams['cms_create_account'] = 0;
1663 //set this variable as we are not creating pledge for
1664 //separate membership payment contribution.
1665 //so for differentiating membership contribution from
1666 //main contribution.
1667 $form->_params
['separate_membership_payment'] = 1;
1668 $contributionParams = array(
1669 'contact_id' => $contactID,
1670 'line_item' => $lineItems,
1671 'is_test' => $isTest,
1672 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $tempParams, CRM_Utils_Array
::value('campaign_id',
1674 'contribution_page_id' => $form->_id
,
1675 'source' => CRM_Utils_Array
::value('source', $tempParams, CRM_Utils_Array
::value('description', $tempParams)),
1677 $isMonetary = !empty($form->_values
['is_monetary']);
1679 if (empty($paymentParams['is_pay_later'])) {
1680 $contributionParams['payment_instrument_id'] = $form->_paymentProcessor
['payment_instrument_id'];
1683 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
1686 $contributionParams,
1692 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
1693 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1694 // now we compensate here.
1695 if (empty($form->_paymentProcessor
['object'])) {
1696 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1699 $payment = $form->_paymentProcessor
['object'];
1701 $result = $payment->doPayment($tempParams, 'contribute');
1702 $form->set('membership_trx_id', $result['trxn_id']);
1703 $form->assign('membership_trx_id', $result['trxn_id']);
1704 $this->completeTransaction($result, $membershipContribution->id
);
1707 return $membershipContribution;
1711 * Is the payment a pending payment.
1713 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1714 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1719 protected function getIsPending() {
1720 if (((isset($this->_contributeMode
)) ||
!empty
1721 ($this->_params
['is_pay_later'])
1723 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1731 * Are we going to do 2 financial transactions.
1733 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1735 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1737 * @param int $formID
1738 * @param bool $amountBlockActiveOnForm
1742 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1743 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1744 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1751 * This function sets the fields.
1753 * - $this->_params['amount_level']
1754 * - $this->_params['selectMembership']
1755 * And under certain circumstances sets
1756 * $this->_params['amount'] = null;
1758 * @param int $priceSetID
1760 public function setFormAmountFields($priceSetID) {
1761 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1762 $priceField = new CRM_Price_DAO_PriceField();
1763 $priceField->price_set_id
= $priceSetID;
1764 $priceField->orderBy('weight');
1765 $priceField->find();
1766 $paramWeDoNotUnderstand = NULL;
1768 while ($priceField->fetch()) {
1769 if ($priceField->name
== "contribution_amount") {
1770 $paramWeDoNotUnderstand = $priceField->id
;
1772 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1773 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1774 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1775 $this->_params
["price_{$priceField->id}"], 'label');
1777 if ($priceField->name
== "membership_amount") {
1778 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1779 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1782 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1783 // as membership amount.
1784 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1785 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1786 // so we should merge them together
1787 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1788 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1790 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
)
1791 && !empty($this->_values
['fee'][$priceField->id
])
1792 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1793 && CRM_Utils_Array
::value("price_{$paramWeDoNotUnderstand}", $this->_params
) < 1
1794 && empty($this->_params
["price_{$priceField->id}"])
1796 $this->_params
['amount'] = NULL;
1799 // Fix for CRM-14375 - If we are using separate payments and "no
1800 // thank you" is selected for the additional contribution, set
1801 // contribution amount to be null, so that it will not show
1802 // contribution amount same as membership amount.
1803 //@todo - merge with section above
1804 if ($this->_membershipBlock
['is_separate_payment']
1805 && !empty($this->_values
['fee'][$priceField->id
])
1806 && CRM_Utils_Array
::value('name', $this->_values
['fee'][$priceField->id
]) == 'contribution_amount'
1807 && CRM_Utils_Array
::value("price_{$priceField->id}", $this->_params
) == '-1'
1809 $this->_params
['amount'] = NULL;
1817 * @param array $params
1819 * @throws CiviCRM_API3_Exception
1821 public static function submit($params) {
1822 $form = new CRM_Contribute_Form_Contribution_Confirm();
1823 $form->_id
= $params['id'];
1825 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1826 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1827 //this way the mocked up controller ignores the session stuff
1828 $_SERVER['REQUEST_METHOD'] = 'GET';
1829 $form->controller
= new CRM_Contribute_Controller_Contribution();
1830 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1831 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1832 $form->_amount
= $params['amount'];
1833 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1834 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1835 $priceSetFields = reset($priceFields);
1836 $form->_values
['fee'] = $priceSetFields['fields'];
1837 $form->_priceSetId
= $priceSetID;
1838 $form->setFormAmountFields($priceSetID);
1839 if (!empty($params['payment_processor_id'])) {
1840 $form->_paymentProcessor
= civicrm_api3('payment_processor', 'getsingle', array(
1841 'id' => $params['payment_processor_id'],
1843 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1844 $form->_contributeMode
= 'direct';
1847 $form->_contributeMode
= 'notify';
1851 $form->_params
['payment_processor_id'] = 0;
1853 $priceFields = $priceFields[$priceSetID]['fields'];
1854 CRM_Price_BAO_PriceSet
::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1855 $form->_lineItem
= array($priceSetID => $lineItems);
1856 $form->processFormSubmission(CRM_Utils_Array
::value('contact_id', $params));
1860 * Helper function for static submit function.
1862 * Set relevant params - help us to build up an array that we can pass in.
1865 * @param array $params
1868 * @throws CiviCRM_API3_Exception
1870 public static function getFormParams($id, array $params) {
1871 if (!isset($params['is_pay_later'])) {
1872 if (!empty($params['payment_processor_id'])) {
1873 $params['is_pay_later'] = 0;
1876 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1878 'return' => 'is_pay_later',
1882 if (empty($params['price_set_id'])) {
1883 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
1889 * Post form submission handling.
1891 * This is also called from the test suite.
1893 * @param int $contactID
1897 protected function processFormSubmission($contactID) {
1898 $isPayLater = $this->_params
['is_pay_later'];
1899 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] == 0) {
1900 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
1902 // add a description field at the very beginning
1903 $this->_params
['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $this->_values
['title']);
1905 $this->_params
['accountingCode'] = CRM_Utils_Array
::value('accountingCode', $this->_values
);
1908 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
1910 //carry payment processor id.
1911 if (CRM_Utils_Array
::value('id', $this->_paymentProcessor
)) {
1912 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
1915 $premiumParams = $membershipParams = $params = $this->_params
;
1916 if (!empty($params['image_URL'])) {
1917 CRM_Contact_BAO_Contact
::processImageParams($params);
1920 $fields = array('email-Primary' => 1);
1922 // get the add to groups
1923 $addToGroups = array();
1925 // now set the values for the billing location.
1926 foreach ($this->_fields
as $name => $value) {
1929 // get the add to groups for uf fields
1930 if (!empty($value['add_to_group_id'])) {
1931 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
1935 if (!array_key_exists('first_name', $fields)) {
1936 $nameFields = array('first_name', 'middle_name', 'last_name');
1937 foreach ($nameFields as $name) {
1939 if (array_key_exists("billing_$name", $params)) {
1940 $params[$name] = $params["billing_{$name}"];
1941 $params['preserveDBName'] = TRUE;
1946 // billing email address
1947 $fields["email-{$this->_bltID}"] = 1;
1949 //unset the billing parameters if it is pay later mode
1950 //to avoid creation of billing location
1951 if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater
) {
1952 $billingFields = array(
1953 'billing_first_name',
1954 'billing_middle_name',
1955 'billing_last_name',
1956 "billing_street_address-{$this->_bltID}",
1957 "billing_city-{$this->_bltID}",
1958 "billing_state_province-{$this->_bltID}",
1959 "billing_state_province_id-{$this->_bltID}",
1960 "billing_postal_code-{$this->_bltID}",
1961 "billing_country-{$this->_bltID}",
1962 "billing_country_id-{$this->_bltID}",
1965 foreach ($billingFields as $value) {
1966 unset($params[$value]);
1967 unset($fields[$value]);
1971 // if onbehalf-of-organization contribution, take out
1972 // organization params in a separate variable, to make sure
1973 // normal behavior is continued. And use that variable to
1974 // process on-behalf-of functionality.
1975 if (!empty($this->_params
['hidden_onbehalf_profile'])) {
1976 $behalfOrganization = array();
1977 $orgFields = array('organization_name', 'organization_id', 'org_option');
1978 foreach ($orgFields as $fld) {
1979 if (array_key_exists($fld, $params)) {
1980 $behalfOrganization[$fld] = $params[$fld];
1981 unset($params[$fld]);
1985 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
1986 foreach ($params['onbehalf'] as $fld => $values) {
1987 if (strstr($fld, 'custom_')) {
1988 $behalfOrganization[$fld] = $values;
1990 elseif (!(strstr($fld, '-'))) {
1991 if (in_array($fld, array(
1992 'contribution_campaign_id',
1993 'member_campaign_id',
1995 $fld = 'campaign_id';
1998 $behalfOrganization[$fld] = $values;
2000 $this->_params
[$fld] = $values;
2005 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2006 foreach ($params['onbehalf_location'] as $block => $vals) {
2007 //fix for custom data (of type checkbox, multi-select)
2008 if (substr($block, 0, 7) == 'custom_') {
2011 // fix the index of block elements
2012 if (is_array($vals)) {
2013 foreach ($vals as $key => $val) {
2014 //dont adjust the index of address block as
2015 //it's index is WRT to location type
2016 $newKey = ($block == 'address') ?
$key : ++
$key;
2017 $behalfOrganization[$block][$newKey] = $val;
2021 unset($params['onbehalf_location']);
2023 if (!empty($params['onbehalf[image_URL]'])) {
2024 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2028 // check for profile double opt-in and get groups to be subscribed
2029 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2031 // since we are directly adding contact to group lets unset it from mailing
2032 if (!empty($addToGroups)) {
2033 foreach ($addToGroups as $groupId) {
2034 if (isset($subscribeGroupIds[$groupId])) {
2035 unset($subscribeGroupIds[$groupId]);
2040 foreach ($addToGroups as $k) {
2041 if (array_key_exists($k, $subscribeGroupIds)) {
2042 unset($addToGroups[$k]);
2046 if (empty($contactID)) {
2047 $dupeParams = $params;
2048 if (!empty($dupeParams['onbehalf'])) {
2049 unset($dupeParams['onbehalf']);
2051 if (!empty($dupeParams['honor'])) {
2052 unset($dupeParams['honor']);
2055 $dedupeParams = CRM_Dedupe_Finder
::formatParams($dupeParams, 'Individual');
2056 $dedupeParams['check_permission'] = FALSE;
2057 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
2059 // if we find more than one contact, use the first one
2060 $contactID = CRM_Utils_Array
::value(0, $ids);
2062 // Fetch default greeting id's if creating a contact
2064 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2065 if (!isset($params[$greeting])) {
2066 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2070 $contactType = NULL;
2073 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2075 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2085 // Make the contact ID associated with the contribution available at the Class level.
2086 // Also make available to the session.
2087 //@todo consider handling this in $this->getContactID();
2088 $this->set('contactID', $contactID);
2089 $this->_contactID
= $contactID;
2091 //get email primary first if exist
2092 $subscriptionEmail = array('email' => CRM_Utils_Array
::value('email-Primary', $params));
2093 if (!$subscriptionEmail['email']) {
2094 $subscriptionEmail['email'] = CRM_Utils_Array
::value("email-{$this->_bltID}", $params);
2096 // subscribing contact to groups
2097 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2098 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2101 // If onbehalf-of-organization contribution / signup, add organization
2102 // and it's location.
2103 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
2104 $ufFields = array();
2105 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2106 $ufFields[$name] = 1;
2108 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2109 $this->_params
, $ufFields
2112 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2113 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2114 // store current user id as related contact for later use for mailing / activity..
2115 $this->_values
['related_contact'] = $contactID;
2116 $this->_params
['related_contact'] = $contactID;
2117 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2118 $contactID = $this->_membershipContactID
;
2121 // lets store the contactID in the session
2122 // for things like tell a friend
2123 $session = CRM_Core_Session
::singleton();
2124 if (!$session->get('userID')) {
2125 $session->set('transaction.userID', $contactID);
2128 $session->set('transaction.userID', NULL);
2131 $this->_useForMember
= $this->get('useForMember');
2133 // store the fact that this is a membership and membership type is selected
2134 if ((!empty($membershipParams['selectMembership']) &&
2135 $membershipParams['selectMembership'] != 'no_thanks'
2137 $this->_useForMember
2139 if (!$this->_useForMember
) {
2140 $this->assign('membership_assign', TRUE);
2141 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2144 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2145 $membershipParams['is_test'] = 1;
2147 if ($this->_params
['is_pay_later']) {
2148 $membershipParams['is_pay_later'] = 1;
2151 //inherit campaign from contribution page.
2152 if (!array_key_exists('campaign_id', $membershipParams)) {
2153 $membershipParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
);
2156 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2157 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater);
2160 // at this point we've created a contact and stored its address etc
2161 // all the payment processors expect the name and address to be in the
2162 // so we copy stuff over to first_name etc.
2163 $paymentParams = $this->_params
;
2165 if (!empty($paymentParams['onbehalf']) &&
2166 is_array($paymentParams['onbehalf'])
2168 foreach ($paymentParams['onbehalf'] as $key => $value) {
2169 if (strstr($key, 'custom_')) {
2170 $this->_params
[$key] = $value;
2175 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2177 $this->wrangleFinancialTypeID($this->_values
['financial_type_id']),
2179 ($this->_mode
== 'test') ?
1 : 0
2182 if (empty($result['is_payment_failure'])) {
2183 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2184 $this->postProcessPremium($premiumParams, $result['contribution']);
2186 if (!empty($result['contribution'])) {
2187 // Not quite sure why it would be empty at this stage but tests show it can be ... at least in tests.
2188 $this->completeTransaction($result, $result['contribution']->id
);
2195 * Membership processing section.
2197 * This is in a separate function as part of a move towards refactoring.
2199 * @param int $contactID
2200 * @param array $membershipParams
2201 * @param array $premiumParams
2202 * @param bool $isPayLater
2204 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater) {
2206 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2207 if (isset($this->_params
['related_contact'])) {
2208 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2211 $membershipParams['cms_contactID'] = $contactID;
2214 if (!empty($membershipParams['onbehalf']) &&
2215 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2217 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2220 $customFieldsFormatted = $fieldTypes = array();
2221 if (!empty($membershipParams['onbehalf']) &&
2222 is_array($membershipParams['onbehalf'])
2224 foreach ($membershipParams['onbehalf'] as $key => $value) {
2225 if (strstr($key, 'custom_')) {
2226 $customFieldId = explode('_', $key);
2227 CRM_Core_BAO_CustomField
::formatCustomField(
2229 $customFieldsFormatted,
2237 $fieldTypes = array('Contact', 'Organization', 'Membership');
2240 $priceFieldIds = $this->get('memberPriceFieldIDS');
2242 if (!empty($priceFieldIds)) {
2243 $contributionTypeID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2244 unset($priceFieldIds['id']);
2245 $membershipTypeIds = array();
2246 $membershipTypeTerms = array();
2247 foreach ($priceFieldIds as $priceFieldId) {
2248 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
2249 $membershipTypeIds[] = $id;
2250 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
2251 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
2253 if ($term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
2254 $membershipTypeTerms[$id] = ($term > 1) ?
$term : 1;
2257 $membershipTypeTerms[$id] = 1;
2261 $membershipParams['selectMembership'] = $membershipTypeIds;
2262 $membershipParams['financial_type_id'] = $contributionTypeID;
2263 $membershipParams['types_terms'] = $membershipTypeTerms;
2265 if (!empty($membershipParams['selectMembership'])) {
2267 $membershipLineItems = array();
2268 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2269 foreach ($this->_values
['fee'] as $key => $feeValues) {
2270 if ($feeValues['name'] == 'membership_amount') {
2271 $fieldId = $this->_params
['price_' . $key];
2272 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2273 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2279 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
2281 catch (CRM_Core_Exception
$e) {
2282 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2283 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2285 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2286 // we need to explicitly create a CMS user in case of free memberships
2287 // since it is done under processConfirm for paid memberships
2288 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2289 $membershipParams['cms_contactID'],
2290 'email-' . $this->_bltID
2297 * Complete transaction if payment has been processed.
2299 * Check the result for a success outcome & if paid then complete the transaction.
2301 * Completing will trigger update of related entities and emails.
2303 * @param array $result
2304 * @param int $contributionID
2306 * @throws \CRM_Core_Exception
2308 protected function completeTransaction($result, $contributionID) {
2309 if (CRM_Utils_Array
::value('payment_status_id', $result) == 1) {
2311 civicrm_api3('contribution', 'completetransaction', array(
2312 'id' => $contributionID,
2313 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $result),
2314 'payment_processor_id' => $this->_paymentProcessor
['id'],
2315 'is_transactional' => FALSE,
2316 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
2320 catch (CiviCRM_API3_Exception
$e) {
2321 if ($e->getErrorCode() != 'contribution_completed') {
2322 throw new CRM_Core_Exception('Failed to update contribution in database');