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