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