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