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