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');
192 if (!empty($this->_params
['onbehalf_values'])) {
193 $this->_params
['onbehalf'] = (array) json_decode($this->_params
['onbehalf_values']);
195 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
196 $this->_params
['amount'] = $this->get('amount');
197 if (isset($this->_params
['amount'])) {
198 $this->setFormAmountFields($this->_params
['priceSetId']);
201 $this->_params
['tax_amount'] = $this->get('tax_amount');
202 $this->_useForMember
= $this->get('useForMember');
204 if (isset($this->_params
['credit_card_exp_date'])) {
205 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
206 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
209 $this->_params
['currencyID'] = $config->defaultCurrency
;
211 if (!empty($this->_membershipBlock
)) {
212 $this->_params
['selectMembership'] = $this->get('selectMembership');
214 if (!empty($this->_paymentProcessor
) && $this->_paymentProcessor
['object']->supports('preApproval')) {
215 $preApprovalParams = $this->_paymentProcessor
['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
216 $this->_params
= array_merge($this->_params
, $preApprovalParams);
219 // We may have fetched some billing details from the getPreApprovalDetails function so we
220 // want to ensure we set this after that function has been called.
221 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $this->_params
, FALSE);
222 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
223 $this->_params
["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($this->_params
["billing_state_province_id-{$this->_bltID}"]);
225 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
226 $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
229 $this->_params
['is_pay_later'] = $this->get('is_pay_later');
230 $this->assign('is_pay_later', $this->_params
['is_pay_later']);
231 if ($this->_params
['is_pay_later']) {
232 $this->assign('pay_later_receipt', $this->_values
['pay_later_receipt']);
234 // if onbehalf-of-organization
235 if (!empty($this->_params
['onbehalf_profile_id'])) {
237 $this->_params
['organization_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_params
['onbehalf']['organization_name'], 'id', 'display_name');
239 $this->_params
['organization_name'] = $this->_params
['onbehalf']['organization_name'];
240 $addressBlocks = array(
246 'supplemental_address_1',
247 'supplemental_address_2',
248 'supplemental_address_3',
249 'postal_code_suffix',
255 $blocks = array('email', 'phone', 'im', 'url', 'openid');
256 foreach ($this->_params
['onbehalf'] as $loc => $value) {
257 $field = $typeId = NULL;
258 if (strstr($loc, '-')) {
259 list($field, $locType) = explode('-', $loc);
262 if (in_array($field, $addressBlocks)) {
263 if ($locType == 'Primary') {
264 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
265 $locType = $defaultLocationType->id
;
268 if ($field == 'country') {
269 $value = CRM_Core_PseudoConstant
::countryIsoCode($value);
271 elseif ($field == 'state_province') {
272 $value = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
276 if (isset($this->_params
['onbehalf_location']['address'])
277 && count($this->_params
['onbehalf_location']['address']) > 0
282 $this->_params
['onbehalf_location']['address'][$locType][$field] = $value;
283 if (empty($this->_params
['onbehalf_location']['address'][$locType]['is_primary'])) {
284 $this->_params
['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
286 $this->_params
['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
288 elseif (in_array($field, $blocks)) {
289 if (!$typeId ||
is_numeric($typeId)) {
290 $blockName = $fieldName = $field;
291 $locationType = 'location_type_id';
292 if ($locType == 'Primary') {
293 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
294 $locationValue = $defaultLocationType->id
;
297 $locationValue = $locType;
300 $phoneExtField = array();
302 if ($field == 'url') {
303 $blockName = 'website';
304 $locationType = 'website_type_id';
305 list($field, $locationValue) = explode('-', $loc);
307 elseif ($field == 'im') {
309 $locTypeId = 'provider_id';
310 $typeId = $this->_params
['onbehalf']["{$loc}-provider_id"];
312 elseif ($field == 'phone') {
313 list($field, $locType, $typeId) = explode('-', $loc);
314 $locTypeId = 'phone_type_id';
316 //check if extension field exists
317 $extField = str_replace('phone', 'phone_ext', $loc);
318 if (isset($this->_params
['onbehalf'][$extField])) {
319 $phoneExtField = array('phone_ext' => $this->_params
['onbehalf'][$extField]);
324 if (isset ($this->_params
['onbehalf_location'][$blockName])
325 && count($this->_params
['onbehalf_location'][$blockName]) > 0
329 if ($locationValue) {
330 $blockValues = array(
331 $fieldName => $value,
332 $locationType => $locationValue,
333 'is_primary' => $isPrimary,
337 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
339 if (!empty($phoneExtField)) {
340 $blockValues = array_merge($blockValues, $phoneExtField);
343 $this->_params
['onbehalf_location'][$blockName][] = $blockValues;
347 elseif (strstr($loc, 'custom')) {
348 if ($value && isset($this->_params
['onbehalf']["{$loc}_id"])) {
349 $value = $this->_params
['onbehalf']["{$loc}_id"];
351 $this->_params
['onbehalf_location']["{$loc}"] = $value;
354 if ($loc == 'contact_sub_type') {
355 $this->_params
['onbehalf_location'][$loc] = $value;
358 $this->_params
['onbehalf_location'][$field] = $value;
363 elseif (!empty($this->_values
['is_for_organization'])) {
364 // no on behalf of an organization, CRM-5519
365 // so reset loc blocks from main params.
371 if (isset($this->_params
[$blk])) {
372 unset($this->_params
[$blk]);
376 $this->setRecurringMembershipParams();
379 $params = $this->processPcp($this, $this->_params
);
380 $this->_params
= $params;
382 $this->_params
['invoiceID'] = $this->get('invoiceID');
384 //carry campaign from profile.
385 if (array_key_exists('contribution_campaign_id', $this->_params
)) {
386 $this->_params
['campaign_id'] = $this->_params
['contribution_campaign_id'];
389 // assign contribution page id to the template so we can add css class for it
390 $this->assign('contributionPageID', $this->_id
);
392 $this->set('params', $this->_params
);
396 * Build the form object.
398 public function buildQuickForm() {
399 $this->assignToTemplate();
401 $params = $this->_params
;
402 // make sure we have values for it
403 if ($this->_honor_block_is_active
&& !empty($params['soft_credit_type_id'])) {
405 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
407 $this->assign('honor_block_is_active', $this->_honor_block_is_active
);
408 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
409 CRM_Contribute_BAO_ContributionSoft
::formatHonoreeProfileFields($this, $params['honor'], $params['honoree_profile_id']);
411 $fieldTypes = array('Contact');
412 $fieldTypes[] = CRM_Core_BAO_UFGroup
::getContactType($params['honoree_profile_id']);
413 $this->buildCustom($params['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
415 $this->assign('receiptFromEmail', CRM_Utils_Array
::value('receipt_from_email', $this->_values
));
416 $amount_block_is_active = $this->get('amount_block_is_active');
417 $this->assign('amount_block_is_active', $amount_block_is_active);
419 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
420 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
422 $getTaxDetails = FALSE;
423 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
424 foreach ($this->_lineItem
as $key => $value) {
425 foreach ($value as $v) {
426 if (isset($v['tax_rate'])) {
427 if ($v['tax_rate'] != '') {
428 $getTaxDetails = TRUE;
433 $this->assign('getTaxDetails', $getTaxDetails);
434 $this->assign('taxTerm', $taxTerm);
435 $this->assign('totalTaxAmount', $params['tax_amount']);
437 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
438 $option = CRM_Utils_Array
::value('options_' . $params['selectProduct'], $params);
439 $productID = $params['selectProduct'];
440 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, FALSE,
443 $this->set('productID', $productID);
444 $this->set('option', $option);
446 $config = CRM_Core_Config
::singleton();
447 if (in_array('CiviMember', $config->enableComponents
)) {
448 if (isset($params['selectMembership']) &&
449 $params['selectMembership'] != 'no_thanks'
451 $this->buildMembershipBlock(
452 $this->_membershipContactID
,
454 $params['selectMembership'],
457 if (!empty($params['auto_renew'])) {
458 $this->assign('auto_renew', TRUE);
462 $this->assign('membershipBlock', FALSE);
465 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
466 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
468 if (!empty($params['onbehalf_profile_id'])) {
470 $fieldTypes = array('Contact', 'Organization');
471 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
472 $fieldTypes = array_merge($fieldTypes, $contactSubType);
473 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
474 $fieldTypes = array_merge($fieldTypes, array('Membership'));
477 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
480 $this->buildCustom($params['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
483 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
484 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
485 if ($this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
486 $this->assign('lineItem', $this->_lineItem
);
489 $this->assign('is_quick_config', 1);
490 $this->_params
['is_quick_config'] = 1;
492 $this->assign('priceSetID', $this->_priceSetId
);
493 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
494 if ($this->_paymentProcessor
&&
495 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('Google_Checkout', $paymentProcessorType)
496 && !$this->_params
['is_pay_later'] && !($this->_amount
== 0)
498 $this->_checkoutButtonName
= $this->getButtonName('next', 'checkout');
500 $this->_checkoutButtonName
,
501 $this->_paymentProcessor
['url_button'],
502 array('class' => 'crm-form-submit')
505 $this->addButtons(array(
508 'name' => ts('Go Back'),
514 if ($this->_contributeMode
== 'notify' ||
!$this->_values
['is_monetary'] ||
515 $this->_amount
<= 0.0 ||
$this->_params
['is_pay_later'] ||
516 ($this->_separateMembershipPayment
&& $this->_amount
<= 0.0)
518 $contribButton = ts('Continue');
519 $this->assign('button', ts('Continue'));
522 $contribButton = ts('Make Contribution');
523 $this->assign('button', ts('Make Contribution'));
525 $this->addButtons(array(
528 'name' => $contribButton,
529 'spacing' => ' ',
531 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name
. "','" . ts('Processing') . "');"),
535 'name' => ts('Go Back'),
542 $fields = array_fill_keys(array_keys($this->_fields
), 1);
543 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
545 $contact = $this->_params
;
546 foreach ($fields as $name => $dontCare) {
547 // Recursively set defaults for nested fields
548 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' ||
$name == 'honor')) {
549 foreach ($contact[$name] as $fieldName => $fieldValue) {
550 if (is_array($fieldValue) && !in_array($this->_fields
[$name][$fieldName]['html_type'], array(
555 foreach ($fieldValue as $key => $value) {
556 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
560 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
564 elseif (isset($contact[$name])) {
565 $defaults[$name] = $contact[$name];
566 if (substr($name, 0, 7) == 'custom_') {
567 $timeField = "{$name}_time";
568 if (isset($contact[$timeField])) {
569 $defaults[$timeField] = $contact[$timeField];
571 if (isset($contact["{$name}_id"])) {
572 $defaults["{$name}_id"] = $contact["{$name}_id"];
575 elseif (in_array($name, array(
579 )) && !empty($contact[$name . '_custom'])
581 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
586 $this->assign('useForMember', $this->get('useForMember'));
588 $this->setDefaults($defaults);
596 * Since we are only showing elements in frozen mode no help display needed.
600 public function getAction() {
601 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
602 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
605 return CRM_Core_Action
::VIEW
;
610 * Set default values for the form.
612 * Note that in edit/view mode
613 * the default values are retrieved from the database
615 public function setDefaultValues() {
621 public function postProcess() {
622 $contactID = $this->getContactID();
623 $result = $this->processFormSubmission($contactID);
624 if (is_array($result) && !empty($result['is_payment_failure'])) {
625 // We will probably have the function that gets this error throw an exception on the next round of refactoring.
626 CRM_Core_Session
::singleton()->setStatus(ts("Payment Processor Error message :") .
627 $result['error']->getMessage());
628 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
629 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
632 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
633 $this->set('params', $this->_params
);
637 * Wrangle financial type ID.
639 * 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
640 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
642 * Comments from previous refactor indicate doubt as to what was going on.
644 * @param int $contributionTypeId
646 * @return null|string
648 public function wrangleFinancialTypeID($contributionTypeId) {
649 if (isset($paymentParams['financial_type'])) {
650 $contributionTypeId = $paymentParams['financial_type'];
652 elseif (!empty($this->_values
['pledge_id'])) {
653 $contributionTypeId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
654 $this->_values
['pledge_id'],
658 return $contributionTypeId;
664 * @param array $premiumParams
665 * @param CRM_Contribute_BAO_Contribution $contribution
667 protected function postProcessPremium($premiumParams, $contribution) {
668 $hour = $minute = $second = 0;
669 // assigning Premium information to receipt tpl
670 $selectProduct = CRM_Utils_Array
::value('selectProduct', $premiumParams);
671 if ($selectProduct &&
672 $selectProduct != 'no_thanks'
674 $startDate = $endDate = "";
675 $this->assign('selectPremium', TRUE);
676 $productDAO = new CRM_Contribute_DAO_Product();
677 $productDAO->id
= $selectProduct;
678 $productDAO->find(TRUE);
679 $this->assign('product_name', $productDAO->name
);
680 $this->assign('price', $productDAO->price
);
681 $this->assign('sku', $productDAO->sku
);
682 $this->assign('option', CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams));
684 $periodType = $productDAO->period_type
;
687 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
688 $duration_unit = $productDAO->duration_unit
;
689 $duration_interval = $productDAO->duration_interval
;
690 if ($periodType == 'rolling') {
691 $startDate = date('Y-m-d');
693 elseif ($periodType == 'fixed') {
694 if ($fixed_period_start_day) {
695 $date = explode('-', date('Y-m-d'));
696 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
697 $day = substr($fixed_period_start_day, -2) . "<br/>";
699 $startDate = $year . '-' . $month . '-' . $day;
702 $startDate = date('Y-m-d');
706 $date = explode('-', $startDate);
711 switch ($duration_unit) {
713 $year = $year +
$duration_interval;
717 $month = $month +
$duration_interval;
721 $day = $day +
$duration_interval;
725 $day = $day +
($duration_interval * 7);
727 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
728 $this->assign('start_date', $startDate);
729 $this->assign('end_date', $endDate);
732 $dao = new CRM_Contribute_DAO_Premium();
733 $dao->entity_table
= 'civicrm_contribution_page';
734 $dao->entity_id
= $this->_id
;
736 $this->assign('contact_phone', $dao->premiums_contact_phone
);
737 $this->assign('contact_email', $dao->premiums_contact_email
);
739 //create Premium record
741 'product_id' => $premiumParams['selectProduct'],
742 'contribution_id' => $contribution->id
,
743 'product_option' => CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams),
745 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
746 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
748 if (!empty($premiumParams['selectProduct'])) {
749 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
750 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
751 $daoPremiumsProduct->premiums_id
= $dao->id
;
752 $daoPremiumsProduct->find(TRUE);
753 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
756 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
757 $daoContrProd->contribution_id
= $contribution->id
;
758 if ($daoContrProd->find(TRUE)) {
759 $params['id'] = $daoContrProd->id
;
762 CRM_Contribute_BAO_Contribution
::addPremium($params);
763 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
765 'cost' => $productDAO->cost
,
766 'currency' => $productDAO->currency
,
767 'financial_type_id' => $params['financial_type_id'],
768 'contributionId' => $contribution->id
,
770 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
773 elseif ($selectProduct == 'no_thanks') {
775 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
776 $daoContrProd->contribution_id
= $contribution->id
;
777 if ($daoContrProd->find(TRUE)) {
778 $daoContrProd->delete();
784 * Process the contribution.
786 * @param CRM_Core_Form $form
787 * @param array $params
788 * @param array $result
789 * @param array $contributionParams
790 * Parameters to be passed to contribution create action.
791 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
792 * passed consistently & 2) documenting them here.
797 * - contribution_page_id
800 * - thankyou_date (not all forms will set this)
802 * @param CRM_Financial_DAO_FinancialType $financialType
803 * @param bool $online
804 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
806 * @param int $billingLocationID
807 * ID of billing location type.
809 * @return \CRM_Contribute_DAO_Contribution
812 public static function processFormContribution(
821 $transaction = new CRM_Core_Transaction();
822 $contactID = $contributionParams['contact_id'];
824 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
825 $isSeparateMembershipPayment = empty($params['separate_membership_payment']) ?
FALSE : TRUE;
826 $pledgeID = empty($params['pledge_id']) ?
NULL : $params['pledge_id'];
827 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
828 (!empty($params['is_pledge']) ||
$pledgeID)) {
835 // add these values for the recurringContrib function ,CRM-10188
836 $params['financial_type_id'] = $financialType->id
;
838 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
840 //@todo - this is being set from the form to resolve CRM-10188 - an
841 // eNotice caused by it not being set @ the front end
842 // however, we then get it being over-written with null for backend contributions
843 // a better fix would be to set the values in the respective forms rather than require
844 // a function being shared by two forms to deal with their respective values
845 // moving it to the BAO & not taking the $form as a param would make sense here.
846 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
847 $params['is_email_receipt'] = $isEmailReceipt;
849 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType, $online);
850 $nonDeductibleAmount = self
::getNonDeductibleAmount($params, $financialType, $online);
852 $now = date('YmdHis');
853 $receiptDate = CRM_Utils_Array
::value('receipt_date', $params);
854 if ($isEmailReceipt) {
858 if (isset($params['amount'])) {
859 $contributionParams = array_merge(self
::getContributionParams(
860 $params, $financialType->id
, $nonDeductibleAmount, TRUE,
861 $result, $receiptDate,
862 $recurringContributionID), $contributionParams
864 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
866 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
867 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
869 $dataArray = array();
870 // @todo - interrogate the line items passed in on the params array.
871 // No reason to assume line items will be set on the form.
872 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
873 foreach ($lineItemValue as $key => $value) {
874 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
875 if (isset($dataArray[$value['tax_rate']])) {
876 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
879 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
884 $smarty = CRM_Core_Smarty
::singleton();
885 $smarty->assign('dataArray', $dataArray);
886 $smarty->assign('totalTaxAmount', $params['tax_amount']);
888 if (is_a($contribution, 'CRM_Core_Error')) {
889 $message = CRM_Core_Error
::getMessages($contribution);
890 CRM_Core_Error
::fatal($message);
893 // lets store it in the form variable so postProcess hook can get to this and use it
894 $form->_contributionID
= $contribution->id
;
897 // process soft credit / pcp params first
898 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
900 //CRM-13981, processing honor contact into soft-credit contribution
901 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
903 //handle pledge stuff.
906 //when user doing pledge payments.
907 //update the schedule when payment(s) are made
908 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
909 $scheduledAmount = CRM_Core_DAO
::getFieldValue(
910 'CRM_Pledge_DAO_PledgePayment',
916 $pledgePaymentParams = array(
918 'contribution_id' => $contribution->id
,
919 'status_id' => $contribution->contribution_status_id
,
920 'actual_amount' => $scheduledAmount,
923 CRM_Pledge_BAO_PledgePayment
::add($pledgePaymentParams);
926 //update pledge status according to the new payment statuses
927 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID);
930 //when user creating pledge record.
931 $pledgeParams = array();
932 $pledgeParams['contact_id'] = $contribution->contact_id
;
933 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount
;
934 $pledgeParams['contribution_id'] = $contribution->id
;
935 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id
;
936 $pledgeParams['financial_type_id'] = $contribution->financial_type_id
;
937 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
938 $pledgeParams['installments'] = $params['pledge_installments'];
939 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
940 if ($pledgeParams['frequency_unit'] == 'month') {
941 $pledgeParams['frequency_day'] = intval(date("d"));
944 $pledgeParams['frequency_day'] = 1;
946 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
947 $pledgeParams['status_id'] = $contribution->contribution_status_id
;
948 $pledgeParams['max_reminders'] = $form->_values
['max_reminders'];
949 $pledgeParams['initial_reminder_day'] = $form->_values
['initial_reminder_day'];
950 $pledgeParams['additional_reminder_day'] = $form->_values
['additional_reminder_day'];
951 $pledgeParams['is_test'] = $contribution->is_test
;
952 $pledgeParams['acknowledge_date'] = date('Ymd');
953 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
955 //inherit campaign from contirb page.
956 $pledgeParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $contributionParams);
958 $pledge = CRM_Pledge_BAO_Pledge
::create($pledgeParams);
960 $form->_params
['pledge_id'] = $pledge->id
;
962 //send acknowledgment email. only when pledge is created
964 //build params to send acknowledgment.
965 $pledgeParams['id'] = $pledge->id
;
966 $pledgeParams['receipt_from_name'] = $form->_values
['receipt_from_name'];
967 $pledgeParams['receipt_from_email'] = $form->_values
['receipt_from_email'];
969 //scheduled amount will be same as installment_amount.
970 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
972 //get total pledge amount.
973 $pledgeParams['total_pledge_amount'] = $pledge->amount
;
975 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($form, $pledgeParams);
980 if ($online && $contribution) {
981 CRM_Core_BAO_CustomValueTable
::postProcess($params,
982 'civicrm_contribution',
987 elseif ($contribution) {
988 //handle custom data.
989 $params['contribution_id'] = $contribution->id
;
990 if (!empty($params['custom']) &&
991 is_array($params['custom']) &&
992 !is_a($contribution, 'CRM_Core_Error')
994 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
998 if ($contribution && !empty($params['contribution_note'])) {
1000 'entity_table' => 'civicrm_contribution',
1001 'note' => $params['contribution_note'],
1002 'entity_id' => $contribution->id
,
1003 'contact_id' => $contribution->contact_id
,
1004 'modified_date' => date('Ymd'),
1007 CRM_Core_BAO_Note
::add($noteParams, array());
1010 if (isset($params['related_contact'])) {
1011 $contactID = $params['related_contact'];
1013 elseif (isset($params['cms_contactID'])) {
1014 $contactID = $params['cms_contactID'];
1017 //create contribution activity w/ individual and target
1018 //activity w/ organisation contact id when onbelf, CRM-4027
1019 $targetContactID = NULL;
1020 if (!empty($params['hidden_onbehalf_profile'])) {
1021 $targetContactID = $contribution->contact_id
;
1022 $contribution->contact_id
= $contactID;
1025 // create an activity record
1026 if ($contribution) {
1027 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
1030 $transaction->commit();
1031 // CRM-13074 - create the CMSUser after the transaction is completed as it
1032 // is not appropriate to delete a valid contribution if a user create problem occurs
1033 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($params,
1035 'email-' . $billingLocationID
1037 return $contribution;
1041 * Create the recurring contribution record.
1043 * @param CRM_Core_Form $form
1044 * @param array $params
1045 * @param int $contactID
1046 * @param string $contributionType
1047 * @param bool $online
1051 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1052 // return if this page is not set for recurring
1053 // or the user has not chosen the recurring option
1055 //this is online case validation.
1056 if ((empty($form->_values
['is_recur']) && $online) ||
empty($params['is_recur'])) {
1060 $recurParams = array('contact_id' => $contactID);
1061 $recurParams['amount'] = CRM_Utils_Array
::value('amount', $params);
1062 $recurParams['auto_renew'] = CRM_Utils_Array
::value('auto_renew', $params);
1063 $recurParams['frequency_unit'] = CRM_Utils_Array
::value('frequency_unit', $params);
1064 $recurParams['frequency_interval'] = CRM_Utils_Array
::value('frequency_interval', $params);
1065 $recurParams['installments'] = CRM_Utils_Array
::value('installments', $params);
1066 $recurParams['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $params);
1067 $recurParams['currency'] = CRM_Utils_Array
::value('currency', $params);
1069 // CRM-14354: For an auto-renewing membership with an additional contribution,
1070 // if separate payments is not enabled, make sure only the membership fee recurs
1071 if (!empty($form->_membershipBlock
)
1072 && $form->_membershipBlock
['is_separate_payment'] === '0'
1073 && isset($params['selectMembership'])
1074 && $form->_values
['is_allow_other_amount'] == '1'
1076 && !empty($form->_membershipTypeValues
)
1077 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1079 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1082 $recurParams['is_test'] = 0;
1083 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1084 (isset($form->_mode
) && ($form->_mode
== 'test'))
1086 $recurParams['is_test'] = 1;
1089 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1090 if (!empty($params['receive_date'])) {
1091 $recurParams['start_date'] = $params['receive_date'];
1093 $recurParams['invoice_id'] = CRM_Utils_Array
::value('invoiceID', $params);
1094 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1095 $recurParams['payment_processor_id'] = CRM_Utils_Array
::value('payment_processor_id', $params);
1096 $recurParams['is_email_receipt'] = CRM_Utils_Array
::value('is_email_receipt', $params);
1097 // we need to add a unique trxn_id to avoid a unique key error
1098 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1099 $recurParams['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params, $params['invoiceID']);
1100 $recurParams['financial_type_id'] = $contributionType->id
;
1102 if (!$online ||
$form->_values
['is_monetary']) {
1103 $recurParams['payment_instrument_id'] = 1;
1106 $campaignId = CRM_Utils_Array
::value('campaign_id', $params);
1108 if (!array_key_exists('campaign_id', $params)) {
1109 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1112 $recurParams['campaign_id'] = $campaignId;
1114 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1115 if (is_a($recurring, 'CRM_Core_Error')) {
1116 CRM_Core_Error
::displaySessionError($recurring);
1117 $urlString = 'civicrm/contribute/transact';
1118 $urlParams = '_qf_Main_display=true';
1119 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1120 $urlString = 'civicrm/contact/view/contribution';
1121 $urlParams = "action=add&cid={$form->_contactID}";
1123 $urlParams .= "&mode={$form->_mode}";
1126 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1129 return $recurring->id
;
1133 * Add on behalf of organization and it's location.
1135 * This situation occurs when on behalf of is enabled for the contribution page and the person
1136 * signing up does so on behalf of an organization.
1138 * @param array $behalfOrganization
1139 * array of organization info.
1140 * @param int $contactID
1141 * individual contact id. One.
1142 * who is doing the process of signup / contribution.
1144 * @param array $values
1145 * form values array.
1146 * @param array $params
1147 * @param array $fields
1148 * Array of fields from the onbehalf profile relevant to the organization.
1150 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1151 $isCurrentEmployer = FALSE;
1154 if (!empty($behalfOrganization['organization_id'])) {
1155 $orgID = $behalfOrganization['organization_id'];
1156 unset($behalfOrganization['organization_id']);
1157 $isCurrentEmployer = TRUE;
1160 // formalities for creating / editing organization.
1161 $behalfOrganization['contact_type'] = 'Organization';
1163 // get the relationship type id
1164 $relType = new CRM_Contact_DAO_RelationshipType();
1165 $relType->name_a_b
= 'Employee of';
1166 $relType->find(TRUE);
1167 $relTypeId = $relType->id
;
1169 // keep relationship params ready
1170 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1171 $relParams['is_permission_a_b'] = 1;
1172 $relParams['is_active'] = 1;
1175 // check if matching organization contact exists
1176 $dedupeParams = CRM_Dedupe_Finder
::formatParams($behalfOrganization, 'Organization');
1177 $dedupeParams['check_permission'] = FALSE;
1178 $dupeIDs = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1180 // CRM-6243 says to pick the first org even if more than one match
1181 if (count($dupeIDs) >= 1) {
1182 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1183 // don't allow name edit
1184 unset($behalfOrganization['organization_name']);
1188 // if found permissioned related organization, allow location edit
1189 $behalfOrganization['contact_id'] = $orgID;
1190 // don't allow name edit
1191 unset($behalfOrganization['organization_name']);
1194 // handling for image url
1195 if (!empty($behalfOrganization['image_URL'])) {
1196 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1199 // create organization, add location
1200 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1201 NULL, NULL, 'Organization'
1203 // create relationship
1204 $relParams['contact_check'][$orgID] = 1;
1205 $cid = array('contact' => $contactID);
1206 CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relParams, $cid);
1208 // if multiple match - send a duplicate alert
1209 if ($dupeIDs && (count($dupeIDs) > 1)) {
1210 $values['onbehalf_dupe_alert'] = 1;
1212 $params['onbehalf_dupe_alert'] = 1;
1215 // make sure organization-contact-id is considered for recording
1216 // contribution/membership etc..
1217 if ($contactID != $orgID) {
1218 // take a note of contact-id, so we can send the
1219 // receipt to individual contact as well.
1221 // required for mailing/template display ..etc
1222 $values['related_contact'] = $contactID;
1224 $params['related_contact'] = $contactID;
1226 //make this employee of relationship as current
1227 //employer / employee relationship, CRM-3532
1228 if ($isCurrentEmployer &&
1229 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1231 $isCurrentEmployer = FALSE;
1234 if (!$isCurrentEmployer && $orgID) {
1235 //build current employer params
1236 $currentEmpParams[$contactID] = $orgID;
1237 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1240 // contribution / signup will be done using this
1242 $contactID = $orgID;
1247 * Function used to send notification mail to pcp owner.
1249 * This is used by contribution and also event PCPs.
1251 * @param object $contribution
1252 * @param object $contributionSoft
1253 * Contribution object.
1255 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1256 $params = array('id' => $contributionSoft->pcp_id
);
1257 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1258 $ownerNotifyID = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1260 if ($ownerNotifyID != CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1261 (($ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1262 CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id
, 'is_notify')) ||
1263 $ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1264 $pcpInfoURL = CRM_Utils_System
::url('civicrm/pcp/info',
1265 "reset=1&id={$contributionSoft->pcp_id}",
1266 TRUE, NULL, FALSE, TRUE
1268 // set email in the template here
1269 // get the billing location type
1270 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1271 $billingLocationTypeId = array_search('Billing', $locationTypes);
1273 if ($billingLocationTypeId) {
1274 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
, FALSE, $billingLocationTypeId);
1276 // get primary location email if no email exist( for billing location).
1278 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
);
1280 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft->contact_id
);
1282 'page_title' => $pcpInfo['title'],
1283 'receive_date' => $contribution->receive_date
,
1284 'total_amount' => $contributionSoft->amount
,
1285 'donors_display_name' => $donorName,
1286 'donors_email' => $email,
1287 'pcpInfoURL' => $pcpInfoURL,
1288 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll
,
1289 'currency' => $contributionSoft->currency
,
1291 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1292 $sendTemplateParams = array(
1293 'groupName' => 'msg_tpl_workflow_contribution',
1294 'valueName' => 'pcp_owner_notify',
1295 'contactId' => $contributionSoft->contact_id
,
1296 'toEmail' => $ownerEmail,
1297 'toName' => $ownerName,
1298 'from' => "$domainValues[0] <$domainValues[1]>",
1299 'tplParams' => $tplParams,
1300 'PDFFilename' => 'receipt.pdf',
1302 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1307 * Function used to se pcp related defaults / params.
1309 * This is used by contribution and also event PCPs
1311 * @param CRM_Core_Form $page
1313 * @param array $params
1317 public static function processPcp(&$page, $params) {
1318 $params['pcp_made_through_id'] = $page->_pcpId
;
1319 $page->assign('pcpBlock', TRUE);
1320 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1321 $params['pcp_roll_nickname'] = ts('Anonymous');
1322 $params['pcp_is_anonymous'] = 1;
1325 $params['pcp_is_anonymous'] = 0;
1328 'pcp_display_in_roll',
1330 'pcp_roll_nickname',
1331 'pcp_personal_note',
1333 if (!empty($params[$val])) {
1334 $page->assign($val, $params[$val]);
1342 * Process membership.
1344 * @param array $membershipParams
1345 * @param int $contactID
1346 * @param array $customFieldsFormatted
1347 * @param array $fieldTypes
1348 * @param array $premiumParams
1349 * @param array $membershipLineItems
1350 * Line items specifically relating to memberships.
1351 * @param bool $isPayLater
1353 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1354 $membershipLineItems, $isPayLater) {
1356 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1357 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1358 $membershipType = empty($membershipTypes) ?
array() : reset($membershipTypes);
1359 $isPending = $this->getIsPending();
1361 $this->assign('membership_name', CRM_Utils_Array
::value('name', $membershipType));
1363 $isPaidMembership = FALSE;
1364 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1365 //amount must be greater than zero for
1366 //adding contribution record to contribution table.
1367 //this condition arises when separate membership payment is
1368 //enabled and contribution amount is not selected. fix for CRM-3010
1369 $isPaidMembership = TRUE;
1371 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1373 if ($this->_values
['amount_block_is_active']) {
1374 $financialTypeID = $this->_values
['financial_type_id'];
1377 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $membershipType, CRM_Utils_Array
::value('financial_type_id', $membershipParams));
1380 if (CRM_Utils_Array
::value('membership_source', $this->_params
)) {
1381 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1384 $this->postProcessMembership($membershipParams, $contactID,
1385 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1386 $membershipLineItems, $isPayLater, $isPending);
1388 $this->assign('membership_assign', TRUE);
1389 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1393 * Process the Memberships.
1395 * @param array $membershipParams
1396 * Array of membership fields.
1397 * @param int $contactID
1399 * @param CRM_Contribute_Form_Contribution_Confirm $form
1400 * Confirmation form object.
1402 * @param array $premiumParams
1403 * @param null $customFieldsFormatted
1404 * @param null $includeFieldTypes
1406 * @param array $membershipDetails
1408 * @param array $membershipTypeIDs
1410 * @param bool $isPaidMembership
1411 * @param array $membershipID
1413 * @param bool $isProcessSeparateMembershipTransaction
1415 * @param int $financialTypeID
1416 * @param array $membershipLineItems
1417 * Line items specific to membership payment that is separate to contribution.
1418 * @param bool $isPayLater
1419 * @param bool $isPending
1421 * @throws \CRM_Core_Exception
1423 protected function postProcessMembership(
1424 $membershipParams, $contactID, &$form, $premiumParams,
1425 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1426 $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending) {
1427 $membershipContribution = NULL;
1428 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1429 $errors = $createdMemberships = $paymentResult = array();
1431 if ($isPaidMembership) {
1432 if ($isProcessSeparateMembershipTransaction) {
1433 // If we have 2 transactions only one can use the invoice id.
1434 $membershipParams['invoiceID'] .= '-2';
1437 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1444 if (!empty($paymentResult['contribution'])) {
1445 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1446 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1447 $membershipContribution = $paymentResult['contribution'];
1448 // Save the contribution ID so that I can be used in email receipts
1449 // For example, if you need to generate a tax receipt for the donation only.
1450 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1454 if ($isProcessSeparateMembershipTransaction) {
1456 $form->_lineItem
= $membershipLineItems;
1457 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1458 unset($membershipParams['is_recur']);
1460 $membershipContribution = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams,
1461 $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1463 catch (CRM_Core_Exception
$e) {
1464 $errors[2] = $e->getMessage();
1465 $membershipContribution = NULL;
1470 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1471 $membershipContributionID = $membershipContribution->id
;
1474 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1475 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1476 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1478 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1479 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1480 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1481 foreach ($membershipTypeIDs as $memType) {
1482 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1483 if (!empty($membershipContribution)) {
1484 $pendingStatus = CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name');
1485 $pending = ($membershipContribution->contribution_status_id
== $pendingStatus) ?
TRUE : FALSE;
1488 $pending = $isPending;
1490 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
1492 $membershipSource = NULL;
1493 if (!empty($form->_params
['membership_source'])) {
1494 $membershipSource = $form->_params
['membership_source'];
1496 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
1497 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
1500 if (isset($form->_params
)) {
1501 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
1504 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
1505 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
1506 if (!array_key_exists('campaign_id', $form->_params
)) {
1507 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1511 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership
::renewMembership(
1512 $contactID, $memType, $isTest,
1513 date('YmdHis'), CRM_Utils_Array
::value('cms_contactID', $membershipParams),
1514 $customFieldsFormatted,
1515 $numTerms, $membershipID, $pending,
1516 $contributionRecurID, $membershipSource, $isPayLater, $campaignId
1518 $form->set('renewal_mode', $renewalMode);
1519 if (!empty($dates)) {
1520 $form->assign('mem_start_date',
1521 CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d')
1523 $form->assign('mem_end_date',
1524 CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d')
1528 if (!empty($membershipContribution)) {
1529 // update recurring id for membership record
1530 CRM_Member_BAO_Membership
::updateRecurMembership($membership, $membershipContribution);
1531 CRM_Member_BAO_Membership
::linkMembershipPayment($membership, $membershipContribution);
1534 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1535 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1536 if (!empty($priceFieldOp['membership_type_id']) &&
1537 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1539 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1540 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1541 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1544 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1547 $form->_values
['lineItem'] = $form->_lineItem
;
1548 $form->assign('lineItem', $form->_lineItem
);
1552 if (!empty($errors)) {
1553 $message = $this->compileErrorMessage($errors);
1554 throw new CRM_Core_Exception($message);
1556 $form->_params
['createdMembershipIDs'] = array();
1558 // CRM-7851 - Moved after processing Payment Errors
1559 //@todo - the reasoning for this being here seems a little outdated
1560 foreach ($createdMemberships as $createdMembership) {
1561 CRM_Core_BAO_CustomValueTable
::postProcess(
1563 'civicrm_membership',
1564 $createdMembership->id
,
1567 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1569 if (count($createdMemberships) == 1) {
1570 //presumably this is only relevant for exactly 1 membership
1571 $form->_params
['membershipID'] = $createdMembership->id
;
1574 //CRM-15232: Check if membership is created and on the basis of it use
1575 //membership receipt template to send payment receipt
1576 if (count($createdMemberships)) {
1577 $form->_values
['isMembership'] = TRUE;
1579 if (isset($membershipContributionID)) {
1580 $form->_values
['contribution_id'] = $membershipContributionID;
1582 if ($form->_contributeMode
) {
1583 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1584 // call postProcess hook before leaving
1585 $form->postProcessHook();
1587 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1588 $paymentActionResult = $payment->doPayment($form->_params
, 'contribute');
1589 $this->completeTransaction($paymentActionResult, $paymentResult['contribution']->id
);
1590 // Do not send an email if Recurring transaction is done via Direct Mode
1591 // Email will we sent when the IPN is received.
1595 //finally send an email receipt
1596 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1604 * Turn array of errors into message string.
1606 * @param array $errors
1610 protected function compileErrorMessage($errors) {
1611 foreach ($errors as $error) {
1612 if (is_string($error)) {
1613 $message[] = $error;
1616 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1620 * Where a second separate financial transaction is supported we will process it here.
1622 * @param int $contactID
1623 * @param CRM_Contribute_Form_Contribution_Confirm $form
1624 * @param array $tempParams
1625 * @param bool $isTest
1626 * @param array $lineItems
1627 * @param $minimumFee
1628 * @param int $financialTypeID
1630 * @throws CRM_Core_Exception
1632 * @return CRM_Contribute_BAO_Contribution
1634 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1636 $financialType = new CRM_Financial_DAO_FinancialType();
1637 $financialType->id
= $financialTypeID;
1638 $financialType->find(TRUE);
1639 $tempParams['amount'] = $minimumFee;
1640 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1642 //assign receive date when separate membership payment
1643 //and contribution amount not selected.
1644 if ($form->_amount
== 0) {
1645 $now = date('YmdHis');
1646 $form->_params
['receive_date'] = $now;
1647 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1648 $form->set('params', $form->_params
);
1649 $form->assign('receive_date', $receiveDate);
1652 $form->set('membership_amount', $minimumFee);
1653 $form->assign('membership_amount', $minimumFee);
1655 // we don't need to create the user twice, so lets disable cms_create_account
1656 // irrespective of the value, CRM-2888
1657 $tempParams['cms_create_account'] = 0;
1659 //set this variable as we are not creating pledge for
1660 //separate membership payment contribution.
1661 //so for differentiating membership contribution from
1662 //main contribution.
1663 $form->_params
['separate_membership_payment'] = 1;
1664 $contributionParams = array(
1665 'contact_id' => $contactID,
1666 'line_item' => $lineItems,
1667 'is_test' => $isTest,
1668 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $tempParams, CRM_Utils_Array
::value('campaign_id',
1670 'contribution_page_id' => $form->_id
,
1671 'source' => CRM_Utils_Array
::value('source', $tempParams, CRM_Utils_Array
::value('description', $tempParams)),
1673 $isMonetary = !empty($form->_values
['is_monetary']);
1675 if (empty($paymentParams['is_pay_later'])) {
1676 $contributionParams['payment_instrument_id'] = $form->_paymentProcessor
['payment_instrument_id'];
1679 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
1682 $contributionParams,
1688 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
1689 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1690 // now we compensate here.
1691 if (empty($form->_paymentProcessor
['object'])) {
1692 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1695 $payment = $form->_paymentProcessor
['object'];
1697 $result = $payment->doPayment($tempParams, 'contribute');
1698 $form->set('membership_trx_id', $result['trxn_id']);
1699 $form->assign('membership_trx_id', $result['trxn_id']);
1700 $this->completeTransaction($result, $membershipContribution->id
);
1703 return $membershipContribution;
1707 * Is the payment a pending payment.
1709 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1710 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1715 protected function getIsPending() {
1716 if (((isset($this->_contributeMode
)) ||
!empty
1717 ($this->_params
['is_pay_later'])
1719 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1727 * Are we going to do 2 financial transactions.
1729 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1731 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1733 * @param int $formID
1734 * @param bool $amountBlockActiveOnForm
1738 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1739 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1740 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1747 * This function sets the fields.
1749 * - $this->_params['amount_level']
1750 * - $this->_params['selectMembership']
1751 * And under certain circumstances sets
1752 * $this->_params['amount'] = null;
1754 * @param int $priceSetID
1756 public function setFormAmountFields($priceSetID) {
1757 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1758 $priceField = new CRM_Price_DAO_PriceField();
1759 $priceField->price_set_id
= $priceSetID;
1760 $priceField->orderBy('weight');
1761 $priceField->find();
1762 $paramWeDoNotUnderstand = NULL;
1764 while ($priceField->fetch()) {
1765 if ($priceField->name
== "contribution_amount") {
1766 $paramWeDoNotUnderstand = $priceField->id
;
1768 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1769 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1770 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1771 $this->_params
["price_{$priceField->id}"], 'label');
1773 if ($priceField->name
== "membership_amount") {
1774 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1775 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1778 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1779 // as membership amount.
1780 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1781 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1782 // so we should merge them together
1783 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1784 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1786 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
)
1787 && !empty($this->_values
['fee'][$priceField->id
])
1788 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1789 && CRM_Utils_Array
::value("price_{$paramWeDoNotUnderstand}", $this->_params
) < 1
1790 && empty($this->_params
["price_{$priceField->id}"])
1792 $this->_params
['amount'] = NULL;
1795 // Fix for CRM-14375 - If we are using separate payments and "no
1796 // thank you" is selected for the additional contribution, set
1797 // contribution amount to be null, so that it will not show
1798 // contribution amount same as membership amount.
1799 //@todo - merge with section above
1800 if ($this->_membershipBlock
['is_separate_payment']
1801 && !empty($this->_values
['fee'][$priceField->id
])
1802 && CRM_Utils_Array
::value('name', $this->_values
['fee'][$priceField->id
]) == 'contribution_amount'
1803 && CRM_Utils_Array
::value("price_{$priceField->id}", $this->_params
) == '-1'
1805 $this->_params
['amount'] = NULL;
1813 * @param array $params
1815 * @throws CiviCRM_API3_Exception
1817 public static function submit($params) {
1818 $form = new CRM_Contribute_Form_Contribution_Confirm();
1819 $form->_id
= $params['id'];
1821 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1822 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1823 //this way the mocked up controller ignores the session stuff
1824 $_SERVER['REQUEST_METHOD'] = 'GET';
1825 $form->controller
= new CRM_Contribute_Controller_Contribution();
1826 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1827 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1828 $form->_amount
= $params['amount'];
1829 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1830 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1831 $priceSetFields = reset($priceFields);
1832 $form->_values
['fee'] = $priceSetFields['fields'];
1833 $form->_priceSetId
= $priceSetID;
1834 $form->setFormAmountFields($priceSetID);
1835 if (!empty($params['payment_processor_id'])) {
1836 $form->_paymentProcessor
= civicrm_api3('payment_processor', 'getsingle', array(
1837 'id' => $params['payment_processor_id'],
1839 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1840 $form->_contributeMode
= 'direct';
1843 $form->_contributeMode
= 'notify';
1847 $form->_params
['payment_processor_id'] = 0;
1849 $priceFields = $priceFields[$priceSetID]['fields'];
1850 CRM_Price_BAO_PriceSet
::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1851 $form->_lineItem
= array($priceSetID => $lineItems);
1852 $form->processFormSubmission(CRM_Utils_Array
::value('contact_id', $params));
1856 * Helper function for static submit function.
1858 * Set relevant params - help us to build up an array that we can pass in.
1861 * @param array $params
1864 * @throws CiviCRM_API3_Exception
1866 public static function getFormParams($id, array $params) {
1867 if (!isset($params['is_pay_later'])) {
1868 if (!empty($params['payment_processor_id'])) {
1869 $params['is_pay_later'] = 0;
1872 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1874 'return' => 'is_pay_later',
1878 if (empty($params['price_set_id'])) {
1879 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
1885 * Post form submission handling.
1887 * This is also called from the test suite.
1889 * @param int $contactID
1893 protected function processFormSubmission($contactID) {
1894 $isPayLater = $this->_params
['is_pay_later'];
1895 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] == 0) {
1896 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
1898 // add a description field at the very beginning
1899 $this->_params
['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $this->_values
['title']);
1901 $this->_params
['accountingCode'] = CRM_Utils_Array
::value('accountingCode', $this->_values
);
1904 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
1906 //carry payment processor id.
1907 if (CRM_Utils_Array
::value('id', $this->_paymentProcessor
)) {
1908 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
1911 $premiumParams = $membershipParams = $params = $this->_params
;
1912 if (!empty($params['image_URL'])) {
1913 CRM_Contact_BAO_Contact
::processImageParams($params);
1916 $fields = array('email-Primary' => 1);
1918 // get the add to groups
1919 $addToGroups = array();
1921 // now set the values for the billing location.
1922 foreach ($this->_fields
as $name => $value) {
1925 // get the add to groups for uf fields
1926 if (!empty($value['add_to_group_id'])) {
1927 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
1931 if (!array_key_exists('first_name', $fields)) {
1932 $nameFields = array('first_name', 'middle_name', 'last_name');
1933 foreach ($nameFields as $name) {
1935 if (array_key_exists("billing_$name", $params)) {
1936 $params[$name] = $params["billing_{$name}"];
1937 $params['preserveDBName'] = TRUE;
1942 // billing email address
1943 $fields["email-{$this->_bltID}"] = 1;
1945 //unset the billing parameters if it is pay later mode
1946 //to avoid creation of billing location
1947 if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater
) {
1948 $billingFields = array(
1949 'billing_first_name',
1950 'billing_middle_name',
1951 'billing_last_name',
1952 "billing_street_address-{$this->_bltID}",
1953 "billing_city-{$this->_bltID}",
1954 "billing_state_province-{$this->_bltID}",
1955 "billing_state_province_id-{$this->_bltID}",
1956 "billing_postal_code-{$this->_bltID}",
1957 "billing_country-{$this->_bltID}",
1958 "billing_country_id-{$this->_bltID}",
1961 foreach ($billingFields as $value) {
1962 unset($params[$value]);
1963 unset($fields[$value]);
1967 // if onbehalf-of-organization contribution, take out
1968 // organization params in a separate variable, to make sure
1969 // normal behavior is continued. And use that variable to
1970 // process on-behalf-of functionality.
1971 if (!empty($this->_params
['onbehalf_profile_id'])) {
1972 $behalfOrganization = array();
1973 $orgFields = array('organization_name', 'organization_id', 'org_option');
1974 foreach ($orgFields as $fld) {
1975 if (array_key_exists($fld, $params)) {
1976 $behalfOrganization[$fld] = $params[$fld];
1977 unset($params[$fld]);
1981 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
1982 foreach ($params['onbehalf'] as $fld => $values) {
1983 if (strstr($fld, 'custom_')) {
1984 $behalfOrganization[$fld] = $values;
1986 elseif (!(strstr($fld, '-'))) {
1987 if (in_array($fld, array(
1988 'contribution_campaign_id',
1989 'member_campaign_id',
1991 $fld = 'campaign_id';
1994 $behalfOrganization[$fld] = $values;
1996 $this->_params
[$fld] = $values;
2001 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2002 foreach ($params['onbehalf_location'] as $block => $vals) {
2003 //fix for custom data (of type checkbox, multi-select)
2004 if (substr($block, 0, 7) == 'custom_') {
2007 // fix the index of block elements
2008 if (is_array($vals)) {
2009 foreach ($vals as $key => $val) {
2010 //dont adjust the index of address block as
2011 //it's index is WRT to location type
2012 $newKey = ($block == 'address') ?
$key : ++
$key;
2013 $behalfOrganization[$block][$newKey] = $val;
2017 unset($params['onbehalf_location']);
2019 if (!empty($params['onbehalf[image_URL]'])) {
2020 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2024 // check for profile double opt-in and get groups to be subscribed
2025 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2027 // since we are directly adding contact to group lets unset it from mailing
2028 if (!empty($addToGroups)) {
2029 foreach ($addToGroups as $groupId) {
2030 if (isset($subscribeGroupIds[$groupId])) {
2031 unset($subscribeGroupIds[$groupId]);
2036 foreach ($addToGroups as $k) {
2037 if (array_key_exists($k, $subscribeGroupIds)) {
2038 unset($addToGroups[$k]);
2042 if (empty($contactID)) {
2043 $dupeParams = $params;
2044 if (!empty($dupeParams['onbehalf'])) {
2045 unset($dupeParams['onbehalf']);
2047 if (!empty($dupeParams['honor'])) {
2048 unset($dupeParams['honor']);
2051 $dedupeParams = CRM_Dedupe_Finder
::formatParams($dupeParams, 'Individual');
2052 $dedupeParams['check_permission'] = FALSE;
2053 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
2055 // if we find more than one contact, use the first one
2056 $contactID = CRM_Utils_Array
::value(0, $ids);
2058 // Fetch default greeting id's if creating a contact
2060 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2061 if (!isset($params[$greeting])) {
2062 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2066 $contactType = NULL;
2069 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2071 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2081 // Make the contact ID associated with the contribution available at the Class level.
2082 // Also make available to the session.
2083 //@todo consider handling this in $this->getContactID();
2084 $this->set('contactID', $contactID);
2085 $this->_contactID
= $contactID;
2087 //get email primary first if exist
2088 $subscriptionEmail = array('email' => CRM_Utils_Array
::value('email-Primary', $params));
2089 if (!$subscriptionEmail['email']) {
2090 $subscriptionEmail['email'] = CRM_Utils_Array
::value("email-{$this->_bltID}", $params);
2092 // subscribing contact to groups
2093 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2094 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2097 // If onbehalf-of-organization contribution / signup, add organization
2098 // and it's location.
2099 if (isset($params['onbehalf_profile_id']) && isset($behalfOrganization['organization_name'])) {
2100 $ufFields = array();
2101 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2102 $ufFields[$name] = 1;
2104 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2105 $this->_params
, $ufFields
2108 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2109 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2110 // store current user id as related contact for later use for mailing / activity..
2111 $this->_values
['related_contact'] = $contactID;
2112 $this->_params
['related_contact'] = $contactID;
2113 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2114 $contactID = $this->_membershipContactID
;
2117 // lets store the contactID in the session
2118 // for things like tell a friend
2119 $session = CRM_Core_Session
::singleton();
2120 if (!$session->get('userID')) {
2121 $session->set('transaction.userID', $contactID);
2124 $session->set('transaction.userID', NULL);
2127 $this->_useForMember
= $this->get('useForMember');
2129 // store the fact that this is a membership and membership type is selected
2130 if ((!empty($membershipParams['selectMembership']) &&
2131 $membershipParams['selectMembership'] != 'no_thanks'
2133 $this->_useForMember
2135 if (!$this->_useForMember
) {
2136 $this->assign('membership_assign', TRUE);
2137 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2140 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2141 $membershipParams['is_test'] = 1;
2143 if ($this->_params
['is_pay_later']) {
2144 $membershipParams['is_pay_later'] = 1;
2147 //inherit campaign from contribution page.
2148 if (!array_key_exists('campaign_id', $membershipParams)) {
2149 $membershipParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
);
2152 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2153 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater);
2156 // at this point we've created a contact and stored its address etc
2157 // all the payment processors expect the name and address to be in the
2158 // so we copy stuff over to first_name etc.
2159 $paymentParams = $this->_params
;
2161 if (!empty($paymentParams['onbehalf']) &&
2162 is_array($paymentParams['onbehalf'])
2164 foreach ($paymentParams['onbehalf'] as $key => $value) {
2165 if (strstr($key, 'custom_')) {
2166 $this->_params
[$key] = $value;
2171 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2173 $this->wrangleFinancialTypeID($this->_values
['financial_type_id']),
2175 ($this->_mode
== 'test') ?
1 : 0
2178 if (empty($result['is_payment_failure'])) {
2179 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2180 $this->postProcessPremium($premiumParams, $result['contribution']);
2182 if (!empty($result['contribution'])) {
2183 // Not quite sure why it would be empty at this stage but tests show it can be ... at least in tests.
2184 $this->completeTransaction($result, $result['contribution']->id
);
2191 * Membership processing section.
2193 * This is in a separate function as part of a move towards refactoring.
2195 * @param int $contactID
2196 * @param array $membershipParams
2197 * @param array $premiumParams
2198 * @param bool $isPayLater
2200 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater) {
2202 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2203 if (isset($this->_params
['related_contact'])) {
2204 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2207 $membershipParams['cms_contactID'] = $contactID;
2210 if (!empty($membershipParams['onbehalf']) &&
2211 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2213 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2216 $customFieldsFormatted = $fieldTypes = array();
2217 if (!empty($membershipParams['onbehalf']) &&
2218 is_array($membershipParams['onbehalf'])
2220 foreach ($membershipParams['onbehalf'] as $key => $value) {
2221 if (strstr($key, 'custom_')) {
2222 $customFieldId = explode('_', $key);
2223 CRM_Core_BAO_CustomField
::formatCustomField(
2225 $customFieldsFormatted,
2233 $fieldTypes = array('Contact', 'Organization', 'Membership');
2236 $priceFieldIds = $this->get('memberPriceFieldIDS');
2238 if (!empty($priceFieldIds)) {
2239 $contributionTypeID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2240 unset($priceFieldIds['id']);
2241 $membershipTypeIds = array();
2242 $membershipTypeTerms = array();
2243 foreach ($priceFieldIds as $priceFieldId) {
2244 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
2245 $membershipTypeIds[] = $id;
2246 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
2247 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
2249 if ($term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
2250 $membershipTypeTerms[$id] = ($term > 1) ?
$term : 1;
2253 $membershipTypeTerms[$id] = 1;
2257 $membershipParams['selectMembership'] = $membershipTypeIds;
2258 $membershipParams['financial_type_id'] = $contributionTypeID;
2259 $membershipParams['types_terms'] = $membershipTypeTerms;
2261 if (!empty($membershipParams['selectMembership'])) {
2263 $membershipLineItems = array();
2264 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2265 foreach ($this->_values
['fee'] as $key => $feeValues) {
2266 if ($feeValues['name'] == 'membership_amount') {
2267 $fieldId = $this->_params
['price_' . $key];
2268 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2269 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2275 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
2277 catch (CRM_Core_Exception
$e) {
2278 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2279 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2281 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2282 // we need to explicitly create a CMS user in case of free memberships
2283 // since it is done under processConfirm for paid memberships
2284 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2285 $membershipParams['cms_contactID'],
2286 'email-' . $this->_bltID
2293 * Complete transaction if payment has been processed.
2295 * Check the result for a success outcome & if paid then complete the transaction.
2297 * Completing will trigger update of related entities and emails.
2299 * @param array $result
2300 * @param int $contributionID
2302 * @throws \CRM_Core_Exception
2304 protected function completeTransaction($result, $contributionID) {
2305 if (CRM_Utils_Array
::value('payment_status_id', $result) == 1) {
2307 civicrm_api3('contribution', 'completetransaction', array(
2308 'id' => $contributionID,
2309 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $result),
2310 'payment_processor_id' => $this->_paymentProcessor
['id'],
2311 'is_transactional' => FALSE,
2312 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
2316 catch (CiviCRM_API3_Exception
$e) {
2317 if ($e->getErrorCode() != 'contribution_completed') {
2318 throw new CRM_Core_Exception('Failed to update contribution in database');