Merge pull request #6404 from eileenmcnaughton/master
[civicrm-core.git] / CRM / Contribute / Form / Contribution / Confirm.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 */
33
34 /**
35 * form to process actions on the group aspect of Custom Data
36 */
37 class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_ContributionBase {
38
39 /**
40 * The id of the contact associated with this contribution.
41 *
42 * @var int
43 */
44 public $_contactID;
45
46
47 /**
48 * The id of the contribution object that is created when the form is submitted.
49 *
50 * @var int
51 */
52 public $_contributionID;
53
54 /**
55 * Set the parameters to be passed to contribution create function.
56 *
57 * @param array $params
58 * @param int $contactID
59 * @param int $financialTypeID
60 * @param bool $online
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
69 * @param bool $isTest
70 * @param int $addressID
71 * @param int $softCreditToID
72 * @param array $lineItems
73 *
74 * @return array
75 */
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,
98 'is_test' => $isTest,
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),
104 );
105 if (!$online && isset($params['thankyou_date'])) {
106 $contributionParam['thankyou_date'] = $params['thankyou_date'];
107 }
108 if (!$online || $isMonetary) {
109 if (empty($params['is_pay_later'])) {
110 $contributionParams['payment_instrument_id'] = 1;
111 }
112 }
113 if ($paymentProcessorOutcome) {
114 $contributionParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $paymentProcessorOutcome);
115 }
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),
124 );
125 }
126
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'], ' '));
130
131 if ($recurringContributionID) {
132 $contributionParams['contribution_recur_id'] = $recurringContributionID;
133 }
134
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'],
140 'id',
141 'invoice_id'
142 );
143 }
144
145 return $contributionParams;
146 }
147
148 /**
149 * Get non-deductible amount.
150 *
151 * This is a bit too much about wierd form interpretation to be this deep.
152 *
153 * CRM-11885
154 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
155 * it.
156 *
157 * @param array $params
158 * @param CRM_Financial_BAO_FinancialType $financialType
159 * @param bool $online
160 *
161 * @return array
162 */
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'];
166 }
167 else {
168 if ($financialType->is_deductible) {
169 if ($online && isset($params['selectProduct'])) {
170 $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
171 }
172 if (!$online && isset($params['product_name'][0])) {
173 $selectProduct = $params['product_name'][0];
174 }
175 // if there is a product - compare the value to the contribution amount
176 if (isset($selectProduct) &&
177 $selectProduct != 'no_thanks'
178 ) {
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;
186 }
187 // product value does NOT exceed contribution amount
188 else {
189 return $productDAO->price;
190 }
191 }
192 // contribution is deductible - but there is no product
193 else {
194 return '0.00';
195 }
196 }
197 // contribution is NOT deductible
198 else {
199 return $params['amount'];
200 }
201 }
202 }
203
204 /**
205 * Set variables up before form is built.
206 */
207 public function preProcess() {
208 $config = CRM_Core_Config::singleton();
209 parent::preProcess();
210
211 // lineItem isn't set until Register postProcess
212 $this->_lineItem = $this->get('lineItem');
213 $this->_paymentProcessor = $this->get('paymentProcessor');
214 $this->_params = $this->controller->exportValues('Main');
215 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
216 $this->_params['amount'] = $this->get('amount');
217 if (isset($this->_params['amount'])) {
218 $this->setFormAmountFields($this->_params['priceSetId']);
219 }
220
221 $this->_params['tax_amount'] = $this->get('tax_amount');
222 $this->_useForMember = $this->get('useForMember');
223
224 if (isset($this->_params['credit_card_exp_date'])) {
225 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
226 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
227 }
228
229 $this->_params['currencyID'] = $config->defaultCurrency;
230
231 if (!empty($this->_membershipBlock)) {
232 $this->_params['selectMembership'] = $this->get('selectMembership');
233 }
234 if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) {
235 $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
236 $this->_params = array_merge($this->_params, $preApprovalParams);
237 }
238
239 // We may have fetched some billing details from the getPreApprovalDetails function so we
240 // want to ensure we set this after that function has been called.
241 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $this->_params, FALSE);
242 if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
243 $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
244 }
245 if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) {
246 $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
247 }
248
249 $this->_params['is_pay_later'] = $this->get('is_pay_later');
250 $this->assign('is_pay_later', $this->_params['is_pay_later']);
251 if ($this->_params['is_pay_later']) {
252 $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
253 }
254 // if onbehalf-of-organization
255 if (!empty($this->_params['hidden_onbehalf_profile'])) {
256 // CRM-15182
257 if (empty($this->_params['org_option']) && empty($this->_params['organization_id'])) {
258 if (!empty($this->_params['onbehalfof_id'])) {
259 $this->_params['organization_id'] = $this->_params['onbehalfof_id'];
260 }
261 else {
262 $this->_params['organization_id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_params['onbehalf']['organization_name'], 'id', 'display_name');
263 }
264 }
265
266 $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name'];
267 $addressBlocks = array(
268 'street_address',
269 'city',
270 'state_province',
271 'postal_code',
272 'country',
273 'supplemental_address_1',
274 'supplemental_address_2',
275 'supplemental_address_3',
276 'postal_code_suffix',
277 'geo_code_1',
278 'geo_code_2',
279 'address_name',
280 );
281
282 $blocks = array('email', 'phone', 'im', 'url', 'openid');
283 foreach ($this->_params['onbehalf'] as $loc => $value) {
284 $field = $typeId = NULL;
285 if (strstr($loc, '-')) {
286 list($field, $locType) = explode('-', $loc);
287 }
288
289 if (in_array($field, $addressBlocks)) {
290 if ($locType == 'Primary') {
291 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
292 $locType = $defaultLocationType->id;
293 }
294
295 if ($field == 'country') {
296 $value = CRM_Core_PseudoConstant::countryIsoCode($value);
297 }
298 elseif ($field == 'state_province') {
299 $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
300 }
301
302 $isPrimary = 1;
303 if (isset($this->_params['onbehalf_location']['address'])
304 && count($this->_params['onbehalf_location']['address']) > 0
305 ) {
306 $isPrimary = 0;
307 }
308
309 $this->_params['onbehalf_location']['address'][$locType][$field] = $value;
310 if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) {
311 $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
312 }
313 $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
314 }
315 elseif (in_array($field, $blocks)) {
316 if (!$typeId || is_numeric($typeId)) {
317 $blockName = $fieldName = $field;
318 $locationType = 'location_type_id';
319 if ($locType == 'Primary') {
320 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
321 $locationValue = $defaultLocationType->id;
322 }
323 else {
324 $locationValue = $locType;
325 }
326 $locTypeId = '';
327 $phoneExtField = array();
328
329 if ($field == 'url') {
330 $blockName = 'website';
331 $locationType = 'website_type_id';
332 list($field, $locationValue) = explode('-', $loc);
333 }
334 elseif ($field == 'im') {
335 $fieldName = 'name';
336 $locTypeId = 'provider_id';
337 $typeId = $this->_params['onbehalf']["{$loc}-provider_id"];
338 }
339 elseif ($field == 'phone') {
340 list($field, $locType, $typeId) = explode('-', $loc);
341 $locTypeId = 'phone_type_id';
342
343 //check if extension field exists
344 $extField = str_replace('phone', 'phone_ext', $loc);
345 if (isset($this->_params['onbehalf'][$extField])) {
346 $phoneExtField = array('phone_ext' => $this->_params['onbehalf'][$extField]);
347 }
348 }
349
350 $isPrimary = 1;
351 if (isset ($this->_params['onbehalf_location'][$blockName])
352 && count($this->_params['onbehalf_location'][$blockName]) > 0
353 ) {
354 $isPrimary = 0;
355 }
356 if ($locationValue) {
357 $blockValues = array(
358 $fieldName => $value,
359 $locationType => $locationValue,
360 'is_primary' => $isPrimary,
361 );
362
363 if ($locTypeId) {
364 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
365 }
366 if (!empty($phoneExtField)) {
367 $blockValues = array_merge($blockValues, $phoneExtField);
368 }
369
370 $this->_params['onbehalf_location'][$blockName][] = $blockValues;
371 }
372 }
373 }
374 elseif (strstr($loc, 'custom')) {
375 if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) {
376 $value = $this->_params['onbehalf']["{$loc}_id"];
377 }
378 $this->_params['onbehalf_location']["{$loc}"] = $value;
379 }
380 else {
381 if ($loc == 'contact_sub_type') {
382 $this->_params['onbehalf_location'][$loc] = $value;
383 }
384 else {
385 $this->_params['onbehalf_location'][$field] = $value;
386 }
387 }
388 }
389 }
390 elseif (!empty($this->_values['is_for_organization'])) {
391 // no on behalf of an organization, CRM-5519
392 // so reset loc blocks from main params.
393 foreach (array(
394 'phone',
395 'email',
396 'address',
397 ) as $blk) {
398 if (isset($this->_params[$blk])) {
399 unset($this->_params[$blk]);
400 }
401 }
402 }
403 $this->setRecurringMembershipParams();
404
405 if ($this->_pcpId) {
406 $params = $this->processPcp($this, $this->_params);
407 $this->_params = $params;
408 }
409 $this->_params['invoiceID'] = $this->get('invoiceID');
410
411 //carry campaign from profile.
412 if (array_key_exists('contribution_campaign_id', $this->_params)) {
413 $this->_params['campaign_id'] = $this->_params['contribution_campaign_id'];
414 }
415
416 // assign contribution page id to the template so we can add css class for it
417 $this->assign('contributionPageID', $this->_id);
418
419 $this->set('params', $this->_params);
420 }
421
422 /**
423 * Build the form object.
424 */
425 public function buildQuickForm() {
426 $this->assignToTemplate();
427
428 $params = $this->_params;
429 // make sure we have values for it
430 if ($this->_honor_block_is_active && !empty($params['soft_credit_type_id'])) {
431 $honorName = NULL;
432 $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
433
434 $this->assign('honor_block_is_active', $this->_honor_block_is_active);
435 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
436 CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($this, $params['honor'], $params['honoree_profile_id']);
437
438 $fieldTypes = array('Contact');
439 $fieldTypes[] = CRM_Core_BAO_UFGroup::getContactType($params['honoree_profile_id']);
440 $this->buildCustom($params['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
441 }
442 $this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values));
443 $amount_block_is_active = $this->get('amount_block_is_active');
444 $this->assign('amount_block_is_active', $amount_block_is_active);
445
446 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
447 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
448 if ($invoicing) {
449 $getTaxDetails = FALSE;
450 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
451 foreach ($this->_lineItem as $key => $value) {
452 foreach ($value as $v) {
453 if (isset($v['tax_rate'])) {
454 if ($v['tax_rate'] != '') {
455 $getTaxDetails = TRUE;
456 }
457 }
458 }
459 }
460 $this->assign('getTaxDetails', $getTaxDetails);
461 $this->assign('taxTerm', $taxTerm);
462 $this->assign('totalTaxAmount', $params['tax_amount']);
463 }
464 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
465 $option = CRM_Utils_Array::value('options_' . $params['selectProduct'], $params);
466 $productID = $params['selectProduct'];
467 CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE,
468 $productID, $option
469 );
470 $this->set('productID', $productID);
471 $this->set('option', $option);
472 }
473 $config = CRM_Core_Config::singleton();
474 if (in_array('CiviMember', $config->enableComponents)) {
475 if (isset($params['selectMembership']) &&
476 $params['selectMembership'] != 'no_thanks'
477 ) {
478 $this->buildMembershipBlock(
479 $this->_membershipContactID,
480 FALSE,
481 $params['selectMembership'],
482 FALSE
483 );
484 if (!empty($params['auto_renew'])) {
485 $this->assign('auto_renew', TRUE);
486 }
487 }
488 else {
489 $this->assign('membershipBlock', FALSE);
490 }
491 }
492 $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE);
493 $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE);
494
495 if (!empty($params['hidden_onbehalf_profile'])) {
496 $ufJoinParams = array(
497 'module' => 'onBehalf',
498 'entity_table' => 'civicrm_contribution_page',
499 'entity_id' => $this->_id,
500 );
501 $OnBehalfProfile = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
502 $profileId = $OnBehalfProfile[0];
503
504 $fieldTypes = array('Contact', 'Organization');
505 $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
506 $fieldTypes = array_merge($fieldTypes, $contactSubType);
507 if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
508 $fieldTypes = array_merge($fieldTypes, array('Membership'));
509 }
510 else {
511 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
512 }
513
514 $this->buildCustom($profileId, 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
515 }
516
517 $this->_separateMembershipPayment = $this->get('separateMembershipPayment');
518 $this->assign('is_separate_payment', $this->_separateMembershipPayment);
519 if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
520 $this->assign('lineItem', $this->_lineItem);
521 }
522 else {
523 $this->assign('is_quick_config', 1);
524 $this->_params['is_quick_config'] = 1;
525 }
526 $this->assign('priceSetID', $this->_priceSetId);
527 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
528 if ($this->_paymentProcessor &&
529 $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('Google_Checkout', $paymentProcessorType)
530 && !$this->_params['is_pay_later'] && !($this->_amount == 0)
531 ) {
532 $this->_checkoutButtonName = $this->getButtonName('next', 'checkout');
533 $this->add('image',
534 $this->_checkoutButtonName,
535 $this->_paymentProcessor['url_button'],
536 array('class' => 'crm-form-submit')
537 );
538
539 $this->addButtons(array(
540 array(
541 'type' => 'back',
542 'name' => ts('Go Back'),
543 ),
544 )
545 );
546 }
547 else {
548 if ($this->_contributeMode == 'notify' || !$this->_values['is_monetary'] ||
549 $this->_amount <= 0.0 || $this->_params['is_pay_later'] ||
550 ($this->_separateMembershipPayment && $this->_amount <= 0.0)
551 ) {
552 $contribButton = ts('Continue');
553 $this->assign('button', ts('Continue'));
554 }
555 else {
556 $contribButton = ts('Make Contribution');
557 $this->assign('button', ts('Make Contribution'));
558 }
559 $this->addButtons(array(
560 array(
561 'type' => 'next',
562 'name' => $contribButton,
563 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
564 'isDefault' => TRUE,
565 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
566 ),
567 array(
568 'type' => 'back',
569 'name' => ts('Go Back'),
570 ),
571 )
572 );
573 }
574
575 $defaults = array();
576 $fields = array_fill_keys(array_keys($this->_fields), 1);
577 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
578
579 $contact = $this->_params;
580 foreach ($fields as $name => $dontCare) {
581 // Recursively set defaults for nested fields
582 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' || $name == 'honor')) {
583 foreach ($contact[$name] as $fieldName => $fieldValue) {
584 if (is_array($fieldValue) && !in_array($this->_fields[$name][$fieldName]['html_type'], array(
585 'Multi-Select',
586 'AdvMulti-Select',
587 ))
588 ) {
589 foreach ($fieldValue as $key => $value) {
590 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
591 }
592 }
593 else {
594 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
595 }
596 }
597 }
598 elseif (isset($contact[$name])) {
599 $defaults[$name] = $contact[$name];
600 if (substr($name, 0, 7) == 'custom_') {
601 $timeField = "{$name}_time";
602 if (isset($contact[$timeField])) {
603 $defaults[$timeField] = $contact[$timeField];
604 }
605 if (isset($contact["{$name}_id"])) {
606 $defaults["{$name}_id"] = $contact["{$name}_id"];
607 }
608 }
609 elseif (in_array($name, array(
610 'addressee',
611 'email_greeting',
612 'postal_greeting',
613 )) && !empty($contact[$name . '_custom'])
614 ) {
615 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
616 }
617 }
618 }
619
620 $this->assign('useForMember', $this->get('useForMember'));
621
622 $this->setDefaults($defaults);
623
624 $this->freeze();
625 }
626
627 /**
628 * Overwrite action.
629 *
630 * Since we are only showing elements in frozen mode no help display needed.
631 *
632 * @return int
633 */
634 public function getAction() {
635 if ($this->_action & CRM_Core_Action::PREVIEW) {
636 return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
637 }
638 else {
639 return CRM_Core_Action::VIEW;
640 }
641 }
642
643 /**
644 * Set default values for the form.
645 *
646 * Note that in edit/view mode
647 * the default values are retrieved from the database
648 */
649 public function setDefaultValues() {
650 }
651
652 /**
653 * Process the form.
654 */
655 public function postProcess() {
656 $contactID = $this->getContactID();
657 $result = $this->processFormSubmission($contactID);
658 if (is_array($result) && !empty($result['is_payment_failure'])) {
659 // We will probably have the function that gets this error throw an exception on the next round of refactoring.
660 CRM_Core_Session::singleton()->setStatus(ts("Payment Processor Error message :") .
661 $result['error']->getMessage());
662 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact',
663 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
664 ));
665 }
666 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
667 $this->set('params', $this->_params);
668 }
669
670 /**
671 * Wrangle financial type ID.
672 *
673 * 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
674 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
675 *
676 * Comments from previous refactor indicate doubt as to what was going on.
677 *
678 * @param int $contributionTypeId
679 *
680 * @return null|string
681 */
682 public function wrangleFinancialTypeID($contributionTypeId) {
683 if (isset($paymentParams['financial_type'])) {
684 $contributionTypeId = $paymentParams['financial_type'];
685 }
686 elseif (!empty($this->_values['pledge_id'])) {
687 $contributionTypeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
688 $this->_values['pledge_id'],
689 'financial_type_id'
690 );
691 }
692 return $contributionTypeId;
693 }
694
695 /**
696 * Process the form.
697 *
698 * @param array $premiumParams
699 * @param CRM_Contribute_BAO_Contribution $contribution
700 */
701 protected function postProcessPremium($premiumParams, $contribution) {
702 $hour = $minute = $second = 0;
703 // assigning Premium information to receipt tpl
704 $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
705 if ($selectProduct &&
706 $selectProduct != 'no_thanks'
707 ) {
708 $startDate = $endDate = "";
709 $this->assign('selectPremium', TRUE);
710 $productDAO = new CRM_Contribute_DAO_Product();
711 $productDAO->id = $selectProduct;
712 $productDAO->find(TRUE);
713 $this->assign('product_name', $productDAO->name);
714 $this->assign('price', $productDAO->price);
715 $this->assign('sku', $productDAO->sku);
716 $this->assign('option', CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams));
717
718 $periodType = $productDAO->period_type;
719
720 if ($periodType) {
721 $fixed_period_start_day = $productDAO->fixed_period_start_day;
722 $duration_unit = $productDAO->duration_unit;
723 $duration_interval = $productDAO->duration_interval;
724 if ($periodType == 'rolling') {
725 $startDate = date('Y-m-d');
726 }
727 elseif ($periodType == 'fixed') {
728 if ($fixed_period_start_day) {
729 $date = explode('-', date('Y-m-d'));
730 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
731 $day = substr($fixed_period_start_day, -2) . "<br/>";
732 $year = $date[0];
733 $startDate = $year . '-' . $month . '-' . $day;
734 }
735 else {
736 $startDate = date('Y-m-d');
737 }
738 }
739
740 $date = explode('-', $startDate);
741 $year = $date[0];
742 $month = $date[1];
743 $day = $date[2];
744
745 switch ($duration_unit) {
746 case 'year':
747 $year = $year + $duration_interval;
748 break;
749
750 case 'month':
751 $month = $month + $duration_interval;
752 break;
753
754 case 'day':
755 $day = $day + $duration_interval;
756 break;
757
758 case 'week':
759 $day = $day + ($duration_interval * 7);
760 }
761 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
762 $this->assign('start_date', $startDate);
763 $this->assign('end_date', $endDate);
764 }
765
766 $dao = new CRM_Contribute_DAO_Premium();
767 $dao->entity_table = 'civicrm_contribution_page';
768 $dao->entity_id = $this->_id;
769 $dao->find(TRUE);
770 $this->assign('contact_phone', $dao->premiums_contact_phone);
771 $this->assign('contact_email', $dao->premiums_contact_email);
772
773 //create Premium record
774 $params = array(
775 'product_id' => $premiumParams['selectProduct'],
776 'contribution_id' => $contribution->id,
777 'product_option' => CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams),
778 'quantity' => 1,
779 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
780 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
781 );
782 if (!empty($premiumParams['selectProduct'])) {
783 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
784 $daoPremiumsProduct->product_id = $premiumParams['selectProduct'];
785 $daoPremiumsProduct->premiums_id = $dao->id;
786 $daoPremiumsProduct->find(TRUE);
787 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id;
788 }
789 //Fixed For CRM-3901
790 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
791 $daoContrProd->contribution_id = $contribution->id;
792 if ($daoContrProd->find(TRUE)) {
793 $params['id'] = $daoContrProd->id;
794 }
795
796 CRM_Contribute_BAO_Contribution::addPremium($params);
797 if ($productDAO->cost && !empty($params['financial_type_id'])) {
798 $trxnParams = array(
799 'cost' => $productDAO->cost,
800 'currency' => $productDAO->currency,
801 'financial_type_id' => $params['financial_type_id'],
802 'contributionId' => $contribution->id,
803 );
804 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
805 }
806 }
807 elseif ($selectProduct == 'no_thanks') {
808 //Fixed For CRM-3901
809 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
810 $daoContrProd->contribution_id = $contribution->id;
811 if ($daoContrProd->find(TRUE)) {
812 $daoContrProd->delete();
813 }
814 }
815 }
816
817 /**
818 * Process the contribution.
819 *
820 * @param CRM_Core_Form $form
821 * @param array $params
822 * @param array $result
823 * @param int $contactID
824 * @param CRM_Financial_DAO_FinancialType $financialType
825 * @param bool $pending
826 * @param bool $online
827 *
828 * @param bool $isTest
829 * @param array $lineItems
830 *
831 * @param int $billingLocationID
832 * ID of billing location type.
833 *
834 * @return \CRM_Contribute_DAO_Contribution
835 * @throws \Exception
836 */
837 public static function processFormContribution(
838 &$form,
839 $params,
840 $result,
841 $contactID,
842 $financialType,
843 $pending,
844 $online,
845 $isTest,
846 $lineItems,
847 $billingLocationID
848 ) {
849 $transaction = new CRM_Core_Transaction();
850 $contribSoftContactId = $addressID = NULL;
851 $isMonetary = !empty($form->_values['is_monetary']);
852 $isEmailReceipt = !empty($form->_values['is_email_receipt']);
853 // How do these vary from params? These are currently passed to
854 // - custom data function....
855 $formParams = $form->_params;
856 $isSeparateMembershipPayment = empty($formParams['separate_membership_payment']) ? FALSE : TRUE;
857 $pledgeID = empty($formParams['pledge_id']) ? NULL : $formParams['pledge_id'];
858 if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) &&
859 (!empty($formParams['is_pledge']) || $pledgeID)) {
860 $isPledge = TRUE;
861 }
862 else {
863 $isPledge = FALSE;
864 }
865
866 // add these values for the recurringContrib function ,CRM-10188
867 $params['financial_type_id'] = $financialType->id;
868
869 $addressID = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID);
870
871 //@todo - this is being set from the form to resolve CRM-10188 - an
872 // eNotice caused by it not being set @ the front end
873 // however, we then get it being over-written with null for backend contributions
874 // a better fix would be to set the values in the respective forms rather than require
875 // a function being shared by two forms to deal with their respective values
876 // moving it to the BAO & not taking the $form as a param would make sense here.
877 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
878 $params['is_email_receipt'] = $isEmailReceipt;
879 }
880 $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType, $online);
881 $nonDeductibleAmount = self::getNonDeductibleAmount($params, $financialType, $online);
882
883 $now = date('YmdHis');
884 $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
885 if ($isEmailReceipt) {
886 $receiptDate = $now;
887 }
888
889 //get the contrib page id.
890 $contributionPageId = NULL;
891 if ($online) {
892 $contributionPageId = $form->_id;
893 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
894 if (!array_key_exists('campaign_id', $params)) {
895 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
896 }
897 }
898 else {
899 //also for offline we do support - CRM-7290
900 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
901 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
902 }
903
904 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
905 if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
906 // if its due to pcp
907 if (!empty($params['pcp_made_through_id'])) {
908 $contribSoftContactId = CRM_Core_DAO::getFieldValue(
909 'CRM_PCP_DAO_PCP',
910 $params['pcp_made_through_id'],
911 'contact_id'
912 );
913 }
914 else {
915 $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
916 }
917
918 // Pass these details onto with the contribution to make them
919 // available at hook_post_process, CRM-8908
920 $params['soft_credit_to'] = $contribSoftContactId;
921 }
922
923 if (isset($params['amount'])) {
924 $contribParams = self::getContributionParams(
925 $params, $contactID, $financialType->id, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending, $result, $receiptDate,
926 $recurringContributionID, $isTest, $addressID, $contribSoftContactId, $lineItems
927 );
928 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
929
930 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
931 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
932 if ($invoicing) {
933 $dataArray = array();
934 foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
935 foreach ($lineItemValue as $key => $value) {
936 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
937 if (isset($dataArray[$value['tax_rate']])) {
938 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
939 }
940 else {
941 $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
942 }
943 }
944 }
945 }
946 $smarty = CRM_Core_Smarty::singleton();
947 $smarty->assign('dataArray', $dataArray);
948 $smarty->assign('totalTaxAmount', $params['tax_amount']);
949 }
950 if (is_a($contribution, 'CRM_Core_Error')) {
951 $message = CRM_Core_Error::getMessages($contribution);
952 CRM_Core_Error::fatal($message);
953 }
954
955 // lets store it in the form variable so postProcess hook can get to this and use it
956 $form->_contributionID = $contribution->id;
957 }
958
959 //CRM-13981, processing honor contact into soft-credit contribution
960 CRM_Contact_Form_ProfileContact::postProcess($form);
961
962 // process soft credit / pcp pages
963 CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
964
965 //handle pledge stuff.
966 if ($isPledge) {
967 if ($pledgeID) {
968 //when user doing pledge payments.
969 //update the schedule when payment(s) are made
970 foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
971 $scheduledAmount = CRM_Core_DAO::getFieldValue(
972 'CRM_Pledge_DAO_PledgePayment',
973 $paymentId,
974 'scheduled_amount',
975 'id'
976 );
977
978 $pledgePaymentParams = array(
979 'id' => $paymentId,
980 'contribution_id' => $contribution->id,
981 'status_id' => $contribution->contribution_status_id,
982 'actual_amount' => $scheduledAmount,
983 );
984
985 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
986 }
987
988 //update pledge status according to the new payment statuses
989 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID);
990 }
991 else {
992 //when user creating pledge record.
993 $pledgeParams = array();
994 $pledgeParams['contact_id'] = $contribution->contact_id;
995 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
996 $pledgeParams['contribution_id'] = $contribution->id;
997 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
998 $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
999 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
1000 $pledgeParams['installments'] = $params['pledge_installments'];
1001 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
1002 if ($pledgeParams['frequency_unit'] == 'month') {
1003 $pledgeParams['frequency_day'] = intval(date("d"));
1004 }
1005 else {
1006 $pledgeParams['frequency_day'] = 1;
1007 }
1008 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
1009 $pledgeParams['status_id'] = $contribution->contribution_status_id;
1010 $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
1011 $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
1012 $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
1013 $pledgeParams['is_test'] = $contribution->is_test;
1014 $pledgeParams['acknowledge_date'] = date('Ymd');
1015 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
1016
1017 //inherit campaign from contirb page.
1018 $pledgeParams['campaign_id'] = $campaignId;
1019
1020 $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
1021
1022 $form->_params['pledge_id'] = $pledge->id;
1023
1024 //send acknowledgment email. only when pledge is created
1025 if ($pledge->id) {
1026 //build params to send acknowledgment.
1027 $pledgeParams['id'] = $pledge->id;
1028 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
1029 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
1030
1031 //scheduled amount will be same as installment_amount.
1032 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
1033
1034 //get total pledge amount.
1035 $pledgeParams['total_pledge_amount'] = $pledge->amount;
1036
1037 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
1038 }
1039 }
1040 }
1041
1042 if ($online && $contribution) {
1043 CRM_Core_BAO_CustomValueTable::postProcess($form->_params,
1044 'civicrm_contribution',
1045 $contribution->id,
1046 'Contribution'
1047 );
1048 }
1049 elseif ($contribution) {
1050 //handle custom data.
1051 $params['contribution_id'] = $contribution->id;
1052 if (!empty($params['custom']) &&
1053 is_array($params['custom']) &&
1054 !is_a($contribution, 'CRM_Core_Error')
1055 ) {
1056 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
1057 }
1058 }
1059 // Save note
1060 if ($contribution && !empty($params['contribution_note'])) {
1061 $noteParams = array(
1062 'entity_table' => 'civicrm_contribution',
1063 'note' => $params['contribution_note'],
1064 'entity_id' => $contribution->id,
1065 'contact_id' => $contribution->contact_id,
1066 'modified_date' => date('Ymd'),
1067 );
1068
1069 CRM_Core_BAO_Note::add($noteParams, array());
1070 }
1071
1072 if (isset($params['related_contact'])) {
1073 $contactID = $params['related_contact'];
1074 }
1075 elseif (isset($params['cms_contactID'])) {
1076 $contactID = $params['cms_contactID'];
1077 }
1078
1079 //create contribution activity w/ individual and target
1080 //activity w/ organisation contact id when onbelf, CRM-4027
1081 $targetContactID = NULL;
1082 if (!empty($params['hidden_onbehalf_profile'])) {
1083 $targetContactID = $contribution->contact_id;
1084 $contribution->contact_id = $contactID;
1085 }
1086
1087 // create an activity record
1088 if ($contribution) {
1089 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
1090 }
1091
1092 $transaction->commit();
1093 // CRM-13074 - create the CMSUser after the transaction is completed as it
1094 // is not appropriate to delete a valid contribution if a user create problem occurs
1095 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params,
1096 $contactID,
1097 'email-' . $billingLocationID
1098 );
1099 return $contribution;
1100 }
1101
1102 /**
1103 * Create the recurring contribution record.
1104 *
1105 * @param CRM_Core_Form $form
1106 * @param array $params
1107 * @param int $contactID
1108 * @param string $contributionType
1109 * @param bool $online
1110 *
1111 * @return mixed
1112 */
1113 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1114 // return if this page is not set for recurring
1115 // or the user has not chosen the recurring option
1116
1117 //this is online case validation.
1118 if ((empty($form->_values['is_recur']) && $online) || empty($params['is_recur'])) {
1119 return NULL;
1120 }
1121
1122 $recurParams = array('contact_id' => $contactID);
1123 $recurParams['amount'] = CRM_Utils_Array::value('amount', $params);
1124 $recurParams['auto_renew'] = CRM_Utils_Array::value('auto_renew', $params);
1125 $recurParams['frequency_unit'] = CRM_Utils_Array::value('frequency_unit', $params);
1126 $recurParams['frequency_interval'] = CRM_Utils_Array::value('frequency_interval', $params);
1127 $recurParams['installments'] = CRM_Utils_Array::value('installments', $params);
1128 $recurParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params);
1129 $recurParams['currency'] = CRM_Utils_Array::value('currency', $params);
1130
1131 // CRM-14354: For an auto-renewing membership with an additional contribution,
1132 // if separate payments is not enabled, make sure only the membership fee recurs
1133 if (!empty($form->_membershipBlock)
1134 && $form->_membershipBlock['is_separate_payment'] === '0'
1135 && isset($params['selectMembership'])
1136 && $form->_values['is_allow_other_amount'] == '1'
1137 // CRM-16331
1138 && !empty($form->_membershipTypeValues)
1139 && !empty($form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'])
1140 ) {
1141 $recurParams['amount'] = $form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'];
1142 }
1143
1144 $recurParams['is_test'] = 0;
1145 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1146 (isset($form->_mode) && ($form->_mode == 'test'))
1147 ) {
1148 $recurParams['is_test'] = 1;
1149 }
1150
1151 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1152 if (!empty($params['receive_date'])) {
1153 $recurParams['start_date'] = $params['receive_date'];
1154 }
1155 $recurParams['invoice_id'] = CRM_Utils_Array::value('invoiceID', $params);
1156 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1157 $recurParams['payment_processor_id'] = CRM_Utils_Array::value('payment_processor_id', $params);
1158 $recurParams['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params);
1159 // we need to add a unique trxn_id to avoid a unique key error
1160 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1161 $recurParams['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params, $params['invoiceID']);
1162 $recurParams['financial_type_id'] = $contributionType->id;
1163
1164 if (!$online || $form->_values['is_monetary']) {
1165 $recurParams['payment_instrument_id'] = 1;
1166 }
1167
1168 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1169 if ($online) {
1170 if (!array_key_exists('campaign_id', $params)) {
1171 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1172 }
1173 }
1174 $recurParams['campaign_id'] = $campaignId;
1175
1176 $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
1177 if (is_a($recurring, 'CRM_Core_Error')) {
1178 CRM_Core_Error::displaySessionError($recurring);
1179 $urlString = 'civicrm/contribute/transact';
1180 $urlParams = '_qf_Main_display=true';
1181 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1182 $urlString = 'civicrm/contact/view/contribution';
1183 $urlParams = "action=add&cid={$form->_contactID}";
1184 if ($form->_mode) {
1185 $urlParams .= "&mode={$form->_mode}";
1186 }
1187 }
1188 CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
1189 }
1190
1191 return $recurring->id;
1192 }
1193
1194 /**
1195 * Add on behalf of organization and it's location.
1196 *
1197 * This situation occurs when on behalf of is enabled for the contribution page and the person
1198 * signing up does so on behalf of an organization.
1199 *
1200 * @param array $behalfOrganization
1201 * array of organization info.
1202 * @param int $contactID
1203 * individual contact id. One.
1204 * who is doing the process of signup / contribution.
1205 *
1206 * @param array $values
1207 * form values array.
1208 * @param array $params
1209 * @param array $fields
1210 * Array of fields from the onbehalf profile relevant to the organization.
1211 */
1212 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1213 $isCurrentEmployer = FALSE;
1214 $dupeIDs = array();
1215 $orgID = NULL;
1216 if (!empty($behalfOrganization['organization_id']) && empty($behalfOrganization['org_option'])) {
1217 $orgID = $behalfOrganization['organization_id'];
1218 unset($behalfOrganization['organization_id']);
1219 $isCurrentEmployer = TRUE;
1220 }
1221
1222 // formalities for creating / editing organization.
1223 $behalfOrganization['contact_type'] = 'Organization';
1224
1225 // get the relationship type id
1226 $relType = new CRM_Contact_DAO_RelationshipType();
1227 $relType->name_a_b = 'Employee of';
1228 $relType->find(TRUE);
1229 $relTypeId = $relType->id;
1230
1231 // keep relationship params ready
1232 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1233 $relParams['is_permission_a_b'] = 1;
1234 $relParams['is_active'] = 1;
1235
1236 if (!$orgID) {
1237 // check if matching organization contact exists
1238 $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization');
1239 $dedupeParams['check_permission'] = FALSE;
1240 $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1241
1242 // CRM-6243 says to pick the first org even if more than one match
1243 if (count($dupeIDs) >= 1) {
1244 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1245 // don't allow name edit
1246 unset($behalfOrganization['organization_name']);
1247 }
1248 }
1249 else {
1250 // if found permissioned related organization, allow location edit
1251 $behalfOrganization['contact_id'] = $orgID;
1252 // don't allow name edit
1253 unset($behalfOrganization['organization_name']);
1254 }
1255
1256 // handling for image url
1257 if (!empty($behalfOrganization['image_URL'])) {
1258 CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
1259 }
1260
1261 // create organization, add location
1262 $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID,
1263 NULL, NULL, 'Organization'
1264 );
1265 // create relationship
1266 $relParams['contact_check'][$orgID] = 1;
1267 $cid = array('contact' => $contactID);
1268 CRM_Contact_BAO_Relationship::legacyCreateMultiple($relParams, $cid);
1269
1270 // if multiple match - send a duplicate alert
1271 if ($dupeIDs && (count($dupeIDs) > 1)) {
1272 $values['onbehalf_dupe_alert'] = 1;
1273 // required for IPN
1274 $params['onbehalf_dupe_alert'] = 1;
1275 }
1276
1277 // make sure organization-contact-id is considered for recording
1278 // contribution/membership etc..
1279 if ($contactID != $orgID) {
1280 // take a note of contact-id, so we can send the
1281 // receipt to individual contact as well.
1282
1283 // required for mailing/template display ..etc
1284 $values['related_contact'] = $contactID;
1285 // required for IPN
1286 $params['related_contact'] = $contactID;
1287
1288 //make this employee of relationship as current
1289 //employer / employee relationship, CRM-3532
1290 if ($isCurrentEmployer &&
1291 ($orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1292 ) {
1293 $isCurrentEmployer = FALSE;
1294 }
1295
1296 if (!$isCurrentEmployer && $orgID) {
1297 //build current employer params
1298 $currentEmpParams[$contactID] = $orgID;
1299 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
1300 }
1301
1302 // contribution / signup will be done using this
1303 // organization id.
1304 $contactID = $orgID;
1305 }
1306 }
1307
1308 /**
1309 * Function used to save pcp / soft credit entry.
1310 *
1311 * This is used by contribution and also event pcps
1312 *
1313 * @param array $params
1314 * @param object $contribution
1315 * Contribution object.
1316 */
1317 public static function processPcpSoft(&$params, &$contribution) {
1318 // Add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1319 if (!empty($params['soft_credit_to'])) {
1320 $contributionSoftParams = array();
1321 foreach (array(
1322 'pcp_display_in_roll',
1323 'pcp_roll_nickname',
1324 'pcp_personal_note',
1325 'amount',
1326 ) as $val) {
1327 if (!empty($params[$val])) {
1328 $contributionSoftParams[$val] = $params[$val];
1329 }
1330 }
1331
1332 $contributionSoftParams['contact_id'] = $params['soft_credit_to'];
1333 // add contribution id
1334 $contributionSoftParams['contribution_id'] = $contribution->id;
1335 // add pcp id
1336 $contributionSoftParams['pcp_id'] = $params['pcp_made_through_id'];
1337
1338 $contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
1339
1340 $contributionSoft = CRM_Contribute_BAO_ContributionSoft::add($contributionSoftParams);
1341
1342 //Send notification to owner for PCP
1343 if ($contributionSoft->id && $contributionSoft->pcp_id) {
1344 CRM_Contribute_Form_Contribution_Confirm::pcpNotifyOwner($contribution, $contributionSoft);
1345 }
1346 }
1347 }
1348
1349 /**
1350 * Function used to send notification mail to pcp owner.
1351 *
1352 * This is used by contribution and also event PCPs.
1353 *
1354 * @param object $contribution
1355 * @param object $contributionSoft
1356 * Contribution object.
1357 */
1358 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1359 $params = array('id' => $contributionSoft->pcp_id);
1360 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1361 $ownerNotifyID = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1362
1363 if ($ownerNotifyID != CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1364 (($ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1365 CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id, 'is_notify')) ||
1366 $ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1367 $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info',
1368 "reset=1&id={$contributionSoft->pcp_id}",
1369 TRUE, NULL, FALSE, TRUE
1370 );
1371 // set email in the template here
1372 // get the billing location type
1373 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1374 $billingLocationTypeId = array_search('Billing', $locationTypes);
1375
1376 if ($billingLocationTypeId) {
1377 list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id, FALSE, $billingLocationTypeId);
1378 }
1379 // get primary location email if no email exist( for billing location).
1380 if (!$email) {
1381 list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id);
1382 }
1383 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contributionSoft->contact_id);
1384 $tplParams = array(
1385 'page_title' => $pcpInfo['title'],
1386 'receive_date' => $contribution->receive_date,
1387 'total_amount' => $contributionSoft->amount,
1388 'donors_display_name' => $donorName,
1389 'donors_email' => $email,
1390 'pcpInfoURL' => $pcpInfoURL,
1391 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll,
1392 'currency' => $contributionSoft->currency,
1393 );
1394 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
1395 $sendTemplateParams = array(
1396 'groupName' => 'msg_tpl_workflow_contribution',
1397 'valueName' => 'pcp_owner_notify',
1398 'contactId' => $contributionSoft->contact_id,
1399 'toEmail' => $ownerEmail,
1400 'toName' => $ownerName,
1401 'from' => "$domainValues[0] <$domainValues[1]>",
1402 'tplParams' => $tplParams,
1403 'PDFFilename' => 'receipt.pdf',
1404 );
1405 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
1406 }
1407 }
1408
1409 /**
1410 * Function used to se pcp related defaults / params.
1411 *
1412 * This is used by contribution and also event PCPs
1413 *
1414 * @param CRM_Core_Form $page
1415 * Form object.
1416 * @param array $params
1417 *
1418 * @return array
1419 */
1420 public static function processPcp(&$page, $params) {
1421 $params['pcp_made_through_id'] = $page->_pcpId;
1422 $page->assign('pcpBlock', TRUE);
1423 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1424 $params['pcp_roll_nickname'] = ts('Anonymous');
1425 $params['pcp_is_anonymous'] = 1;
1426 }
1427 else {
1428 $params['pcp_is_anonymous'] = 0;
1429 }
1430 foreach (array(
1431 'pcp_display_in_roll',
1432 'pcp_is_anonymous',
1433 'pcp_roll_nickname',
1434 'pcp_personal_note',
1435 ) as $val) {
1436 if (!empty($params[$val])) {
1437 $page->assign($val, $params[$val]);
1438 }
1439 }
1440
1441 return $params;
1442 }
1443
1444 /**
1445 * Process membership.
1446 *
1447 * @param array $membershipParams
1448 * @param int $contactID
1449 * @param array $customFieldsFormatted
1450 * @param array $fieldTypes
1451 * @param array $premiumParams
1452 * @param array $membershipLineItems
1453 * Line items specifically relating to memberships.
1454 * @param bool $isPayLater
1455 */
1456 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1457 $membershipLineItems, $isPayLater) {
1458
1459 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1460 $membershipTypes = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIDs);
1461 $membershipType = empty($membershipTypes) ? array() : reset($membershipTypes);
1462 $isPending = $this->getIsPending();
1463
1464 $this->assign('membership_name', CRM_Utils_Array::value('name', $membershipType));
1465
1466 $isPaidMembership = FALSE;
1467 if ($this->_amount >= 0.0 && isset($membershipParams['amount'])) {
1468 //amount must be greater than zero for
1469 //adding contribution record to contribution table.
1470 //this condition arises when separate membership payment is
1471 //enabled and contribution amount is not selected. fix for CRM-3010
1472 $isPaidMembership = TRUE;
1473 }
1474 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id, $this->_values['amount_block_is_active']);
1475
1476 if ($this->_values['amount_block_is_active']) {
1477 $financialTypeID = $this->_values['financial_type_id'];
1478 }
1479 else {
1480 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $membershipType, CRM_Utils_Array::value('financial_type_id', $membershipParams));
1481 }
1482
1483 if (CRM_Utils_Array::value('membership_source', $this->_params)) {
1484 $membershipParams['contribution_source'] = $this->_params['membership_source'];
1485 }
1486
1487 $this->postProcessMembership($membershipParams, $contactID,
1488 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId, $isProcessSeparateMembershipTransaction, $financialTypeID,
1489 $membershipLineItems, $isPayLater, $isPending);
1490
1491 $this->assign('membership_assign', TRUE);
1492 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1493 }
1494
1495 /**
1496 * Process the Memberships.
1497 *
1498 * @param array $membershipParams
1499 * Array of membership fields.
1500 * @param int $contactID
1501 * Contact id.
1502 * @param CRM_Contribute_Form_Contribution_Confirm $form
1503 * Confirmation form object.
1504 *
1505 * @param array $premiumParams
1506 * @param null $customFieldsFormatted
1507 * @param null $includeFieldTypes
1508 *
1509 * @param array $membershipDetails
1510 *
1511 * @param array $membershipTypeIDs
1512 *
1513 * @param bool $isPaidMembership
1514 * @param array $membershipID
1515 *
1516 * @param bool $isProcessSeparateMembershipTransaction
1517 *
1518 * @param int $financialTypeID
1519 * @param array $membershipLineItems
1520 * Line items specific to membership payment that is separate to contribution.
1521 * @param bool $isPayLater
1522 * @param bool $isPending
1523 *
1524 * @throws \CRM_Core_Exception
1525 */
1526 protected function postProcessMembership(
1527 $membershipParams, $contactID, &$form, $premiumParams,
1528 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1529 $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending) {
1530 $membershipContribution = NULL;
1531 $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE);
1532 $errors = $createdMemberships = $paymentResult = array();
1533
1534 if ($isPaidMembership) {
1535 if ($isProcessSeparateMembershipTransaction) {
1536 // If we have 2 transactions only one can use the invoice id.
1537 $membershipParams['invoiceID'] .= '-2';
1538 }
1539
1540 $paymentResult = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams,
1541 $contactID,
1542 $financialTypeID,
1543 'membership',
1544 array(),
1545 $isTest,
1546 $isPayLater
1547 );
1548
1549 if (!empty($paymentResult['contribution'])) {
1550 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1551 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1552 $membershipContribution = $paymentResult['contribution'];
1553 // Save the contribution ID so that I can be used in email receipts
1554 // For example, if you need to generate a tax receipt for the donation only.
1555 $form->_values['contribution_other_id'] = $membershipContribution->id;
1556 }
1557 }
1558
1559 if ($isProcessSeparateMembershipTransaction) {
1560 try {
1561 $form->_lineItem = $membershipLineItems;
1562 if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) {
1563 unset($membershipParams['is_recur']);
1564 }
1565 $membershipContribution = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams,
1566 $isTest, $membershipLineItems, CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array::value('financial_type_id', $membershipDetails));
1567 }
1568 catch (CRM_Core_Exception $e) {
1569 $errors[2] = $e->getMessage();
1570 $membershipContribution = NULL;
1571 }
1572 }
1573
1574 $membership = NULL;
1575 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1576 $membershipContributionID = $membershipContribution->id;
1577 }
1578
1579 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1580 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1581 $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1582 }
1583 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1584 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1585 $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
1586 foreach ($membershipTypeIDs as $memType) {
1587 $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
1588 if (!empty($membershipContribution)) {
1589 $pendingStatus = CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name');
1590 $pending = ($membershipContribution->contribution_status_id == $pendingStatus) ? TRUE : FALSE;
1591 }
1592 else {
1593 $pending = $isPending;
1594 }
1595 $contributionRecurID = isset($form->_params['contributionRecurID']) ? $form->_params['contributionRecurID'] : NULL;
1596
1597 $membershipSource = NULL;
1598 if (!empty($form->_params['membership_source'])) {
1599 $membershipSource = $form->_params['membership_source'];
1600 }
1601 elseif (isset($form->_values['title']) && !empty($form->_values['title'])) {
1602 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values['title'];
1603 }
1604 $isPayLater = NULL;
1605 if (isset($form->_params)) {
1606 $isPayLater = CRM_Utils_Array::value('is_pay_later', $form->_params);
1607 }
1608 $campaignId = NULL;
1609 if (isset($form->_values) && is_array($form->_values) && !empty($form->_values)) {
1610 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_params);
1611 if (!array_key_exists('campaign_id', $form->_params)) {
1612 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1613 }
1614 }
1615
1616 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership::renewMembership(
1617 $contactID, $memType, $isTest,
1618 date('YmdHis'), CRM_Utils_Array::value('cms_contactID', $membershipParams),
1619 $customFieldsFormatted,
1620 $numTerms, $membershipID, $pending,
1621 $contributionRecurID, $membershipSource, $isPayLater, $campaignId
1622 );
1623 $form->set('renewal_mode', $renewalMode);
1624 if (!empty($dates)) {
1625 $form->assign('mem_start_date',
1626 CRM_Utils_Date::customFormat($dates['start_date'], '%Y%m%d')
1627 );
1628 $form->assign('mem_end_date',
1629 CRM_Utils_Date::customFormat($dates['end_date'], '%Y%m%d')
1630 );
1631 }
1632
1633 if (!empty($membershipContribution)) {
1634 // update recurring id for membership record
1635 CRM_Member_BAO_Membership::updateRecurMembership($membership, $membershipContribution);
1636 CRM_Member_BAO_Membership::linkMembershipPayment($membership, $membershipContribution);
1637 }
1638 }
1639 if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
1640 foreach ($form->_lineItem[$form->_priceSetId] as & $priceFieldOp) {
1641 if (!empty($priceFieldOp['membership_type_id']) &&
1642 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1643 ) {
1644 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1645 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%B %E%f, %Y') : '-';
1646 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%B %E%f, %Y') : '-';
1647 }
1648 else {
1649 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1650 }
1651 }
1652 $form->_values['lineItem'] = $form->_lineItem;
1653 $form->assign('lineItem', $form->_lineItem);
1654 }
1655 }
1656
1657 if (!empty($errors)) {
1658 $message = $this->compileErrorMessage($errors);
1659 throw new CRM_Core_Exception($message);
1660 }
1661 $form->_params['createdMembershipIDs'] = array();
1662
1663 // CRM-7851 - Moved after processing Payment Errors
1664 //@todo - the reasoning for this being here seems a little outdated
1665 foreach ($createdMemberships as $createdMembership) {
1666 CRM_Core_BAO_CustomValueTable::postProcess(
1667 $form->_params,
1668 'civicrm_membership',
1669 $createdMembership->id,
1670 'Membership'
1671 );
1672 $form->_params['createdMembershipIDs'][] = $createdMembership->id;
1673 }
1674 if (count($createdMemberships) == 1) {
1675 //presumably this is only relevant for exactly 1 membership
1676 $form->_params['membershipID'] = $createdMembership->id;
1677 }
1678
1679 //CRM-15232: Check if membership is created and on the basis of it use
1680 //membership receipt template to send payment receipt
1681 if (count($createdMemberships)) {
1682 $form->_values['isMembership'] = TRUE;
1683 }
1684 if (isset($membershipContributionID)) {
1685 $form->_values['contribution_id'] = $membershipContributionID;
1686 }
1687 if ($form->_contributeMode) {
1688 if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
1689 // call postProcess hook before leaving
1690 $form->postProcessHook();
1691 }
1692 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
1693 $paymentActionResult = $payment->doPayment($form->_params, 'contribute');
1694
1695 if (CRM_Utils_Array::value('payment_status_id', $paymentActionResult) == 1) {
1696 // Refer to CRM-16737. Payment processors 'should' return payment_status_id
1697 // to denote the outcome of the transaction.
1698 try {
1699 civicrm_api3('contribution', 'completetransaction', array(
1700 'id' => $paymentResult['contribution']->id,
1701 'trxn_id' => CRM_Utils_Array::value('trxn_id', $paymentActionResult, $paymentResult['contribution']->trxn_id),
1702 'is_transactional' => FALSE,
1703 'payment_processor_id' => $form->_paymentProcessor['id'],
1704 ));
1705 }
1706 catch (CiviCRM_API3_Exception $e) {
1707 if ($e->getErrorCode() != 'contribution_completed') {
1708 throw new CRM_Core_Exception('Failed to update contribution in database');
1709 }
1710 }
1711 }
1712 // Do not send an email if Recurring transaction is done via Direct Mode
1713 // Email will we sent when the IPN is received.
1714 return;
1715 }
1716
1717 //finally send an email receipt
1718 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
1719 $form->_values,
1720 $isTest, FALSE,
1721 $includeFieldTypes
1722 );
1723 }
1724
1725 /**
1726 * Turn array of errors into message string.
1727 *
1728 * @param array $errors
1729 *
1730 * @return string
1731 */
1732 protected function compileErrorMessage($errors) {
1733 foreach ($errors as $error) {
1734 if (is_string($error)) {
1735 $message[] = $error;
1736 }
1737 }
1738 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1739 }
1740
1741 /**
1742 * Where a second separate financial transaction is supported we will process it here.
1743 *
1744 * @param int $contactID
1745 * @param CRM_Contribute_Form_Contribution_Confirm $form
1746 * @param array $tempParams
1747 * @param bool $isTest
1748 * @param array $lineItems
1749 * @param $minimumFee
1750 * @param int $financialTypeID
1751 *
1752 * @throws CRM_Core_Exception
1753 * @throws Exception
1754 * @return CRM_Contribute_BAO_Contribution
1755 */
1756 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1757 $financialTypeID) {
1758 $financialType = new CRM_Financial_DAO_FinancialType();
1759 $financialType->id = $financialTypeID;
1760 $financialType->find(TRUE);
1761 $tempParams['amount'] = $minimumFee;
1762 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1763
1764 $result = NULL;
1765 if ($form->_values['is_monetary'] && !$form->_params['is_pay_later'] && $minimumFee > 0.0) {
1766 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1767 // now we compensate here.
1768 if (empty($form->_paymentProcessor['object'])) {
1769 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1770 }
1771 else {
1772 $payment = $form->_paymentProcessor['object'];
1773 }
1774 $result = $payment->doPayment($tempParams, 'contribute');
1775 }
1776
1777 //assign receive date when separate membership payment
1778 //and contribution amount not selected.
1779 if ($form->_amount == 0) {
1780 $now = date('YmdHis');
1781 $form->_params['receive_date'] = $now;
1782 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
1783 $form->set('params', $form->_params);
1784 $form->assign('receive_date', $receiveDate);
1785 }
1786
1787 $form->set('membership_trx_id', $result['trxn_id']);
1788 $form->set('membership_amount', $minimumFee);
1789
1790 $form->assign('membership_trx_id', $result['trxn_id']);
1791 $form->assign('membership_amount', $minimumFee);
1792
1793 // we don't need to create the user twice, so lets disable cms_create_account
1794 // irrespective of the value, CRM-2888
1795 $tempParams['cms_create_account'] = 0;
1796
1797 //CRM-16165, scenarios are
1798 // 1) If contribution is_pay_later and if contribution amount is > 0.0 we set pending = TRUE, vice-versa FALSE
1799 // 2) If not pay later but auto-renewal membership is chosen then pending = TRUE as it later triggers
1800 // pending recurring contribution, vice-versa FALSE
1801 $pending = $form->_params['is_pay_later'] ? (($minimumFee > 0.0) ? TRUE : FALSE) : (!empty($form->_params['auto_renew']) ? TRUE : FALSE);
1802
1803 //set this variable as we are not creating pledge for
1804 //separate membership payment contribution.
1805 //so for differentiating membership contribution from
1806 //main contribution.
1807 $form->_params['separate_membership_payment'] = 1;
1808 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($form,
1809 $tempParams,
1810 $result,
1811 $contactID,
1812 $financialType,
1813 $pending,
1814 TRUE,
1815 $isTest,
1816 $lineItems,
1817 $form->_bltID
1818 );
1819 return $membershipContribution;
1820 }
1821
1822 /**
1823 * Is the payment a pending payment.
1824 *
1825 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1826 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1827 *
1828 *
1829 * @return bool
1830 */
1831 protected function getIsPending() {
1832 if (((isset($this->_contributeMode)) || !empty
1833 ($this->_params['is_pay_later'])
1834 ) &&
1835 (($this->_values['is_monetary'] && $this->_amount > 0.0))
1836 ) {
1837 return TRUE;
1838 }
1839 return FALSE;
1840 }
1841
1842 /**
1843 * Are we going to do 2 financial transactions.
1844 *
1845 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1846 * contribution
1847 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1848 *
1849 * @param int $formID
1850 * @param bool $amountBlockActiveOnForm
1851 *
1852 * @return bool
1853 */
1854 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1855 $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($formID);
1856 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1857 return TRUE;
1858 }
1859 return FALSE;
1860 }
1861
1862 /**
1863 * This function sets the fields.
1864 *
1865 * - $this->_params['amount_level']
1866 * - $this->_params['selectMembership']
1867 * And under certain circumstances sets
1868 * $this->_params['amount'] = null;
1869 *
1870 * @param int $priceSetID
1871 */
1872 public function setFormAmountFields($priceSetID) {
1873 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config');
1874 $priceField = new CRM_Price_DAO_PriceField();
1875 $priceField->price_set_id = $priceSetID;
1876 $priceField->orderBy('weight');
1877 $priceField->find();
1878 $paramWeDoNotUnderstand = NULL;
1879
1880 while ($priceField->fetch()) {
1881 if ($priceField->name == "contribution_amount") {
1882 $paramWeDoNotUnderstand = $priceField->id;
1883 }
1884 if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) {
1885 if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') {
1886 $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1887 $this->_params["price_{$priceField->id}"], 'label');
1888 }
1889 if ($priceField->name == "membership_amount") {
1890 $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1891 $this->_params["price_{$priceField->id}"], 'membership_type_id');
1892 }
1893 }
1894 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1895 // as membership amount.
1896 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1897 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1898 // so we should merge them together
1899 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1900 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1901 elseif (
1902 CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock)
1903 && !empty($this->_values['fee'][$priceField->id])
1904 && ($this->_values['fee'][$priceField->id]['name'] == "other_amount")
1905 && CRM_Utils_Array::value("price_{$paramWeDoNotUnderstand}", $this->_params) < 1
1906 && empty($this->_params["price_{$priceField->id}"])
1907 ) {
1908 $this->_params['amount'] = NULL;
1909 }
1910
1911 // Fix for CRM-14375 - If we are using separate payments and "no
1912 // thank you" is selected for the additional contribution, set
1913 // contribution amount to be null, so that it will not show
1914 // contribution amount same as membership amount.
1915 //@todo - merge with section above
1916 if ($this->_membershipBlock['is_separate_payment']
1917 && !empty($this->_values['fee'][$priceField->id])
1918 && CRM_Utils_Array::value('name', $this->_values['fee'][$priceField->id]) == 'contribution_amount'
1919 && CRM_Utils_Array::value("price_{$priceField->id}", $this->_params) == '-1'
1920 ) {
1921 $this->_params['amount'] = NULL;
1922 }
1923 }
1924 }
1925
1926 /**
1927 * Submit function.
1928 *
1929 * @param array $params
1930 *
1931 * @throws CiviCRM_API3_Exception
1932 */
1933 public static function submit($params) {
1934 $form = new CRM_Contribute_Form_Contribution_Confirm();
1935 $form->_id = $params['id'];
1936
1937 CRM_Contribute_BAO_ContributionPage::setValues($form->_id, $form->_values);
1938 $form->_separateMembershipPayment = CRM_Contribute_BAO_ContributionPage::getIsMembershipPayment($form->_id);
1939 //this way the mocked up controller ignores the session stuff
1940 $_SERVER['REQUEST_METHOD'] = 'GET';
1941 $form->controller = new CRM_Contribute_Controller_Contribution();
1942 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1943 $paramsProcessedForForm = $form->_params = self::getFormParams($params['id'], $params);
1944 $form->_amount = $params['amount'];
1945 $priceSetID = $form->_params['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1946 $priceFields = CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
1947 $priceSetFields = reset($priceFields);
1948 $form->_values['fee'] = $priceSetFields['fields'];
1949 $form->_priceSetId = $priceSetID;
1950 $form->setFormAmountFields($priceSetID);
1951 if (!empty($params['payment_processor_id'])) {
1952 $form->_paymentProcessor = civicrm_api3('payment_processor', 'getsingle', array(
1953 'id' => $params['payment_processor_id'],
1954 ));
1955 if ($form->_paymentProcessor['billing_mode'] == 1) {
1956 $form->_contributeMode = 'direct';
1957 }
1958 else {
1959 $form->_contributeMode = 'notify';
1960 }
1961 }
1962 else {
1963 $form->_params['payment_processor_id'] = 0;
1964 }
1965 $priceFields = $priceFields[$priceSetID]['fields'];
1966 CRM_Price_BAO_PriceSet::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1967 $form->_lineItem = array($priceSetID => $lineItems);
1968 $form->processFormSubmission(CRM_Utils_Array::value('contact_id', $params));
1969 }
1970
1971 /**
1972 * Helper function for static submit function.
1973 *
1974 * Set relevant params - help us to build up an array that we can pass in.
1975 *
1976 * @param int $id
1977 * @param array $params
1978 *
1979 * @return array
1980 * @throws CiviCRM_API3_Exception
1981 */
1982 public static function getFormParams($id, array $params) {
1983 if (!isset($params['is_pay_later'])) {
1984 if (!empty($params['payment_processor_id'])) {
1985 $params['is_pay_later'] = 0;
1986 }
1987 else {
1988 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1989 'id' => $id,
1990 'return' => 'is_pay_later',
1991 ));
1992 }
1993 }
1994 if (empty($params['price_set_id'])) {
1995 $params['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id']);
1996 }
1997 return $params;
1998 }
1999
2000 /**
2001 * Post form submission handling.
2002 *
2003 * This is also called from the test suite.
2004 *
2005 * @param int $contactID
2006 *
2007 * @return array
2008 */
2009 protected function processFormSubmission($contactID) {
2010 $isPayLater = $this->_params['is_pay_later'];
2011 if (isset($this->_params['payment_processor_id']) && $this->_params['payment_processor_id'] == 0) {
2012 $this->_params['is_pay_later'] = $isPayLater = TRUE;
2013 }
2014 // add a description field at the very beginning
2015 $this->_params['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
2016
2017 $this->_params['accountingCode'] = CRM_Utils_Array::value('accountingCode', $this->_values);
2018
2019 // fix currency ID
2020 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
2021
2022 //carry payment processor id.
2023 if (CRM_Utils_Array::value('id', $this->_paymentProcessor)) {
2024 $this->_params['payment_processor_id'] = $this->_paymentProcessor['id'];
2025 }
2026
2027 $premiumParams = $membershipParams = $params = $this->_params;
2028 if (!empty($params['image_URL'])) {
2029 CRM_Contact_BAO_Contact::processImageParams($params);
2030 }
2031
2032 $fields = array('email-Primary' => 1);
2033
2034 // get the add to groups
2035 $addToGroups = array();
2036
2037 // now set the values for the billing location.
2038 foreach ($this->_fields as $name => $value) {
2039 $fields[$name] = 1;
2040
2041 // get the add to groups for uf fields
2042 if (!empty($value['add_to_group_id'])) {
2043 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2044 }
2045 }
2046
2047 if (!array_key_exists('first_name', $fields)) {
2048 $nameFields = array('first_name', 'middle_name', 'last_name');
2049 foreach ($nameFields as $name) {
2050 $fields[$name] = 1;
2051 if (array_key_exists("billing_$name", $params)) {
2052 $params[$name] = $params["billing_{$name}"];
2053 $params['preserveDBName'] = TRUE;
2054 }
2055 }
2056 }
2057
2058 // billing email address
2059 $fields["email-{$this->_bltID}"] = 1;
2060
2061 //unset the billing parameters if it is pay later mode
2062 //to avoid creation of billing location
2063 if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater) {
2064 $billingFields = array(
2065 'billing_first_name',
2066 'billing_middle_name',
2067 'billing_last_name',
2068 "billing_street_address-{$this->_bltID}",
2069 "billing_city-{$this->_bltID}",
2070 "billing_state_province-{$this->_bltID}",
2071 "billing_state_province_id-{$this->_bltID}",
2072 "billing_postal_code-{$this->_bltID}",
2073 "billing_country-{$this->_bltID}",
2074 "billing_country_id-{$this->_bltID}",
2075 );
2076
2077 foreach ($billingFields as $value) {
2078 unset($params[$value]);
2079 unset($fields[$value]);
2080 }
2081 }
2082
2083 // if onbehalf-of-organization contribution, take out
2084 // organization params in a separate variable, to make sure
2085 // normal behavior is continued. And use that variable to
2086 // process on-behalf-of functionality.
2087 if (!empty($this->_params['hidden_onbehalf_profile'])) {
2088 $behalfOrganization = array();
2089 $orgFields = array('organization_name', 'organization_id', 'org_option');
2090 foreach ($orgFields as $fld) {
2091 if (array_key_exists($fld, $params)) {
2092 $behalfOrganization[$fld] = $params[$fld];
2093 unset($params[$fld]);
2094 }
2095 }
2096
2097 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2098 foreach ($params['onbehalf'] as $fld => $values) {
2099 if (strstr($fld, 'custom_')) {
2100 $behalfOrganization[$fld] = $values;
2101 }
2102 elseif (!(strstr($fld, '-'))) {
2103 if (in_array($fld, array(
2104 'contribution_campaign_id',
2105 'member_campaign_id',
2106 ))) {
2107 $fld = 'campaign_id';
2108 }
2109 else {
2110 $behalfOrganization[$fld] = $values;
2111 }
2112 $this->_params[$fld] = $values;
2113 }
2114 }
2115 }
2116
2117 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2118 foreach ($params['onbehalf_location'] as $block => $vals) {
2119 //fix for custom data (of type checkbox, multi-select)
2120 if (substr($block, 0, 7) == 'custom_') {
2121 continue;
2122 }
2123 // fix the index of block elements
2124 if (is_array($vals)) {
2125 foreach ($vals as $key => $val) {
2126 //dont adjust the index of address block as
2127 //it's index is WRT to location type
2128 $newKey = ($block == 'address') ? $key : ++$key;
2129 $behalfOrganization[$block][$newKey] = $val;
2130 }
2131 }
2132 }
2133 unset($params['onbehalf_location']);
2134 }
2135 if (!empty($params['onbehalf[image_URL]'])) {
2136 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2137 }
2138 }
2139
2140 // check for profile double opt-in and get groups to be subscribed
2141 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
2142
2143 // since we are directly adding contact to group lets unset it from mailing
2144 if (!empty($addToGroups)) {
2145 foreach ($addToGroups as $groupId) {
2146 if (isset($subscribeGroupIds[$groupId])) {
2147 unset($subscribeGroupIds[$groupId]);
2148 }
2149 }
2150 }
2151
2152 foreach ($addToGroups as $k) {
2153 if (array_key_exists($k, $subscribeGroupIds)) {
2154 unset($addToGroups[$k]);
2155 }
2156 }
2157
2158 if (empty($contactID)) {
2159 $dupeParams = $params;
2160 if (!empty($dupeParams['onbehalf'])) {
2161 unset($dupeParams['onbehalf']);
2162 }
2163 if (!empty($dupeParams['honor'])) {
2164 unset($dupeParams['honor']);
2165 }
2166
2167 $dedupeParams = CRM_Dedupe_Finder::formatParams($dupeParams, 'Individual');
2168 $dedupeParams['check_permission'] = FALSE;
2169 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
2170
2171 // if we find more than one contact, use the first one
2172 $contactID = CRM_Utils_Array::value(0, $ids);
2173
2174 // Fetch default greeting id's if creating a contact
2175 if (!$contactID) {
2176 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
2177 if (!isset($params[$greeting])) {
2178 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
2179 }
2180 }
2181 }
2182 $contactType = NULL;
2183 }
2184 else {
2185 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2186 }
2187 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
2188 $params,
2189 $fields,
2190 $contactID,
2191 $addToGroups,
2192 NULL,
2193 $contactType,
2194 TRUE
2195 );
2196
2197 // Make the contact ID associated with the contribution available at the Class level.
2198 // Also make available to the session.
2199 //@todo consider handling this in $this->getContactID();
2200 $this->set('contactID', $contactID);
2201 $this->_contactID = $contactID;
2202
2203 //get email primary first if exist
2204 $subscriptionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
2205 if (!$subscriptionEmail['email']) {
2206 $subscriptionEmail['email'] = CRM_Utils_Array::value("email-{$this->_bltID}", $params);
2207 }
2208 // subscribing contact to groups
2209 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2210 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2211 }
2212
2213 // If onbehalf-of-organization contribution / signup, add organization
2214 // and it's location.
2215 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
2216 $ufFields = array();
2217 foreach ($this->_fields['onbehalf'] as $name => $value) {
2218 $ufFields[$name] = 1;
2219 }
2220 self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values,
2221 $this->_params, $ufFields
2222 );
2223 }
2224 elseif (!empty($this->_membershipContactID) && $contactID != $this->_membershipContactID) {
2225 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2226 // store current user id as related contact for later use for mailing / activity..
2227 $this->_values['related_contact'] = $contactID;
2228 $this->_params['related_contact'] = $contactID;
2229 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2230 $contactID = $this->_membershipContactID;
2231 }
2232
2233 // lets store the contactID in the session
2234 // for things like tell a friend
2235 $session = CRM_Core_Session::singleton();
2236 if (!$session->get('userID')) {
2237 $session->set('transaction.userID', $contactID);
2238 }
2239 else {
2240 $session->set('transaction.userID', NULL);
2241 }
2242
2243 $this->_useForMember = $this->get('useForMember');
2244
2245 // store the fact that this is a membership and membership type is selected
2246 if ((!empty($membershipParams['selectMembership']) &&
2247 $membershipParams['selectMembership'] != 'no_thanks'
2248 ) ||
2249 $this->_useForMember
2250 ) {
2251 if (!$this->_useForMember) {
2252 $this->assign('membership_assign', TRUE);
2253 $this->set('membershipTypeID', $this->_params['selectMembership']);
2254 }
2255
2256 if ($this->_action & CRM_Core_Action::PREVIEW) {
2257 $membershipParams['is_test'] = 1;
2258 }
2259 if ($this->_params['is_pay_later']) {
2260 $membershipParams['is_pay_later'] = 1;
2261 }
2262
2263 //inherit campaign from contribution page.
2264 if (!array_key_exists('campaign_id', $membershipParams)) {
2265 $membershipParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
2266 }
2267
2268 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE);
2269 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater);
2270 }
2271 else {
2272 // at this point we've created a contact and stored its address etc
2273 // all the payment processors expect the name and address to be in the
2274 // so we copy stuff over to first_name etc.
2275 $paymentParams = $this->_params;
2276 $contributionTypeId = $this->_values['financial_type_id'];
2277
2278 $fieldTypes = array();
2279 if (!empty($paymentParams['onbehalf']) &&
2280 is_array($paymentParams['onbehalf'])
2281 ) {
2282 foreach ($paymentParams['onbehalf'] as $key => $value) {
2283 if (strstr($key, 'custom_')) {
2284 $this->_params[$key] = $value;
2285 }
2286 }
2287 $fieldTypes = array('Contact', 'Organization', 'Contribution');
2288 }
2289 $financialTypeID = $this->wrangleFinancialTypeID($contributionTypeId);
2290
2291 $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($this, $paymentParams,
2292 $contactID,
2293 $financialTypeID,
2294 'contribution',
2295 $fieldTypes,
2296 ($this->_mode == 'test') ? 1 : 0,
2297 $isPayLater
2298 );
2299
2300 if (!empty($result['is_payment_failure'])) {
2301 return $result;
2302 }
2303 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2304 $this->postProcessPremium($premiumParams, $result['contribution']);
2305 if (CRM_Utils_Array::value('payment_status_id', $result) == 1) {
2306 try {
2307 civicrm_api3('contribution', 'completetransaction', array(
2308 'id' => $result['contribution']->id,
2309 'trxn_id' => CRM_Utils_Array::value('trxn_id', $result),
2310 'payment_processor_id' => $this->_paymentProcessor['id'],
2311 'is_transactional' => FALSE,
2312 )
2313 );
2314 }
2315 catch (CiviCRM_API3_Exception $e) {
2316 if ($e->getErrorCode() != 'contribution_completed') {
2317 throw new CRM_Core_Exception('Failed to update contribution in database');
2318 }
2319 }
2320
2321 }
2322 return $result;
2323 }
2324 }
2325
2326 /**
2327 * Membership processing section.
2328 *
2329 * This is in a separate function as part of a move towards refactoring.
2330 *
2331 * @param int $contactID
2332 * @param array $membershipParams
2333 * @param array $premiumParams
2334 * @param bool $isPayLater
2335 */
2336 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater) {
2337
2338 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2339 if (isset($this->_params['related_contact'])) {
2340 $membershipParams['cms_contactID'] = $this->_params['related_contact'];
2341 }
2342 else {
2343 $membershipParams['cms_contactID'] = $contactID;
2344 }
2345
2346 if (!empty($membershipParams['onbehalf']) &&
2347 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2348 ) {
2349 $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2350 }
2351
2352 $customFieldsFormatted = $fieldTypes = array();
2353 if (!empty($membershipParams['onbehalf']) &&
2354 is_array($membershipParams['onbehalf'])
2355 ) {
2356 foreach ($membershipParams['onbehalf'] as $key => $value) {
2357 if (strstr($key, 'custom_')) {
2358 $customFieldId = explode('_', $key);
2359 CRM_Core_BAO_CustomField::formatCustomField(
2360 $customFieldId[1],
2361 $customFieldsFormatted,
2362 $value,
2363 'Membership',
2364 NULL,
2365 $contactID
2366 );
2367 }
2368 }
2369 $fieldTypes = array('Contact', 'Organization', 'Membership');
2370 }
2371
2372 $priceFieldIds = $this->get('memberPriceFieldIDS');
2373
2374 if (!empty($priceFieldIds)) {
2375 $contributionTypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2376 unset($priceFieldIds['id']);
2377 $membershipTypeIds = array();
2378 $membershipTypeTerms = array();
2379 foreach ($priceFieldIds as $priceFieldId) {
2380 if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
2381 $membershipTypeIds[] = $id;
2382 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
2383 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
2384 $term = 1;
2385 if ($term = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
2386 $membershipTypeTerms[$id] = ($term > 1) ? $term : 1;
2387 }
2388 else {
2389 $membershipTypeTerms[$id] = 1;
2390 }
2391 }
2392 }
2393 $membershipParams['selectMembership'] = $membershipTypeIds;
2394 $membershipParams['financial_type_id'] = $contributionTypeID;
2395 $membershipParams['types_terms'] = $membershipTypeTerms;
2396 }
2397 if (!empty($membershipParams['selectMembership'])) {
2398 // CRM-12233
2399 $membershipLineItems = array();
2400 if ($this->_separateMembershipPayment && $this->_values['amount_block_is_active']) {
2401 foreach ($this->_values['fee'] as $key => $feeValues) {
2402 if ($feeValues['name'] == 'membership_amount') {
2403 $fieldId = $this->_params['price_' . $key];
2404 $membershipLineItems[$this->_priceSetId][$fieldId] = $this->_lineItem[$this->_priceSetId][$fieldId];
2405 unset($this->_lineItem[$this->_priceSetId][$fieldId]);
2406 break;
2407 }
2408 }
2409 }
2410 try {
2411 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
2412 }
2413 catch (CRM_Core_Exception $e) {
2414 CRM_Core_Session::singleton()->setStatus($e->getMessage());
2415 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2416 }
2417 if (!$this->_amount > 0.0 || !$membershipParams['amount']) {
2418 // we need to explicitly create a CMS user in case of free memberships
2419 // since it is done under processConfirm for paid memberships
2420 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams,
2421 $membershipParams['cms_contactID'],
2422 'email-' . $this->_bltID
2423 );
2424 }
2425 }
2426 }
2427
2428 }