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