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