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