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