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 $financialTypeID
60 * @param float $nonDeductibleAmount
61 * @param bool $isMonetary
62 * @param bool $pending
63 * @param array $paymentProcessorOutcome
64 * @param string $receiptDate
65 * @param int $recurringContributionID
69 public static function getContributionParams(
70 $params, $financialTypeID, $online, $nonDeductibleAmount, $isMonetary, $pending,
71 $paymentProcessorOutcome, $receiptDate, $recurringContributionID) {
72 $contributionParams = array(
73 'financial_type_id' => $financialTypeID,
74 'receive_date' => (CRM_Utils_Array
::value('receive_date', $params)) ? CRM_Utils_Date
::processDate($params['receive_date']) : date('YmdHis'),
75 'non_deductible_amount' => $nonDeductibleAmount,
76 'total_amount' => $params['amount'],
77 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $params),
78 'amount_level' => CRM_Utils_Array
::value('amount_level', $params),
79 'invoice_id' => $params['invoiceID'],
80 'currency' => $params['currencyID'],
81 'source' => (!$online ||
!empty($params['source'])) ? CRM_Utils_Array
::value('source', $params) : CRM_Utils_Array
::value('description', $params),
82 'is_pay_later' => CRM_Utils_Array
::value('is_pay_later', $params, 0),
83 //configure cancel reason, cancel date and thankyou date
84 //from 'contribution' type profile if included
85 'cancel_reason' => CRM_Utils_Array
::value('cancel_reason', $params, 0),
86 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date
::format($params['cancel_date']) : NULL,
87 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date
::format($params['thankyou_date']) : NULL,
88 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
89 'skipLineItem' => CRM_Utils_Array
::value('skipLineItem', $params, 0),
91 if (!$online && isset($params['thankyou_date'])) {
92 $contributionParam['thankyou_date'] = $params['thankyou_date'];
94 if (!$online ||
$isMonetary) {
95 if (empty($params['is_pay_later'])) {
96 // @todo look up payment_instrument_id on payment processor table.
97 $contributionParams['payment_instrument_id'] = 1;
100 if ($paymentProcessorOutcome) {
101 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor', $paymentProcessorOutcome);
103 if (!$pending && $paymentProcessorOutcome) {
104 $contributionParams +
= array(
105 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $paymentProcessorOutcome),
106 'net_amount' => CRM_Utils_Array
::value('net_amount', $paymentProcessorOutcome, $params['amount']),
107 'trxn_id' => $paymentProcessorOutcome['trxn_id'],
108 'receipt_date' => $receiptDate,
109 // also add financial_trxn details as part of fix for CRM-4724
110 'trxn_result_code' => CRM_Utils_Array
::value('trxn_result_code', $paymentProcessorOutcome),
114 // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
115 $contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money
::format($contributionParams['non_deductible_amount'], ' '));
116 $contributionParams['total_amount'] = trim(CRM_Utils_Money
::format($contributionParams['total_amount'], ' '));
118 if ($recurringContributionID) {
119 $contributionParams['contribution_recur_id'] = $recurringContributionID;
122 $contributionParams['contribution_status_id'] = $pending ?
2 : 1;
123 if (isset($contributionParams['invoice_id'])) {
124 $contributionParams['id'] = CRM_Core_DAO
::getFieldValue(
125 'CRM_Contribute_DAO_Contribution',
126 $contributionParams['invoice_id'],
132 return $contributionParams;
136 * Get non-deductible amount.
138 * This is a bit too much about wierd form interpretation to be this deep.
141 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
144 * @param array $params
145 * @param CRM_Financial_BAO_FinancialType $financialType
146 * @param bool $online
150 protected static function getNonDeductibleAmount($params, $financialType, $online) {
151 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
152 return $params['non_deductible_amount'];
155 if ($financialType->is_deductible
) {
156 if ($online && isset($params['selectProduct'])) {
157 $selectProduct = CRM_Utils_Array
::value('selectProduct', $params);
159 if (!$online && isset($params['product_name'][0])) {
160 $selectProduct = $params['product_name'][0];
162 // if there is a product - compare the value to the contribution amount
163 if (isset($selectProduct) &&
164 $selectProduct != 'no_thanks'
166 $productDAO = new CRM_Contribute_DAO_Product();
167 $productDAO->id
= $selectProduct;
168 $productDAO->find(TRUE);
169 // product value exceeds contribution amount
170 if ($params['amount'] < $productDAO->price
) {
171 $nonDeductibleAmount = $params['amount'];
172 return $nonDeductibleAmount;
174 // product value does NOT exceed contribution amount
176 return $productDAO->price
;
179 // contribution is deductible - but there is no product
184 // contribution is NOT deductible
186 return $params['amount'];
192 * Set variables up before form is built.
194 public function preProcess() {
195 $config = CRM_Core_Config
::singleton();
196 parent
::preProcess();
198 // lineItem isn't set until Register postProcess
199 $this->_lineItem
= $this->get('lineItem');
200 $this->_paymentProcessor
= $this->get('paymentProcessor');
201 $this->_params
= $this->controller
->exportValues('Main');
202 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
203 $this->_params
['amount'] = $this->get('amount');
204 if (isset($this->_params
['amount'])) {
205 $this->setFormAmountFields($this->_params
['priceSetId']);
208 $this->_params
['tax_amount'] = $this->get('tax_amount');
209 $this->_useForMember
= $this->get('useForMember');
211 if (isset($this->_params
['credit_card_exp_date'])) {
212 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
213 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
216 $this->_params
['currencyID'] = $config->defaultCurrency
;
218 if (!empty($this->_membershipBlock
)) {
219 $this->_params
['selectMembership'] = $this->get('selectMembership');
221 if (!empty($this->_paymentProcessor
) && $this->_paymentProcessor
['object']->supports('preApproval')) {
222 $preApprovalParams = $this->_paymentProcessor
['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
223 $this->_params
= array_merge($this->_params
, $preApprovalParams);
226 // We may have fetched some billing details from the getPreApprovalDetails function so we
227 // want to ensure we set this after that function has been called.
228 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $this->_params
, FALSE);
229 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
230 $this->_params
["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($this->_params
["billing_state_province_id-{$this->_bltID}"]);
232 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
233 $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
236 $this->_params
['is_pay_later'] = $this->get('is_pay_later');
237 $this->assign('is_pay_later', $this->_params
['is_pay_later']);
238 if ($this->_params
['is_pay_later']) {
239 $this->assign('pay_later_receipt', $this->_values
['pay_later_receipt']);
241 // if onbehalf-of-organization
242 if (!empty($this->_params
['hidden_onbehalf_profile'])) {
244 if (empty($this->_params
['org_option']) && empty($this->_params
['organization_id'])) {
245 if (!empty($this->_params
['onbehalfof_id'])) {
246 $this->_params
['organization_id'] = $this->_params
['onbehalfof_id'];
249 $this->_params
['organization_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_params
['onbehalf']['organization_name'], 'id', 'display_name');
253 $this->_params
['organization_name'] = $this->_params
['onbehalf']['organization_name'];
254 $addressBlocks = array(
260 'supplemental_address_1',
261 'supplemental_address_2',
262 'supplemental_address_3',
263 'postal_code_suffix',
269 $blocks = array('email', 'phone', 'im', 'url', 'openid');
270 foreach ($this->_params
['onbehalf'] as $loc => $value) {
271 $field = $typeId = NULL;
272 if (strstr($loc, '-')) {
273 list($field, $locType) = explode('-', $loc);
276 if (in_array($field, $addressBlocks)) {
277 if ($locType == 'Primary') {
278 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
279 $locType = $defaultLocationType->id
;
282 if ($field == 'country') {
283 $value = CRM_Core_PseudoConstant
::countryIsoCode($value);
285 elseif ($field == 'state_province') {
286 $value = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
290 if (isset($this->_params
['onbehalf_location']['address'])
291 && count($this->_params
['onbehalf_location']['address']) > 0
296 $this->_params
['onbehalf_location']['address'][$locType][$field] = $value;
297 if (empty($this->_params
['onbehalf_location']['address'][$locType]['is_primary'])) {
298 $this->_params
['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
300 $this->_params
['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
302 elseif (in_array($field, $blocks)) {
303 if (!$typeId ||
is_numeric($typeId)) {
304 $blockName = $fieldName = $field;
305 $locationType = 'location_type_id';
306 if ($locType == 'Primary') {
307 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
308 $locationValue = $defaultLocationType->id
;
311 $locationValue = $locType;
314 $phoneExtField = array();
316 if ($field == 'url') {
317 $blockName = 'website';
318 $locationType = 'website_type_id';
319 list($field, $locationValue) = explode('-', $loc);
321 elseif ($field == 'im') {
323 $locTypeId = 'provider_id';
324 $typeId = $this->_params
['onbehalf']["{$loc}-provider_id"];
326 elseif ($field == 'phone') {
327 list($field, $locType, $typeId) = explode('-', $loc);
328 $locTypeId = 'phone_type_id';
330 //check if extension field exists
331 $extField = str_replace('phone', 'phone_ext', $loc);
332 if (isset($this->_params
['onbehalf'][$extField])) {
333 $phoneExtField = array('phone_ext' => $this->_params
['onbehalf'][$extField]);
338 if (isset ($this->_params
['onbehalf_location'][$blockName])
339 && count($this->_params
['onbehalf_location'][$blockName]) > 0
343 if ($locationValue) {
344 $blockValues = array(
345 $fieldName => $value,
346 $locationType => $locationValue,
347 'is_primary' => $isPrimary,
351 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
353 if (!empty($phoneExtField)) {
354 $blockValues = array_merge($blockValues, $phoneExtField);
357 $this->_params
['onbehalf_location'][$blockName][] = $blockValues;
361 elseif (strstr($loc, 'custom')) {
362 if ($value && isset($this->_params
['onbehalf']["{$loc}_id"])) {
363 $value = $this->_params
['onbehalf']["{$loc}_id"];
365 $this->_params
['onbehalf_location']["{$loc}"] = $value;
368 if ($loc == 'contact_sub_type') {
369 $this->_params
['onbehalf_location'][$loc] = $value;
372 $this->_params
['onbehalf_location'][$field] = $value;
377 elseif (!empty($this->_values
['is_for_organization'])) {
378 // no on behalf of an organization, CRM-5519
379 // so reset loc blocks from main params.
385 if (isset($this->_params
[$blk])) {
386 unset($this->_params
[$blk]);
390 $this->setRecurringMembershipParams();
393 $params = $this->processPcp($this, $this->_params
);
394 $this->_params
= $params;
396 $this->_params
['invoiceID'] = $this->get('invoiceID');
398 //carry campaign from profile.
399 if (array_key_exists('contribution_campaign_id', $this->_params
)) {
400 $this->_params
['campaign_id'] = $this->_params
['contribution_campaign_id'];
403 // assign contribution page id to the template so we can add css class for it
404 $this->assign('contributionPageID', $this->_id
);
406 $this->set('params', $this->_params
);
410 * Build the form object.
412 public function buildQuickForm() {
413 $this->assignToTemplate();
415 $params = $this->_params
;
416 // make sure we have values for it
417 if ($this->_honor_block_is_active
&& !empty($params['soft_credit_type_id'])) {
419 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
421 $this->assign('honor_block_is_active', $this->_honor_block_is_active
);
422 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
423 CRM_Contribute_BAO_ContributionSoft
::formatHonoreeProfileFields($this, $params['honor'], $params['honoree_profile_id']);
425 $fieldTypes = array('Contact');
426 $fieldTypes[] = CRM_Core_BAO_UFGroup
::getContactType($params['honoree_profile_id']);
427 $this->buildCustom($params['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
429 $this->assign('receiptFromEmail', CRM_Utils_Array
::value('receipt_from_email', $this->_values
));
430 $amount_block_is_active = $this->get('amount_block_is_active');
431 $this->assign('amount_block_is_active', $amount_block_is_active);
433 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
434 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
436 $getTaxDetails = FALSE;
437 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
438 foreach ($this->_lineItem
as $key => $value) {
439 foreach ($value as $v) {
440 if (isset($v['tax_rate'])) {
441 if ($v['tax_rate'] != '') {
442 $getTaxDetails = TRUE;
447 $this->assign('getTaxDetails', $getTaxDetails);
448 $this->assign('taxTerm', $taxTerm);
449 $this->assign('totalTaxAmount', $params['tax_amount']);
451 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
452 $option = CRM_Utils_Array
::value('options_' . $params['selectProduct'], $params);
453 $productID = $params['selectProduct'];
454 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, FALSE,
457 $this->set('productID', $productID);
458 $this->set('option', $option);
460 $config = CRM_Core_Config
::singleton();
461 if (in_array('CiviMember', $config->enableComponents
)) {
462 if (isset($params['selectMembership']) &&
463 $params['selectMembership'] != 'no_thanks'
465 $this->buildMembershipBlock(
466 $this->_membershipContactID
,
468 $params['selectMembership'],
471 if (!empty($params['auto_renew'])) {
472 $this->assign('auto_renew', TRUE);
476 $this->assign('membershipBlock', FALSE);
479 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
480 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
482 if (!empty($params['hidden_onbehalf_profile'])) {
483 $ufJoinParams = array(
484 'module' => 'onBehalf',
485 'entity_table' => 'civicrm_contribution_page',
486 'entity_id' => $this->_id
,
488 $OnBehalfProfile = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
489 $profileId = $OnBehalfProfile[0];
491 $fieldTypes = array('Contact', 'Organization');
492 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
493 $fieldTypes = array_merge($fieldTypes, $contactSubType);
494 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
495 $fieldTypes = array_merge($fieldTypes, array('Membership'));
498 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
501 $this->buildCustom($profileId, 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
504 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
505 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
506 if ($this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
507 $this->assign('lineItem', $this->_lineItem
);
510 $this->assign('is_quick_config', 1);
511 $this->_params
['is_quick_config'] = 1;
513 $this->assign('priceSetID', $this->_priceSetId
);
514 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
515 if ($this->_paymentProcessor
&&
516 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('Google_Checkout', $paymentProcessorType)
517 && !$this->_params
['is_pay_later'] && !($this->_amount
== 0)
519 $this->_checkoutButtonName
= $this->getButtonName('next', 'checkout');
521 $this->_checkoutButtonName
,
522 $this->_paymentProcessor
['url_button'],
523 array('class' => 'crm-form-submit')
526 $this->addButtons(array(
529 'name' => ts('Go Back'),
535 if ($this->_contributeMode
== 'notify' ||
!$this->_values
['is_monetary'] ||
536 $this->_amount
<= 0.0 ||
$this->_params
['is_pay_later'] ||
537 ($this->_separateMembershipPayment
&& $this->_amount
<= 0.0)
539 $contribButton = ts('Continue');
540 $this->assign('button', ts('Continue'));
543 $contribButton = ts('Make Contribution');
544 $this->assign('button', ts('Make Contribution'));
546 $this->addButtons(array(
549 'name' => $contribButton,
550 'spacing' => ' ',
552 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name
. "','" . ts('Processing') . "');"),
556 'name' => ts('Go Back'),
563 $fields = array_fill_keys(array_keys($this->_fields
), 1);
564 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
566 $contact = $this->_params
;
567 foreach ($fields as $name => $dontCare) {
568 // Recursively set defaults for nested fields
569 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' ||
$name == 'honor')) {
570 foreach ($contact[$name] as $fieldName => $fieldValue) {
571 if (is_array($fieldValue) && !in_array($this->_fields
[$name][$fieldName]['html_type'], array(
576 foreach ($fieldValue as $key => $value) {
577 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
581 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
585 elseif (isset($contact[$name])) {
586 $defaults[$name] = $contact[$name];
587 if (substr($name, 0, 7) == 'custom_') {
588 $timeField = "{$name}_time";
589 if (isset($contact[$timeField])) {
590 $defaults[$timeField] = $contact[$timeField];
592 if (isset($contact["{$name}_id"])) {
593 $defaults["{$name}_id"] = $contact["{$name}_id"];
596 elseif (in_array($name, array(
600 )) && !empty($contact[$name . '_custom'])
602 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
607 $this->assign('useForMember', $this->get('useForMember'));
609 $this->setDefaults($defaults);
617 * Since we are only showing elements in frozen mode no help display needed.
621 public function getAction() {
622 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
623 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
626 return CRM_Core_Action
::VIEW
;
631 * Set default values for the form.
633 * Note that in edit/view mode
634 * the default values are retrieved from the database
636 public function setDefaultValues() {
642 public function postProcess() {
643 $contactID = $this->getContactID();
644 $result = $this->processFormSubmission($contactID);
645 if (is_array($result) && !empty($result['is_payment_failure'])) {
646 // We will probably have the function that gets this error throw an exception on the next round of refactoring.
647 CRM_Core_Session
::singleton()->setStatus(ts("Payment Processor Error message :") .
648 $result['error']->getMessage());
649 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
650 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
653 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
654 $this->set('params', $this->_params
);
658 * Wrangle financial type ID.
660 * 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
661 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
663 * Comments from previous refactor indicate doubt as to what was going on.
665 * @param int $contributionTypeId
667 * @return null|string
669 public function wrangleFinancialTypeID($contributionTypeId) {
670 if (isset($paymentParams['financial_type'])) {
671 $contributionTypeId = $paymentParams['financial_type'];
673 elseif (!empty($this->_values
['pledge_id'])) {
674 $contributionTypeId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
675 $this->_values
['pledge_id'],
679 return $contributionTypeId;
685 * @param array $premiumParams
686 * @param CRM_Contribute_BAO_Contribution $contribution
688 protected function postProcessPremium($premiumParams, $contribution) {
689 $hour = $minute = $second = 0;
690 // assigning Premium information to receipt tpl
691 $selectProduct = CRM_Utils_Array
::value('selectProduct', $premiumParams);
692 if ($selectProduct &&
693 $selectProduct != 'no_thanks'
695 $startDate = $endDate = "";
696 $this->assign('selectPremium', TRUE);
697 $productDAO = new CRM_Contribute_DAO_Product();
698 $productDAO->id
= $selectProduct;
699 $productDAO->find(TRUE);
700 $this->assign('product_name', $productDAO->name
);
701 $this->assign('price', $productDAO->price
);
702 $this->assign('sku', $productDAO->sku
);
703 $this->assign('option', CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams));
705 $periodType = $productDAO->period_type
;
708 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
709 $duration_unit = $productDAO->duration_unit
;
710 $duration_interval = $productDAO->duration_interval
;
711 if ($periodType == 'rolling') {
712 $startDate = date('Y-m-d');
714 elseif ($periodType == 'fixed') {
715 if ($fixed_period_start_day) {
716 $date = explode('-', date('Y-m-d'));
717 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
718 $day = substr($fixed_period_start_day, -2) . "<br/>";
720 $startDate = $year . '-' . $month . '-' . $day;
723 $startDate = date('Y-m-d');
727 $date = explode('-', $startDate);
732 switch ($duration_unit) {
734 $year = $year +
$duration_interval;
738 $month = $month +
$duration_interval;
742 $day = $day +
$duration_interval;
746 $day = $day +
($duration_interval * 7);
748 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
749 $this->assign('start_date', $startDate);
750 $this->assign('end_date', $endDate);
753 $dao = new CRM_Contribute_DAO_Premium();
754 $dao->entity_table
= 'civicrm_contribution_page';
755 $dao->entity_id
= $this->_id
;
757 $this->assign('contact_phone', $dao->premiums_contact_phone
);
758 $this->assign('contact_email', $dao->premiums_contact_email
);
760 //create Premium record
762 'product_id' => $premiumParams['selectProduct'],
763 'contribution_id' => $contribution->id
,
764 'product_option' => CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams),
766 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
767 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
769 if (!empty($premiumParams['selectProduct'])) {
770 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
771 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
772 $daoPremiumsProduct->premiums_id
= $dao->id
;
773 $daoPremiumsProduct->find(TRUE);
774 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
777 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
778 $daoContrProd->contribution_id
= $contribution->id
;
779 if ($daoContrProd->find(TRUE)) {
780 $params['id'] = $daoContrProd->id
;
783 CRM_Contribute_BAO_Contribution
::addPremium($params);
784 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
786 'cost' => $productDAO->cost
,
787 'currency' => $productDAO->currency
,
788 'financial_type_id' => $params['financial_type_id'],
789 'contributionId' => $contribution->id
,
791 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
794 elseif ($selectProduct == 'no_thanks') {
796 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
797 $daoContrProd->contribution_id
= $contribution->id
;
798 if ($daoContrProd->find(TRUE)) {
799 $daoContrProd->delete();
805 * Process the contribution.
807 * @param CRM_Core_Form $form
808 * @param array $params
809 * @param array $result
810 * @param array $contributionParams
811 * Parameters to be passed to contribution create action.
812 * @param CRM_Financial_DAO_FinancialType $financialType
813 * @param bool $pending
814 * @param bool $online
816 * @param int $billingLocationID
817 * ID of billing location type.
819 * @return \CRM_Contribute_DAO_Contribution
822 public static function processFormContribution(
832 $transaction = new CRM_Core_Transaction();
833 $contactID = $contributionParams['contact_id'];
835 $isMonetary = !empty($form->_values
['is_monetary']);
836 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
837 // How do these vary from params? These are currently passed to
838 // - custom data function....
839 $formParams = $form->_params
;
840 $isSeparateMembershipPayment = empty($formParams['separate_membership_payment']) ?
FALSE : TRUE;
841 $pledgeID = empty($formParams['pledge_id']) ?
NULL : $formParams['pledge_id'];
842 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
843 (!empty($formParams['is_pledge']) ||
$pledgeID)) {
850 // add these values for the recurringContrib function ,CRM-10188
851 $params['financial_type_id'] = $financialType->id
;
853 $contribParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
855 //@todo - this is being set from the form to resolve CRM-10188 - an
856 // eNotice caused by it not being set @ the front end
857 // however, we then get it being over-written with null for backend contributions
858 // a better fix would be to set the values in the respective forms rather than require
859 // a function being shared by two forms to deal with their respective values
860 // moving it to the BAO & not taking the $form as a param would make sense here.
861 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
862 $params['is_email_receipt'] = $isEmailReceipt;
864 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType, $online);
865 $nonDeductibleAmount = self
::getNonDeductibleAmount($params, $financialType, $online);
867 $now = date('YmdHis');
868 $receiptDate = CRM_Utils_Array
::value('receipt_date', $params);
869 if ($isEmailReceipt) {
873 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
874 if (!empty($params['pcp_made_through_id']) ||
!empty($params['soft_credit_to'])) {
876 if (!empty($params['pcp_made_through_id'])) {
877 $contributionParams['soft_credit_to'] = CRM_Core_DAO
::getFieldValue(
879 $params['pcp_made_through_id'],
882 // Pass these details onto with the contribution to make them
883 // available at hook_post_process, CRM-8908
885 $params['soft_credit_to'] = $contributionParams['soft_credit_to'];
888 $contributionParams['soft_credit_to'] = CRM_Utils_Array
::value('soft_credit_to', $params);
892 if (isset($params['amount'])) {
893 $contributionParams = array_merge(self
::getContributionParams(
894 $params, $financialType->id
, $online, $nonDeductibleAmount, $isMonetary, $pending,
895 $result, $receiptDate,
896 $recurringContributionID), $contributionParams
898 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
900 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
901 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
903 $dataArray = array();
904 // @todo - interrogate the line items passed in on the params array.
905 // No reason to assume line items will be set on the form.
906 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
907 foreach ($lineItemValue as $key => $value) {
908 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
909 if (isset($dataArray[$value['tax_rate']])) {
910 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
913 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
918 $smarty = CRM_Core_Smarty
::singleton();
919 $smarty->assign('dataArray', $dataArray);
920 $smarty->assign('totalTaxAmount', $params['tax_amount']);
922 if (is_a($contribution, 'CRM_Core_Error')) {
923 $message = CRM_Core_Error
::getMessages($contribution);
924 CRM_Core_Error
::fatal($message);
927 // lets store it in the form variable so postProcess hook can get to this and use it
928 $form->_contributionID
= $contribution->id
;
931 //CRM-13981, processing honor contact into soft-credit contribution
932 CRM_Contact_Form_ProfileContact
::postProcess($form);
934 // process soft credit / pcp pages
935 CRM_Contribute_Form_Contribution_Confirm
::processPcpSoft($params, $contribution);
937 //handle pledge stuff.
940 //when user doing pledge payments.
941 //update the schedule when payment(s) are made
942 foreach ($form->_params
['pledge_amount'] as $paymentId => $dontCare) {
943 $scheduledAmount = CRM_Core_DAO
::getFieldValue(
944 'CRM_Pledge_DAO_PledgePayment',
950 $pledgePaymentParams = array(
952 'contribution_id' => $contribution->id
,
953 'status_id' => $contribution->contribution_status_id
,
954 'actual_amount' => $scheduledAmount,
957 CRM_Pledge_BAO_PledgePayment
::add($pledgePaymentParams);
960 //update pledge status according to the new payment statuses
961 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID);
964 //when user creating pledge record.
965 $pledgeParams = array();
966 $pledgeParams['contact_id'] = $contribution->contact_id
;
967 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount
;
968 $pledgeParams['contribution_id'] = $contribution->id
;
969 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id
;
970 $pledgeParams['financial_type_id'] = $contribution->financial_type_id
;
971 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
972 $pledgeParams['installments'] = $params['pledge_installments'];
973 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
974 if ($pledgeParams['frequency_unit'] == 'month') {
975 $pledgeParams['frequency_day'] = intval(date("d"));
978 $pledgeParams['frequency_day'] = 1;
980 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
981 $pledgeParams['status_id'] = $contribution->contribution_status_id
;
982 $pledgeParams['max_reminders'] = $form->_values
['max_reminders'];
983 $pledgeParams['initial_reminder_day'] = $form->_values
['initial_reminder_day'];
984 $pledgeParams['additional_reminder_day'] = $form->_values
['additional_reminder_day'];
985 $pledgeParams['is_test'] = $contribution->is_test
;
986 $pledgeParams['acknowledge_date'] = date('Ymd');
987 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
989 //inherit campaign from contirb page.
990 $pledgeParams['campaign_id'] = $campaignId;
992 $pledge = CRM_Pledge_BAO_Pledge
::create($pledgeParams);
994 $form->_params
['pledge_id'] = $pledge->id
;
996 //send acknowledgment email. only when pledge is created
998 //build params to send acknowledgment.
999 $pledgeParams['id'] = $pledge->id
;
1000 $pledgeParams['receipt_from_name'] = $form->_values
['receipt_from_name'];
1001 $pledgeParams['receipt_from_email'] = $form->_values
['receipt_from_email'];
1003 //scheduled amount will be same as installment_amount.
1004 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
1006 //get total pledge amount.
1007 $pledgeParams['total_pledge_amount'] = $pledge->amount
;
1009 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($form, $pledgeParams);
1014 if ($online && $contribution) {
1015 CRM_Core_BAO_CustomValueTable
::postProcess($form->_params
,
1016 'civicrm_contribution',
1021 elseif ($contribution) {
1022 //handle custom data.
1023 $params['contribution_id'] = $contribution->id
;
1024 if (!empty($params['custom']) &&
1025 is_array($params['custom']) &&
1026 !is_a($contribution, 'CRM_Core_Error')
1028 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
1032 if ($contribution && !empty($params['contribution_note'])) {
1033 $noteParams = array(
1034 'entity_table' => 'civicrm_contribution',
1035 'note' => $params['contribution_note'],
1036 'entity_id' => $contribution->id
,
1037 'contact_id' => $contribution->contact_id
,
1038 'modified_date' => date('Ymd'),
1041 CRM_Core_BAO_Note
::add($noteParams, array());
1044 if (isset($params['related_contact'])) {
1045 $contactID = $params['related_contact'];
1047 elseif (isset($params['cms_contactID'])) {
1048 $contactID = $params['cms_contactID'];
1051 //create contribution activity w/ individual and target
1052 //activity w/ organisation contact id when onbelf, CRM-4027
1053 $targetContactID = NULL;
1054 if (!empty($params['hidden_onbehalf_profile'])) {
1055 $targetContactID = $contribution->contact_id
;
1056 $contribution->contact_id
= $contactID;
1059 // create an activity record
1060 if ($contribution) {
1061 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
1064 $transaction->commit();
1065 // CRM-13074 - create the CMSUser after the transaction is completed as it
1066 // is not appropriate to delete a valid contribution if a user create problem occurs
1067 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($params,
1069 'email-' . $billingLocationID
1071 return $contribution;
1075 * Create the recurring contribution record.
1077 * @param CRM_Core_Form $form
1078 * @param array $params
1079 * @param int $contactID
1080 * @param string $contributionType
1081 * @param bool $online
1085 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1086 // return if this page is not set for recurring
1087 // or the user has not chosen the recurring option
1089 //this is online case validation.
1090 if ((empty($form->_values
['is_recur']) && $online) ||
empty($params['is_recur'])) {
1094 $recurParams = array('contact_id' => $contactID);
1095 $recurParams['amount'] = CRM_Utils_Array
::value('amount', $params);
1096 $recurParams['auto_renew'] = CRM_Utils_Array
::value('auto_renew', $params);
1097 $recurParams['frequency_unit'] = CRM_Utils_Array
::value('frequency_unit', $params);
1098 $recurParams['frequency_interval'] = CRM_Utils_Array
::value('frequency_interval', $params);
1099 $recurParams['installments'] = CRM_Utils_Array
::value('installments', $params);
1100 $recurParams['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $params);
1101 $recurParams['currency'] = CRM_Utils_Array
::value('currency', $params);
1103 // CRM-14354: For an auto-renewing membership with an additional contribution,
1104 // if separate payments is not enabled, make sure only the membership fee recurs
1105 if (!empty($form->_membershipBlock
)
1106 && $form->_membershipBlock
['is_separate_payment'] === '0'
1107 && isset($params['selectMembership'])
1108 && $form->_values
['is_allow_other_amount'] == '1'
1110 && !empty($form->_membershipTypeValues
)
1111 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1113 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1116 $recurParams['is_test'] = 0;
1117 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1118 (isset($form->_mode
) && ($form->_mode
== 'test'))
1120 $recurParams['is_test'] = 1;
1123 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1124 if (!empty($params['receive_date'])) {
1125 $recurParams['start_date'] = $params['receive_date'];
1127 $recurParams['invoice_id'] = CRM_Utils_Array
::value('invoiceID', $params);
1128 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1129 $recurParams['payment_processor_id'] = CRM_Utils_Array
::value('payment_processor_id', $params);
1130 $recurParams['is_email_receipt'] = CRM_Utils_Array
::value('is_email_receipt', $params);
1131 // we need to add a unique trxn_id to avoid a unique key error
1132 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1133 $recurParams['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params, $params['invoiceID']);
1134 $recurParams['financial_type_id'] = $contributionType->id
;
1136 if (!$online ||
$form->_values
['is_monetary']) {
1137 $recurParams['payment_instrument_id'] = 1;
1140 $campaignId = CRM_Utils_Array
::value('campaign_id', $params);
1142 if (!array_key_exists('campaign_id', $params)) {
1143 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1146 $recurParams['campaign_id'] = $campaignId;
1148 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1149 if (is_a($recurring, 'CRM_Core_Error')) {
1150 CRM_Core_Error
::displaySessionError($recurring);
1151 $urlString = 'civicrm/contribute/transact';
1152 $urlParams = '_qf_Main_display=true';
1153 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1154 $urlString = 'civicrm/contact/view/contribution';
1155 $urlParams = "action=add&cid={$form->_contactID}";
1157 $urlParams .= "&mode={$form->_mode}";
1160 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1163 return $recurring->id
;
1167 * Add on behalf of organization and it's location.
1169 * This situation occurs when on behalf of is enabled for the contribution page and the person
1170 * signing up does so on behalf of an organization.
1172 * @param array $behalfOrganization
1173 * array of organization info.
1174 * @param int $contactID
1175 * individual contact id. One.
1176 * who is doing the process of signup / contribution.
1178 * @param array $values
1179 * form values array.
1180 * @param array $params
1181 * @param array $fields
1182 * Array of fields from the onbehalf profile relevant to the organization.
1184 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1185 $isCurrentEmployer = FALSE;
1188 if (!empty($behalfOrganization['organization_id']) && empty($behalfOrganization['org_option'])) {
1189 $orgID = $behalfOrganization['organization_id'];
1190 unset($behalfOrganization['organization_id']);
1191 $isCurrentEmployer = TRUE;
1194 // formalities for creating / editing organization.
1195 $behalfOrganization['contact_type'] = 'Organization';
1197 // get the relationship type id
1198 $relType = new CRM_Contact_DAO_RelationshipType();
1199 $relType->name_a_b
= 'Employee of';
1200 $relType->find(TRUE);
1201 $relTypeId = $relType->id
;
1203 // keep relationship params ready
1204 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1205 $relParams['is_permission_a_b'] = 1;
1206 $relParams['is_active'] = 1;
1209 // check if matching organization contact exists
1210 $dedupeParams = CRM_Dedupe_Finder
::formatParams($behalfOrganization, 'Organization');
1211 $dedupeParams['check_permission'] = FALSE;
1212 $dupeIDs = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1214 // CRM-6243 says to pick the first org even if more than one match
1215 if (count($dupeIDs) >= 1) {
1216 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1217 // don't allow name edit
1218 unset($behalfOrganization['organization_name']);
1222 // if found permissioned related organization, allow location edit
1223 $behalfOrganization['contact_id'] = $orgID;
1224 // don't allow name edit
1225 unset($behalfOrganization['organization_name']);
1228 // handling for image url
1229 if (!empty($behalfOrganization['image_URL'])) {
1230 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1233 // create organization, add location
1234 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1235 NULL, NULL, 'Organization'
1237 // create relationship
1238 $relParams['contact_check'][$orgID] = 1;
1239 $cid = array('contact' => $contactID);
1240 CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relParams, $cid);
1242 // if multiple match - send a duplicate alert
1243 if ($dupeIDs && (count($dupeIDs) > 1)) {
1244 $values['onbehalf_dupe_alert'] = 1;
1246 $params['onbehalf_dupe_alert'] = 1;
1249 // make sure organization-contact-id is considered for recording
1250 // contribution/membership etc..
1251 if ($contactID != $orgID) {
1252 // take a note of contact-id, so we can send the
1253 // receipt to individual contact as well.
1255 // required for mailing/template display ..etc
1256 $values['related_contact'] = $contactID;
1258 $params['related_contact'] = $contactID;
1260 //make this employee of relationship as current
1261 //employer / employee relationship, CRM-3532
1262 if ($isCurrentEmployer &&
1263 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1265 $isCurrentEmployer = FALSE;
1268 if (!$isCurrentEmployer && $orgID) {
1269 //build current employer params
1270 $currentEmpParams[$contactID] = $orgID;
1271 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1274 // contribution / signup will be done using this
1276 $contactID = $orgID;
1281 * Function used to save pcp / soft credit entry.
1283 * This is used by contribution and also event pcps
1285 * @param array $params
1286 * @param object $contribution
1287 * Contribution object.
1289 public static function processPcpSoft(&$params, &$contribution) {
1290 // Add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1291 if (!empty($params['soft_credit_to'])) {
1292 $contributionSoftParams = array();
1294 'pcp_display_in_roll',
1295 'pcp_roll_nickname',
1296 'pcp_personal_note',
1299 if (!empty($params[$val])) {
1300 $contributionSoftParams[$val] = $params[$val];
1304 $contributionSoftParams['contact_id'] = $params['soft_credit_to'];
1305 // add contribution id
1306 $contributionSoftParams['contribution_id'] = $contribution->id
;
1308 $contributionSoftParams['pcp_id'] = $params['pcp_made_through_id'];
1310 $contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
1312 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
1314 //Send notification to owner for PCP
1315 if ($contributionSoft->id
&& $contributionSoft->pcp_id
) {
1316 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
1322 * Function used to send notification mail to pcp owner.
1324 * This is used by contribution and also event PCPs.
1326 * @param object $contribution
1327 * @param object $contributionSoft
1328 * Contribution object.
1330 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1331 $params = array('id' => $contributionSoft->pcp_id
);
1332 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1333 $ownerNotifyID = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1335 if ($ownerNotifyID != CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1336 (($ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1337 CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id
, 'is_notify')) ||
1338 $ownerNotifyID == CRM_Core_OptionGroup
::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1339 $pcpInfoURL = CRM_Utils_System
::url('civicrm/pcp/info',
1340 "reset=1&id={$contributionSoft->pcp_id}",
1341 TRUE, NULL, FALSE, TRUE
1343 // set email in the template here
1344 // get the billing location type
1345 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1346 $billingLocationTypeId = array_search('Billing', $locationTypes);
1348 if ($billingLocationTypeId) {
1349 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
, FALSE, $billingLocationTypeId);
1351 // get primary location email if no email exist( for billing location).
1353 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
);
1355 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft->contact_id
);
1357 'page_title' => $pcpInfo['title'],
1358 'receive_date' => $contribution->receive_date
,
1359 'total_amount' => $contributionSoft->amount
,
1360 'donors_display_name' => $donorName,
1361 'donors_email' => $email,
1362 'pcpInfoURL' => $pcpInfoURL,
1363 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll
,
1364 'currency' => $contributionSoft->currency
,
1366 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1367 $sendTemplateParams = array(
1368 'groupName' => 'msg_tpl_workflow_contribution',
1369 'valueName' => 'pcp_owner_notify',
1370 'contactId' => $contributionSoft->contact_id
,
1371 'toEmail' => $ownerEmail,
1372 'toName' => $ownerName,
1373 'from' => "$domainValues[0] <$domainValues[1]>",
1374 'tplParams' => $tplParams,
1375 'PDFFilename' => 'receipt.pdf',
1377 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1382 * Function used to se pcp related defaults / params.
1384 * This is used by contribution and also event PCPs
1386 * @param CRM_Core_Form $page
1388 * @param array $params
1392 public static function processPcp(&$page, $params) {
1393 $params['pcp_made_through_id'] = $page->_pcpId
;
1394 $page->assign('pcpBlock', TRUE);
1395 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1396 $params['pcp_roll_nickname'] = ts('Anonymous');
1397 $params['pcp_is_anonymous'] = 1;
1400 $params['pcp_is_anonymous'] = 0;
1403 'pcp_display_in_roll',
1405 'pcp_roll_nickname',
1406 'pcp_personal_note',
1408 if (!empty($params[$val])) {
1409 $page->assign($val, $params[$val]);
1417 * Process membership.
1419 * @param array $membershipParams
1420 * @param int $contactID
1421 * @param array $customFieldsFormatted
1422 * @param array $fieldTypes
1423 * @param array $premiumParams
1424 * @param array $membershipLineItems
1425 * Line items specifically relating to memberships.
1426 * @param bool $isPayLater
1428 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1429 $membershipLineItems, $isPayLater) {
1431 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1432 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1433 $membershipType = empty($membershipTypes) ?
array() : reset($membershipTypes);
1434 $isPending = $this->getIsPending();
1436 $this->assign('membership_name', CRM_Utils_Array
::value('name', $membershipType));
1438 $isPaidMembership = FALSE;
1439 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1440 //amount must be greater than zero for
1441 //adding contribution record to contribution table.
1442 //this condition arises when separate membership payment is
1443 //enabled and contribution amount is not selected. fix for CRM-3010
1444 $isPaidMembership = TRUE;
1446 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1448 if ($this->_values
['amount_block_is_active']) {
1449 $financialTypeID = $this->_values
['financial_type_id'];
1452 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $membershipType, CRM_Utils_Array
::value('financial_type_id', $membershipParams));
1455 if (CRM_Utils_Array
::value('membership_source', $this->_params
)) {
1456 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1459 $this->postProcessMembership($membershipParams, $contactID,
1460 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1461 $membershipLineItems, $isPayLater, $isPending);
1463 $this->assign('membership_assign', TRUE);
1464 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1468 * Process the Memberships.
1470 * @param array $membershipParams
1471 * Array of membership fields.
1472 * @param int $contactID
1474 * @param CRM_Contribute_Form_Contribution_Confirm $form
1475 * Confirmation form object.
1477 * @param array $premiumParams
1478 * @param null $customFieldsFormatted
1479 * @param null $includeFieldTypes
1481 * @param array $membershipDetails
1483 * @param array $membershipTypeIDs
1485 * @param bool $isPaidMembership
1486 * @param array $membershipID
1488 * @param bool $isProcessSeparateMembershipTransaction
1490 * @param int $financialTypeID
1491 * @param array $membershipLineItems
1492 * Line items specific to membership payment that is separate to contribution.
1493 * @param bool $isPayLater
1494 * @param bool $isPending
1496 * @throws \CRM_Core_Exception
1498 protected function postProcessMembership(
1499 $membershipParams, $contactID, &$form, $premiumParams,
1500 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1501 $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending) {
1502 $membershipContribution = NULL;
1503 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1504 $errors = $createdMemberships = $paymentResult = array();
1506 if ($isPaidMembership) {
1507 if ($isProcessSeparateMembershipTransaction) {
1508 // If we have 2 transactions only one can use the invoice id.
1509 $membershipParams['invoiceID'] .= '-2';
1512 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1521 if (!empty($paymentResult['contribution'])) {
1522 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1523 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1524 $membershipContribution = $paymentResult['contribution'];
1525 // Save the contribution ID so that I can be used in email receipts
1526 // For example, if you need to generate a tax receipt for the donation only.
1527 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1531 if ($isProcessSeparateMembershipTransaction) {
1533 $form->_lineItem
= $membershipLineItems;
1534 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1535 unset($membershipParams['is_recur']);
1537 $membershipContribution = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams,
1538 $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1540 catch (CRM_Core_Exception
$e) {
1541 $errors[2] = $e->getMessage();
1542 $membershipContribution = NULL;
1547 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1548 $membershipContributionID = $membershipContribution->id
;
1551 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1552 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1553 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1555 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1556 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1557 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1558 foreach ($membershipTypeIDs as $memType) {
1559 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1560 if (!empty($membershipContribution)) {
1561 $pendingStatus = CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name');
1562 $pending = ($membershipContribution->contribution_status_id
== $pendingStatus) ?
TRUE : FALSE;
1565 $pending = $isPending;
1567 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
1569 $membershipSource = NULL;
1570 if (!empty($form->_params
['membership_source'])) {
1571 $membershipSource = $form->_params
['membership_source'];
1573 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
1574 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
1577 if (isset($form->_params
)) {
1578 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
1581 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
1582 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
1583 if (!array_key_exists('campaign_id', $form->_params
)) {
1584 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
1588 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership
::renewMembership(
1589 $contactID, $memType, $isTest,
1590 date('YmdHis'), CRM_Utils_Array
::value('cms_contactID', $membershipParams),
1591 $customFieldsFormatted,
1592 $numTerms, $membershipID, $pending,
1593 $contributionRecurID, $membershipSource, $isPayLater, $campaignId
1595 $form->set('renewal_mode', $renewalMode);
1596 if (!empty($dates)) {
1597 $form->assign('mem_start_date',
1598 CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d')
1600 $form->assign('mem_end_date',
1601 CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d')
1605 if (!empty($membershipContribution)) {
1606 // update recurring id for membership record
1607 CRM_Member_BAO_Membership
::updateRecurMembership($membership, $membershipContribution);
1608 CRM_Member_BAO_Membership
::linkMembershipPayment($membership, $membershipContribution);
1611 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1612 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1613 if (!empty($priceFieldOp['membership_type_id']) &&
1614 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1616 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1617 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1618 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1621 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1624 $form->_values
['lineItem'] = $form->_lineItem
;
1625 $form->assign('lineItem', $form->_lineItem
);
1629 if (!empty($errors)) {
1630 $message = $this->compileErrorMessage($errors);
1631 throw new CRM_Core_Exception($message);
1633 $form->_params
['createdMembershipIDs'] = array();
1635 // CRM-7851 - Moved after processing Payment Errors
1636 //@todo - the reasoning for this being here seems a little outdated
1637 foreach ($createdMemberships as $createdMembership) {
1638 CRM_Core_BAO_CustomValueTable
::postProcess(
1640 'civicrm_membership',
1641 $createdMembership->id
,
1644 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1646 if (count($createdMemberships) == 1) {
1647 //presumably this is only relevant for exactly 1 membership
1648 $form->_params
['membershipID'] = $createdMembership->id
;
1651 //CRM-15232: Check if membership is created and on the basis of it use
1652 //membership receipt template to send payment receipt
1653 if (count($createdMemberships)) {
1654 $form->_values
['isMembership'] = TRUE;
1656 if (isset($membershipContributionID)) {
1657 $form->_values
['contribution_id'] = $membershipContributionID;
1659 if ($form->_contributeMode
) {
1660 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1661 // call postProcess hook before leaving
1662 $form->postProcessHook();
1664 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1665 $paymentActionResult = $payment->doPayment($form->_params
, 'contribute');
1667 if (CRM_Utils_Array
::value('payment_status_id', $paymentActionResult) == 1) {
1668 // Refer to CRM-16737. Payment processors 'should' return payment_status_id
1669 // to denote the outcome of the transaction.
1671 civicrm_api3('contribution', 'completetransaction', array(
1672 'id' => $paymentResult['contribution']->id
,
1673 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $paymentActionResult, $paymentResult['contribution']->trxn_id
),
1674 'is_transactional' => FALSE,
1675 'payment_processor_id' => $form->_paymentProcessor
['id'],
1678 catch (CiviCRM_API3_Exception
$e) {
1679 if ($e->getErrorCode() != 'contribution_completed') {
1680 throw new CRM_Core_Exception('Failed to update contribution in database');
1684 // Do not send an email if Recurring transaction is done via Direct Mode
1685 // Email will we sent when the IPN is received.
1689 //finally send an email receipt
1690 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1698 * Turn array of errors into message string.
1700 * @param array $errors
1704 protected function compileErrorMessage($errors) {
1705 foreach ($errors as $error) {
1706 if (is_string($error)) {
1707 $message[] = $error;
1710 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1714 * Where a second separate financial transaction is supported we will process it here.
1716 * @param int $contactID
1717 * @param CRM_Contribute_Form_Contribution_Confirm $form
1718 * @param array $tempParams
1719 * @param bool $isTest
1720 * @param array $lineItems
1721 * @param $minimumFee
1722 * @param int $financialTypeID
1724 * @throws CRM_Core_Exception
1726 * @return CRM_Contribute_BAO_Contribution
1728 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1730 $financialType = new CRM_Financial_DAO_FinancialType();
1731 $financialType->id
= $financialTypeID;
1732 $financialType->find(TRUE);
1733 $tempParams['amount'] = $minimumFee;
1734 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1737 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
1738 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1739 // now we compensate here.
1740 if (empty($form->_paymentProcessor
['object'])) {
1741 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1744 $payment = $form->_paymentProcessor
['object'];
1746 $result = $payment->doPayment($tempParams, 'contribute');
1749 //assign receive date when separate membership payment
1750 //and contribution amount not selected.
1751 if ($form->_amount
== 0) {
1752 $now = date('YmdHis');
1753 $form->_params
['receive_date'] = $now;
1754 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1755 $form->set('params', $form->_params
);
1756 $form->assign('receive_date', $receiveDate);
1759 $form->set('membership_trx_id', $result['trxn_id']);
1760 $form->set('membership_amount', $minimumFee);
1762 $form->assign('membership_trx_id', $result['trxn_id']);
1763 $form->assign('membership_amount', $minimumFee);
1765 // we don't need to create the user twice, so lets disable cms_create_account
1766 // irrespective of the value, CRM-2888
1767 $tempParams['cms_create_account'] = 0;
1769 //CRM-16165, scenarios are
1770 // 1) If contribution is_pay_later and if contribution amount is > 0.0 we set pending = TRUE, vice-versa FALSE
1771 // 2) If not pay later but auto-renewal membership is chosen then pending = TRUE as it later triggers
1772 // pending recurring contribution, vice-versa FALSE
1773 $pending = $form->_params
['is_pay_later'] ?
(($minimumFee > 0.0) ?
TRUE : FALSE) : (!empty($form->_params
['auto_renew']) ?
TRUE : FALSE);
1775 //set this variable as we are not creating pledge for
1776 //separate membership payment contribution.
1777 //so for differentiating membership contribution from
1778 //main contribution.
1779 $form->_params
['separate_membership_payment'] = 1;
1780 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
1784 'contact_id' => $contactID,
1785 'line_item' => $lineItems,
1786 'is_test' => $isTest,
1787 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $tempParams, CRM_Utils_Array
::value('campaign_id',
1789 'contribution_page_id' => $form->_id
,
1796 return $membershipContribution;
1800 * Is the payment a pending payment.
1802 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1803 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1808 protected function getIsPending() {
1809 if (((isset($this->_contributeMode
)) ||
!empty
1810 ($this->_params
['is_pay_later'])
1812 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1820 * Are we going to do 2 financial transactions.
1822 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1824 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1826 * @param int $formID
1827 * @param bool $amountBlockActiveOnForm
1831 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1832 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1833 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1840 * This function sets the fields.
1842 * - $this->_params['amount_level']
1843 * - $this->_params['selectMembership']
1844 * And under certain circumstances sets
1845 * $this->_params['amount'] = null;
1847 * @param int $priceSetID
1849 public function setFormAmountFields($priceSetID) {
1850 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1851 $priceField = new CRM_Price_DAO_PriceField();
1852 $priceField->price_set_id
= $priceSetID;
1853 $priceField->orderBy('weight');
1854 $priceField->find();
1855 $paramWeDoNotUnderstand = NULL;
1857 while ($priceField->fetch()) {
1858 if ($priceField->name
== "contribution_amount") {
1859 $paramWeDoNotUnderstand = $priceField->id
;
1861 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1862 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1863 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1864 $this->_params
["price_{$priceField->id}"], 'label');
1866 if ($priceField->name
== "membership_amount") {
1867 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1868 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1871 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1872 // as membership amount.
1873 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1874 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1875 // so we should merge them together
1876 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1877 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1879 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
)
1880 && !empty($this->_values
['fee'][$priceField->id
])
1881 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1882 && CRM_Utils_Array
::value("price_{$paramWeDoNotUnderstand}", $this->_params
) < 1
1883 && empty($this->_params
["price_{$priceField->id}"])
1885 $this->_params
['amount'] = NULL;
1888 // Fix for CRM-14375 - If we are using separate payments and "no
1889 // thank you" is selected for the additional contribution, set
1890 // contribution amount to be null, so that it will not show
1891 // contribution amount same as membership amount.
1892 //@todo - merge with section above
1893 if ($this->_membershipBlock
['is_separate_payment']
1894 && !empty($this->_values
['fee'][$priceField->id
])
1895 && CRM_Utils_Array
::value('name', $this->_values
['fee'][$priceField->id
]) == 'contribution_amount'
1896 && CRM_Utils_Array
::value("price_{$priceField->id}", $this->_params
) == '-1'
1898 $this->_params
['amount'] = NULL;
1906 * @param array $params
1908 * @throws CiviCRM_API3_Exception
1910 public static function submit($params) {
1911 $form = new CRM_Contribute_Form_Contribution_Confirm();
1912 $form->_id
= $params['id'];
1914 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1915 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1916 //this way the mocked up controller ignores the session stuff
1917 $_SERVER['REQUEST_METHOD'] = 'GET';
1918 $form->controller
= new CRM_Contribute_Controller_Contribution();
1919 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1920 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1921 $form->_amount
= $params['amount'];
1922 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1923 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1924 $priceSetFields = reset($priceFields);
1925 $form->_values
['fee'] = $priceSetFields['fields'];
1926 $form->_priceSetId
= $priceSetID;
1927 $form->setFormAmountFields($priceSetID);
1928 if (!empty($params['payment_processor_id'])) {
1929 $form->_paymentProcessor
= civicrm_api3('payment_processor', 'getsingle', array(
1930 'id' => $params['payment_processor_id'],
1932 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1933 $form->_contributeMode
= 'direct';
1936 $form->_contributeMode
= 'notify';
1940 $form->_params
['payment_processor_id'] = 0;
1942 $priceFields = $priceFields[$priceSetID]['fields'];
1943 CRM_Price_BAO_PriceSet
::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1944 $form->_lineItem
= array($priceSetID => $lineItems);
1945 $form->processFormSubmission(CRM_Utils_Array
::value('contact_id', $params));
1949 * Helper function for static submit function.
1951 * Set relevant params - help us to build up an array that we can pass in.
1954 * @param array $params
1957 * @throws CiviCRM_API3_Exception
1959 public static function getFormParams($id, array $params) {
1960 if (!isset($params['is_pay_later'])) {
1961 if (!empty($params['payment_processor_id'])) {
1962 $params['is_pay_later'] = 0;
1965 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1967 'return' => 'is_pay_later',
1971 if (empty($params['price_set_id'])) {
1972 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
1978 * Post form submission handling.
1980 * This is also called from the test suite.
1982 * @param int $contactID
1986 protected function processFormSubmission($contactID) {
1987 $isPayLater = $this->_params
['is_pay_later'];
1988 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] == 0) {
1989 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
1991 // add a description field at the very beginning
1992 $this->_params
['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $this->_values
['title']);
1994 $this->_params
['accountingCode'] = CRM_Utils_Array
::value('accountingCode', $this->_values
);
1997 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
1999 //carry payment processor id.
2000 if (CRM_Utils_Array
::value('id', $this->_paymentProcessor
)) {
2001 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
2004 $premiumParams = $membershipParams = $params = $this->_params
;
2005 if (!empty($params['image_URL'])) {
2006 CRM_Contact_BAO_Contact
::processImageParams($params);
2009 $fields = array('email-Primary' => 1);
2011 // get the add to groups
2012 $addToGroups = array();
2014 // now set the values for the billing location.
2015 foreach ($this->_fields
as $name => $value) {
2018 // get the add to groups for uf fields
2019 if (!empty($value['add_to_group_id'])) {
2020 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2024 if (!array_key_exists('first_name', $fields)) {
2025 $nameFields = array('first_name', 'middle_name', 'last_name');
2026 foreach ($nameFields as $name) {
2028 if (array_key_exists("billing_$name", $params)) {
2029 $params[$name] = $params["billing_{$name}"];
2030 $params['preserveDBName'] = TRUE;
2035 // billing email address
2036 $fields["email-{$this->_bltID}"] = 1;
2038 //unset the billing parameters if it is pay later mode
2039 //to avoid creation of billing location
2040 if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater
) {
2041 $billingFields = array(
2042 'billing_first_name',
2043 'billing_middle_name',
2044 'billing_last_name',
2045 "billing_street_address-{$this->_bltID}",
2046 "billing_city-{$this->_bltID}",
2047 "billing_state_province-{$this->_bltID}",
2048 "billing_state_province_id-{$this->_bltID}",
2049 "billing_postal_code-{$this->_bltID}",
2050 "billing_country-{$this->_bltID}",
2051 "billing_country_id-{$this->_bltID}",
2054 foreach ($billingFields as $value) {
2055 unset($params[$value]);
2056 unset($fields[$value]);
2060 // if onbehalf-of-organization contribution, take out
2061 // organization params in a separate variable, to make sure
2062 // normal behavior is continued. And use that variable to
2063 // process on-behalf-of functionality.
2064 if (!empty($this->_params
['hidden_onbehalf_profile'])) {
2065 $behalfOrganization = array();
2066 $orgFields = array('organization_name', 'organization_id', 'org_option');
2067 foreach ($orgFields as $fld) {
2068 if (array_key_exists($fld, $params)) {
2069 $behalfOrganization[$fld] = $params[$fld];
2070 unset($params[$fld]);
2074 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2075 foreach ($params['onbehalf'] as $fld => $values) {
2076 if (strstr($fld, 'custom_')) {
2077 $behalfOrganization[$fld] = $values;
2079 elseif (!(strstr($fld, '-'))) {
2080 if (in_array($fld, array(
2081 'contribution_campaign_id',
2082 'member_campaign_id',
2084 $fld = 'campaign_id';
2087 $behalfOrganization[$fld] = $values;
2089 $this->_params
[$fld] = $values;
2094 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2095 foreach ($params['onbehalf_location'] as $block => $vals) {
2096 //fix for custom data (of type checkbox, multi-select)
2097 if (substr($block, 0, 7) == 'custom_') {
2100 // fix the index of block elements
2101 if (is_array($vals)) {
2102 foreach ($vals as $key => $val) {
2103 //dont adjust the index of address block as
2104 //it's index is WRT to location type
2105 $newKey = ($block == 'address') ?
$key : ++
$key;
2106 $behalfOrganization[$block][$newKey] = $val;
2110 unset($params['onbehalf_location']);
2112 if (!empty($params['onbehalf[image_URL]'])) {
2113 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2117 // check for profile double opt-in and get groups to be subscribed
2118 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2120 // since we are directly adding contact to group lets unset it from mailing
2121 if (!empty($addToGroups)) {
2122 foreach ($addToGroups as $groupId) {
2123 if (isset($subscribeGroupIds[$groupId])) {
2124 unset($subscribeGroupIds[$groupId]);
2129 foreach ($addToGroups as $k) {
2130 if (array_key_exists($k, $subscribeGroupIds)) {
2131 unset($addToGroups[$k]);
2135 if (empty($contactID)) {
2136 $dupeParams = $params;
2137 if (!empty($dupeParams['onbehalf'])) {
2138 unset($dupeParams['onbehalf']);
2140 if (!empty($dupeParams['honor'])) {
2141 unset($dupeParams['honor']);
2144 $dedupeParams = CRM_Dedupe_Finder
::formatParams($dupeParams, 'Individual');
2145 $dedupeParams['check_permission'] = FALSE;
2146 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
2148 // if we find more than one contact, use the first one
2149 $contactID = CRM_Utils_Array
::value(0, $ids);
2151 // Fetch default greeting id's if creating a contact
2153 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2154 if (!isset($params[$greeting])) {
2155 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2159 $contactType = NULL;
2162 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2164 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2174 // Make the contact ID associated with the contribution available at the Class level.
2175 // Also make available to the session.
2176 //@todo consider handling this in $this->getContactID();
2177 $this->set('contactID', $contactID);
2178 $this->_contactID
= $contactID;
2180 //get email primary first if exist
2181 $subscriptionEmail = array('email' => CRM_Utils_Array
::value('email-Primary', $params));
2182 if (!$subscriptionEmail['email']) {
2183 $subscriptionEmail['email'] = CRM_Utils_Array
::value("email-{$this->_bltID}", $params);
2185 // subscribing contact to groups
2186 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2187 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2190 // If onbehalf-of-organization contribution / signup, add organization
2191 // and it's location.
2192 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
2193 $ufFields = array();
2194 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2195 $ufFields[$name] = 1;
2197 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2198 $this->_params
, $ufFields
2201 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2202 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2203 // store current user id as related contact for later use for mailing / activity..
2204 $this->_values
['related_contact'] = $contactID;
2205 $this->_params
['related_contact'] = $contactID;
2206 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2207 $contactID = $this->_membershipContactID
;
2210 // lets store the contactID in the session
2211 // for things like tell a friend
2212 $session = CRM_Core_Session
::singleton();
2213 if (!$session->get('userID')) {
2214 $session->set('transaction.userID', $contactID);
2217 $session->set('transaction.userID', NULL);
2220 $this->_useForMember
= $this->get('useForMember');
2222 // store the fact that this is a membership and membership type is selected
2223 if ((!empty($membershipParams['selectMembership']) &&
2224 $membershipParams['selectMembership'] != 'no_thanks'
2226 $this->_useForMember
2228 if (!$this->_useForMember
) {
2229 $this->assign('membership_assign', TRUE);
2230 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2233 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2234 $membershipParams['is_test'] = 1;
2236 if ($this->_params
['is_pay_later']) {
2237 $membershipParams['is_pay_later'] = 1;
2240 //inherit campaign from contribution page.
2241 if (!array_key_exists('campaign_id', $membershipParams)) {
2242 $membershipParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
);
2245 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2246 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater);
2249 // at this point we've created a contact and stored its address etc
2250 // all the payment processors expect the name and address to be in the
2251 // so we copy stuff over to first_name etc.
2252 $paymentParams = $this->_params
;
2253 $contributionTypeId = $this->_values
['financial_type_id'];
2255 $fieldTypes = array();
2256 if (!empty($paymentParams['onbehalf']) &&
2257 is_array($paymentParams['onbehalf'])
2259 foreach ($paymentParams['onbehalf'] as $key => $value) {
2260 if (strstr($key, 'custom_')) {
2261 $this->_params
[$key] = $value;
2264 $fieldTypes = array('Contact', 'Organization', 'Contribution');
2266 $financialTypeID = $this->wrangleFinancialTypeID($contributionTypeId);
2268 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2273 ($this->_mode
== 'test') ?
1 : 0,
2277 if (!empty($result['is_payment_failure'])) {
2280 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2281 $this->postProcessPremium($premiumParams, $result['contribution']);
2282 if (CRM_Utils_Array
::value('payment_status_id', $result) == 1) {
2284 civicrm_api3('contribution', 'completetransaction', array(
2285 'id' => $result['contribution']->id
,
2286 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $result),
2287 'payment_processor_id' => $this->_paymentProcessor
['id'],
2288 'is_transactional' => FALSE,
2292 catch (CiviCRM_API3_Exception
$e) {
2293 if ($e->getErrorCode() != 'contribution_completed') {
2294 throw new CRM_Core_Exception('Failed to update contribution in database');
2304 * Membership processing section.
2306 * This is in a separate function as part of a move towards refactoring.
2308 * @param int $contactID
2309 * @param array $membershipParams
2310 * @param array $premiumParams
2311 * @param bool $isPayLater
2313 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater) {
2315 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2316 if (isset($this->_params
['related_contact'])) {
2317 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2320 $membershipParams['cms_contactID'] = $contactID;
2323 if (!empty($membershipParams['onbehalf']) &&
2324 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2326 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2329 $customFieldsFormatted = $fieldTypes = array();
2330 if (!empty($membershipParams['onbehalf']) &&
2331 is_array($membershipParams['onbehalf'])
2333 foreach ($membershipParams['onbehalf'] as $key => $value) {
2334 if (strstr($key, 'custom_')) {
2335 $customFieldId = explode('_', $key);
2336 CRM_Core_BAO_CustomField
::formatCustomField(
2338 $customFieldsFormatted,
2346 $fieldTypes = array('Contact', 'Organization', 'Membership');
2349 $priceFieldIds = $this->get('memberPriceFieldIDS');
2351 if (!empty($priceFieldIds)) {
2352 $contributionTypeID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2353 unset($priceFieldIds['id']);
2354 $membershipTypeIds = array();
2355 $membershipTypeTerms = array();
2356 foreach ($priceFieldIds as $priceFieldId) {
2357 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
2358 $membershipTypeIds[] = $id;
2359 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
2360 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
2362 if ($term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
2363 $membershipTypeTerms[$id] = ($term > 1) ?
$term : 1;
2366 $membershipTypeTerms[$id] = 1;
2370 $membershipParams['selectMembership'] = $membershipTypeIds;
2371 $membershipParams['financial_type_id'] = $contributionTypeID;
2372 $membershipParams['types_terms'] = $membershipTypeTerms;
2374 if (!empty($membershipParams['selectMembership'])) {
2376 $membershipLineItems = array();
2377 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2378 foreach ($this->_values
['fee'] as $key => $feeValues) {
2379 if ($feeValues['name'] == 'membership_amount') {
2380 $fieldId = $this->_params
['price_' . $key];
2381 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2382 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2388 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
2390 catch (CRM_Core_Exception
$e) {
2391 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2392 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2394 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2395 // we need to explicitly create a CMS user in case of free memberships
2396 // since it is done under processConfirm for paid memberships
2397 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2398 $membershipParams['cms_contactID'],
2399 'email-' . $this->_bltID