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