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