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