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