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