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