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