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->_values
['onbehalf_profile_id']) && !empty($this->_params
['onbehalf']['organization_name'])) {
233 $this->_params
['organization_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_params
['onbehalf']['organization_name'], 'id', 'display_name');
235 $this->_params
['organization_name'] = $this->_params
['onbehalf']['organization_name'];
236 $addressBlocks = array(
242 'supplemental_address_1',
243 'supplemental_address_2',
244 'supplemental_address_3',
245 'postal_code_suffix',
251 $blocks = array('email', 'phone', 'im', 'url', 'openid');
252 foreach ($this->_params
['onbehalf'] as $loc => $value) {
253 $field = $typeId = NULL;
254 if (strstr($loc, '-')) {
255 list($field, $locType) = explode('-', $loc);
258 if (in_array($field, $addressBlocks)) {
259 if ($locType == 'Primary') {
260 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
261 $locType = $defaultLocationType->id
;
264 if ($field == 'country') {
265 $value = CRM_Core_PseudoConstant
::countryIsoCode($value);
267 elseif ($field == 'state_province') {
268 $value = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
272 if (isset($this->_params
['onbehalf_location']['address'])
273 && count($this->_params
['onbehalf_location']['address']) > 0
278 $this->_params
['onbehalf_location']['address'][$locType][$field] = $value;
279 if (empty($this->_params
['onbehalf_location']['address'][$locType]['is_primary'])) {
280 $this->_params
['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
282 $this->_params
['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
284 elseif (in_array($field, $blocks)) {
285 if (!$typeId ||
is_numeric($typeId)) {
286 $blockName = $fieldName = $field;
287 $locationType = 'location_type_id';
288 if ($locType == 'Primary') {
289 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
290 $locationValue = $defaultLocationType->id
;
293 $locationValue = $locType;
296 $phoneExtField = array();
298 if ($field == 'url') {
299 $blockName = 'website';
300 $locationType = 'website_type_id';
301 list($field, $locationValue) = explode('-', $loc);
303 elseif ($field == 'im') {
305 $locTypeId = 'provider_id';
306 $typeId = $this->_params
['onbehalf']["{$loc}-provider_id"];
308 elseif ($field == 'phone') {
309 list($field, $locType, $typeId) = explode('-', $loc);
310 $locTypeId = 'phone_type_id';
312 //check if extension field exists
313 $extField = str_replace('phone', 'phone_ext', $loc);
314 if (isset($this->_params
['onbehalf'][$extField])) {
315 $phoneExtField = array('phone_ext' => $this->_params
['onbehalf'][$extField]);
320 if (isset ($this->_params
['onbehalf_location'][$blockName])
321 && count($this->_params
['onbehalf_location'][$blockName]) > 0
325 if ($locationValue) {
326 $blockValues = array(
327 $fieldName => $value,
328 $locationType => $locationValue,
329 'is_primary' => $isPrimary,
333 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
335 if (!empty($phoneExtField)) {
336 $blockValues = array_merge($blockValues, $phoneExtField);
339 $this->_params
['onbehalf_location'][$blockName][] = $blockValues;
343 elseif (strstr($loc, 'custom')) {
344 if ($value && isset($this->_params
['onbehalf']["{$loc}_id"])) {
345 $value = $this->_params
['onbehalf']["{$loc}_id"];
347 $this->_params
['onbehalf_location']["{$loc}"] = $value;
350 if ($loc == 'contact_sub_type') {
351 $this->_params
['onbehalf_location'][$loc] = $value;
354 $this->_params
['onbehalf_location'][$field] = $value;
359 elseif (!empty($this->_values
['is_for_organization'])) {
360 // no on behalf of an organization, CRM-5519
361 // so reset loc blocks from main params.
367 if (isset($this->_params
[$blk])) {
368 unset($this->_params
[$blk]);
372 $this->setRecurringMembershipParams();
375 $params = $this->processPcp($this, $this->_params
);
376 $this->_params
= $params;
378 $this->_params
['invoiceID'] = $this->get('invoiceID');
380 //carry campaign from profile.
381 if (array_key_exists('contribution_campaign_id', $this->_params
)) {
382 $this->_params
['campaign_id'] = $this->_params
['contribution_campaign_id'];
385 // assign contribution page id to the template so we can add css class for it
386 $this->assign('contributionPageID', $this->_id
);
388 $this->set('params', $this->_params
);
392 * Build the form object.
394 public function buildQuickForm() {
395 $this->assignToTemplate();
397 $params = $this->_params
;
398 // make sure we have values for it
399 if (!empty($this->_values
['honoree_profile_id']) && !empty($params['soft_credit_type_id'])) {
401 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
403 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
404 CRM_Contribute_BAO_ContributionSoft
::formatHonoreeProfileFields($this, $params['honor']);
406 $fieldTypes = array('Contact');
407 $fieldTypes[] = CRM_Core_BAO_UFGroup
::getContactType($this->_values
['honoree_profile_id']);
408 $this->buildCustom($this->_values
['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
410 $this->assign('receiptFromEmail', CRM_Utils_Array
::value('receipt_from_email', $this->_values
));
411 $amount_block_is_active = $this->get('amount_block_is_active');
412 $this->assign('amount_block_is_active', $amount_block_is_active);
414 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
415 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
417 $getTaxDetails = FALSE;
418 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
419 foreach ($this->_lineItem
as $key => $value) {
420 foreach ($value as $v) {
421 if (isset($v['tax_rate'])) {
422 if ($v['tax_rate'] != '') {
423 $getTaxDetails = TRUE;
428 $this->assign('getTaxDetails', $getTaxDetails);
429 $this->assign('taxTerm', $taxTerm);
430 $this->assign('totalTaxAmount', $params['tax_amount']);
432 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
433 $option = CRM_Utils_Array
::value('options_' . $params['selectProduct'], $params);
434 $productID = $params['selectProduct'];
435 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, FALSE,
438 $this->set('productID', $productID);
439 $this->set('option', $option);
441 $config = CRM_Core_Config
::singleton();
442 if (in_array('CiviMember', $config->enableComponents
)) {
443 if (isset($params['selectMembership']) &&
444 $params['selectMembership'] != 'no_thanks'
446 $this->buildMembershipBlock(
447 $this->_membershipContactID
,
449 $params['selectMembership'],
452 if (!empty($params['auto_renew'])) {
453 $this->assign('auto_renew', TRUE);
457 $this->assign('membershipBlock', FALSE);
460 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
461 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
463 if (!empty($this->_values
['onbehalf_profile_id']) && !empty($params['onbehalf'])) {
464 $fieldTypes = array('Contact', 'Organization');
465 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
466 $fieldTypes = array_merge($fieldTypes, $contactSubType);
467 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
468 $fieldTypes = array_merge($fieldTypes, array('Membership'));
471 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
474 $this->buildCustom($this->_values
['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
477 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
478 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
479 if ($this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
480 $this->assign('lineItem', $this->_lineItem
);
483 $this->assign('is_quick_config', 1);
484 $this->_params
['is_quick_config'] = 1;
486 $this->assign('priceSetID', $this->_priceSetId
);
487 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
488 if ($this->_paymentProcessor
&&
489 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('Google_Checkout', $paymentProcessorType)
490 && !$this->_params
['is_pay_later'] && !($this->_amount
== 0)
492 $this->_checkoutButtonName
= $this->getButtonName('next', 'checkout');
494 $this->_checkoutButtonName
,
495 $this->_paymentProcessor
['url_button'],
496 array('class' => 'crm-form-submit')
499 $this->addButtons(array(
502 'name' => ts('Go Back'),
508 if ($this->_contributeMode
== 'notify' ||
!$this->_values
['is_monetary'] ||
509 $this->_amount
<= 0.0 ||
$this->_params
['is_pay_later'] ||
510 ($this->_separateMembershipPayment
&& $this->_amount
<= 0.0)
512 $contribButton = ts('Continue');
513 $this->assign('button', ts('Continue'));
516 $contribButton = ts('Make Contribution');
517 $this->assign('button', ts('Make Contribution'));
519 $this->addButtons(array(
522 'name' => $contribButton,
523 'spacing' => ' ',
525 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name
. "','" . ts('Processing') . "');"),
529 'name' => ts('Go Back'),
536 $fields = array_fill_keys(array_keys($this->_fields
), 1);
537 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
539 $contact = $this->_params
;
540 foreach ($fields as $name => $dontCare) {
541 // Recursively set defaults for nested fields
542 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' ||
$name == 'honor')) {
543 foreach ($contact[$name] as $fieldName => $fieldValue) {
544 if (is_array($fieldValue) && !in_array($this->_fields
[$name][$fieldName]['html_type'], array(
549 foreach ($fieldValue as $key => $value) {
550 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
554 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
558 elseif (isset($contact[$name])) {
559 $defaults[$name] = $contact[$name];
560 if (substr($name, 0, 7) == 'custom_') {
561 $timeField = "{$name}_time";
562 if (isset($contact[$timeField])) {
563 $defaults[$timeField] = $contact[$timeField];
565 if (isset($contact["{$name}_id"])) {
566 $defaults["{$name}_id"] = $contact["{$name}_id"];
569 elseif (in_array($name, array(
573 )) && !empty($contact[$name . '_custom'])
575 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
580 $this->assign('useForMember', $this->get('useForMember'));
582 $this->setDefaults($defaults);
590 * Since we are only showing elements in frozen mode no help display needed.
594 public function getAction() {
595 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
596 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
599 return CRM_Core_Action
::VIEW
;
604 * Set default values for the form.
606 * Note that in edit/view mode
607 * the default values are retrieved from the database
609 public function setDefaultValues() {
615 public function postProcess() {
616 $contactID = $this->getContactID();
617 $result = $this->processFormSubmission($contactID);
618 if (is_array($result) && !empty($result['is_payment_failure'])) {
619 // We will probably have the function that gets this error throw an exception on the next round of refactoring.
620 CRM_Core_Session
::singleton()->setStatus(ts("Payment Processor Error message :") .
621 $result['error']->getMessage());
622 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
623 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
626 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
627 $this->set('params', $this->_params
);
631 * Wrangle financial type ID.
633 * 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
634 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
636 * Comments from previous refactor indicate doubt as to what was going on.
638 * @param int $contributionTypeId
640 * @return null|string
642 public function wrangleFinancialTypeID($contributionTypeId) {
643 if (isset($paymentParams['financial_type'])) {
644 $contributionTypeId = $paymentParams['financial_type'];
646 elseif (!empty($this->_values
['pledge_id'])) {
647 $contributionTypeId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
648 $this->_values
['pledge_id'],
652 return $contributionTypeId;
658 * @param array $premiumParams
659 * @param CRM_Contribute_BAO_Contribution $contribution
661 protected function postProcessPremium($premiumParams, $contribution) {
662 $hour = $minute = $second = 0;
663 // assigning Premium information to receipt tpl
664 $selectProduct = CRM_Utils_Array
::value('selectProduct', $premiumParams);
665 if ($selectProduct &&
666 $selectProduct != 'no_thanks'
668 $startDate = $endDate = "";
669 $this->assign('selectPremium', TRUE);
670 $productDAO = new CRM_Contribute_DAO_Product();
671 $productDAO->id
= $selectProduct;
672 $productDAO->find(TRUE);
673 $this->assign('product_name', $productDAO->name
);
674 $this->assign('price', $productDAO->price
);
675 $this->assign('sku', $productDAO->sku
);
676 $this->assign('option', CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams));
678 $periodType = $productDAO->period_type
;
681 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
682 $duration_unit = $productDAO->duration_unit
;
683 $duration_interval = $productDAO->duration_interval
;
684 if ($periodType == 'rolling') {
685 $startDate = date('Y-m-d');
687 elseif ($periodType == 'fixed') {
688 if ($fixed_period_start_day) {
689 $date = explode('-', date('Y-m-d'));
690 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
691 $day = substr($fixed_period_start_day, -2) . "<br/>";
693 $startDate = $year . '-' . $month . '-' . $day;
696 $startDate = date('Y-m-d');
700 $date = explode('-', $startDate);
705 switch ($duration_unit) {
707 $year = $year +
$duration_interval;
711 $month = $month +
$duration_interval;
715 $day = $day +
$duration_interval;
719 $day = $day +
($duration_interval * 7);
721 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
722 $this->assign('start_date', $startDate);
723 $this->assign('end_date', $endDate);
726 $dao = new CRM_Contribute_DAO_Premium();
727 $dao->entity_table
= 'civicrm_contribution_page';
728 $dao->entity_id
= $this->_id
;
730 $this->assign('contact_phone', $dao->premiums_contact_phone
);
731 $this->assign('contact_email', $dao->premiums_contact_email
);
733 //create Premium record
735 'product_id' => $premiumParams['selectProduct'],
736 'contribution_id' => $contribution->id
,
737 'product_option' => CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams),
739 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
740 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
742 if (!empty($premiumParams['selectProduct'])) {
743 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
744 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
745 $daoPremiumsProduct->premiums_id
= $dao->id
;
746 $daoPremiumsProduct->find(TRUE);
747 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
750 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
751 $daoContrProd->contribution_id
= $contribution->id
;
752 if ($daoContrProd->find(TRUE)) {
753 $params['id'] = $daoContrProd->id
;
756 CRM_Contribute_BAO_Contribution
::addPremium($params);
757 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
759 'cost' => $productDAO->cost
,
760 'currency' => $productDAO->currency
,
761 'financial_type_id' => $params['financial_type_id'],
762 'contributionId' => $contribution->id
,
764 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
767 elseif ($selectProduct == 'no_thanks') {
769 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
770 $daoContrProd->contribution_id
= $contribution->id
;
771 if ($daoContrProd->find(TRUE)) {
772 $daoContrProd->delete();
778 * Process the contribution.
780 * @param CRM_Core_Form $form
781 * @param array $params
782 * @param array $result
783 * @param array $contributionParams
784 * Parameters to be passed to contribution create action.
785 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
786 * passed consistently & 2) documenting them here.
791 * - contribution_page_id
794 * - thankyou_date (not all forms will set this)
796 * @param CRM_Financial_DAO_FinancialType $financialType
797 * @param bool $online
798 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
800 * @param int $billingLocationID
801 * ID of billing location type.
803 * @return \CRM_Contribute_DAO_Contribution
806 public static function processFormContribution(
815 $transaction = new CRM_Core_Transaction();
816 $contactID = $contributionParams['contact_id'];
818 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
819 $isSeparateMembershipPayment = empty($params['separate_membership_payment']) ?
FALSE : TRUE;
820 $pledgeID = empty($params['pledge_id']) ?
NULL : $params['pledge_id'];
821 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
822 (!empty($params['is_pledge']) ||
$pledgeID)) {
829 // add these values for the recurringContrib function ,CRM-10188
830 $params['financial_type_id'] = $financialType->id
;
832 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
834 //@todo - this is being set from the form to resolve CRM-10188 - an
835 // eNotice caused by it not being set @ the front end
836 // however, we then get it being over-written with null for backend contributions
837 // a better fix would be to set the values in the respective forms rather than require
838 // a function being shared by two forms to deal with their respective values
839 // moving it to the BAO & not taking the $form as a param would make sense here.
840 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
841 $params['is_email_receipt'] = $isEmailReceipt;
843 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType, $online);
844 $nonDeductibleAmount = self
::getNonDeductibleAmount($params, $financialType, $online);
846 $now = date('YmdHis');
847 $receiptDate = CRM_Utils_Array
::value('receipt_date', $params);
848 if ($isEmailReceipt) {
852 if (isset($params['amount'])) {
853 $contributionParams = array_merge(self
::getContributionParams(
854 $params, $financialType->id
, $nonDeductibleAmount, TRUE,
855 $result, $receiptDate,
856 $recurringContributionID), $contributionParams
858 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
860 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
861 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
863 $dataArray = array();
864 // @todo - interrogate the line items passed in on the params array.
865 // No reason to assume line items will be set on the form.
866 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
867 foreach ($lineItemValue as $key => $value) {
868 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
869 if (isset($dataArray[$value['tax_rate']])) {
870 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
873 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
878 $smarty = CRM_Core_Smarty
::singleton();
879 $smarty->assign('dataArray', $dataArray);
880 $smarty->assign('totalTaxAmount', $params['tax_amount']);
882 if (is_a($contribution, 'CRM_Core_Error')) {
883 $message = CRM_Core_Error
::getMessages($contribution);
884 CRM_Core_Error
::fatal($message);
887 // lets store it in the form variable so postProcess hook can get to this and use it
888 $form->_contributionID
= $contribution->id
;
891 // process soft credit / pcp params first
892 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
894 //CRM-13981, processing honor contact into soft-credit contribution
895 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
897 //handle pledge stuff.
900 //when user doing pledge payments.
901 //update the schedule when payment(s) are made
902 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
903 $scheduledAmount = CRM_Core_DAO
::getFieldValue(
904 'CRM_Pledge_DAO_PledgePayment',
910 $pledgePaymentParams = array(
912 'contribution_id' => $contribution->id
,
913 'status_id' => $contribution->contribution_status_id
,
914 'actual_amount' => $scheduledAmount,
917 CRM_Pledge_BAO_PledgePayment
::add($pledgePaymentParams);
920 //update pledge status according to the new payment statuses
921 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID);
924 //when user creating pledge record.
925 $pledgeParams = array();
926 $pledgeParams['contact_id'] = $contribution->contact_id
;
927 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount
;
928 $pledgeParams['contribution_id'] = $contribution->id
;
929 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id
;
930 $pledgeParams['financial_type_id'] = $contribution->financial_type_id
;
931 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
932 $pledgeParams['installments'] = $params['pledge_installments'];
933 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
934 if ($pledgeParams['frequency_unit'] == 'month') {
935 $pledgeParams['frequency_day'] = intval(date("d"));
938 $pledgeParams['frequency_day'] = 1;
940 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
941 $pledgeParams['status_id'] = $contribution->contribution_status_id
;
942 $pledgeParams['max_reminders'] = $form->_values
['max_reminders'];
943 $pledgeParams['initial_reminder_day'] = $form->_values
['initial_reminder_day'];
944 $pledgeParams['additional_reminder_day'] = $form->_values
['additional_reminder_day'];
945 $pledgeParams['is_test'] = $contribution->is_test
;
946 $pledgeParams['acknowledge_date'] = date('Ymd');
947 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
949 //inherit campaign from contirb page.
950 $pledgeParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $contributionParams);
952 $pledge = CRM_Pledge_BAO_Pledge
::create($pledgeParams);
954 $form->_params
['pledge_id'] = $pledge->id
;
956 //send acknowledgment email. only when pledge is created
958 //build params to send acknowledgment.
959 $pledgeParams['id'] = $pledge->id
;
960 $pledgeParams['receipt_from_name'] = $form->_values
['receipt_from_name'];
961 $pledgeParams['receipt_from_email'] = $form->_values
['receipt_from_email'];
963 //scheduled amount will be same as installment_amount.
964 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
966 //get total pledge amount.
967 $pledgeParams['total_pledge_amount'] = $pledge->amount
;
969 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($form, $pledgeParams);
974 if ($online && $contribution) {
975 CRM_Core_BAO_CustomValueTable
::postProcess($params,
976 'civicrm_contribution',
981 elseif ($contribution) {
982 //handle custom data.
983 $params['contribution_id'] = $contribution->id
;
984 if (!empty($params['custom']) &&
985 is_array($params['custom']) &&
986 !is_a($contribution, 'CRM_Core_Error')
988 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
992 if ($contribution && !empty($params['contribution_note'])) {
994 'entity_table' => 'civicrm_contribution',
995 'note' => $params['contribution_note'],
996 'entity_id' => $contribution->id
,
997 'contact_id' => $contribution->contact_id
,
998 'modified_date' => date('Ymd'),
1001 CRM_Core_BAO_Note
::add($noteParams, array());
1004 if (isset($params['related_contact'])) {
1005 $contactID = $params['related_contact'];
1007 elseif (isset($params['cms_contactID'])) {
1008 $contactID = $params['cms_contactID'];
1011 //create contribution activity w/ individual and target
1012 //activity w/ organisation contact id when onbelf, CRM-4027
1013 $targetContactID = NULL;
1014 if (!empty($params['hidden_onbehalf_profile'])) {
1015 $targetContactID = $contribution->contact_id
;
1016 $contribution->contact_id
= $contactID;
1019 // create an activity record
1020 if ($contribution) {
1021 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
1024 $transaction->commit();
1025 // CRM-13074 - create the CMSUser after the transaction is completed as it
1026 // is not appropriate to delete a valid contribution if a user create problem occurs
1027 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($params,
1029 'email-' . $billingLocationID
1031 return $contribution;
1035 * Create the recurring contribution record.
1037 * @param CRM_Core_Form $form
1038 * @param array $params
1039 * @param int $contactID
1040 * @param string $contributionType
1041 * @param bool $online
1045 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1046 // return if this page is not set for recurring
1047 // or the user has not chosen the recurring option
1049 //this is online case validation.
1050 if ((empty($form->_values
['is_recur']) && $online) ||
empty($params['is_recur'])) {
1054 $recurParams = array('contact_id' => $contactID);
1055 $recurParams['amount'] = CRM_Utils_Array
::value('amount', $params);
1056 $recurParams['auto_renew'] = CRM_Utils_Array
::value('auto_renew', $params);
1057 $recurParams['frequency_unit'] = CRM_Utils_Array
::value('frequency_unit', $params);
1058 $recurParams['frequency_interval'] = CRM_Utils_Array
::value('frequency_interval', $params);
1059 $recurParams['installments'] = CRM_Utils_Array
::value('installments', $params);
1060 $recurParams['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $params);
1061 $recurParams['currency'] = CRM_Utils_Array
::value('currency', $params);
1063 // CRM-14354: For an auto-renewing membership with an additional contribution,
1064 // if separate payments is not enabled, make sure only the membership fee recurs
1065 if (!empty($form->_membershipBlock
)
1066 && $form->_membershipBlock
['is_separate_payment'] === '0'
1067 && isset($params['selectMembership'])
1068 && $form->_values
['is_allow_other_amount'] == '1'
1070 && !empty($form->_membershipTypeValues
)
1071 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1073 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1076 $recurParams['is_test'] = 0;
1077 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1078 (isset($form->_mode
) && ($form->_mode
== 'test'))
1080 $recurParams['is_test'] = 1;
1083 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1084 if (!empty($params['receive_date'])) {
1085 $recurParams['start_date'] = $params['receive_date'];
1087 $recurParams['invoice_id'] = CRM_Utils_Array
::value('invoiceID', $params);
1088 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1089 $recurParams['payment_processor_id'] = CRM_Utils_Array
::value('payment_processor_id', $params);
1090 $recurParams['is_email_receipt'] = CRM_Utils_Array
::value('is_email_receipt', $params);
1091 // we need to add a unique trxn_id to avoid a unique key error
1092 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1093 $recurParams['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params, $params['invoiceID']);
1094 $recurParams['financial_type_id'] = $contributionType->id
;
1096 if (!$online ||
$form->_values
['is_monetary']) {
1097 $recurParams['payment_instrument_id'] = 1;
1100 $campaignId = CRM_Utils_Array
::value('campaign_id', $params);
1102 if (!array_key_exists('campaign_id', $params)) {
1103 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1106 $recurParams['campaign_id'] = $campaignId;
1108 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1109 if (is_a($recurring, 'CRM_Core_Error')) {
1110 CRM_Core_Error
::displaySessionError($recurring);
1111 $urlString = 'civicrm/contribute/transact';
1112 $urlParams = '_qf_Main_display=true';
1113 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1114 $urlString = 'civicrm/contact/view/contribution';
1115 $urlParams = "action=add&cid={$form->_contactID}";
1117 $urlParams .= "&mode={$form->_mode}";
1120 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1123 return $recurring->id
;
1127 * Add on behalf of organization and it's location.
1129 * This situation occurs when on behalf of is enabled for the contribution page and the person
1130 * signing up does so on behalf of an organization.
1132 * @param array $behalfOrganization
1133 * array of organization info.
1134 * @param int $contactID
1135 * individual contact id. One.
1136 * who is doing the process of signup / contribution.
1138 * @param array $values
1139 * form values array.
1140 * @param array $params
1141 * @param array $fields
1142 * Array of fields from the onbehalf profile relevant to the organization.
1144 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1145 $isNotCurrentEmployer = FALSE;
1148 if (!empty($behalfOrganization['organization_id'])) {
1149 $orgID = $behalfOrganization['organization_id'];
1150 unset($behalfOrganization['organization_id']);
1152 // create employer relationship with $contactID only when new organization is there
1153 // else retain the existing relationship
1155 // get the Employee relationship type id
1156 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
1158 // keep relationship params ready
1159 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1160 $relParams['is_permission_a_b'] = 1;
1161 $relParams['is_active'] = 1;
1162 $isNotCurrentEmployer = TRUE;
1165 // formalities for creating / editing organization.
1166 $behalfOrganization['contact_type'] = 'Organization';
1169 // check if matching organization contact exists
1170 $dedupeParams = CRM_Dedupe_Finder
::formatParams($behalfOrganization, 'Organization');
1171 $dedupeParams['check_permission'] = FALSE;
1172 $dupeIDs = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1174 // CRM-6243 says to pick the first org even if more than one match
1175 if (count($dupeIDs) >= 1) {
1176 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1177 // don't allow name edit
1178 unset($behalfOrganization['organization_name']);
1182 // if found permissioned related organization, allow location edit
1183 $behalfOrganization['contact_id'] = $orgID;
1184 // don't allow name edit
1185 unset($behalfOrganization['organization_name']);
1188 // handling for image url
1189 if (!empty($behalfOrganization['image_URL'])) {
1190 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1193 // create organization, add location
1194 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1195 NULL, NULL, 'Organization'
1197 // create relationship
1198 if ($isNotCurrentEmployer) {
1199 $relParams['contact_check'][$orgID] = 1;
1200 $cid = array('contact' => $contactID);
1201 CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relParams, $cid);
1204 // if multiple match - send a duplicate alert
1205 if ($dupeIDs && (count($dupeIDs) > 1)) {
1206 $values['onbehalf_dupe_alert'] = 1;
1208 $params['onbehalf_dupe_alert'] = 1;
1211 // make sure organization-contact-id is considered for recording
1212 // contribution/membership etc..
1213 if ($contactID != $orgID) {
1214 // take a note of contact-id, so we can send the
1215 // receipt to individual contact as well.
1217 // required for mailing/template display ..etc
1218 $values['related_contact'] = $contactID;
1220 //make this employee of relationship as current
1221 //employer / employee relationship, CRM-3532
1222 if ($isNotCurrentEmployer &&
1223 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1225 $isNotCurrentEmployer = FALSE;
1228 if (!$isNotCurrentEmployer && $orgID) {
1229 //build current employer params
1230 $currentEmpParams[$contactID] = $orgID;
1231 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1234 // contribution / signup will be done using this
1236 $contactID = $orgID;
1241 * Function used to send notification mail to pcp owner.
1243 * This is used by contribution and also event PCPs.
1245 * @param object $contribution
1246 * @param object $contributionSoft
1247 * Contribution object.
1249 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1250 $params = array('id' => $contributionSoft->pcp_id
);
1251 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1252 $ownerNotifyID = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1254 if ($ownerNotifyID != CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1255 (($ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1256 CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id
, 'is_notify')) ||
1257 $ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1258 $pcpInfoURL = CRM_Utils_System
::url('civicrm/pcp/info',
1259 "reset=1&id={$contributionSoft->pcp_id}",
1260 TRUE, NULL, FALSE, TRUE
1262 // set email in the template here
1263 // get the billing location type
1264 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1265 $billingLocationTypeId = array_search('Billing', $locationTypes);
1267 if ($billingLocationTypeId) {
1268 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
, FALSE, $billingLocationTypeId);
1270 // get primary location email if no email exist( for billing location).
1272 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
);
1274 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft->contact_id
);
1276 'page_title' => $pcpInfo['title'],
1277 'receive_date' => $contribution->receive_date
,
1278 'total_amount' => $contributionSoft->amount
,
1279 'donors_display_name' => $donorName,
1280 'donors_email' => $email,
1281 'pcpInfoURL' => $pcpInfoURL,
1282 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll
,
1283 'currency' => $contributionSoft->currency
,
1285 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1286 $sendTemplateParams = array(
1287 'groupName' => 'msg_tpl_workflow_contribution',
1288 'valueName' => 'pcp_owner_notify',
1289 'contactId' => $contributionSoft->contact_id
,
1290 'toEmail' => $ownerEmail,
1291 'toName' => $ownerName,
1292 'from' => "$domainValues[0] <$domainValues[1]>",
1293 'tplParams' => $tplParams,
1294 'PDFFilename' => 'receipt.pdf',
1296 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1301 * Function used to se pcp related defaults / params.
1303 * This is used by contribution and also event PCPs
1305 * @param CRM_Core_Form $page
1307 * @param array $params
1311 public static function processPcp(&$page, $params) {
1312 $params['pcp_made_through_id'] = $page->_pcpId
;
1313 $page->assign('pcpBlock', TRUE);
1314 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1315 $params['pcp_roll_nickname'] = ts('Anonymous');
1316 $params['pcp_is_anonymous'] = 1;
1319 $params['pcp_is_anonymous'] = 0;
1322 'pcp_display_in_roll',
1324 'pcp_roll_nickname',
1325 'pcp_personal_note',
1327 if (!empty($params[$val])) {
1328 $page->assign($val, $params[$val]);
1336 * Process membership.
1338 * @param array $membershipParams
1339 * @param int $contactID
1340 * @param array $customFieldsFormatted
1341 * @param array $fieldTypes
1342 * @param array $premiumParams
1343 * @param array $membershipLineItems
1344 * Line items specifically relating to memberships.
1345 * @param bool $isPayLater
1347 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1348 $membershipLineItems, $isPayLater) {
1350 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1351 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1352 $membershipType = empty($membershipTypes) ?
array() : reset($membershipTypes);
1353 $isPending = $this->getIsPending();
1355 $this->assign('membership_name', CRM_Utils_Array
::value('name', $membershipType));
1357 $isPaidMembership = FALSE;
1358 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1359 //amount must be greater than zero for
1360 //adding contribution record to contribution table.
1361 //this condition arises when separate membership payment is
1362 //enabled and contribution amount is not selected. fix for CRM-3010
1363 $isPaidMembership = TRUE;
1365 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1367 if ($this->_values
['amount_block_is_active']) {
1368 $financialTypeID = $this->_values
['financial_type_id'];
1371 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $membershipType, CRM_Utils_Array
::value('financial_type_id', $membershipParams));
1374 if (CRM_Utils_Array
::value('membership_source', $this->_params
)) {
1375 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1378 $this->postProcessMembership($membershipParams, $contactID,
1379 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1380 $membershipLineItems, $isPayLater, $isPending);
1382 $this->assign('membership_assign', TRUE);
1383 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1387 * Process the Memberships.
1389 * @param array $membershipParams
1390 * Array of membership fields.
1391 * @param int $contactID
1393 * @param CRM_Contribute_Form_Contribution_Confirm $form
1394 * Confirmation form object.
1396 * @param array $premiumParams
1397 * @param null $customFieldsFormatted
1398 * @param null $includeFieldTypes
1400 * @param array $membershipDetails
1402 * @param array $membershipTypeIDs
1404 * @param bool $isPaidMembership
1405 * @param array $membershipID
1407 * @param bool $isProcessSeparateMembershipTransaction
1409 * @param int $financialTypeID
1410 * @param array $membershipLineItems
1411 * Line items specific to membership payment that is separate to contribution.
1412 * @param bool $isPayLater
1413 * @param bool $isPending
1415 * @throws \CRM_Core_Exception
1417 protected function postProcessMembership(
1418 $membershipParams, $contactID, &$form, $premiumParams,
1419 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1420 $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending) {
1421 $membershipContribution = NULL;
1422 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1423 $errors = $createdMemberships = $paymentResult = array();
1425 if ($isPaidMembership) {
1426 if ($isProcessSeparateMembershipTransaction) {
1427 // If we have 2 transactions only one can use the invoice id.
1428 $membershipParams['invoiceID'] .= '-2';
1431 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1438 if (!empty($paymentResult['contribution'])) {
1439 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1440 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1441 $membershipContribution = $paymentResult['contribution'];
1442 // Save the contribution ID so that I can be used in email receipts
1443 // For example, if you need to generate a tax receipt for the donation only.
1444 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1448 if ($isProcessSeparateMembershipTransaction) {
1450 $form->_lineItem
= $membershipLineItems;
1451 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1452 unset($membershipParams['is_recur']);
1454 $membershipContribution = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams,
1455 $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1457 catch (CRM_Core_Exception
$e) {
1458 $errors[2] = $e->getMessage();
1459 $membershipContribution = NULL;
1464 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1465 $membershipContributionID = $membershipContribution->id
;
1468 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1469 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1470 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1472 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1473 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1474 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1475 foreach ($membershipTypeIDs as $memType) {
1476 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1477 if (!empty($membershipContribution)) {
1478 $pendingStatus = CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name');
1479 $pending = ($membershipContribution->contribution_status_id
== $pendingStatus) ?
TRUE : FALSE;
1482 $pending = $isPending;
1484 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
1486 $membershipSource = NULL;
1487 if (!empty($form->_params
['membership_source'])) {
1488 $membershipSource = $form->_params
['membership_source'];
1490 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
1491 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
1494 if (isset($form->_params
)) {
1495 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
1498 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
1499 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
1500 if (!array_key_exists('campaign_id', $form->_params
)) {
1501 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1505 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership
::renewMembership(
1506 $contactID, $memType, $isTest,
1507 date('YmdHis'), CRM_Utils_Array
::value('cms_contactID', $membershipParams),
1508 $customFieldsFormatted,
1509 $numTerms, $membershipID, $pending,
1510 $contributionRecurID, $membershipSource, $isPayLater, $campaignId
1512 $form->set('renewal_mode', $renewalMode);
1513 if (!empty($dates)) {
1514 $form->assign('mem_start_date',
1515 CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d')
1517 $form->assign('mem_end_date',
1518 CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d')
1522 if (!empty($membershipContribution)) {
1523 // update recurring id for membership record
1524 CRM_Member_BAO_Membership
::updateRecurMembership($membership, $membershipContribution);
1525 CRM_Member_BAO_Membership
::linkMembershipPayment($membership, $membershipContribution);
1528 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1529 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1530 if (!empty($priceFieldOp['membership_type_id']) &&
1531 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1533 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1534 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1535 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1538 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1541 $form->_values
['lineItem'] = $form->_lineItem
;
1542 $form->assign('lineItem', $form->_lineItem
);
1546 if (!empty($errors)) {
1547 $message = $this->compileErrorMessage($errors);
1548 throw new CRM_Core_Exception($message);
1550 $form->_params
['createdMembershipIDs'] = array();
1552 // CRM-7851 - Moved after processing Payment Errors
1553 //@todo - the reasoning for this being here seems a little outdated
1554 foreach ($createdMemberships as $createdMembership) {
1555 CRM_Core_BAO_CustomValueTable
::postProcess(
1557 'civicrm_membership',
1558 $createdMembership->id
,
1561 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1563 if (count($createdMemberships) == 1) {
1564 //presumably this is only relevant for exactly 1 membership
1565 $form->_params
['membershipID'] = $createdMembership->id
;
1568 //CRM-15232: Check if membership is created and on the basis of it use
1569 //membership receipt template to send payment receipt
1570 if (count($createdMemberships)) {
1571 $form->_values
['isMembership'] = TRUE;
1573 if (isset($membershipContributionID)) {
1574 $form->_values
['contribution_id'] = $membershipContributionID;
1576 if ($form->_contributeMode
) {
1577 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1578 // call postProcess hook before leaving
1579 $form->postProcessHook();
1581 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1582 $paymentActionResult = $payment->doPayment($form->_params
, 'contribute');
1583 $this->completeTransaction($paymentActionResult, $paymentResult['contribution']->id
);
1584 // Do not send an email if Recurring transaction is done via Direct Mode
1585 // Email will we sent when the IPN is received.
1589 //finally send an email receipt
1590 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1598 * Turn array of errors into message string.
1600 * @param array $errors
1604 protected function compileErrorMessage($errors) {
1605 foreach ($errors as $error) {
1606 if (is_string($error)) {
1607 $message[] = $error;
1610 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1614 * Where a second separate financial transaction is supported we will process it here.
1616 * @param int $contactID
1617 * @param CRM_Contribute_Form_Contribution_Confirm $form
1618 * @param array $tempParams
1619 * @param bool $isTest
1620 * @param array $lineItems
1621 * @param $minimumFee
1622 * @param int $financialTypeID
1624 * @throws CRM_Core_Exception
1626 * @return CRM_Contribute_BAO_Contribution
1628 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1630 $financialType = new CRM_Financial_DAO_FinancialType();
1631 $financialType->id
= $financialTypeID;
1632 $financialType->find(TRUE);
1633 $tempParams['amount'] = $minimumFee;
1634 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1636 //assign receive date when separate membership payment
1637 //and contribution amount not selected.
1638 if ($form->_amount
== 0) {
1639 $now = date('YmdHis');
1640 $form->_params
['receive_date'] = $now;
1641 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1642 $form->set('params', $form->_params
);
1643 $form->assign('receive_date', $receiveDate);
1646 $form->set('membership_amount', $minimumFee);
1647 $form->assign('membership_amount', $minimumFee);
1649 // we don't need to create the user twice, so lets disable cms_create_account
1650 // irrespective of the value, CRM-2888
1651 $tempParams['cms_create_account'] = 0;
1653 //set this variable as we are not creating pledge for
1654 //separate membership payment contribution.
1655 //so for differentiating membership contribution from
1656 //main contribution.
1657 $form->_params
['separate_membership_payment'] = 1;
1658 $contributionParams = array(
1659 'contact_id' => $contactID,
1660 'line_item' => $lineItems,
1661 'is_test' => $isTest,
1662 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $tempParams, CRM_Utils_Array
::value('campaign_id',
1664 'contribution_page_id' => $form->_id
,
1665 'source' => CRM_Utils_Array
::value('source', $tempParams, CRM_Utils_Array
::value('description', $tempParams)),
1667 $isMonetary = !empty($form->_values
['is_monetary']);
1669 if (empty($paymentParams['is_pay_later'])) {
1670 $contributionParams['payment_instrument_id'] = $form->_paymentProcessor
['payment_instrument_id'];
1673 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
1676 $contributionParams,
1682 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
1683 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1684 // now we compensate here.
1685 if (empty($form->_paymentProcessor
['object'])) {
1686 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1689 $payment = $form->_paymentProcessor
['object'];
1691 $result = $payment->doPayment($tempParams, 'contribute');
1692 $form->set('membership_trx_id', $result['trxn_id']);
1693 $form->assign('membership_trx_id', $result['trxn_id']);
1694 $this->completeTransaction($result, $membershipContribution->id
);
1697 return $membershipContribution;
1701 * Is the payment a pending payment.
1703 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1704 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1709 protected function getIsPending() {
1710 if (((isset($this->_contributeMode
)) ||
!empty
1711 ($this->_params
['is_pay_later'])
1713 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1721 * Are we going to do 2 financial transactions.
1723 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1725 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1727 * @param int $formID
1728 * @param bool $amountBlockActiveOnForm
1732 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1733 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1734 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1741 * This function sets the fields.
1743 * - $this->_params['amount_level']
1744 * - $this->_params['selectMembership']
1745 * And under certain circumstances sets
1746 * $this->_params['amount'] = null;
1748 * @param int $priceSetID
1750 public function setFormAmountFields($priceSetID) {
1751 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1752 $priceField = new CRM_Price_DAO_PriceField();
1753 $priceField->price_set_id
= $priceSetID;
1754 $priceField->orderBy('weight');
1755 $priceField->find();
1756 $paramWeDoNotUnderstand = NULL;
1758 while ($priceField->fetch()) {
1759 if ($priceField->name
== "contribution_amount") {
1760 $paramWeDoNotUnderstand = $priceField->id
;
1762 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1763 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1764 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1765 $this->_params
["price_{$priceField->id}"], 'label');
1767 if ($priceField->name
== "membership_amount") {
1768 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1769 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1772 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1773 // as membership amount.
1774 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1775 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1776 // so we should merge them together
1777 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1778 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1780 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
)
1781 && !empty($this->_values
['fee'][$priceField->id
])
1782 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1783 && CRM_Utils_Array
::value("price_{$paramWeDoNotUnderstand}", $this->_params
) < 1
1784 && empty($this->_params
["price_{$priceField->id}"])
1786 $this->_params
['amount'] = NULL;
1789 // Fix for CRM-14375 - If we are using separate payments and "no
1790 // thank you" is selected for the additional contribution, set
1791 // contribution amount to be null, so that it will not show
1792 // contribution amount same as membership amount.
1793 //@todo - merge with section above
1794 if ($this->_membershipBlock
['is_separate_payment']
1795 && !empty($this->_values
['fee'][$priceField->id
])
1796 && CRM_Utils_Array
::value('name', $this->_values
['fee'][$priceField->id
]) == 'contribution_amount'
1797 && CRM_Utils_Array
::value("price_{$priceField->id}", $this->_params
) == '-1'
1799 $this->_params
['amount'] = NULL;
1807 * @param array $params
1809 * @throws CiviCRM_API3_Exception
1811 public static function submit($params) {
1812 $form = new CRM_Contribute_Form_Contribution_Confirm();
1813 $form->_id
= $params['id'];
1815 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1816 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1817 //this way the mocked up controller ignores the session stuff
1818 $_SERVER['REQUEST_METHOD'] = 'GET';
1819 $form->controller
= new CRM_Contribute_Controller_Contribution();
1820 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1821 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1822 $form->_amount
= $params['amount'];
1823 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1824 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1825 $priceSetFields = reset($priceFields);
1826 $form->_values
['fee'] = $priceSetFields['fields'];
1827 $form->_priceSetId
= $priceSetID;
1828 $form->setFormAmountFields($priceSetID);
1829 if (!empty($params['payment_processor_id'])) {
1830 $form->_paymentProcessor
= civicrm_api3('payment_processor', 'getsingle', array(
1831 'id' => $params['payment_processor_id'],
1833 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1834 $form->_contributeMode
= 'direct';
1837 $form->_contributeMode
= 'notify';
1841 $form->_params
['payment_processor_id'] = 0;
1843 $priceFields = $priceFields[$priceSetID]['fields'];
1844 CRM_Price_BAO_PriceSet
::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1845 $form->_lineItem
= array($priceSetID => $lineItems);
1846 $form->processFormSubmission(CRM_Utils_Array
::value('contact_id', $params));
1850 * Helper function for static submit function.
1852 * Set relevant params - help us to build up an array that we can pass in.
1855 * @param array $params
1858 * @throws CiviCRM_API3_Exception
1860 public static function getFormParams($id, array $params) {
1861 if (!isset($params['is_pay_later'])) {
1862 if (!empty($params['payment_processor_id'])) {
1863 $params['is_pay_later'] = 0;
1866 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1868 'return' => 'is_pay_later',
1872 if (empty($params['price_set_id'])) {
1873 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
1879 * Post form submission handling.
1881 * This is also called from the test suite.
1883 * @param int $contactID
1887 protected function processFormSubmission($contactID) {
1888 $isPayLater = $this->_params
['is_pay_later'];
1889 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] == 0) {
1890 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
1892 // add a description field at the very beginning
1893 $this->_params
['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $this->_values
['title']);
1895 $this->_params
['accountingCode'] = CRM_Utils_Array
::value('accountingCode', $this->_values
);
1898 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
1900 //carry payment processor id.
1901 if (CRM_Utils_Array
::value('id', $this->_paymentProcessor
)) {
1902 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
1905 $premiumParams = $membershipParams = $params = $this->_params
;
1906 if (!empty($params['image_URL'])) {
1907 CRM_Contact_BAO_Contact
::processImageParams($params);
1910 $fields = array('email-Primary' => 1);
1912 // get the add to groups
1913 $addToGroups = array();
1915 // now set the values for the billing location.
1916 foreach ($this->_fields
as $name => $value) {
1919 // get the add to groups for uf fields
1920 if (!empty($value['add_to_group_id'])) {
1921 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
1925 $fields = $this->formatParamsForPaymentProcessor($fields);
1927 // billing email address
1928 $fields["email-{$this->_bltID}"] = 1;
1930 //unset the billing parameters if it is pay later mode
1931 //to avoid creation of billing location
1932 // @todo - note that elsewhere we don't unset these - we simply make
1933 // a sensible decision about including them when building the form
1934 // and if they are submitted we handle them. Check out abstractEditPaymentForm.
1935 if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater
) {
1936 $billingFields = array(
1937 'billing_first_name',
1938 'billing_middle_name',
1939 'billing_last_name',
1940 "billing_street_address-{$this->_bltID}",
1941 "billing_city-{$this->_bltID}",
1942 "billing_state_province-{$this->_bltID}",
1943 "billing_state_province_id-{$this->_bltID}",
1944 "billing_postal_code-{$this->_bltID}",
1945 "billing_country-{$this->_bltID}",
1946 "billing_country_id-{$this->_bltID}",
1949 foreach ($billingFields as $value) {
1950 unset($params[$value]);
1951 unset($fields[$value]);
1955 // if onbehalf-of-organization contribution, take out
1956 // organization params in a separate variable, to make sure
1957 // normal behavior is continued. And use that variable to
1958 // process on-behalf-of functionality.
1959 if (!empty($this->_values
['onbehalf_profile_id'])) {
1960 $behalfOrganization = array();
1961 $orgFields = array('organization_name', 'organization_id', 'org_option');
1962 foreach ($orgFields as $fld) {
1963 if (array_key_exists($fld, $params)) {
1964 $behalfOrganization[$fld] = $params[$fld];
1965 unset($params[$fld]);
1969 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
1970 foreach ($params['onbehalf'] as $fld => $values) {
1971 if (strstr($fld, 'custom_')) {
1972 $behalfOrganization[$fld] = $values;
1974 elseif (!(strstr($fld, '-'))) {
1975 if (in_array($fld, array(
1976 'contribution_campaign_id',
1977 'member_campaign_id',
1979 $fld = 'campaign_id';
1982 $behalfOrganization[$fld] = $values;
1984 $this->_params
[$fld] = $values;
1989 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
1990 foreach ($params['onbehalf_location'] as $block => $vals) {
1991 //fix for custom data (of type checkbox, multi-select)
1992 if (substr($block, 0, 7) == 'custom_') {
1995 // fix the index of block elements
1996 if (is_array($vals)) {
1997 foreach ($vals as $key => $val) {
1998 //dont adjust the index of address block as
1999 //it's index is WRT to location type
2000 $newKey = ($block == 'address') ?
$key : ++
$key;
2001 $behalfOrganization[$block][$newKey] = $val;
2005 unset($params['onbehalf_location']);
2007 if (!empty($params['onbehalf[image_URL]'])) {
2008 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2012 // check for profile double opt-in and get groups to be subscribed
2013 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2015 // since we are directly adding contact to group lets unset it from mailing
2016 if (!empty($addToGroups)) {
2017 foreach ($addToGroups as $groupId) {
2018 if (isset($subscribeGroupIds[$groupId])) {
2019 unset($subscribeGroupIds[$groupId]);
2024 foreach ($addToGroups as $k) {
2025 if (array_key_exists($k, $subscribeGroupIds)) {
2026 unset($addToGroups[$k]);
2030 if (empty($contactID)) {
2031 $dupeParams = $params;
2032 if (!empty($dupeParams['onbehalf'])) {
2033 unset($dupeParams['onbehalf']);
2035 if (!empty($dupeParams['honor'])) {
2036 unset($dupeParams['honor']);
2039 $dedupeParams = CRM_Dedupe_Finder
::formatParams($dupeParams, 'Individual');
2040 $dedupeParams['check_permission'] = FALSE;
2041 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
2043 // if we find more than one contact, use the first one
2044 $contactID = CRM_Utils_Array
::value(0, $ids);
2046 // Fetch default greeting id's if creating a contact
2048 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2049 if (!isset($params[$greeting])) {
2050 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2054 $contactType = NULL;
2057 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2059 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2069 // Make the contact ID associated with the contribution available at the Class level.
2070 // Also make available to the session.
2071 //@todo consider handling this in $this->getContactID();
2072 $this->set('contactID', $contactID);
2073 $this->_contactID
= $contactID;
2075 //get email primary first if exist
2076 $subscriptionEmail = array('email' => CRM_Utils_Array
::value('email-Primary', $params));
2077 if (!$subscriptionEmail['email']) {
2078 $subscriptionEmail['email'] = CRM_Utils_Array
::value("email-{$this->_bltID}", $params);
2080 // subscribing contact to groups
2081 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2082 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2085 // If onbehalf-of-organization contribution / signup, add organization
2086 // and it's location.
2087 if (isset($this->_values
['onbehalf_profile_id']) && isset($behalfOrganization['organization_name'])) {
2088 $ufFields = array();
2089 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2090 $ufFields[$name] = 1;
2092 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2093 $this->_params
, $ufFields
2096 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2097 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2098 // store current user id as related contact for later use for mailing / activity..
2099 $this->_values
['related_contact'] = $contactID;
2100 $this->_params
['related_contact'] = $contactID;
2101 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2102 $contactID = $this->_membershipContactID
;
2105 // lets store the contactID in the session
2106 // for things like tell a friend
2107 $session = CRM_Core_Session
::singleton();
2108 if (!$session->get('userID')) {
2109 $session->set('transaction.userID', $contactID);
2112 $session->set('transaction.userID', NULL);
2115 $this->_useForMember
= $this->get('useForMember');
2117 // store the fact that this is a membership and membership type is selected
2118 if ((!empty($membershipParams['selectMembership']) &&
2119 $membershipParams['selectMembership'] != 'no_thanks'
2121 $this->_useForMember
2123 if (!$this->_useForMember
) {
2124 $this->assign('membership_assign', TRUE);
2125 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2128 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2129 $membershipParams['is_test'] = 1;
2131 if ($this->_params
['is_pay_later']) {
2132 $membershipParams['is_pay_later'] = 1;
2135 //inherit campaign from contribution page.
2136 if (!array_key_exists('campaign_id', $membershipParams)) {
2137 $membershipParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
);
2140 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2141 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater);
2144 // at this point we've created a contact and stored its address etc
2145 // all the payment processors expect the name and address to be in the
2146 // so we copy stuff over to first_name etc.
2147 $paymentParams = $this->_params
;
2149 if (!empty($paymentParams['onbehalf']) &&
2150 is_array($paymentParams['onbehalf'])
2152 foreach ($paymentParams['onbehalf'] as $key => $value) {
2153 if (strstr($key, 'custom_')) {
2154 $this->_params
[$key] = $value;
2159 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2161 $this->wrangleFinancialTypeID($this->_values
['financial_type_id']),
2163 ($this->_mode
== 'test') ?
1 : 0
2166 if (empty($result['is_payment_failure'])) {
2167 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2168 $this->postProcessPremium($premiumParams, $result['contribution']);
2170 if (!empty($result['contribution'])) {
2171 // Not quite sure why it would be empty at this stage but tests show it can be ... at least in tests.
2172 $this->completeTransaction($result, $result['contribution']->id
);
2179 * Membership processing section.
2181 * This is in a separate function as part of a move towards refactoring.
2183 * @param int $contactID
2184 * @param array $membershipParams
2185 * @param array $premiumParams
2186 * @param bool $isPayLater
2188 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater) {
2190 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2191 if (isset($this->_params
['related_contact'])) {
2192 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2195 $membershipParams['cms_contactID'] = $contactID;
2198 if (!empty($membershipParams['onbehalf']) &&
2199 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2201 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2204 $customFieldsFormatted = $fieldTypes = array();
2205 if (!empty($membershipParams['onbehalf']) &&
2206 is_array($membershipParams['onbehalf'])
2208 foreach ($membershipParams['onbehalf'] as $key => $value) {
2209 if (strstr($key, 'custom_')) {
2210 $customFieldId = explode('_', $key);
2211 CRM_Core_BAO_CustomField
::formatCustomField(
2213 $customFieldsFormatted,
2221 $fieldTypes = array('Contact', 'Organization', 'Membership');
2224 $priceFieldIds = $this->get('memberPriceFieldIDS');
2226 if (!empty($priceFieldIds)) {
2227 $contributionTypeID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2228 unset($priceFieldIds['id']);
2229 $membershipTypeIds = array();
2230 $membershipTypeTerms = array();
2231 foreach ($priceFieldIds as $priceFieldId) {
2232 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
2233 $membershipTypeIds[] = $id;
2234 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
2235 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
2237 if ($term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
2238 $membershipTypeTerms[$id] = ($term > 1) ?
$term : 1;
2241 $membershipTypeTerms[$id] = 1;
2245 $membershipParams['selectMembership'] = $membershipTypeIds;
2246 $membershipParams['financial_type_id'] = $contributionTypeID;
2247 $membershipParams['types_terms'] = $membershipTypeTerms;
2249 if (!empty($membershipParams['selectMembership'])) {
2251 $membershipLineItems = array();
2252 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2253 foreach ($this->_values
['fee'] as $key => $feeValues) {
2254 if ($feeValues['name'] == 'membership_amount') {
2255 $fieldId = $this->_params
['price_' . $key];
2256 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2257 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2263 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
2265 catch (CRM_Core_Exception
$e) {
2266 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2267 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2269 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2270 // we need to explicitly create a CMS user in case of free memberships
2271 // since it is done under processConfirm for paid memberships
2272 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2273 $membershipParams['cms_contactID'],
2274 'email-' . $this->_bltID
2281 * Complete transaction if payment has been processed.
2283 * Check the result for a success outcome & if paid then complete the transaction.
2285 * Completing will trigger update of related entities and emails.
2287 * @param array $result
2288 * @param int $contributionID
2290 * @throws \CRM_Core_Exception
2292 protected function completeTransaction($result, $contributionID) {
2293 if (CRM_Utils_Array
::value('payment_status_id', $result) == 1) {
2295 civicrm_api3('contribution', 'completetransaction', array(
2296 'id' => $contributionID,
2297 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $result),
2298 'payment_processor_id' => $this->_paymentProcessor
['id'],
2299 'is_transactional' => FALSE,
2300 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
2304 catch (CiviCRM_API3_Exception
$e) {
2305 if ($e->getErrorCode() != 'contribution_completed') {
2306 throw new CRM_Core_Exception('Failed to update contribution in database');