Merge pull request #5234 from pratikshad/FixedWebtest4
[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-2014 |
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-2014
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'] = $expressParams['payer'];
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 }
509 else {
510 $this->assign('membershipBlock', FALSE);
511 }
512 }
513 $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE);
514 $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE);
515
516 if (!empty($params['hidden_onbehalf_profile'])) {
517 $ufJoinParams = array(
518 'module' => 'onBehalf',
519 'entity_table' => 'civicrm_contribution_page',
520 'entity_id' => $this->_id,
521 );
522 $OnBehalfProfile = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
523 $profileId = $OnBehalfProfile[0];
524
525 $fieldTypes = array('Contact', 'Organization');
526 $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
527 $fieldTypes = array_merge($fieldTypes, $contactSubType);
528 if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
529 $fieldTypes = array_merge($fieldTypes, array('Membership'));
530 }
531 else {
532 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
533 }
534
535 $this->buildCustom($profileId, 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
536 }
537
538 $this->_separateMembershipPayment = $this->get('separateMembershipPayment');
539 $this->assign('is_separate_payment', $this->_separateMembershipPayment);
540 if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
541 $this->assign('lineItem', $this->_lineItem);
542 }
543 else {
544 $this->assign('is_quick_config', 1);
545 $this->_params['is_quick_config'] = 1;
546 }
547 $this->assign('priceSetID', $this->_priceSetId);
548 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
549 if ($this->_paymentProcessor &&
550 $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('Google_Checkout', $paymentProcessorType)
551 && !$this->_params['is_pay_later'] && !($this->_amount == 0)
552 ) {
553 $this->_checkoutButtonName = $this->getButtonName('next', 'checkout');
554 $this->add('image',
555 $this->_checkoutButtonName,
556 $this->_paymentProcessor['url_button'],
557 array('class' => 'crm-form-submit')
558 );
559
560 $this->addButtons(array(
561 array(
562 'type' => 'back',
563 'name' => ts('Go Back'),
564 ),
565 )
566 );
567 }
568 else {
569 if ($this->_contributeMode == 'notify' || !$this->_values['is_monetary'] ||
570 $this->_amount <= 0.0 || $this->_params['is_pay_later'] ||
571 ($this->_separateMembershipPayment && $this->_amount <= 0.0)
572 ) {
573 $contribButton = ts('Continue');
574 $this->assign('button', ts('Continue'));
575 }
576 else {
577 $contribButton = ts('Make Contribution');
578 $this->assign('button', ts('Make Contribution'));
579 }
580 $this->addButtons(array(
581 array(
582 'type' => 'next',
583 'name' => $contribButton,
584 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
585 'isDefault' => TRUE,
586 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
587 ),
588 array(
589 'type' => 'back',
590 'name' => ts('Go Back'),
591 ),
592 )
593 );
594 }
595
596 $defaults = array();
597 $fields = array_fill_keys(array_keys($this->_fields), 1);
598 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
599
600 $contact = $this->_params;
601 foreach ($fields as $name => $dontCare) {
602 // Recursively set defaults for nested fields
603 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' || $name == 'honor')) {
604 foreach ($contact[$name] as $fieldName => $fieldValue) {
605 if (is_array($fieldValue) && !in_array($this->_fields[$name][$fieldName]['html_type'], array(
606 'Multi-Select',
607 'AdvMulti-Select',
608 ))
609 ) {
610 foreach ($fieldValue as $key => $value) {
611 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
612 }
613 }
614 else {
615 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
616 }
617 }
618 }
619 elseif (isset($contact[$name])) {
620 $defaults[$name] = $contact[$name];
621 if (substr($name, 0, 7) == 'custom_') {
622 $timeField = "{$name}_time";
623 if (isset($contact[$timeField])) {
624 $defaults[$timeField] = $contact[$timeField];
625 }
626 if (isset($contact["{$name}_id"])) {
627 $defaults["{$name}_id"] = $contact["{$name}_id"];
628 }
629 }
630 elseif (in_array($name, array(
631 'addressee',
632 'email_greeting',
633 'postal_greeting',
634 )) && !empty($contact[$name . '_custom'])
635 ) {
636 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
637 }
638 }
639 }
640
641 $this->assign('useForMember', $this->get('useForMember'));
642
643 $this->setDefaults($defaults);
644
645 $this->freeze();
646 }
647
648 /**
649 * Overwrite action, since we are only showing elements in frozen mode
650 * no help display needed
651 *
652 * @return int
653 */
654 public function getAction() {
655 if ($this->_action & CRM_Core_Action::PREVIEW) {
656 return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
657 }
658 else {
659 return CRM_Core_Action::VIEW;
660 }
661 }
662
663 /**
664 * Set default values for the form.
665 *
666 * Note that in edit/view mode
667 * the default values are retrieved from the database
668 *
669 * @return void
670 */
671 public function setDefaultValues() {
672 }
673
674 /**
675 * Process the form.
676 *
677 * @return void
678 */
679 public function postProcess() {
680 $contactID = $this->getContactID();
681 $isPayLater = $this->_params['is_pay_later'];
682 if ($this->_params['payment_processor'] == 0) {
683 $this->_params['is_pay_later'] = $isPayLater = TRUE;
684 }
685 // add a description field at the very beginning
686 $this->_params['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
687
688 // also add accounting code
689 $this->_params['accountingCode'] = CRM_Utils_Array::value('accountingCode',
690 $this->_values
691 );
692
693 // fix currency ID
694 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
695
696 //carry payment processor id.
697 if ($paymentProcessorId = CRM_Utils_Array::value('id', $this->_paymentProcessor)) {
698 $this->_params['payment_processor_id'] = $paymentProcessorId;
699 }
700 if (!empty($params['image_URL'])) {
701 CRM_Contact_BAO_Contact::processImageParams($params);
702 }
703 $premiumParams = $membershipParams = $params = $this->_params;
704 $fields = array('email-Primary' => 1);
705
706 // get the add to groups
707 $addToGroups = array();
708
709 // now set the values for the billing location.
710 foreach ($this->_fields as $name => $value) {
711 $fields[$name] = 1;
712
713 // get the add to groups for uf fields
714 if (!empty($value['add_to_group_id'])) {
715 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
716 }
717 }
718
719 if (!array_key_exists('first_name', $fields)) {
720 $nameFields = array('first_name', 'middle_name', 'last_name');
721 foreach ($nameFields as $name) {
722 $fields[$name] = 1;
723 if (array_key_exists("billing_$name", $params)) {
724 $params[$name] = $params["billing_{$name}"];
725 $params['preserveDBName'] = TRUE;
726 }
727 }
728 }
729
730 // billing email address
731 $fields["email-{$this->_bltID}"] = 1;
732
733 //unset the billing parameters if it is pay later mode
734 //to avoid creation of billing location
735 if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater) {
736 $billingFields = array(
737 'billing_first_name',
738 'billing_middle_name',
739 'billing_last_name',
740 "billing_street_address-{$this->_bltID}",
741 "billing_city-{$this->_bltID}",
742 "billing_state_province-{$this->_bltID}",
743 "billing_state_province_id-{$this->_bltID}",
744 "billing_postal_code-{$this->_bltID}",
745 "billing_country-{$this->_bltID}",
746 "billing_country_id-{$this->_bltID}",
747 );
748
749 foreach ($billingFields as $value) {
750 unset($params[$value]);
751 unset($fields[$value]);
752 }
753 }
754
755 // if onbehalf-of-organization contribution, take out
756 // organization params in a separate variable, to make sure
757 // normal behavior is continued. And use that variable to
758 // process on-behalf-of functionality.
759 if (!empty($this->_params['hidden_onbehalf_profile'])) {
760 $behalfOrganization = array();
761 $orgFields = array('organization_name', 'organization_id', 'org_option');
762 foreach ($orgFields as $fld) {
763 if (array_key_exists($fld, $params)) {
764 $behalfOrganization[$fld] = $params[$fld];
765 unset($params[$fld]);
766 }
767 }
768
769 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
770 foreach ($params['onbehalf'] as $fld => $values) {
771 if (strstr($fld, 'custom_')) {
772 $behalfOrganization[$fld] = $values;
773 }
774 elseif (!(strstr($fld, '-'))) {
775 if (in_array($fld, array(
776 'contribution_campaign_id',
777 'member_campaign_id',
778 ))) {
779 $fld = 'campaign_id';
780 }
781 else {
782 $behalfOrganization[$fld] = $values;
783 }
784 $this->_params[$fld] = $values;
785 }
786 }
787 }
788
789 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
790 foreach ($params['onbehalf_location'] as $block => $vals) {
791 //fix for custom data (of type checkbox, multi-select)
792 if (substr($block, 0, 7) == 'custom_') {
793 continue;
794 }
795 // fix the index of block elements
796 if (is_array($vals)) {
797 foreach ($vals as $key => $val) {
798 //dont adjust the index of address block as
799 //it's index is WRT to location type
800 $newKey = ($block == 'address') ? $key : ++$key;
801 $behalfOrganization[$block][$newKey] = $val;
802 }
803 }
804 }
805 unset($params['onbehalf_location']);
806 }
807 if (!empty($params['onbehalf[image_URL]'])) {
808 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
809 }
810 }
811
812 // check for profile double opt-in and get groups to be subscribed
813 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
814
815 // since we are directly adding contact to group lets unset it from mailing
816 if (!empty($addToGroups)) {
817 foreach ($addToGroups as $groupId) {
818 if (isset($subscribeGroupIds[$groupId])) {
819 unset($subscribeGroupIds[$groupId]);
820 }
821 }
822 }
823
824 foreach ($addToGroups as $k) {
825 if (array_key_exists($k, $subscribeGroupIds)) {
826 unset($addToGroups[$k]);
827 }
828 }
829
830 if (empty($contactID)) {
831 $dupeParams = $params;
832 if (!empty($dupeParams['onbehalf'])) {
833 unset($dupeParams['onbehalf']);
834 }
835 if (!empty($dupeParams['honor'])) {
836 unset($dupeParams['honor']);
837 }
838
839 $dedupeParams = CRM_Dedupe_Finder::formatParams($dupeParams, 'Individual');
840 $dedupeParams['check_permission'] = FALSE;
841 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
842
843 // if we find more than one contact, use the first one
844 $contactID = CRM_Utils_Array::value(0, $ids);
845
846 // Fetch default greeting id's if creating a contact
847 if (!$contactID) {
848 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
849 if (!isset($params[$greeting])) {
850 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
851 }
852 }
853 }
854 $contactType = NULL;
855 }
856 else {
857 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
858 }
859 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
860 $params,
861 $fields,
862 $contactID,
863 $addToGroups,
864 NULL,
865 $contactType,
866 TRUE
867 );
868
869 // Make the contact ID associated with the contribution available at the Class level.
870 // Also make available to the session.
871 //@todo consider handling this in $this->getContactID();
872 $this->set('contactID', $contactID);
873 $this->_contactID = $contactID;
874
875 //get email primary first if exist
876 $subscriptionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
877 if (!$subscriptionEmail['email']) {
878 $subscriptionEmail['email'] = CRM_Utils_Array::value("email-{$this->_bltID}", $params);
879 }
880 // subscribing contact to groups
881 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
882 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
883 }
884
885 // If onbehalf-of-organization contribution / signup, add organization
886 // and it's location.
887 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
888 $ufFields = array();
889 foreach ($this->_fields['onbehalf'] as $name => $value) {
890 $ufFields[$name] = 1;
891 }
892 self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values,
893 $this->_params, $ufFields
894 );
895 }
896 elseif (!empty($this->_membershipContactID) && $contactID != $this->_membershipContactID) {
897 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
898 // store current user id as related contact for later use for mailing / activity..
899 $this->_values['related_contact'] = $contactID;
900 $this->_params['related_contact'] = $contactID;
901 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
902 $contactID = $this->_membershipContactID;
903 }
904
905 // lets store the contactID in the session
906 // for things like tell a friend
907 $session = CRM_Core_Session::singleton();
908 if (!$session->get('userID')) {
909 $session->set('transaction.userID', $contactID);
910 }
911 else {
912 $session->set('transaction.userID', NULL);
913 }
914
915 $this->_useForMember = $this->get('useForMember');
916
917 // store the fact that this is a membership and membership type is selected
918 $processMembership = FALSE;
919 if ((!empty($membershipParams['selectMembership']) &&
920 $membershipParams['selectMembership'] != 'no_thanks'
921 ) ||
922 $this->_useForMember
923 ) {
924 $processMembership = TRUE;
925
926 if (!$this->_useForMember) {
927 $this->assign('membership_assign', TRUE);
928 $this->set('membershipTypeID', $this->_params['selectMembership']);
929 }
930
931 if ($this->_action & CRM_Core_Action::PREVIEW) {
932 $membershipParams['is_test'] = 1;
933 }
934 if ($this->_params['is_pay_later']) {
935 $membershipParams['is_pay_later'] = 1;
936 }
937 }
938
939 if ($processMembership) {
940 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE);
941
942 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
943 if (isset($this->_params['related_contact'])) {
944 $membershipParams['cms_contactID'] = $this->_params['related_contact'];
945 }
946 else {
947 $membershipParams['cms_contactID'] = $contactID;
948 }
949
950 //inherit campaign from contribution page.
951 if (!array_key_exists('campaign_id', $membershipParams)) {
952 $membershipParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
953 }
954
955 if (!empty($membershipParams['onbehalf']) &&
956 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
957 ) {
958 $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
959 }
960
961 $customFieldsFormatted = $fieldTypes = array();
962 if (!empty($membershipParams['onbehalf']) &&
963 is_array($membershipParams['onbehalf'])
964 ) {
965 foreach ($membershipParams['onbehalf'] as $key => $value) {
966 if (strstr($key, 'custom_')) {
967 $customFieldId = explode('_', $key);
968 CRM_Core_BAO_CustomField::formatCustomField(
969 $customFieldId[1],
970 $customFieldsFormatted,
971 $value,
972 'Membership',
973 NULL,
974 $contactID
975 );
976 }
977 }
978 $fieldTypes = array('Contact', 'Organization', 'Membership');
979 }
980
981 $priceFieldIds = $this->get('memberPriceFieldIDS');
982
983 if (!empty($priceFieldIds)) {
984 $contributionTypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
985 unset($priceFieldIds['id']);
986 $membershipTypeIds = array();
987 $membershipTypeTerms = array();
988 foreach ($priceFieldIds as $priceFieldId) {
989 if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
990 $membershipTypeIds[] = $id;
991 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
992 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
993 $term = 1;
994 if ($term = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
995 $membershipTypeTerms[$id] = ($term > 1) ? $term : 1;
996 }
997 else {
998 $membershipTypeTerms[$id] = 1;
999 }
1000 }
1001 }
1002 $membershipParams['selectMembership'] = $membershipTypeIds;
1003 $membershipParams['financial_type_id'] = $contributionTypeID;
1004 $membershipParams['types_terms'] = $membershipTypeTerms;
1005 }
1006 if (!empty($membershipParams['selectMembership'])) {
1007 // CRM-12233
1008 $membershipLineItems = array();
1009 if ($this->_separateMembershipPayment && $this->_values['amount_block_is_active']) {
1010 foreach ($this->_values['fee'] as $key => $feeValues) {
1011 if ($feeValues['name'] == 'membership_amount') {
1012 $fieldId = $this->_params['price_' . $key];
1013 $membershipLineItems[$this->_priceSetId][$fieldId] = $this->_lineItem[$this->_priceSetId][$fieldId];
1014 unset($this->_lineItem[$this->_priceSetId][$fieldId]);
1015 break;
1016 }
1017 }
1018 }
1019 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
1020 if (!$this->_amount > 0.0 || !$membershipParams['amount']) {
1021 // we need to explicitly create a CMS user in case of free memberships
1022 // since it is done under processConfirm for paid memberships
1023 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams,
1024 $membershipParams['cms_contactID'],
1025 'email-' . $this->_bltID
1026 );
1027 }
1028 }
1029 }
1030 else {
1031 // at this point we've created a contact and stored its address etc
1032 // all the payment processors expect the name and address to be in the
1033 // so we copy stuff over to first_name etc.
1034 $paymentParams = $this->_params;
1035 $contributionTypeId = $this->_values['financial_type_id'];
1036
1037 $fieldTypes = array();
1038 if (!empty($paymentParams['onbehalf']) &&
1039 is_array($paymentParams['onbehalf'])
1040 ) {
1041 foreach ($paymentParams['onbehalf'] as $key => $value) {
1042 if (strstr($key, 'custom_')) {
1043 $this->_params[$key] = $value;
1044 }
1045 }
1046 $fieldTypes = array('Contact', 'Organization', 'Contribution');
1047 }
1048 $financialTypeID = $this->wrangleFinancialTypeID($contributionTypeId);
1049
1050 CRM_Contribute_BAO_Contribution_Utils::processConfirm($this, $paymentParams,
1051 $premiumParams, $contactID,
1052 $financialTypeID,
1053 'contribution',
1054 $fieldTypes,
1055 ($this->_mode == 'test') ? 1 : 0,
1056 $isPayLater
1057 );
1058 }
1059 }
1060
1061 /**
1062 * Wrangle financial type ID.
1063 *
1064 * 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
1065 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
1066 *
1067 * Comments from previous refactor indicate doubt as to what was going on.
1068 *
1069 * @param int $contributionTypeId
1070 *
1071 * @return null|string
1072 */
1073 public function wrangleFinancialTypeID($contributionTypeId) {
1074 if (isset($paymentParams['financial_type'])) {
1075 $contributionTypeId = $paymentParams['financial_type'];
1076 }
1077 elseif (!empty($this->_values['pledge_id'])) {
1078 $contributionTypeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
1079 $this->_values['pledge_id'],
1080 'financial_type_id'
1081 );
1082 }
1083 return $contributionTypeId;
1084 }
1085
1086 /**
1087 * Process the form.
1088 *
1089 * @param array $premiumParams
1090 * @param $contribution
1091 */
1092 public function postProcessPremium($premiumParams, $contribution) {
1093 $hour = $minute = $second = 0;
1094 // assigning Premium information to receipt tpl
1095 $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
1096 if ($selectProduct &&
1097 $selectProduct != 'no_thanks'
1098 ) {
1099 $startDate = $endDate = "";
1100 $this->assign('selectPremium', TRUE);
1101 $productDAO = new CRM_Contribute_DAO_Product();
1102 $productDAO->id = $selectProduct;
1103 $productDAO->find(TRUE);
1104 $this->assign('product_name', $productDAO->name);
1105 $this->assign('price', $productDAO->price);
1106 $this->assign('sku', $productDAO->sku);
1107 $this->assign('option', CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams));
1108
1109 $periodType = $productDAO->period_type;
1110
1111 if ($periodType) {
1112 $fixed_period_start_day = $productDAO->fixed_period_start_day;
1113 $duration_unit = $productDAO->duration_unit;
1114 $duration_interval = $productDAO->duration_interval;
1115 if ($periodType == 'rolling') {
1116 $startDate = date('Y-m-d');
1117 }
1118 elseif ($periodType == 'fixed') {
1119 if ($fixed_period_start_day) {
1120 $date = explode('-', date('Y-m-d'));
1121 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
1122 $day = substr($fixed_period_start_day, -2) . "<br/>";
1123 $year = $date[0];
1124 $startDate = $year . '-' . $month . '-' . $day;
1125 }
1126 else {
1127 $startDate = date('Y-m-d');
1128 }
1129 }
1130
1131 $date = explode('-', $startDate);
1132 $year = $date[0];
1133 $month = $date[1];
1134 $day = $date[2];
1135
1136 switch ($duration_unit) {
1137 case 'year':
1138 $year = $year + $duration_interval;
1139 break;
1140
1141 case 'month':
1142 $month = $month + $duration_interval;
1143 break;
1144
1145 case 'day':
1146 $day = $day + $duration_interval;
1147 break;
1148
1149 case 'week':
1150 $day = $day + ($duration_interval * 7);
1151 }
1152 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
1153 $this->assign('start_date', $startDate);
1154 $this->assign('end_date', $endDate);
1155 }
1156
1157 $dao = new CRM_Contribute_DAO_Premium();
1158 $dao->entity_table = 'civicrm_contribution_page';
1159 $dao->entity_id = $this->_id;
1160 $dao->find(TRUE);
1161 $this->assign('contact_phone', $dao->premiums_contact_phone);
1162 $this->assign('contact_email', $dao->premiums_contact_email);
1163
1164 //create Premium record
1165 $params = array(
1166 'product_id' => $premiumParams['selectProduct'],
1167 'contribution_id' => $contribution->id,
1168 'product_option' => CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams),
1169 'quantity' => 1,
1170 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
1171 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
1172 );
1173 if (!empty($premiumParams['selectProduct'])) {
1174 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
1175 $daoPremiumsProduct->product_id = $premiumParams['selectProduct'];
1176 $daoPremiumsProduct->premiums_id = $dao->id;
1177 $daoPremiumsProduct->find(TRUE);
1178 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id;
1179 }
1180 //Fixed For CRM-3901
1181 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1182 $daoContrProd->contribution_id = $contribution->id;
1183 if ($daoContrProd->find(TRUE)) {
1184 $params['id'] = $daoContrProd->id;
1185 }
1186
1187 CRM_Contribute_BAO_Contribution::addPremium($params);
1188 if ($productDAO->cost && !empty($params['financial_type_id'])) {
1189 $trxnParams = array(
1190 'cost' => $productDAO->cost,
1191 'currency' => $productDAO->currency,
1192 'financial_type_id' => $params['financial_type_id'],
1193 'contributionId' => $contribution->id,
1194 );
1195 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
1196 }
1197 }
1198 elseif ($selectProduct == 'no_thanks') {
1199 //Fixed For CRM-3901
1200 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1201 $daoContrProd->contribution_id = $contribution->id;
1202 if ($daoContrProd->find(TRUE)) {
1203 $daoContrProd->delete();
1204 }
1205 }
1206 }
1207
1208 /**
1209 * Process the contribution.
1210 *
1211 * @param CRM_Core_Form $form
1212 * @param array $params
1213 * @param array $result
1214 * @param int $contactID
1215 * @param CRM_Financial_DAO_FinancialType $financialType
1216 * @param bool $pending
1217 * @param bool $online
1218 *
1219 * @param bool $isTest
1220 * @param array $lineItems
1221 *
1222 * @throws Exception
1223 * @return CRM_Contribute_DAO_Contribution
1224 */
1225 public static function processContribution(
1226 &$form,
1227 $params,
1228 $result,
1229 $contactID,
1230 $financialType,
1231 $pending,
1232 $online,
1233 $isTest,
1234 $lineItems
1235 ) {
1236 $transaction = new CRM_Core_Transaction();
1237 $contribSoftContactId = $addressID = NULL;
1238
1239 // add these values for the recurringContrib function ,CRM-10188
1240 $params['financial_type_id'] = $financialType->id;
1241
1242 //create an contribution address
1243 if ($form->_contributeMode != 'notify' && empty($params['is_pay_later']) && !empty($form->_values['is_monetary'])) {
1244 $addressID = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
1245 }
1246
1247 //@todo - this is being set from the form to resolve CRM-10188 - an
1248 // eNotice caused by it not being set @ the front end
1249 // however, we then get it being over-written with null for backend contributions
1250 // a better fix would be to set the values in the respective forms rather than require
1251 // a function being shared by two forms to deal with their respective values
1252 // moving it to the BAO & not taking the $form as a param would make sense here.
1253 if (!isset($params['is_email_receipt']) && !empty($form->_values['is_email_receipt'])) {
1254 $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $form->_values);
1255 }
1256 $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType, $online);
1257
1258 // CRM-11885
1259 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
1260 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
1261 $nonDeductibleAmount = $params['non_deductible_amount'];
1262 }
1263 // if non_deductible_amount does NOT exist - then calculate it depending on:
1264 // $contributionType->is_deductible and whether there is a product (premium).
1265 else {
1266 //if ($contributionType->is_deductible && $deductibleMode) {
1267 if ($financialType->is_deductible) {
1268 if ($online && isset($params['selectProduct'])) {
1269 $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
1270 }
1271 if (!$online && isset($params['product_name'][0])) {
1272 $selectProduct = $params['product_name'][0];
1273 }
1274 // if there is a product - compare the value to the contribution amount
1275 if (isset($selectProduct) &&
1276 $selectProduct != 'no_thanks'
1277 ) {
1278 $productDAO = new CRM_Contribute_DAO_Product();
1279 $productDAO->id = $selectProduct;
1280 $productDAO->find(TRUE);
1281 // product value exceeds contribution amount
1282 if ($params['amount'] < $productDAO->price) {
1283 $nonDeductibleAmount = $params['amount'];
1284 }
1285 // product value does NOT exceed contribution amount
1286 else {
1287 $nonDeductibleAmount = $productDAO->price;
1288 }
1289 }
1290 // contribution is deductible - but there is no product
1291 else {
1292 $nonDeductibleAmount = '0.00';
1293 }
1294 }
1295 // contribution is NOT deductible
1296 else {
1297 $nonDeductibleAmount = $params['amount'];
1298 }
1299 }
1300
1301 $now = date('YmdHis');
1302 $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
1303 if (!empty($form->_values['is_email_receipt'])) {
1304 $receiptDate = $now;
1305 }
1306
1307 //get the contrib page id.
1308 $contributionPageId = NULL;
1309 if ($online) {
1310 $contributionPageId = $form->_id;
1311 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1312 if (!array_key_exists('campaign_id', $params)) {
1313 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1314 }
1315 }
1316 else {
1317 //also for offline we do support - CRM-7290
1318 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
1319 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1320 }
1321
1322 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1323 if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
1324 // if its due to pcp
1325 if (!empty($params['pcp_made_through_id'])) {
1326 $contribSoftContactId = CRM_Core_DAO::getFieldValue(
1327 'CRM_PCP_DAO_PCP',
1328 $params['pcp_made_through_id'],
1329 'contact_id'
1330 );
1331 }
1332 else {
1333 $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
1334 }
1335
1336 // Pass these details onto with the contribution to make them
1337 // available at hook_post_process, CRM-8908
1338 $params['soft_credit_to'] = $contribSoftContactId;
1339 }
1340
1341 if (isset($params['amount'])) {
1342 $isMonetary = NULL;
1343 if (!empty($form->_values['is_monetary'])) {
1344 $isMonetary = $form->_values['is_monetary'];
1345 }
1346 $contribParams = self::getContributionParams(
1347 $params, $contactID, $financialType->id, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending, $result, $receiptDate,
1348 $recurringContributionID, $isTest, $addressID, $contribSoftContactId, $lineItems
1349 );
1350 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
1351
1352 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
1353 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1354 if ($invoicing) {
1355 $totalTaxAmount = 0;
1356 $dataArray = array();
1357 foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
1358 foreach ($lineItemValue as $key => $value) {
1359 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1360 if (isset($dataArray[$value['tax_rate']])) {
1361 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1362 }
1363 else {
1364 $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1365 }
1366 }
1367 }
1368 }
1369 $smarty = CRM_Core_Smarty::singleton();
1370 $smarty->assign('dataArray', $dataArray);
1371 $smarty->assign('totalTaxAmount', $params['tax_amount']);
1372 }
1373 if (is_a($contribution, 'CRM_Core_Error')) {
1374 $message = CRM_Core_Error::getMessages($contribution);
1375 CRM_Core_Error::fatal($message);
1376 }
1377
1378 // lets store it in the form variable so postProcess hook can get to this and use it
1379 $form->_contributionID = $contribution->id;
1380 }
1381
1382 //CRM-13981, processing honor contact into soft-credit contribution
1383 CRM_Contact_Form_ProfileContact::postProcess($form);
1384
1385 // process soft credit / pcp pages
1386 CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
1387
1388 //handle pledge stuff.
1389 if (empty($form->_params['separate_membership_payment']) && !empty($form->_values['pledge_block_id']) &&
1390 (!empty($form->_params['is_pledge']) || !empty($form->_values['pledge_id']))
1391 ) {
1392
1393 if (!empty($form->_values['pledge_id'])) {
1394
1395 //when user doing pledge payments.
1396 //update the schedule when payment(s) are made
1397 foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
1398 $scheduledAmount = CRM_Core_DAO::getFieldValue(
1399 'CRM_Pledge_DAO_PledgePayment',
1400 $paymentId,
1401 'scheduled_amount',
1402 'id'
1403 );
1404
1405 $pledgePaymentParams = array(
1406 'id' => $paymentId,
1407 'contribution_id' => $contribution->id,
1408 'status_id' => $contribution->contribution_status_id,
1409 'actual_amount' => $scheduledAmount,
1410 );
1411
1412 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
1413 }
1414
1415 //update pledge status according to the new payment statuses
1416 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']);
1417 }
1418 else {
1419 //when user creating pledge record.
1420 $pledgeParams = array();
1421 $pledgeParams['contact_id'] = $contribution->contact_id;
1422 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
1423 $pledgeParams['contribution_id'] = $contribution->id;
1424 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
1425 $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
1426 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
1427 $pledgeParams['installments'] = $params['pledge_installments'];
1428 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
1429 if ($pledgeParams['frequency_unit'] == 'month') {
1430 $pledgeParams['frequency_day'] = intval(date("d"));
1431 }
1432 else {
1433 $pledgeParams['frequency_day'] = 1;
1434 }
1435 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
1436 $pledgeParams['status_id'] = $contribution->contribution_status_id;
1437 $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
1438 $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
1439 $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
1440 $pledgeParams['is_test'] = $contribution->is_test;
1441 $pledgeParams['acknowledge_date'] = date('Ymd');
1442 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
1443
1444 //inherit campaign from contirb page.
1445 $pledgeParams['campaign_id'] = $campaignId;
1446
1447 $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
1448
1449 $form->_params['pledge_id'] = $pledge->id;
1450
1451 //send acknowledgment email. only when pledge is created
1452 if ($pledge->id) {
1453 //build params to send acknowledgment.
1454 $pledgeParams['id'] = $pledge->id;
1455 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
1456 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
1457
1458 //scheduled amount will be same as installment_amount.
1459 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
1460
1461 //get total pledge amount.
1462 $pledgeParams['total_pledge_amount'] = $pledge->amount;
1463
1464 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
1465 }
1466 }
1467 }
1468
1469 if ($online && $contribution) {
1470 CRM_Core_BAO_CustomValueTable::postProcess($form->_params,
1471 CRM_Core_DAO::$_nullArray,
1472 'civicrm_contribution',
1473 $contribution->id,
1474 'Contribution'
1475 );
1476 }
1477 elseif ($contribution) {
1478 //handle custom data.
1479 $params['contribution_id'] = $contribution->id;
1480 if (!empty($params['custom']) &&
1481 is_array($params['custom']) &&
1482 !is_a($contribution, 'CRM_Core_Error')
1483 ) {
1484 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
1485 }
1486 }
1487 // Save note
1488 if ($contribution && !empty($params['contribution_note'])) {
1489 $noteParams = array(
1490 'entity_table' => 'civicrm_contribution',
1491 'note' => $params['contribution_note'],
1492 'entity_id' => $contribution->id,
1493 'contact_id' => $contribution->contact_id,
1494 'modified_date' => date('Ymd'),
1495 );
1496
1497 CRM_Core_BAO_Note::add($noteParams, array());
1498 }
1499
1500 if (isset($params['related_contact'])) {
1501 $contactID = $params['related_contact'];
1502 }
1503 elseif (isset($params['cms_contactID'])) {
1504 $contactID = $params['cms_contactID'];
1505 }
1506
1507 //create contribution activity w/ individual and target
1508 //activity w/ organisation contact id when onbelf, CRM-4027
1509 $targetContactID = NULL;
1510 if (!empty($params['hidden_onbehalf_profile'])) {
1511 $targetContactID = $contribution->contact_id;
1512 $contribution->contact_id = $contactID;
1513 }
1514
1515 // create an activity record
1516 if ($contribution) {
1517 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
1518 }
1519
1520 $transaction->commit();
1521 // CRM-13074 - create the CMSUser after the transaction is completed as it
1522 // is not appropriate to delete a valid contribution if a user create problem occurs
1523 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params,
1524 $contactID,
1525 'email-' . $form->_bltID
1526 );
1527 return $contribution;
1528 }
1529
1530 /**
1531 * Create the recurring contribution record.
1532 *
1533 * @param CRM_Core_Form $form
1534 * @param array $params
1535 * @param int $contactID
1536 * @param string $contributionType
1537 * @param bool $online
1538 *
1539 * @return mixed
1540 */
1541 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1542 // return if this page is not set for recurring
1543 // or the user has not chosen the recurring option
1544
1545 //this is online case validation.
1546 if ((empty($form->_values['is_recur']) && $online) || empty($params['is_recur'])) {
1547 return NULL;
1548 }
1549
1550 $recurParams = array('contact_id' => $contactID);
1551 $recurParams['amount'] = CRM_Utils_Array::value('amount', $params);
1552 $recurParams['auto_renew'] = CRM_Utils_Array::value('auto_renew', $params);
1553 $recurParams['frequency_unit'] = CRM_Utils_Array::value('frequency_unit', $params);
1554 $recurParams['frequency_interval'] = CRM_Utils_Array::value('frequency_interval', $params);
1555 $recurParams['installments'] = CRM_Utils_Array::value('installments', $params);
1556 $recurParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params);
1557
1558 // CRM-14354: For an auto-renewing membership with an additional contribution,
1559 // if separate payments is not enabled, make sure only the membership fee recurs
1560 if (!empty($form->_membershipBlock)
1561 && $form->_membershipBlock['is_separate_payment'] === '0'
1562 && isset($params['selectMembership'])
1563 && $form->_values['is_allow_other_amount'] == '1'
1564 ) {
1565 $recurParams['amount'] = $form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'];
1566 }
1567
1568 $recurParams['is_test'] = 0;
1569 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1570 (isset($form->_mode) && ($form->_mode == 'test'))
1571 ) {
1572 $recurParams['is_test'] = 1;
1573 }
1574
1575 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1576 if (!empty($params['receive_date'])) {
1577 $recurParams['start_date'] = $params['receive_date'];
1578 }
1579 $recurParams['invoice_id'] = CRM_Utils_Array::value('invoiceID', $params);
1580 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1581 $recurParams['payment_processor_id'] = CRM_Utils_Array::value('payment_processor_id', $params);
1582 $recurParams['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params);
1583 // we need to add a unique trxn_id to avoid a unique key error
1584 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1585 $recurParams['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params, $params['invoiceID']);
1586 $recurParams['financial_type_id'] = $contributionType->id;
1587
1588 if (!$online || $form->_values['is_monetary']) {
1589 $recurParams['payment_instrument_id'] = 1;
1590 }
1591
1592 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1593 if ($online) {
1594 if (!array_key_exists('campaign_id', $params)) {
1595 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1596 }
1597 }
1598 $recurParams['campaign_id'] = $campaignId;
1599
1600 $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
1601 if (is_a($recurring, 'CRM_Core_Error')) {
1602 CRM_Core_Error::displaySessionError($recurring);
1603 $urlString = 'civicrm/contribute/transact';
1604 $urlParams = '_qf_Main_display=true';
1605 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1606 $urlString = 'civicrm/contact/view/contribution';
1607 $urlParams = "action=add&cid={$form->_contactID}";
1608 if ($form->_mode) {
1609 $urlParams .= "&mode={$form->_mode}";
1610 }
1611 }
1612 CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
1613 }
1614
1615 return $recurring->id;
1616 }
1617
1618 /**
1619 * Add on behalf of organization and it's location.
1620 *
1621 * @param array $behalfOrganization
1622 * array of organization info.
1623 * @param int $contactID
1624 * individual contact id. One.
1625 * who is doing the process of signup / contribution.
1626 *
1627 * @param array $values
1628 * form values array.
1629 * @param array $params
1630 * @param null $fields
1631 */
1632 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1633 $isCurrentEmployer = FALSE;
1634 $dupeIDs = array();
1635 $orgID = NULL;
1636 if (!empty($behalfOrganization['organization_id']) && empty($behalfOrganization['org_option'])) {
1637 $orgID = $behalfOrganization['organization_id'];
1638 unset($behalfOrganization['organization_id']);
1639 $isCurrentEmployer = TRUE;
1640 }
1641
1642 // formalities for creating / editing organization.
1643 $behalfOrganization['contact_type'] = 'Organization';
1644
1645 // get the relationship type id
1646 $relType = new CRM_Contact_DAO_RelationshipType();
1647 $relType->name_a_b = 'Employee of';
1648 $relType->find(TRUE);
1649 $relTypeId = $relType->id;
1650
1651 // keep relationship params ready
1652 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1653 $relParams['is_permission_a_b'] = 1;
1654 $relParams['is_active'] = 1;
1655
1656 if (!$orgID) {
1657 // check if matching organization contact exists
1658 $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization');
1659 $dedupeParams['check_permission'] = FALSE;
1660 $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1661
1662 // CRM-6243 says to pick the first org even if more than one match
1663 if (count($dupeIDs) >= 1) {
1664 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1665 // don't allow name edit
1666 unset($behalfOrganization['organization_name']);
1667 }
1668 }
1669 else {
1670 // if found permissioned related organization, allow location edit
1671 $behalfOrganization['contact_id'] = $orgID;
1672 // don't allow name edit
1673 unset($behalfOrganization['organization_name']);
1674 }
1675
1676 // handling for image url
1677 if (!empty($behalfOrganization['image_URL'])) {
1678 CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
1679 }
1680
1681 // create organization, add location
1682 $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID,
1683 NULL, NULL, 'Organization'
1684 );
1685 // create relationship
1686 $relParams['contact_check'][$orgID] = 1;
1687 $cid = array('contact' => $contactID);
1688 CRM_Contact_BAO_Relationship::createMultiple($relParams, $cid);
1689
1690 // if multiple match - send a duplicate alert
1691 if ($dupeIDs && (count($dupeIDs) > 1)) {
1692 $values['onbehalf_dupe_alert'] = 1;
1693 // required for IPN
1694 $params['onbehalf_dupe_alert'] = 1;
1695 }
1696
1697 // make sure organization-contact-id is considered for recording
1698 // contribution/membership etc..
1699 if ($contactID != $orgID) {
1700 // take a note of contact-id, so we can send the
1701 // receipt to individual contact as well.
1702
1703 // required for mailing/template display ..etc
1704 $values['related_contact'] = $contactID;
1705 // required for IPN
1706 $params['related_contact'] = $contactID;
1707
1708 //make this employee of relationship as current
1709 //employer / employee relationship, CRM-3532
1710 if ($isCurrentEmployer &&
1711 ($orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1712 ) {
1713 $isCurrentEmployer = FALSE;
1714 }
1715
1716 if (!$isCurrentEmployer && $orgID) {
1717 //build current employer params
1718 $currentEmpParams[$contactID] = $orgID;
1719 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
1720 }
1721
1722 // contribution / signup will be done using this
1723 // organization id.
1724 $contactID = $orgID;
1725 }
1726 }
1727
1728 /**
1729 * Function used to save pcp / soft credit entry.
1730 *
1731 * This is used by contribution and also event pcps
1732 *
1733 * @param array $params
1734 * @param object $contribution
1735 * Contribution object.
1736 */
1737 public static function processPcpSoft(&$params, &$contribution) {
1738 // Add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1739 if (!empty($params['soft_credit_to'])) {
1740 $contributionSoftParams = array();
1741 foreach (array(
1742 'pcp_display_in_roll',
1743 'pcp_roll_nickname',
1744 'pcp_personal_note',
1745 'amount',
1746 ) as $val) {
1747 if (!empty($params[$val])) {
1748 $contributionSoftParams[$val] = $params[$val];
1749 }
1750 }
1751
1752 $contributionSoftParams['contact_id'] = $params['soft_credit_to'];
1753 // add contribution id
1754 $contributionSoftParams['contribution_id'] = $contribution->id;
1755 // add pcp id
1756 $contributionSoftParams['pcp_id'] = $params['pcp_made_through_id'];
1757
1758 $contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
1759
1760 $contributionSoft = CRM_Contribute_BAO_ContributionSoft::add($contributionSoftParams);
1761
1762 //Send notification to owner for PCP
1763 if ($contributionSoft->id && $contributionSoft->pcp_id) {
1764 CRM_Contribute_Form_Contribution_Confirm::pcpNotifyOwner($contribution, $contributionSoft);
1765 }
1766 }
1767 }
1768
1769 /**
1770 * Function used to send notification mail to pcp owner.
1771 *
1772 * This is used by contribution and also event PCPs.
1773 *
1774 * @param object $contribution
1775 * @param object $contributionSoft
1776 * Contribution object.
1777 */
1778 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1779 $params = array('id' => $contributionSoft->pcp_id);
1780 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1781 $ownerNotifyID = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1782
1783 if ($ownerNotifyID != CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1784 (($ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1785 CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id, 'is_notify')) ||
1786 $ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1787 $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info',
1788 "reset=1&id={$contributionSoft->pcp_id}",
1789 TRUE, NULL, FALSE, TRUE
1790 );
1791 // set email in the template here
1792 // get the billing location type
1793 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1794 $billingLocationTypeId = array_search('Billing', $locationTypes);
1795
1796 if ($billingLocationTypeId) {
1797 list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id, FALSE, $billingLocationTypeId);
1798 }
1799 // get primary location email if no email exist( for billing location).
1800 if (!$email) {
1801 list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id);
1802 }
1803 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contributionSoft->contact_id);
1804 $tplParams = array(
1805 'page_title' => $pcpInfo['title'],
1806 'receive_date' => $contribution->receive_date,
1807 'total_amount' => $contributionSoft->amount,
1808 'donors_display_name' => $donorName,
1809 'donors_email' => $email,
1810 'pcpInfoURL' => $pcpInfoURL,
1811 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll,
1812 );
1813 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
1814 $sendTemplateParams = array(
1815 'groupName' => 'msg_tpl_workflow_contribution',
1816 'valueName' => 'pcp_owner_notify',
1817 'contactId' => $contributionSoft->contact_id,
1818 'toEmail' => $ownerEmail,
1819 'toName' => $ownerName,
1820 'from' => "$domainValues[0] <$domainValues[1]>",
1821 'tplParams' => $tplParams,
1822 'PDFFilename' => 'receipt.pdf',
1823 );
1824 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
1825 }
1826 }
1827
1828 /**
1829 * Function used to se pcp related defaults / params.
1830 *
1831 * This is used by contribution and also event PCPs
1832 *
1833 * @param CRM_Core_Form $page
1834 * Form object.
1835 * @param array $params
1836 *
1837 * @return array
1838 */
1839 public static function processPcp(&$page, $params) {
1840 $params['pcp_made_through_id'] = $page->_pcpId;
1841 $page->assign('pcpBlock', TRUE);
1842 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1843 $params['pcp_roll_nickname'] = ts('Anonymous');
1844 $params['pcp_is_anonymous'] = 1;
1845 }
1846 else {
1847 $params['pcp_is_anonymous'] = 0;
1848 }
1849 foreach (array(
1850 'pcp_display_in_roll',
1851 'pcp_is_anonymous',
1852 'pcp_roll_nickname',
1853 'pcp_personal_note',
1854 ) as $val) {
1855 if (!empty($params[$val])) {
1856 $page->assign($val, $params[$val]);
1857 }
1858 }
1859
1860 return $params;
1861 }
1862
1863 /**
1864 * Process membership.
1865 *
1866 * @param array $membershipParams
1867 * @param int $contactID
1868 * @param array $customFieldsFormatted
1869 * @param array $fieldTypes
1870 * @param array $premiumParams
1871 * @param array $membershipLineItems
1872 * Line items specifically relating to memberships.
1873 * @param $isPayLater
1874 */
1875 public function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater) {
1876 try {
1877 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1878 $membershipTypes = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIDs);
1879 $membershipType = empty($membershipTypes) ? array() : reset($membershipTypes);
1880 $this->assign('membership_name', CRM_Utils_Array::value('name', $membershipType));
1881
1882 $isPaidMembership = FALSE;
1883 if ($this->_amount >= 0.0 && isset($membershipParams['amount'])) {
1884 //amount must be greater than zero for
1885 //adding contribution record to contribution table.
1886 //this condition arises when separate membership payment is
1887 //enabled and contribution amount is not selected. fix for CRM-3010
1888 $isPaidMembership = TRUE;
1889 }
1890 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id, $this->_values['amount_block_is_active']);
1891
1892 if ($this->_values['amount_block_is_active']) {
1893 $contributionTypeId = $this->_values['financial_type_id'];
1894 }
1895 else {
1896 $contributionTypeId = CRM_Utils_Array::value('financial_type_id', $membershipType, CRM_Utils_Array::value('financial_type_id', $membershipParams));
1897 }
1898
1899 CRM_Member_BAO_Membership::postProcessMembership($membershipParams, $contactID,
1900 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId, $isProcessSeparateMembershipTransaction, $contributionTypeId,
1901 $membershipLineItems, $isPayLater
1902 );
1903 $this->assign('membership_assign', TRUE);
1904 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1905 }
1906 catch (CRM_Core_Exception $e) {
1907 CRM_Core_Session::singleton()->setStatus($e->getMessage());
1908 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
1909 }
1910 }
1911
1912 /**
1913 * Are we going to do 2 financial transactions.
1914 *
1915 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1916 * contribution
1917 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1918 *
1919 * @param int $formID
1920 * @param bool $amountBlockActiveOnForm
1921 *
1922 * @return bool
1923 */
1924 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1925 $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($formID);
1926 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1927 return TRUE;
1928 }
1929 return FALSE;
1930 }
1931
1932 /**
1933 * This function sets the fields.
1934 *
1935 * - $this->_params['amount_level']
1936 * - $this->_params['selectMembership']
1937 * And under certain circumstances sets
1938 * $this->_params['amount'] = null;
1939 *
1940 * @param int $priceSetID
1941 */
1942 public function setFormAmountFields($priceSetID) {
1943 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config');
1944 $priceField = new CRM_Price_DAO_PriceField();
1945 $priceField->price_set_id = $priceSetID;
1946 $priceField->orderBy('weight');
1947 $priceField->find();
1948 $paramWeDoNotUnderstand = NULL;
1949
1950 while ($priceField->fetch()) {
1951 if ($priceField->name == "contribution_amount") {
1952 $paramWeDoNotUnderstand = $priceField->id;
1953 }
1954 if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) {
1955 if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') {
1956 $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1957 $this->_params["price_{$priceField->id}"], 'label');
1958 }
1959 if ($priceField->name == "membership_amount") {
1960 $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1961 $this->_params["price_{$priceField->id}"], 'membership_type_id');
1962 }
1963 }
1964 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1965 // as membership amount.
1966 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1967 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1968 // so we should merge them together
1969 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1970 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1971 elseif (
1972 CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock)
1973 && !empty($this->_values['fee'][$priceField->id])
1974 && ($this->_values['fee'][$priceField->id]['name'] == "other_amount")
1975 && CRM_Utils_Array::value("price_{$paramWeDoNotUnderstand}", $this->_params) < 1
1976 && empty($this->_params["price_{$priceField->id}"])
1977 ) {
1978 $this->_params['amount'] = NULL;
1979 }
1980
1981 // Fix for CRM-14375 - If we are using separate payments and "no
1982 // thank you" is selected for the additional contribution, set
1983 // contribution amount to be null, so that it will not show
1984 // contribution amount same as membership amount.
1985 //@todo - merge with section above
1986 if ($this->_membershipBlock['is_separate_payment']
1987 && !empty($this->_values['fee'][$priceField->id])
1988 && CRM_Utils_Array::value('name', $this->_values['fee'][$priceField->id]) == 'contribution_amount'
1989 && CRM_Utils_Array::value("price_{$priceField->id}", $this->_params) == '-1'
1990 ) {
1991 $this->_params['amount'] = NULL;
1992 }
1993 }
1994 }
1995
1996 /**
1997 * Submit function.
1998 *
1999 * @param array $params
2000 *
2001 * @throws CiviCRM_API3_Exception
2002 */
2003 public static function submit($params) {
2004 $form = new CRM_Contribute_Form_Contribution_Confirm();
2005 $form->_id = $params['id'];
2006 if (!empty($params['contact_id'])) {
2007 $form->_contactID = $params['contact_id'];
2008 }
2009 CRM_Contribute_BAO_ContributionPage::setValues($form->_id, $form->_values);
2010 $form->_separateMembershipPayment = CRM_Contribute_BAO_ContributionPage::getIsMembershipPayment($form->_id);
2011 //this way the mocked up controller ignores the session stuff
2012 $_SERVER['REQUEST_METHOD'] = 'GET';
2013 $form->controller = new CRM_Contribute_Controller_Contribution();
2014 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
2015 $paramsProcessedForForm = $form->_params = self::getFormParams($params['id'], $params);
2016 $form->_amount = $params['amount'];
2017 $priceSetID = $form->_params['priceSetId'] = $paramsProcessedForForm['price_set_id'];
2018 $priceFields = CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
2019 $priceSetFields = reset($priceFields);
2020 $form->_values['fee'] = $priceSetFields['fields'];
2021 $form->_priceSetId = $priceSetID;
2022 $form->setFormAmountFields($priceSetID);
2023 if (!empty($params['payment_processor'])) {
2024 $form->_paymentProcessor = civicrm_api3('payment_processor', 'getsingle', array('id' => $params['payment_processor']));
2025 if ($form->_paymentProcessor['billing_mode'] == 1) {
2026 $form->_contributeMode = 'direct';
2027 }
2028 else {
2029 $form->_contributeMode = 'notify';
2030 }
2031 }
2032 else {
2033 $form->_params['payment_processor'] = 0;
2034 }
2035 $priceFields = $priceFields[$priceSetID]['fields'];
2036 CRM_Price_BAO_PriceSet::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
2037 $form->_lineItem = array($priceSetID => $lineItems);
2038 $form->postProcess();
2039 }
2040
2041 /**
2042 * Helper function for static submit function - set relevant params - help us to build up an array that we can pass
2043 * in.
2044 *
2045 * @param int $id
2046 * @param array $params
2047 *
2048 * @return array
2049 * @throws CiviCRM_API3_Exception
2050 */
2051 public static function getFormParams($id, array $params) {
2052 if (!isset($params['is_pay_later'])) {
2053 if (!empty($params['payment_processor'])) {
2054 $params['is_pay_later'] = 0;
2055 }
2056 else {
2057 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
2058 'id' => $id,
2059 'return' => 'is_pay_later',
2060 ));
2061 }
2062 }
2063 if (empty($params['price_set_id'])) {
2064 $params['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id']);
2065 }
2066 return $params;
2067 }
2068
2069 }