3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
35 * form to process actions on the group aspect of Custom Data
37 class CRM_Contribute_Form_Contribution_Confirm
extends CRM_Contribute_Form_ContributionBase
{
40 * The id of the contact associated with this contribution.
48 * The id of the contribution object that is created when the form is submitted.
52 public $_contributionID;
55 * Set the parameters to be passed to contribution create function.
57 * @param array $params
58 * @param int $contactID
59 * @param int $financialTypeID
61 * @param int $contributionPageId
62 * @param float $nonDeductibleAmount
63 * @param int $campaignId
64 * @param bool $isMonetary
65 * @param bool $pending
66 * @param array $paymentProcessorOutcome
67 * @param string $receiptDate
68 * @param int $recurringContributionID
70 * @param int $addressID
71 * @param int $softCreditToID
72 * @param array $lineItems
76 public static function getContributionParams(
77 $params, $contactID, $financialTypeID, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending,
78 $paymentProcessorOutcome, $receiptDate, $recurringContributionID, $isTest, $addressID, $softCreditToID, $lineItems) {
79 $contributionParams = array(
80 'contact_id' => $contactID,
81 'financial_type_id' => $financialTypeID,
82 'contribution_page_id' => $contributionPageId,
83 'receive_date' => (CRM_Utils_Array
::value('receive_date', $params)) ? CRM_Utils_Date
::processDate($params['receive_date']) : date('YmdHis'),
84 'non_deductible_amount' => $nonDeductibleAmount,
85 'total_amount' => $params['amount'],
86 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $params),
87 'amount_level' => CRM_Utils_Array
::value('amount_level', $params),
88 'invoice_id' => $params['invoiceID'],
89 'currency' => $params['currencyID'],
90 'source' => (!$online ||
!empty($params['source'])) ? CRM_Utils_Array
::value('source', $params) : CRM_Utils_Array
::value('description', $params),
91 'is_pay_later' => CRM_Utils_Array
::value('is_pay_later', $params, 0),
92 //configure cancel reason, cancel date and thankyou date
93 //from 'contribution' type profile if included
94 'cancel_reason' => CRM_Utils_Array
::value('cancel_reason', $params, 0),
95 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date
::format($params['cancel_date']) : NULL,
96 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date
::format($params['thankyou_date']) : NULL,
97 'campaign_id' => $campaignId,
99 'address_id' => $addressID,
100 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
101 'soft_credit_to' => $softCreditToID,
102 'line_item' => $lineItems,
103 'skipLineItem' => CRM_Utils_Array
::value('skipLineItem', $params, 0),
105 if (!$online && isset($params['thankyou_date'])) {
106 $contributionParam['thankyou_date'] = $params['thankyou_date'];
108 if (!$online ||
$isMonetary) {
109 if (empty($params['is_pay_later'])) {
110 $contributionParams['payment_instrument_id'] = 1;
113 if ($paymentProcessorOutcome) {
114 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor', $paymentProcessorOutcome);
116 if (!$pending && $paymentProcessorOutcome) {
117 $contributionParams +
= array(
118 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $paymentProcessorOutcome),
119 'net_amount' => CRM_Utils_Array
::value('net_amount', $paymentProcessorOutcome, $params['amount']),
120 'trxn_id' => $paymentProcessorOutcome['trxn_id'],
121 'receipt_date' => $receiptDate,
122 // also add financial_trxn details as part of fix for CRM-4724
123 'trxn_result_code' => CRM_Utils_Array
::value('trxn_result_code', $paymentProcessorOutcome),
127 // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
128 $contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money
::format($contributionParams['non_deductible_amount'], ' '));
129 $contributionParams['total_amount'] = trim(CRM_Utils_Money
::format($contributionParams['total_amount'], ' '));
131 if ($recurringContributionID) {
132 $contributionParams['contribution_recur_id'] = $recurringContributionID;
135 $contributionParams['contribution_status_id'] = $pending ?
2 : 1;
136 if (isset($contributionParams['invoice_id'])) {
137 $contributionParams['id'] = CRM_Core_DAO
::getFieldValue(
138 'CRM_Contribute_DAO_Contribution',
139 $contributionParams['invoice_id'],
145 return $contributionParams;
149 * Get non-deductible amount.
151 * This is a bit too much about wierd form interpretation to be this deep.
154 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
157 * @param array $params
158 * @param CRM_Financial_BAO_FinancialType $financialType
159 * @param bool $online
163 protected static function getNonDeductibleAmount($params, $financialType, $online) {
164 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
165 return $params['non_deductible_amount'];
168 if ($financialType->is_deductible
) {
169 if ($online && isset($params['selectProduct'])) {
170 $selectProduct = CRM_Utils_Array
::value('selectProduct', $params);
172 if (!$online && isset($params['product_name'][0])) {
173 $selectProduct = $params['product_name'][0];
175 // if there is a product - compare the value to the contribution amount
176 if (isset($selectProduct) &&
177 $selectProduct != 'no_thanks'
179 $productDAO = new CRM_Contribute_DAO_Product();
180 $productDAO->id
= $selectProduct;
181 $productDAO->find(TRUE);
182 // product value exceeds contribution amount
183 if ($params['amount'] < $productDAO->price
) {
184 $nonDeductibleAmount = $params['amount'];
185 return $nonDeductibleAmount;
187 // product value does NOT exceed contribution amount
189 return $productDAO->price
;
192 // contribution is deductible - but there is no product
197 // contribution is NOT deductible
199 return $params['amount'];
205 * Set variables up before form is built.
207 public function preProcess() {
208 $config = CRM_Core_Config
::singleton();
209 parent
::preProcess();
211 // lineItem isn't set until Register postProcess
212 $this->_lineItem
= $this->get('lineItem');
213 $this->_paymentProcessor
= $this->get('paymentProcessor');
215 if ($this->_contributeMode
== 'express') {
216 // rfp == redirect from paypal
217 $rfp = CRM_Utils_Request
::retrieve('rfp', 'Boolean',
218 CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET'
221 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this);
222 $expressParams = $payment->getExpressCheckoutDetails($this->get('token'));
224 $this->_params
['payer'] = CRM_Utils_Array
::value('payer', $expressParams);
225 $this->_params
['payer_id'] = $expressParams['payer_id'];
226 $this->_params
['payer_status'] = $expressParams['payer_status'];
228 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $expressParams, $this->_params
, FALSE);
230 // fix state and country id if present
231 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
232 $this->_params
["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($this->_params
["billing_state_province_id-{$this->_bltID}"]);
234 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"]) && $this->_params
["billing_country_id-{$this->_bltID}"]) {
235 $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
238 // set a few other parameters for PayPal
239 $this->_params
['token'] = $this->get('token');
241 $this->_params
['amount'] = $this->get('amount');
243 if (!empty($this->_membershipBlock
)) {
244 $this->_params
['selectMembership'] = $this->get('selectMembership');
246 // we use this here to incorporate any changes made by folks in hooks
247 $this->_params
['currencyID'] = $config->defaultCurrency
;
249 // also merge all the other values from the profile fields
250 $values = $this->controller
->exportValues('Main');
254 "billing_street_address-{$this->_bltID}",
255 "billing_city-{$this->_bltID}",
256 "billing_state_province_id-{$this->_bltID}",
257 "billing_postal_code-{$this->_bltID}",
258 "billing_country_id-{$this->_bltID}",
260 foreach ($values as $name => $value) {
262 if (!in_array($name, $skipFields)) {
263 $this->_params
[$name] = $value;
266 $this->set('getExpressCheckoutDetails', $this->_params
);
269 $this->_params
= $this->get('getExpressCheckoutDetails');
273 $this->_params
= $this->controller
->exportValues('Main');
275 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
276 $this->_params
["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($this->_params
["billing_state_province_id-{$this->_bltID}"]);
278 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
279 $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
282 if (isset($this->_params
['credit_card_exp_date'])) {
283 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
284 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
287 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
288 $this->_params
['amount'] = $this->get('amount');
289 $this->_params
['tax_amount'] = $this->get('tax_amount');
291 $this->_useForMember
= $this->get('useForMember');
293 if (isset($this->_params
['amount'])) {
294 $this->setFormAmountFields($this->_params
['priceSetId']);
296 $this->_params
['currencyID'] = $config->defaultCurrency
;
299 $this->_params
['is_pay_later'] = $this->get('is_pay_later');
300 $this->assign('is_pay_later', $this->_params
['is_pay_later']);
301 if ($this->_params
['is_pay_later']) {
302 $this->assign('pay_later_receipt', $this->_values
['pay_later_receipt']);
304 // if onbehalf-of-organization
305 if (!empty($this->_params
['hidden_onbehalf_profile'])) {
307 if (empty($this->_params
['org_option']) && empty($this->_params
['organization_id'])) {
308 if (!empty($this->_params
['onbehalfof_id'])) {
309 $this->_params
['organization_id'] = $this->_params
['onbehalfof_id'];
312 $this->_params
['organization_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_params
['onbehalf']['organization_name'], 'id', 'display_name');
316 $this->_params
['organization_name'] = $this->_params
['onbehalf']['organization_name'];
317 $addressBlocks = array(
323 'supplemental_address_1',
324 'supplemental_address_2',
325 'supplemental_address_3',
326 'postal_code_suffix',
332 $blocks = array('email', 'phone', 'im', 'url', 'openid');
333 foreach ($this->_params
['onbehalf'] as $loc => $value) {
334 $field = $typeId = NULL;
335 if (strstr($loc, '-')) {
336 list($field, $locType) = explode('-', $loc);
339 if (in_array($field, $addressBlocks)) {
340 if ($locType == 'Primary') {
341 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
342 $locType = $defaultLocationType->id
;
345 if ($field == 'country') {
346 $value = CRM_Core_PseudoConstant
::countryIsoCode($value);
348 elseif ($field == 'state_province') {
349 $value = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
353 if (isset($this->_params
['onbehalf_location']['address'])
354 && count($this->_params
['onbehalf_location']['address']) > 0
359 $this->_params
['onbehalf_location']['address'][$locType][$field] = $value;
360 if (empty($this->_params
['onbehalf_location']['address'][$locType]['is_primary'])) {
361 $this->_params
['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
363 $this->_params
['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
365 elseif (in_array($field, $blocks)) {
366 if (!$typeId ||
is_numeric($typeId)) {
367 $blockName = $fieldName = $field;
368 $locationType = 'location_type_id';
369 if ($locType == 'Primary') {
370 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
371 $locationValue = $defaultLocationType->id
;
374 $locationValue = $locType;
377 $phoneExtField = array();
379 if ($field == 'url') {
380 $blockName = 'website';
381 $locationType = 'website_type_id';
382 list($field, $locationValue) = explode('-', $loc);
384 elseif ($field == 'im') {
386 $locTypeId = 'provider_id';
387 $typeId = $this->_params
['onbehalf']["{$loc}-provider_id"];
389 elseif ($field == 'phone') {
390 list($field, $locType, $typeId) = explode('-', $loc);
391 $locTypeId = 'phone_type_id';
393 //check if extension field exists
394 $extField = str_replace('phone', 'phone_ext', $loc);
395 if (isset($this->_params
['onbehalf'][$extField])) {
396 $phoneExtField = array('phone_ext' => $this->_params
['onbehalf'][$extField]);
401 if (isset ($this->_params
['onbehalf_location'][$blockName])
402 && count($this->_params
['onbehalf_location'][$blockName]) > 0
406 if ($locationValue) {
407 $blockValues = array(
408 $fieldName => $value,
409 $locationType => $locationValue,
410 'is_primary' => $isPrimary,
414 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
416 if (!empty($phoneExtField)) {
417 $blockValues = array_merge($blockValues, $phoneExtField);
420 $this->_params
['onbehalf_location'][$blockName][] = $blockValues;
424 elseif (strstr($loc, 'custom')) {
425 if ($value && isset($this->_params
['onbehalf']["{$loc}_id"])) {
426 $value = $this->_params
['onbehalf']["{$loc}_id"];
428 $this->_params
['onbehalf_location']["{$loc}"] = $value;
431 if ($loc == 'contact_sub_type') {
432 $this->_params
['onbehalf_location'][$loc] = $value;
435 $this->_params
['onbehalf_location'][$field] = $value;
440 elseif (!empty($this->_values
['is_for_organization'])) {
441 // no on behalf of an organization, CRM-5519
442 // so reset loc blocks from main params.
448 if (isset($this->_params
[$blk])) {
449 unset($this->_params
[$blk]);
454 // if auto renew checkbox is set, initiate a open-ended recurring membership
455 if ((!empty($this->_params
['selectMembership']) ||
!empty($this->_params
['priceSetId'])) && !empty($this->_paymentProcessor
['is_recur']) &&
456 CRM_Utils_Array
::value('auto_renew', $this->_params
) && empty($this->_params
['is_recur']) && empty($this->_params
['frequency_interval'])
459 $this->_params
['is_recur'] = $this->_values
['is_recur'] = 1;
460 // check if price set is not quick config
461 if (!empty($this->_params
['priceSetId']) && !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config')) {
462 list($this->_params
['frequency_interval'], $this->_params
['frequency_unit']) = CRM_Price_BAO_PriceSet
::getRecurDetails($this->_params
['priceSetId']);
465 // FIXME: set interval and unit based on selected membership type
466 $this->_params
['frequency_interval'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
467 $this->_params
['selectMembership'], 'duration_interval'
469 $this->_params
['frequency_unit'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
470 $this->_params
['selectMembership'], 'duration_unit'
476 $params = $this->processPcp($this, $this->_params
);
477 $this->_params
= $params;
479 $this->_params
['invoiceID'] = $this->get('invoiceID');
481 //carry campaign from profile.
482 if (array_key_exists('contribution_campaign_id', $this->_params
)) {
483 $this->_params
['campaign_id'] = $this->_params
['contribution_campaign_id'];
486 // assign contribution page id to the template so we can add css class for it
487 $this->assign('contributionPageID', $this->_id
);
489 $this->set('params', $this->_params
);
493 * Build the form object.
495 public function buildQuickForm() {
496 $this->assignToTemplate();
498 $params = $this->_params
;
499 // make sure we have values for it
500 if ($this->_honor_block_is_active
&& !empty($params['soft_credit_type_id'])) {
502 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
504 $this->assign('honor_block_is_active', $this->_honor_block_is_active
);
505 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
506 CRM_Contribute_BAO_ContributionSoft
::formatHonoreeProfileFields($this, $params['honor'], $params['honoree_profile_id']);
508 $fieldTypes = array('Contact');
509 $fieldTypes[] = CRM_Core_BAO_UFGroup
::getContactType($params['honoree_profile_id']);
510 $this->buildCustom($params['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
512 $this->assign('receiptFromEmail', CRM_Utils_Array
::value('receipt_from_email', $this->_values
));
513 $amount_block_is_active = $this->get('amount_block_is_active');
514 $this->assign('amount_block_is_active', $amount_block_is_active);
516 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
517 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
519 $getTaxDetails = FALSE;
520 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
521 foreach ($this->_lineItem
as $key => $value) {
522 foreach ($value as $v) {
523 if (isset($v['tax_rate'])) {
524 if ($v['tax_rate'] != '') {
525 $getTaxDetails = TRUE;
530 $this->assign('getTaxDetails', $getTaxDetails);
531 $this->assign('taxTerm', $taxTerm);
532 $this->assign('totalTaxAmount', $params['tax_amount']);
534 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
535 $option = CRM_Utils_Array
::value('options_' . $params['selectProduct'], $params);
536 $productID = $params['selectProduct'];
537 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, FALSE,
540 $this->set('productID', $productID);
541 $this->set('option', $option);
543 $config = CRM_Core_Config
::singleton();
544 if (in_array('CiviMember', $config->enableComponents
)) {
545 if (isset($params['selectMembership']) &&
546 $params['selectMembership'] != 'no_thanks'
548 $this->buildMembershipBlock(
549 $this->_membershipContactID
,
551 $params['selectMembership'],
554 if (!empty($params['auto_renew'])) {
555 $this->assign('auto_renew', TRUE);
559 $this->assign('membershipBlock', FALSE);
562 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
563 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
565 if (!empty($params['hidden_onbehalf_profile'])) {
566 $ufJoinParams = array(
567 'module' => 'onBehalf',
568 'entity_table' => 'civicrm_contribution_page',
569 'entity_id' => $this->_id
,
571 $OnBehalfProfile = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
572 $profileId = $OnBehalfProfile[0];
574 $fieldTypes = array('Contact', 'Organization');
575 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
576 $fieldTypes = array_merge($fieldTypes, $contactSubType);
577 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
578 $fieldTypes = array_merge($fieldTypes, array('Membership'));
581 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
584 $this->buildCustom($profileId, 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
587 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
588 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
589 if ($this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
590 $this->assign('lineItem', $this->_lineItem
);
593 $this->assign('is_quick_config', 1);
594 $this->_params
['is_quick_config'] = 1;
596 $this->assign('priceSetID', $this->_priceSetId
);
597 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
598 if ($this->_paymentProcessor
&&
599 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('Google_Checkout', $paymentProcessorType)
600 && !$this->_params
['is_pay_later'] && !($this->_amount
== 0)
602 $this->_checkoutButtonName
= $this->getButtonName('next', 'checkout');
604 $this->_checkoutButtonName
,
605 $this->_paymentProcessor
['url_button'],
606 array('class' => 'crm-form-submit')
609 $this->addButtons(array(
612 'name' => ts('Go Back'),
618 if ($this->_contributeMode
== 'notify' ||
!$this->_values
['is_monetary'] ||
619 $this->_amount
<= 0.0 ||
$this->_params
['is_pay_later'] ||
620 ($this->_separateMembershipPayment
&& $this->_amount
<= 0.0)
622 $contribButton = ts('Continue');
623 $this->assign('button', ts('Continue'));
626 $contribButton = ts('Make Contribution');
627 $this->assign('button', ts('Make Contribution'));
629 $this->addButtons(array(
632 'name' => $contribButton,
633 'spacing' => ' ',
635 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name
. "','" . ts('Processing') . "');"),
639 'name' => ts('Go Back'),
646 $fields = array_fill_keys(array_keys($this->_fields
), 1);
647 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
649 $contact = $this->_params
;
650 foreach ($fields as $name => $dontCare) {
651 // Recursively set defaults for nested fields
652 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' ||
$name == 'honor')) {
653 foreach ($contact[$name] as $fieldName => $fieldValue) {
654 if (is_array($fieldValue) && !in_array($this->_fields
[$name][$fieldName]['html_type'], array(
659 foreach ($fieldValue as $key => $value) {
660 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
664 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
668 elseif (isset($contact[$name])) {
669 $defaults[$name] = $contact[$name];
670 if (substr($name, 0, 7) == 'custom_') {
671 $timeField = "{$name}_time";
672 if (isset($contact[$timeField])) {
673 $defaults[$timeField] = $contact[$timeField];
675 if (isset($contact["{$name}_id"])) {
676 $defaults["{$name}_id"] = $contact["{$name}_id"];
679 elseif (in_array($name, array(
683 )) && !empty($contact[$name . '_custom'])
685 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
690 $this->assign('useForMember', $this->get('useForMember'));
692 $this->setDefaults($defaults);
700 * Since we are only showing elements in frozen mode no help display needed.
704 public function getAction() {
705 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
706 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
709 return CRM_Core_Action
::VIEW
;
714 * Set default values for the form.
716 * Note that in edit/view mode
717 * the default values are retrieved from the database
719 public function setDefaultValues() {
725 public function postProcess() {
726 $contactID = $this->getContactID();
727 $result = $this->processFormSubmission($contactID);
728 if (is_array($result) && !empty($result['is_payment_failure'])) {
729 // We will probably have the function that gets this error throw an exception on the next round of refactoring.
730 CRM_Core_Session
::singleton()->setStatus(ts("Payment Processor Error message :") .
731 $result['error']->getMessage());
732 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
733 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
739 * Wrangle financial type ID.
741 * 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
742 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
744 * Comments from previous refactor indicate doubt as to what was going on.
746 * @param int $contributionTypeId
748 * @return null|string
750 public function wrangleFinancialTypeID($contributionTypeId) {
751 if (isset($paymentParams['financial_type'])) {
752 $contributionTypeId = $paymentParams['financial_type'];
754 elseif (!empty($this->_values
['pledge_id'])) {
755 $contributionTypeId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
756 $this->_values
['pledge_id'],
760 return $contributionTypeId;
766 * @param array $premiumParams
767 * @param CRM_Contribute_BAO_Contribution $contribution
769 public function postProcessPremium($premiumParams, $contribution) {
770 $hour = $minute = $second = 0;
771 // assigning Premium information to receipt tpl
772 $selectProduct = CRM_Utils_Array
::value('selectProduct', $premiumParams);
773 if ($selectProduct &&
774 $selectProduct != 'no_thanks'
776 $startDate = $endDate = "";
777 $this->assign('selectPremium', TRUE);
778 $productDAO = new CRM_Contribute_DAO_Product();
779 $productDAO->id
= $selectProduct;
780 $productDAO->find(TRUE);
781 $this->assign('product_name', $productDAO->name
);
782 $this->assign('price', $productDAO->price
);
783 $this->assign('sku', $productDAO->sku
);
784 $this->assign('option', CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams));
786 $periodType = $productDAO->period_type
;
789 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
790 $duration_unit = $productDAO->duration_unit
;
791 $duration_interval = $productDAO->duration_interval
;
792 if ($periodType == 'rolling') {
793 $startDate = date('Y-m-d');
795 elseif ($periodType == 'fixed') {
796 if ($fixed_period_start_day) {
797 $date = explode('-', date('Y-m-d'));
798 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
799 $day = substr($fixed_period_start_day, -2) . "<br/>";
801 $startDate = $year . '-' . $month . '-' . $day;
804 $startDate = date('Y-m-d');
808 $date = explode('-', $startDate);
813 switch ($duration_unit) {
815 $year = $year +
$duration_interval;
819 $month = $month +
$duration_interval;
823 $day = $day +
$duration_interval;
827 $day = $day +
($duration_interval * 7);
829 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
830 $this->assign('start_date', $startDate);
831 $this->assign('end_date', $endDate);
834 $dao = new CRM_Contribute_DAO_Premium();
835 $dao->entity_table
= 'civicrm_contribution_page';
836 $dao->entity_id
= $this->_id
;
838 $this->assign('contact_phone', $dao->premiums_contact_phone
);
839 $this->assign('contact_email', $dao->premiums_contact_email
);
841 //create Premium record
843 'product_id' => $premiumParams['selectProduct'],
844 'contribution_id' => $contribution->id
,
845 'product_option' => CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams),
847 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
848 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
850 if (!empty($premiumParams['selectProduct'])) {
851 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
852 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
853 $daoPremiumsProduct->premiums_id
= $dao->id
;
854 $daoPremiumsProduct->find(TRUE);
855 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
858 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
859 $daoContrProd->contribution_id
= $contribution->id
;
860 if ($daoContrProd->find(TRUE)) {
861 $params['id'] = $daoContrProd->id
;
864 CRM_Contribute_BAO_Contribution
::addPremium($params);
865 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
867 'cost' => $productDAO->cost
,
868 'currency' => $productDAO->currency
,
869 'financial_type_id' => $params['financial_type_id'],
870 'contributionId' => $contribution->id
,
872 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
875 elseif ($selectProduct == 'no_thanks') {
877 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
878 $daoContrProd->contribution_id
= $contribution->id
;
879 if ($daoContrProd->find(TRUE)) {
880 $daoContrProd->delete();
886 * Process the contribution.
888 * @param CRM_Core_Form $form
889 * @param array $params
890 * @param array $result
891 * @param int $contactID
892 * @param CRM_Financial_DAO_FinancialType $financialType
893 * @param bool $pending
894 * @param bool $online
896 * @param bool $isTest
897 * @param array $lineItems
899 * @param int $billingLocationID
900 * ID of billing location type.
902 * @return \CRM_Contribute_DAO_Contribution
905 public static function processFormContribution(
917 $transaction = new CRM_Core_Transaction();
918 $contribSoftContactId = $addressID = NULL;
919 $contributeMode = $form->_contributeMode
;
920 $isMonetary = !empty($form->_values
['is_monetary']);
921 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
922 // How do these vary from params? These are currently passed to
923 // - custom data function....
924 $formParams = $form->_params
;
925 $isSeparateMembershipPayment = empty($formParams['separate_membership_payment']) ?
FALSE : TRUE;
926 $pledgeID = empty($formParams['pledge_id']) ?
NULL : $formParams['pledge_id'];
927 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
928 (!empty($formParams['is_pledge']) ||
$pledgeID)) {
935 // add these values for the recurringContrib function ,CRM-10188
936 $params['financial_type_id'] = $financialType->id
;
938 //create an contribution address
939 if ($contributeMode != 'notify' && empty($params['is_pay_later']) && $isMonetary) {
940 $addressID = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
943 //@todo - this is being set from the form to resolve CRM-10188 - an
944 // eNotice caused by it not being set @ the front end
945 // however, we then get it being over-written with null for backend contributions
946 // a better fix would be to set the values in the respective forms rather than require
947 // a function being shared by two forms to deal with their respective values
948 // moving it to the BAO & not taking the $form as a param would make sense here.
949 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
950 $params['is_email_receipt'] = $isEmailReceipt;
952 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType, $online);
953 $nonDeductibleAmount = self
::getNonDeductibleAmount($params, $financialType, $online);
955 $now = date('YmdHis');
956 $receiptDate = CRM_Utils_Array
::value('receipt_date', $params);
957 if ($isEmailReceipt) {
961 //get the contrib page id.
962 $contributionPageId = NULL;
964 $contributionPageId = $form->_id
;
965 $campaignId = CRM_Utils_Array
::value('campaign_id', $params);
966 if (!array_key_exists('campaign_id', $params)) {
967 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
971 //also for offline we do support - CRM-7290
972 $contributionPageId = CRM_Utils_Array
::value('contribution_page_id', $params);
973 $campaignId = CRM_Utils_Array
::value('campaign_id', $params);
976 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
977 if (!empty($params['pcp_made_through_id']) ||
!empty($params['soft_credit_to'])) {
979 if (!empty($params['pcp_made_through_id'])) {
980 $contribSoftContactId = CRM_Core_DAO
::getFieldValue(
982 $params['pcp_made_through_id'],
987 $contribSoftContactId = CRM_Utils_Array
::value('soft_credit_to', $params);
990 // Pass these details onto with the contribution to make them
991 // available at hook_post_process, CRM-8908
992 $params['soft_credit_to'] = $contribSoftContactId;
995 if (isset($params['amount'])) {
996 $contribParams = self
::getContributionParams(
997 $params, $contactID, $financialType->id
, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending, $result, $receiptDate,
998 $recurringContributionID, $isTest, $addressID, $contribSoftContactId, $lineItems
1000 $contribution = CRM_Contribute_BAO_Contribution
::add($contribParams);
1002 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1003 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
1005 $dataArray = array();
1006 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
1007 foreach ($lineItemValue as $key => $value) {
1008 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1009 if (isset($dataArray[$value['tax_rate']])) {
1010 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
1013 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
1018 $smarty = CRM_Core_Smarty
::singleton();
1019 $smarty->assign('dataArray', $dataArray);
1020 $smarty->assign('totalTaxAmount', $params['tax_amount']);
1022 if (is_a($contribution, 'CRM_Core_Error')) {
1023 $message = CRM_Core_Error
::getMessages($contribution);
1024 CRM_Core_Error
::fatal($message);
1027 // lets store it in the form variable so postProcess hook can get to this and use it
1028 $form->_contributionID
= $contribution->id
;
1031 //CRM-13981, processing honor contact into soft-credit contribution
1032 CRM_Contact_Form_ProfileContact
::postProcess($form);
1034 // process soft credit / pcp pages
1035 CRM_Contribute_Form_Contribution_Confirm
::processPcpSoft($params, $contribution);
1037 //handle pledge stuff.
1040 //when user doing pledge payments.
1041 //update the schedule when payment(s) are made
1042 foreach ($form->_params
['pledge_amount'] as $paymentId => $dontCare) {
1043 $scheduledAmount = CRM_Core_DAO
::getFieldValue(
1044 'CRM_Pledge_DAO_PledgePayment',
1050 $pledgePaymentParams = array(
1052 'contribution_id' => $contribution->id
,
1053 'status_id' => $contribution->contribution_status_id
,
1054 'actual_amount' => $scheduledAmount,
1057 CRM_Pledge_BAO_PledgePayment
::add($pledgePaymentParams);
1060 //update pledge status according to the new payment statuses
1061 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID);
1064 //when user creating pledge record.
1065 $pledgeParams = array();
1066 $pledgeParams['contact_id'] = $contribution->contact_id
;
1067 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount
;
1068 $pledgeParams['contribution_id'] = $contribution->id
;
1069 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id
;
1070 $pledgeParams['financial_type_id'] = $contribution->financial_type_id
;
1071 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
1072 $pledgeParams['installments'] = $params['pledge_installments'];
1073 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
1074 if ($pledgeParams['frequency_unit'] == 'month') {
1075 $pledgeParams['frequency_day'] = intval(date("d"));
1078 $pledgeParams['frequency_day'] = 1;
1080 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
1081 $pledgeParams['status_id'] = $contribution->contribution_status_id
;
1082 $pledgeParams['max_reminders'] = $form->_values
['max_reminders'];
1083 $pledgeParams['initial_reminder_day'] = $form->_values
['initial_reminder_day'];
1084 $pledgeParams['additional_reminder_day'] = $form->_values
['additional_reminder_day'];
1085 $pledgeParams['is_test'] = $contribution->is_test
;
1086 $pledgeParams['acknowledge_date'] = date('Ymd');
1087 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
1089 //inherit campaign from contirb page.
1090 $pledgeParams['campaign_id'] = $campaignId;
1092 $pledge = CRM_Pledge_BAO_Pledge
::create($pledgeParams);
1094 $form->_params
['pledge_id'] = $pledge->id
;
1096 //send acknowledgment email. only when pledge is created
1098 //build params to send acknowledgment.
1099 $pledgeParams['id'] = $pledge->id
;
1100 $pledgeParams['receipt_from_name'] = $form->_values
['receipt_from_name'];
1101 $pledgeParams['receipt_from_email'] = $form->_values
['receipt_from_email'];
1103 //scheduled amount will be same as installment_amount.
1104 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
1106 //get total pledge amount.
1107 $pledgeParams['total_pledge_amount'] = $pledge->amount
;
1109 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($form, $pledgeParams);
1114 if ($online && $contribution) {
1115 CRM_Core_BAO_CustomValueTable
::postProcess($form->_params
,
1116 'civicrm_contribution',
1121 elseif ($contribution) {
1122 //handle custom data.
1123 $params['contribution_id'] = $contribution->id
;
1124 if (!empty($params['custom']) &&
1125 is_array($params['custom']) &&
1126 !is_a($contribution, 'CRM_Core_Error')
1128 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
1132 if ($contribution && !empty($params['contribution_note'])) {
1133 $noteParams = array(
1134 'entity_table' => 'civicrm_contribution',
1135 'note' => $params['contribution_note'],
1136 'entity_id' => $contribution->id
,
1137 'contact_id' => $contribution->contact_id
,
1138 'modified_date' => date('Ymd'),
1141 CRM_Core_BAO_Note
::add($noteParams, array());
1144 if (isset($params['related_contact'])) {
1145 $contactID = $params['related_contact'];
1147 elseif (isset($params['cms_contactID'])) {
1148 $contactID = $params['cms_contactID'];
1151 //create contribution activity w/ individual and target
1152 //activity w/ organisation contact id when onbelf, CRM-4027
1153 $targetContactID = NULL;
1154 if (!empty($params['hidden_onbehalf_profile'])) {
1155 $targetContactID = $contribution->contact_id
;
1156 $contribution->contact_id
= $contactID;
1159 // create an activity record
1160 if ($contribution) {
1161 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
1164 $transaction->commit();
1165 // CRM-13074 - create the CMSUser after the transaction is completed as it
1166 // is not appropriate to delete a valid contribution if a user create problem occurs
1167 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($params,
1169 'email-' . $billingLocationID
1171 return $contribution;
1175 * Create the recurring contribution record.
1177 * @param CRM_Core_Form $form
1178 * @param array $params
1179 * @param int $contactID
1180 * @param string $contributionType
1181 * @param bool $online
1185 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1186 // return if this page is not set for recurring
1187 // or the user has not chosen the recurring option
1189 //this is online case validation.
1190 if ((empty($form->_values
['is_recur']) && $online) ||
empty($params['is_recur'])) {
1194 $recurParams = array('contact_id' => $contactID);
1195 $recurParams['amount'] = CRM_Utils_Array
::value('amount', $params);
1196 $recurParams['auto_renew'] = CRM_Utils_Array
::value('auto_renew', $params);
1197 $recurParams['frequency_unit'] = CRM_Utils_Array
::value('frequency_unit', $params);
1198 $recurParams['frequency_interval'] = CRM_Utils_Array
::value('frequency_interval', $params);
1199 $recurParams['installments'] = CRM_Utils_Array
::value('installments', $params);
1200 $recurParams['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $params);
1201 $recurParams['currency'] = CRM_Utils_Array
::value('currency', $params);
1203 // CRM-14354: For an auto-renewing membership with an additional contribution,
1204 // if separate payments is not enabled, make sure only the membership fee recurs
1205 if (!empty($form->_membershipBlock
)
1206 && $form->_membershipBlock
['is_separate_payment'] === '0'
1207 && isset($params['selectMembership'])
1208 && $form->_values
['is_allow_other_amount'] == '1'
1210 && !empty($form->_membershipTypeValues
)
1211 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1213 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1216 $recurParams['is_test'] = 0;
1217 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1218 (isset($form->_mode
) && ($form->_mode
== 'test'))
1220 $recurParams['is_test'] = 1;
1223 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1224 if (!empty($params['receive_date'])) {
1225 $recurParams['start_date'] = $params['receive_date'];
1227 $recurParams['invoice_id'] = CRM_Utils_Array
::value('invoiceID', $params);
1228 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1229 $recurParams['payment_processor_id'] = CRM_Utils_Array
::value('payment_processor_id', $params);
1230 $recurParams['is_email_receipt'] = CRM_Utils_Array
::value('is_email_receipt', $params);
1231 // we need to add a unique trxn_id to avoid a unique key error
1232 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1233 $recurParams['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params, $params['invoiceID']);
1234 $recurParams['financial_type_id'] = $contributionType->id
;
1236 if (!$online ||
$form->_values
['is_monetary']) {
1237 $recurParams['payment_instrument_id'] = 1;
1240 $campaignId = CRM_Utils_Array
::value('campaign_id', $params);
1242 if (!array_key_exists('campaign_id', $params)) {
1243 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1246 $recurParams['campaign_id'] = $campaignId;
1248 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1249 if (is_a($recurring, 'CRM_Core_Error')) {
1250 CRM_Core_Error
::displaySessionError($recurring);
1251 $urlString = 'civicrm/contribute/transact';
1252 $urlParams = '_qf_Main_display=true';
1253 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1254 $urlString = 'civicrm/contact/view/contribution';
1255 $urlParams = "action=add&cid={$form->_contactID}";
1257 $urlParams .= "&mode={$form->_mode}";
1260 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1263 return $recurring->id
;
1267 * Add on behalf of organization and it's location.
1269 * This situation occurs when on behalf of is enabled for the contribution page and the person
1270 * signing up does so on behalf of an organization.
1272 * @param array $behalfOrganization
1273 * array of organization info.
1274 * @param int $contactID
1275 * individual contact id. One.
1276 * who is doing the process of signup / contribution.
1278 * @param array $values
1279 * form values array.
1280 * @param array $params
1281 * @param array $fields
1282 * Array of fields from the onbehalf profile relevant to the organization.
1284 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1285 $isCurrentEmployer = FALSE;
1288 if (!empty($behalfOrganization['organization_id']) && empty($behalfOrganization['org_option'])) {
1289 $orgID = $behalfOrganization['organization_id'];
1290 unset($behalfOrganization['organization_id']);
1291 $isCurrentEmployer = TRUE;
1294 // formalities for creating / editing organization.
1295 $behalfOrganization['contact_type'] = 'Organization';
1297 // get the relationship type id
1298 $relType = new CRM_Contact_DAO_RelationshipType();
1299 $relType->name_a_b
= 'Employee of';
1300 $relType->find(TRUE);
1301 $relTypeId = $relType->id
;
1303 // keep relationship params ready
1304 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1305 $relParams['is_permission_a_b'] = 1;
1306 $relParams['is_active'] = 1;
1309 // check if matching organization contact exists
1310 $dedupeParams = CRM_Dedupe_Finder
::formatParams($behalfOrganization, 'Organization');
1311 $dedupeParams['check_permission'] = FALSE;
1312 $dupeIDs = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1314 // CRM-6243 says to pick the first org even if more than one match
1315 if (count($dupeIDs) >= 1) {
1316 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1317 // don't allow name edit
1318 unset($behalfOrganization['organization_name']);
1322 // if found permissioned related organization, allow location edit
1323 $behalfOrganization['contact_id'] = $orgID;
1324 // don't allow name edit
1325 unset($behalfOrganization['organization_name']);
1328 // handling for image url
1329 if (!empty($behalfOrganization['image_URL'])) {
1330 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1333 // create organization, add location
1334 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1335 NULL, NULL, 'Organization'
1337 // create relationship
1338 $relParams['contact_check'][$orgID] = 1;
1339 $cid = array('contact' => $contactID);
1340 CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relParams, $cid);
1342 // if multiple match - send a duplicate alert
1343 if ($dupeIDs && (count($dupeIDs) > 1)) {
1344 $values['onbehalf_dupe_alert'] = 1;
1346 $params['onbehalf_dupe_alert'] = 1;
1349 // make sure organization-contact-id is considered for recording
1350 // contribution/membership etc..
1351 if ($contactID != $orgID) {
1352 // take a note of contact-id, so we can send the
1353 // receipt to individual contact as well.
1355 // required for mailing/template display ..etc
1356 $values['related_contact'] = $contactID;
1358 $params['related_contact'] = $contactID;
1360 //make this employee of relationship as current
1361 //employer / employee relationship, CRM-3532
1362 if ($isCurrentEmployer &&
1363 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1365 $isCurrentEmployer = FALSE;
1368 if (!$isCurrentEmployer && $orgID) {
1369 //build current employer params
1370 $currentEmpParams[$contactID] = $orgID;
1371 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1374 // contribution / signup will be done using this
1376 $contactID = $orgID;
1381 * Function used to save pcp / soft credit entry.
1383 * This is used by contribution and also event pcps
1385 * @param array $params
1386 * @param object $contribution
1387 * Contribution object.
1389 public static function processPcpSoft(&$params, &$contribution) {
1390 // Add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1391 if (!empty($params['soft_credit_to'])) {
1392 $contributionSoftParams = array();
1394 'pcp_display_in_roll',
1395 'pcp_roll_nickname',
1396 'pcp_personal_note',
1399 if (!empty($params[$val])) {
1400 $contributionSoftParams[$val] = $params[$val];
1404 $contributionSoftParams['contact_id'] = $params['soft_credit_to'];
1405 // add contribution id
1406 $contributionSoftParams['contribution_id'] = $contribution->id
;
1408 $contributionSoftParams['pcp_id'] = $params['pcp_made_through_id'];
1410 $contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
1412 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
1414 //Send notification to owner for PCP
1415 if ($contributionSoft->id
&& $contributionSoft->pcp_id
) {
1416 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
1422 * Function used to send notification mail to pcp owner.
1424 * This is used by contribution and also event PCPs.
1426 * @param object $contribution
1427 * @param object $contributionSoft
1428 * Contribution object.
1430 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1431 $params = array('id' => $contributionSoft->pcp_id
);
1432 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1433 $ownerNotifyID = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1435 if ($ownerNotifyID != CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1436 (($ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1437 CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id
, 'is_notify')) ||
1438 $ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1439 $pcpInfoURL = CRM_Utils_System
::url('civicrm/pcp/info',
1440 "reset=1&id={$contributionSoft->pcp_id}",
1441 TRUE, NULL, FALSE, TRUE
1443 // set email in the template here
1444 // get the billing location type
1445 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1446 $billingLocationTypeId = array_search('Billing', $locationTypes);
1448 if ($billingLocationTypeId) {
1449 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
, FALSE, $billingLocationTypeId);
1451 // get primary location email if no email exist( for billing location).
1453 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
);
1455 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft->contact_id
);
1457 'page_title' => $pcpInfo['title'],
1458 'receive_date' => $contribution->receive_date
,
1459 'total_amount' => $contributionSoft->amount
,
1460 'donors_display_name' => $donorName,
1461 'donors_email' => $email,
1462 'pcpInfoURL' => $pcpInfoURL,
1463 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll
,
1465 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1466 $sendTemplateParams = array(
1467 'groupName' => 'msg_tpl_workflow_contribution',
1468 'valueName' => 'pcp_owner_notify',
1469 'contactId' => $contributionSoft->contact_id
,
1470 'toEmail' => $ownerEmail,
1471 'toName' => $ownerName,
1472 'from' => "$domainValues[0] <$domainValues[1]>",
1473 'tplParams' => $tplParams,
1474 'PDFFilename' => 'receipt.pdf',
1476 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1481 * Function used to se pcp related defaults / params.
1483 * This is used by contribution and also event PCPs
1485 * @param CRM_Core_Form $page
1487 * @param array $params
1491 public static function processPcp(&$page, $params) {
1492 $params['pcp_made_through_id'] = $page->_pcpId
;
1493 $page->assign('pcpBlock', TRUE);
1494 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1495 $params['pcp_roll_nickname'] = ts('Anonymous');
1496 $params['pcp_is_anonymous'] = 1;
1499 $params['pcp_is_anonymous'] = 0;
1502 'pcp_display_in_roll',
1504 'pcp_roll_nickname',
1505 'pcp_personal_note',
1507 if (!empty($params[$val])) {
1508 $page->assign($val, $params[$val]);
1516 * Process membership.
1518 * @param array $membershipParams
1519 * @param int $contactID
1520 * @param array $customFieldsFormatted
1521 * @param array $fieldTypes
1522 * @param array $premiumParams
1523 * @param array $membershipLineItems
1524 * Line items specifically relating to memberships.
1525 * @param bool $isPayLater
1527 public function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater) {
1529 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1530 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1531 $membershipType = empty($membershipTypes) ?
array() : reset($membershipTypes);
1532 $isPending = $this->getIsPending();
1534 $this->assign('membership_name', CRM_Utils_Array
::value('name', $membershipType));
1536 $isPaidMembership = FALSE;
1537 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1538 //amount must be greater than zero for
1539 //adding contribution record to contribution table.
1540 //this condition arises when separate membership payment is
1541 //enabled and contribution amount is not selected. fix for CRM-3010
1542 $isPaidMembership = TRUE;
1544 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1546 if ($this->_values
['amount_block_is_active']) {
1547 $financialTypeID = $this->_values
['financial_type_id'];
1550 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $membershipType, CRM_Utils_Array
::value('financial_type_id', $membershipParams));
1553 if (CRM_Utils_Array
::value('membership_source', $this->_params
)) {
1554 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1557 CRM_Member_BAO_Membership
::postProcessMembership($membershipParams, $contactID,
1558 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1559 $membershipLineItems, $isPayLater, $isPending);
1561 $this->assign('membership_assign', TRUE);
1562 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1564 catch (CRM_Core_Exception
$e) {
1565 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
1566 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
1571 * Is the payment a pending payment.
1573 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1574 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1579 protected function getIsPending() {
1580 if (((isset($this->_contributeMode
)) ||
!empty
1581 ($this->_params
['is_pay_later'])
1583 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1591 * Are we going to do 2 financial transactions.
1593 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1595 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1597 * @param int $formID
1598 * @param bool $amountBlockActiveOnForm
1602 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1603 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1604 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1611 * This function sets the fields.
1613 * - $this->_params['amount_level']
1614 * - $this->_params['selectMembership']
1615 * And under certain circumstances sets
1616 * $this->_params['amount'] = null;
1618 * @param int $priceSetID
1620 public function setFormAmountFields($priceSetID) {
1621 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1622 $priceField = new CRM_Price_DAO_PriceField();
1623 $priceField->price_set_id
= $priceSetID;
1624 $priceField->orderBy('weight');
1625 $priceField->find();
1626 $paramWeDoNotUnderstand = NULL;
1628 while ($priceField->fetch()) {
1629 if ($priceField->name
== "contribution_amount") {
1630 $paramWeDoNotUnderstand = $priceField->id
;
1632 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1633 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1634 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1635 $this->_params
["price_{$priceField->id}"], 'label');
1637 if ($priceField->name
== "membership_amount") {
1638 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1639 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1642 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1643 // as membership amount.
1644 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1645 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1646 // so we should merge them together
1647 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1648 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1650 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
)
1651 && !empty($this->_values
['fee'][$priceField->id
])
1652 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1653 && CRM_Utils_Array
::value("price_{$paramWeDoNotUnderstand}", $this->_params
) < 1
1654 && empty($this->_params
["price_{$priceField->id}"])
1656 $this->_params
['amount'] = NULL;
1659 // Fix for CRM-14375 - If we are using separate payments and "no
1660 // thank you" is selected for the additional contribution, set
1661 // contribution amount to be null, so that it will not show
1662 // contribution amount same as membership amount.
1663 //@todo - merge with section above
1664 if ($this->_membershipBlock
['is_separate_payment']
1665 && !empty($this->_values
['fee'][$priceField->id
])
1666 && CRM_Utils_Array
::value('name', $this->_values
['fee'][$priceField->id
]) == 'contribution_amount'
1667 && CRM_Utils_Array
::value("price_{$priceField->id}", $this->_params
) == '-1'
1669 $this->_params
['amount'] = NULL;
1677 * @param array $params
1679 * @throws CiviCRM_API3_Exception
1681 public static function submit($params) {
1682 $form = new CRM_Contribute_Form_Contribution_Confirm();
1683 $form->_id
= $params['id'];
1685 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1686 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1687 //this way the mocked up controller ignores the session stuff
1688 $_SERVER['REQUEST_METHOD'] = 'GET';
1689 $form->controller
= new CRM_Contribute_Controller_Contribution();
1690 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1691 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1692 $form->_amount
= $params['amount'];
1693 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1694 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1695 $priceSetFields = reset($priceFields);
1696 $form->_values
['fee'] = $priceSetFields['fields'];
1697 $form->_priceSetId
= $priceSetID;
1698 $form->setFormAmountFields($priceSetID);
1699 if (!empty($params['payment_processor_id'])) {
1700 $form->_paymentProcessor
= civicrm_api3('payment_processor', 'getsingle', array(
1701 'id' => $params['payment_processor_id'],
1703 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1704 $form->_contributeMode
= 'direct';
1707 $form->_contributeMode
= 'notify';
1711 $form->_params
['payment_processor_id'] = 0;
1713 $priceFields = $priceFields[$priceSetID]['fields'];
1714 CRM_Price_BAO_PriceSet
::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1715 $form->_lineItem
= array($priceSetID => $lineItems);
1716 $form->processFormSubmission(CRM_Utils_Array
::value('contact_id', $params));
1720 * Helper function for static submit function.
1722 * Set relevant params - help us to build up an array that we can pass in.
1725 * @param array $params
1728 * @throws CiviCRM_API3_Exception
1730 public static function getFormParams($id, array $params) {
1731 if (!isset($params['is_pay_later'])) {
1732 if (!empty($params['payment_processor_id'])) {
1733 $params['is_pay_later'] = 0;
1736 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1738 'return' => 'is_pay_later',
1742 if (empty($params['price_set_id'])) {
1743 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
1749 * Post form submission handling.
1751 * This is also called from the test suite.
1753 * @param int $contactID
1757 protected function processFormSubmission($contactID) {
1758 $isPayLater = $this->_params
['is_pay_later'];
1759 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] == 0) {
1760 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
1762 // add a description field at the very beginning
1763 $this->_params
['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $this->_values
['title']);
1765 $this->_params
['accountingCode'] = CRM_Utils_Array
::value('accountingCode', $this->_values
);
1768 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
1770 //carry payment processor id.
1771 if (CRM_Utils_Array
::value('id', $this->_paymentProcessor
)) {
1772 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
1774 if (!empty($params['image_URL'])) {
1775 CRM_Contact_BAO_Contact
::processImageParams($params);
1777 $premiumParams = $membershipParams = $params = $this->_params
;
1778 $fields = array('email-Primary' => 1);
1780 // get the add to groups
1781 $addToGroups = array();
1783 // now set the values for the billing location.
1784 foreach ($this->_fields
as $name => $value) {
1787 // get the add to groups for uf fields
1788 if (!empty($value['add_to_group_id'])) {
1789 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
1793 if (!array_key_exists('first_name', $fields)) {
1794 $nameFields = array('first_name', 'middle_name', 'last_name');
1795 foreach ($nameFields as $name) {
1797 if (array_key_exists("billing_$name", $params)) {
1798 $params[$name] = $params["billing_{$name}"];
1799 $params['preserveDBName'] = TRUE;
1804 // billing email address
1805 $fields["email-{$this->_bltID}"] = 1;
1807 //unset the billing parameters if it is pay later mode
1808 //to avoid creation of billing location
1809 if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater
) {
1810 $billingFields = array(
1811 'billing_first_name',
1812 'billing_middle_name',
1813 'billing_last_name',
1814 "billing_street_address-{$this->_bltID}",
1815 "billing_city-{$this->_bltID}",
1816 "billing_state_province-{$this->_bltID}",
1817 "billing_state_province_id-{$this->_bltID}",
1818 "billing_postal_code-{$this->_bltID}",
1819 "billing_country-{$this->_bltID}",
1820 "billing_country_id-{$this->_bltID}",
1823 foreach ($billingFields as $value) {
1824 unset($params[$value]);
1825 unset($fields[$value]);
1829 // if onbehalf-of-organization contribution, take out
1830 // organization params in a separate variable, to make sure
1831 // normal behavior is continued. And use that variable to
1832 // process on-behalf-of functionality.
1833 if (!empty($this->_params
['hidden_onbehalf_profile'])) {
1834 $behalfOrganization = array();
1835 $orgFields = array('organization_name', 'organization_id', 'org_option');
1836 foreach ($orgFields as $fld) {
1837 if (array_key_exists($fld, $params)) {
1838 $behalfOrganization[$fld] = $params[$fld];
1839 unset($params[$fld]);
1843 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
1844 foreach ($params['onbehalf'] as $fld => $values) {
1845 if (strstr($fld, 'custom_')) {
1846 $behalfOrganization[$fld] = $values;
1848 elseif (!(strstr($fld, '-'))) {
1849 if (in_array($fld, array(
1850 'contribution_campaign_id',
1851 'member_campaign_id',
1853 $fld = 'campaign_id';
1856 $behalfOrganization[$fld] = $values;
1858 $this->_params
[$fld] = $values;
1863 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
1864 foreach ($params['onbehalf_location'] as $block => $vals) {
1865 //fix for custom data (of type checkbox, multi-select)
1866 if (substr($block, 0, 7) == 'custom_') {
1869 // fix the index of block elements
1870 if (is_array($vals)) {
1871 foreach ($vals as $key => $val) {
1872 //dont adjust the index of address block as
1873 //it's index is WRT to location type
1874 $newKey = ($block == 'address') ?
$key : ++
$key;
1875 $behalfOrganization[$block][$newKey] = $val;
1879 unset($params['onbehalf_location']);
1881 if (!empty($params['onbehalf[image_URL]'])) {
1882 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
1886 // check for profile double opt-in and get groups to be subscribed
1887 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
1889 // since we are directly adding contact to group lets unset it from mailing
1890 if (!empty($addToGroups)) {
1891 foreach ($addToGroups as $groupId) {
1892 if (isset($subscribeGroupIds[$groupId])) {
1893 unset($subscribeGroupIds[$groupId]);
1898 foreach ($addToGroups as $k) {
1899 if (array_key_exists($k, $subscribeGroupIds)) {
1900 unset($addToGroups[$k]);
1904 if (empty($contactID)) {
1905 $dupeParams = $params;
1906 if (!empty($dupeParams['onbehalf'])) {
1907 unset($dupeParams['onbehalf']);
1909 if (!empty($dupeParams['honor'])) {
1910 unset($dupeParams['honor']);
1913 $dedupeParams = CRM_Dedupe_Finder
::formatParams($dupeParams, 'Individual');
1914 $dedupeParams['check_permission'] = FALSE;
1915 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
1917 // if we find more than one contact, use the first one
1918 $contactID = CRM_Utils_Array
::value(0, $ids);
1920 // Fetch default greeting id's if creating a contact
1922 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1923 if (!isset($params[$greeting])) {
1924 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
1928 $contactType = NULL;
1931 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
1933 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
1943 // Make the contact ID associated with the contribution available at the Class level.
1944 // Also make available to the session.
1945 //@todo consider handling this in $this->getContactID();
1946 $this->set('contactID', $contactID);
1947 $this->_contactID
= $contactID;
1949 //get email primary first if exist
1950 $subscriptionEmail = array('email' => CRM_Utils_Array
::value('email-Primary', $params));
1951 if (!$subscriptionEmail['email']) {
1952 $subscriptionEmail['email'] = CRM_Utils_Array
::value("email-{$this->_bltID}", $params);
1954 // subscribing contact to groups
1955 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
1956 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
1959 // If onbehalf-of-organization contribution / signup, add organization
1960 // and it's location.
1961 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
1962 $ufFields = array();
1963 foreach ($this->_fields
['onbehalf'] as $name => $value) {
1964 $ufFields[$name] = 1;
1966 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
1967 $this->_params
, $ufFields
1970 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
1971 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
1972 // store current user id as related contact for later use for mailing / activity..
1973 $this->_values
['related_contact'] = $contactID;
1974 $this->_params
['related_contact'] = $contactID;
1975 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
1976 $contactID = $this->_membershipContactID
;
1979 // lets store the contactID in the session
1980 // for things like tell a friend
1981 $session = CRM_Core_Session
::singleton();
1982 if (!$session->get('userID')) {
1983 $session->set('transaction.userID', $contactID);
1986 $session->set('transaction.userID', NULL);
1989 $this->_useForMember
= $this->get('useForMember');
1991 // store the fact that this is a membership and membership type is selected
1992 if ((!empty($membershipParams['selectMembership']) &&
1993 $membershipParams['selectMembership'] != 'no_thanks'
1995 $this->_useForMember
1997 if (!$this->_useForMember
) {
1998 $this->assign('membership_assign', TRUE);
1999 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2002 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2003 $membershipParams['is_test'] = 1;
2005 if ($this->_params
['is_pay_later']) {
2006 $membershipParams['is_pay_later'] = 1;
2009 //inherit campaign from contribution page.
2010 if (!array_key_exists('campaign_id', $membershipParams)) {
2011 $membershipParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
);
2014 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2015 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater);
2018 // at this point we've created a contact and stored its address etc
2019 // all the payment processors expect the name and address to be in the
2020 // so we copy stuff over to first_name etc.
2021 $paymentParams = $this->_params
;
2022 $contributionTypeId = $this->_values
['financial_type_id'];
2024 $fieldTypes = array();
2025 if (!empty($paymentParams['onbehalf']) &&
2026 is_array($paymentParams['onbehalf'])
2028 foreach ($paymentParams['onbehalf'] as $key => $value) {
2029 if (strstr($key, 'custom_')) {
2030 $this->_params
[$key] = $value;
2033 $fieldTypes = array('Contact', 'Organization', 'Contribution');
2035 $financialTypeID = $this->wrangleFinancialTypeID($contributionTypeId);
2037 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2038 $premiumParams, $contactID,
2042 ($this->_mode
== 'test') ?
1 : 0,
2046 if (CRM_Utils_Array
::value('contribution_status_id', $result) == 1) {
2047 civicrm_api3('contribution', 'completetransaction', array(
2048 'id' => $result['contribution']->id
,
2049 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $result),
2058 * Membership processing section.
2060 * This is in a separate function as part of a move towards refactoring.
2062 * @param int $contactID
2063 * @param array $membershipParams
2064 * @param array $premiumParams
2065 * @param bool $isPayLater
2067 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater) {
2069 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2070 if (isset($this->_params
['related_contact'])) {
2071 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2074 $membershipParams['cms_contactID'] = $contactID;
2077 if (!empty($membershipParams['onbehalf']) &&
2078 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2080 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2083 $customFieldsFormatted = $fieldTypes = array();
2084 if (!empty($membershipParams['onbehalf']) &&
2085 is_array($membershipParams['onbehalf'])
2087 foreach ($membershipParams['onbehalf'] as $key => $value) {
2088 if (strstr($key, 'custom_')) {
2089 $customFieldId = explode('_', $key);
2090 CRM_Core_BAO_CustomField
::formatCustomField(
2092 $customFieldsFormatted,
2100 $fieldTypes = array('Contact', 'Organization', 'Membership');
2103 $priceFieldIds = $this->get('memberPriceFieldIDS');
2105 if (!empty($priceFieldIds)) {
2106 $contributionTypeID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2107 unset($priceFieldIds['id']);
2108 $membershipTypeIds = array();
2109 $membershipTypeTerms = array();
2110 foreach ($priceFieldIds as $priceFieldId) {
2111 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
2112 $membershipTypeIds[] = $id;
2113 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
2114 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
2116 if ($term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
2117 $membershipTypeTerms[$id] = ($term > 1) ?
$term : 1;
2120 $membershipTypeTerms[$id] = 1;
2124 $membershipParams['selectMembership'] = $membershipTypeIds;
2125 $membershipParams['financial_type_id'] = $contributionTypeID;
2126 $membershipParams['types_terms'] = $membershipTypeTerms;
2128 if (!empty($membershipParams['selectMembership'])) {
2130 $membershipLineItems = array();
2131 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2132 foreach ($this->_values
['fee'] as $key => $feeValues) {
2133 if ($feeValues['name'] == 'membership_amount') {
2134 $fieldId = $this->_params
['price_' . $key];
2135 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2136 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2141 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
2142 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2143 // we need to explicitly create a CMS user in case of free memberships
2144 // since it is done under processConfirm for paid memberships
2145 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2146 $membershipParams['cms_contactID'],
2147 'email-' . $this->_bltID