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