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