Merge pull request #2327 from colemanw/4.4
[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 CRM_Member_BAO_Membership::postProcessMembership($membershipParams, $contactID,
943 $this, $premiumParams, $customFieldsFormatted,
944 $fieldTypes
945 );
946 }
947 }
948 else {
949 // at this point we've created a contact and stored its address etc
950 // all the payment processors expect the name and address to be in the
951 // so we copy stuff over to first_name etc.
952 $paymentParams = $this->_params;
953 $contributionTypeId = $this->_values['financial_type_id'];
954
955 $fieldTypes = array();
956 if (!empty($paymentParams['onbehalf']) &&
957 is_array($paymentParams['onbehalf'])
958 ) {
959 foreach ($paymentParams['onbehalf'] as $key => $value) {
960 if (strstr($key, 'custom_')) {
961 $this->_params[$key] = $value;
962 }
963 }
964 $fieldTypes = array('Contact', 'Organization', 'Contribution');
965 }
966
967 CRM_Contribute_BAO_Contribution_Utils::processConfirm($this, $paymentParams,
968 $premiumParams, $contactID,
969 $contributionTypeId,
970 'contribution',
971 $fieldTypes
972 );
973 }
974 }
975
976 /**
977 * Process the form
978 *
979 * @param $premiumParams
980 * @param $contribution
981 *
982 * @return void
983 * @access public
984 */
985 public function postProcessPremium($premiumParams, $contribution) {
986 // assigning Premium information to receipt tpl
987 $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
988 if ($selectProduct &&
989 $selectProduct != 'no_thanks'
990 ) {
991 $startDate = $endDate = "";
992 $this->assign('selectPremium', TRUE);
993 $productDAO = new CRM_Contribute_DAO_Product();
994 $productDAO->id = $selectProduct;
995 $productDAO->find(TRUE);
996 $this->assign('product_name', $productDAO->name);
997 $this->assign('price', $productDAO->price);
998 $this->assign('sku', $productDAO->sku);
999 $this->assign('option', CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams));
1000
1001 $periodType = $productDAO->period_type;
1002
1003 if ($periodType) {
1004 $fixed_period_start_day = $productDAO->fixed_period_start_day;
1005 $duration_unit = $productDAO->duration_unit;
1006 $duration_interval = $productDAO->duration_interval;
1007 if ($periodType == 'rolling') {
1008 $startDate = date('Y-m-d');
1009 }
1010 elseif ($periodType == 'fixed') {
1011 if ($fixed_period_start_day) {
1012 $date = explode('-', date('Y-m-d'));
1013 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
1014 $day = substr($fixed_period_start_day, -2) . "<br>";
1015 $year = $date[0];
1016 $startDate = $year . '-' . $month . '-' . $day;
1017 }
1018 else {
1019 $startDate = date('Y-m-d');
1020 }
1021 }
1022
1023 $date = explode('-', $startDate);
1024 $year = $date[0];
1025 $month = $date[1];
1026 $day = $date[2];
1027
1028 switch ($duration_unit) {
1029 case 'year':
1030 $year = $year + $duration_interval;
1031 break;
1032
1033 case 'month':
1034 $month = $month + $duration_interval;
1035 break;
1036
1037 case 'day':
1038 $day = $day + $duration_interval;
1039 break;
1040
1041 case 'week':
1042 $day = $day + ($duration_interval * 7);
1043 }
1044 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
1045 $this->assign('start_date', $startDate);
1046 $this->assign('end_date', $endDate);
1047 }
1048
1049 $dao = new CRM_Contribute_DAO_Premium();
1050 $dao->entity_table = 'civicrm_contribution_page';
1051 $dao->entity_id = $this->_id;
1052 $dao->find(TRUE);
1053 $this->assign('contact_phone', $dao->premiums_contact_phone);
1054 $this->assign('contact_email', $dao->premiums_contact_email);
1055
1056 //create Premium record
1057 $params = array(
1058 'product_id' => $premiumParams['selectProduct'],
1059 'contribution_id' => $contribution->id,
1060 'product_option' => CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams),
1061 'quantity' => 1,
1062 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
1063 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
1064 );
1065 if( CRM_Utils_Array::value( 'selectProduct', $premiumParams ) ){
1066 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
1067 $daoPremiumsProduct->product_id = $premiumParams['selectProduct'];
1068 $daoPremiumsProduct->premiums_id = $dao->id;
1069 $daoPremiumsProduct->find(true);
1070 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id;
1071 }
1072 //Fixed For CRM-3901
1073 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1074 $daoContrProd->contribution_id = $contribution->id;
1075 if ($daoContrProd->find(TRUE)) {
1076 $params['id'] = $daoContrProd->id;
1077 }
1078
1079 CRM_Contribute_BAO_Contribution::addPremium($params);
1080 if ($productDAO->cost && CRM_Utils_Array::value('financial_type_id', $params)) {
1081 $trxnParams = array(
1082 'cost' => $productDAO->cost,
1083 'currency' => $productDAO->currency,
1084 'financial_type_id' => $params['financial_type_id'],
1085 'contributionId' => $contribution->id
1086 );
1087 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
1088 }
1089 }
1090 elseif ($selectProduct == 'no_thanks') {
1091 //Fixed For CRM-3901
1092 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1093 $daoContrProd->contribution_id = $contribution->id;
1094 if ($daoContrProd->find(TRUE)) {
1095 $daoContrProd->delete();
1096 }
1097 }
1098 }
1099
1100 /**
1101 * Process the contribution
1102 *
1103 * @param $form
1104 * @param $params
1105 * @param $result
1106 * @param $contactID
1107 * @param $contributionType
1108 * @param bool $deductibleMode
1109 * @param bool $pending
1110 * @param bool $online
1111 *
1112 * @return CRM_Contribute_DAO_Contribution
1113 * @access public
1114 */
1115 static function processContribution(
1116 &$form,
1117 $params,
1118 $result,
1119 $contactID,
1120 $contributionType,
1121 $deductibleMode = TRUE,
1122 $pending = FALSE,
1123 $online = TRUE
1124 ) {
1125 $transaction = new CRM_Core_Transaction();
1126 $className = get_class($form);
1127 $honorCId = $recurringContributionID = NULL;
1128
1129 if ($online && $form->get('honor_block_is_active')) {
1130 $honorCId = $form->createHonorContact();
1131 }
1132
1133 // add these values for the recurringContrib function ,CRM-10188
1134 $params['financial_type_id'] = $contributionType->id;
1135 //@todo - this is being set from the form to resolve CRM-10188 - an
1136 // eNotice caused by it not being set @ the front end
1137 // however, we then get it being over-written with null for backend contributions
1138 // a better fix would be to set the values in the respective forms rather than require
1139 // a function being shared by two forms to deal with their respective values
1140 // moving it to the BAO & not taking the $form as a param would make sense here.
1141 if(!isset($params['is_email_receipt'])){
1142 $params['is_email_receipt'] = CRM_Utils_Array::value( 'is_email_receipt', $form->_values );
1143 }
1144 $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online);
1145
1146 if (!$online && isset($params['honor_contact_id'])) {
1147 $honorCId = $params['honor_contact_id'];
1148 }
1149
1150 $config = CRM_Core_Config::singleton();
1151 // CRM-11885
1152 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
1153 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
1154 $nonDeductibleAmount = $params['non_deductible_amount'];
1155 }
1156 // if non_deductible_amount does NOT exist - then calculate it depending on:
1157 // $contributionType->is_deductible and whether there is a product (premium).
1158 else {
1159 //if ($contributionType->is_deductible && $deductibleMode) {
1160 if ($contributionType->is_deductible) {
1161 if ($online && isset($params['selectProduct'])) {
1162 $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
1163 }
1164 if (!$online && isset($params['product_name'][0])) {
1165 $selectProduct = $params['product_name'][0];
1166 }
1167 // if there is a product - compare the value to the contribution amount
1168 if (isset($selectProduct) &&
1169 $selectProduct != 'no_thanks'
1170 ) {
1171 $productDAO = new CRM_Contribute_DAO_Product();
1172 $productDAO->id = $selectProduct;
1173 $productDAO->find(TRUE);
1174 // product value exceeds contribution amount
1175 if ($params['amount'] < $productDAO->price) {
1176 $nonDeductibleAmount = $params['amount'];
1177 }
1178 // product value does NOT exceed contribution amount
1179 else {
1180 $nonDeductibleAmount = $productDAO->price;
1181 }
1182 }
1183 // contribution is deductible - but there is no product
1184 else {
1185 $nonDeductibleAmount = '0.00';
1186 }
1187 }
1188 // contribution is NOT deductible
1189 else {
1190 $nonDeductibleAmount = $params['amount'];
1191 }
1192 }
1193
1194 $now = date('YmdHis');
1195 $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
1196 if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) {
1197 $receiptDate = $now;
1198 }
1199
1200 //get the contrib page id.
1201 $campaignId = $contributionPageId = NULL;
1202 if ($online) {
1203 $contributionPageId = $form->_id;
1204 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1205 if (!array_key_exists('campaign_id', $params)) {
1206 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1207 }
1208 }
1209 else {
1210 //also for offline we do support - CRM-7290
1211 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
1212 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1213 }
1214
1215 // first create the contribution record
1216 $contribParams = array(
1217 'contact_id' => $contactID,
1218 'financial_type_id' => $contributionType->id,
1219 'contribution_page_id' => $contributionPageId,
1220 'receive_date' => (CRM_Utils_Array::value('receive_date', $params)) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'),
1221 'non_deductible_amount' => $nonDeductibleAmount,
1222 'total_amount' => $params['amount'],
1223 'amount_level' => CRM_Utils_Array::value('amount_level', $params),
1224 'invoice_id' => $params['invoiceID'],
1225 'currency' => $params['currencyID'],
1226 'source' =>
1227 (!$online || CRM_Utils_Array::value('source', $params)) ?
1228 CRM_Utils_Array::value('source', $params) :
1229 CRM_Utils_Array::value('description', $params),
1230 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
1231 //configure cancel reason, cancel date and thankyou date
1232 //from 'contribution' type profile if included
1233 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0),
1234 'cancel_date' =>
1235 isset($params['cancel_date']) ?
1236 CRM_Utils_Date::format($params['cancel_date']) :
1237 NULL,
1238 'thankyou_date' =>
1239 isset($params['thankyou_date']) ?
1240 CRM_Utils_Date::format($params['thankyou_date']) :
1241 NULL,
1242 'campaign_id' => $campaignId,
1243 );
1244
1245 if (!$online && isset($params['thankyou_date'])) {
1246 $contribParams['thankyou_date'] = $params['thankyou_date'];
1247 }
1248
1249 if (!$online || $form->_values['is_monetary']) {
1250 if (!CRM_Utils_Array::value('is_pay_later', $params)) {
1251 $contribParams['payment_instrument_id'] = 1;
1252 }
1253 }
1254
1255 if (!$pending && $result) {
1256 $contribParams += array(
1257 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
1258 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']),
1259 'trxn_id' => $result['trxn_id'],
1260 'receipt_date' => $receiptDate,
1261 // also add financial_trxn details as part of fix for CRM-4724
1262 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $result),
1263 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result),
1264 );
1265 }
1266
1267 if (isset($honorCId)) {
1268 $contribParams['honor_contact_id'] = $honorCId;
1269 $contribParams['honor_type_id'] = $params['honor_type_id'];
1270 }
1271
1272 if ($recurringContributionID) {
1273 $contribParams['contribution_recur_id'] = $recurringContributionID;
1274 }
1275
1276 $contribParams['contribution_status_id'] = $pending ? 2 : 1;
1277
1278 $contribParams['is_test'] = 0;
1279 if ($form->_mode == 'test') {
1280 $contribParams['is_test'] = 1;
1281 }
1282
1283 $ids = array();
1284 if (isset($contribParams['invoice_id'])) {
1285 $contribID = CRM_Core_DAO::getFieldValue(
1286 'CRM_Contribute_DAO_Contribution',
1287 $contribParams['invoice_id'],
1288 'id',
1289 'invoice_id'
1290 );
1291 if (isset($contribID)) {
1292 $ids['contribution'] = $contribID;
1293 $contribParams['id'] = $contribID;
1294 }
1295 }
1296
1297
1298 //create an contribution address
1299 if (
1300 $form->_contributeMode != 'notify' &&
1301 !CRM_Utils_Array::value('is_pay_later', $params) &&
1302 CRM_Utils_Array::value('is_monetary', $form->_values)
1303 ) {
1304 $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
1305 }
1306
1307 // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
1308 $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' '));
1309 $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' '));
1310
1311 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1312 if (
1313 CRM_Utils_Array::value('pcp_made_through_id', $params) ||
1314 CRM_Utils_Array::value('soft_credit_to', $params)
1315 ) {
1316 // if its due to pcp
1317 if (CRM_Utils_Array::value('pcp_made_through_id', $params)) {
1318 $contribSoftContactId = CRM_Core_DAO::getFieldValue(
1319 'CRM_PCP_DAO_PCP',
1320 $params['pcp_made_through_id'],
1321 'contact_id'
1322 );
1323 }
1324 else {
1325 $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
1326 }
1327
1328 // Pass these details onto with the contribution to make them
1329 // available at hook_post_process, CRM-8908
1330 $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId;
1331 }
1332
1333 if (isset($params['amount'])) {
1334 $contribParams['line_item'] = $form->_lineItem;
1335 //add contribution record
1336 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
1337 if (is_a($contribution, 'CRM_Core_Error')) {
1338 $message = CRM_Core_Error::getMessages($contribution);
1339 CRM_Core_Error::fatal($message);
1340 }
1341
1342 // lets store it in the form variable so postProcess hook can get to this and use it
1343 $form->_contributionID = $contribution->id;
1344 }
1345
1346 // process soft credit / pcp pages
1347 CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
1348
1349 //handle pledge stuff.
1350 if (
1351 !CRM_Utils_Array::value('separate_membership_payment', $form->_params) &&
1352 CRM_Utils_Array::value('pledge_block_id', $form->_values) &&
1353 (CRM_Utils_Array::value('is_pledge', $form->_params) ||
1354 CRM_Utils_Array::value('pledge_id', $form->_values)
1355 )
1356 ) {
1357
1358 if (CRM_Utils_Array::value('pledge_id', $form->_values)) {
1359
1360 //when user doing pledge payments.
1361 //update the schedule when payment(s) are made
1362 foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
1363 $scheduledAmount = CRM_Core_DAO::getFieldValue(
1364 'CRM_Pledge_DAO_PledgePayment',
1365 $paymentId,
1366 'scheduled_amount',
1367 'id'
1368 );
1369
1370 $pledgePaymentParams = array(
1371 'id' => $paymentId,
1372 'contribution_id' => $contribution->id,
1373 'status_id' => $contribution->contribution_status_id,
1374 'actual_amount' => $scheduledAmount,
1375 );
1376
1377
1378 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
1379 }
1380
1381 //update pledge status according to the new payment statuses
1382 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']);
1383 }
1384 else {
1385 //when user creating pledge record.
1386 $pledgeParams = array();
1387 $pledgeParams['contact_id'] = $contribution->contact_id;
1388 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
1389 $pledgeParams['contribution_id'] = $contribution->id;
1390 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
1391 $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
1392 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
1393 $pledgeParams['installments'] = $params['pledge_installments'];
1394 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
1395 if ($pledgeParams['frequency_unit'] == 'month') {
1396 $pledgeParams['frequency_day'] = intval(date("d"));
1397 }
1398 else {
1399 $pledgeParams['frequency_day'] = 1;
1400 }
1401 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
1402 $pledgeParams['status_id'] = $contribution->contribution_status_id;
1403 $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
1404 $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
1405 $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
1406 $pledgeParams['is_test'] = $contribution->is_test;
1407 $pledgeParams['acknowledge_date'] = date('Ymd');
1408 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
1409
1410 //inherit campaign from contirb page.
1411 $pledgeParams['campaign_id'] = $campaignId;
1412
1413 $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
1414
1415 $form->_params['pledge_id'] = $pledge->id;
1416
1417 //send acknowledgment email. only when pledge is created
1418 if ($pledge->id) {
1419 //build params to send acknowledgment.
1420 $pledgeParams['id'] = $pledge->id;
1421 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
1422 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
1423
1424 //scheduled amount will be same as installment_amount.
1425 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
1426
1427 //get total pledge amount.
1428 $pledgeParams['total_pledge_amount'] = $pledge->amount;
1429
1430 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
1431 }
1432 }
1433 }
1434
1435 if ($online && $contribution) {
1436 CRM_Core_BAO_CustomValueTable::postProcess($form->_params,
1437 CRM_Core_DAO::$_nullArray,
1438 'civicrm_contribution',
1439 $contribution->id,
1440 'Contribution'
1441 );
1442 }
1443 elseif ($contribution) {
1444 //handle custom data.
1445 $params['contribution_id'] = $contribution->id;
1446 if (CRM_Utils_Array::value('custom', $params) &&
1447 is_array($params['custom']) &&
1448 !is_a($contribution, 'CRM_Core_Error')
1449 ) {
1450 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
1451 }
1452 }
1453 // Save note
1454 if ($contribution && !empty($params['contribution_note'])) {
1455 $noteParams = array(
1456 'entity_table' => 'civicrm_contribution',
1457 'note' => $params['contribution_note'],
1458 'entity_id' => $contribution->id,
1459 'contact_id' => $contribution->contact_id,
1460 'modified_date' => date('Ymd'),
1461 );
1462
1463 CRM_Core_BAO_Note::add($noteParams, array());
1464 }
1465
1466
1467 if (isset($params['related_contact'])) {
1468 $contactID = $params['related_contact'];
1469 }
1470 elseif (isset($params['cms_contactID'])) {
1471 $contactID = $params['cms_contactID'];
1472 }
1473
1474 //create contribution activity w/ individual and target
1475 //activity w/ organisation contact id when onbelf, CRM-4027
1476 $targetContactID = NULL;
1477 if (CRM_Utils_Array::value('hidden_onbehalf_profile', $params)) {
1478 $targetContactID = $contribution->contact_id;
1479 $contribution->contact_id = $contactID;
1480 }
1481
1482 // create an activity record
1483 if ($contribution) {
1484 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
1485 }
1486
1487 $transaction->commit();
1488 // CRM-13074 - create the CMSUser after the transaction is completed as it
1489 // is not appropriate to delete a valid contribution if a user create problem occurs
1490 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params,
1491 $contactID,
1492 'email-' . $form->_bltID
1493 );
1494 return $contribution;
1495 }
1496
1497 /**
1498 * Create the recurring contribution record
1499 *
1500 */
1501 static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1502 // return if this page is not set for recurring
1503 // or the user has not chosen the recurring option
1504
1505 //this is online case validation.
1506 if ((!CRM_Utils_Array::value('is_recur', $form->_values) && $online) ||
1507 !CRM_Utils_Array::value('is_recur', $params)
1508 ) {
1509 return NULL;
1510 }
1511
1512 $recurParams = array();
1513 $config = CRM_Core_Config::singleton();
1514 $recurParams['contact_id'] = $contactID;
1515 $recurParams['amount'] = CRM_Utils_Array::value('amount', $params);
1516 $recurParams['auto_renew'] = CRM_Utils_Array::value('auto_renew', $params);
1517 $recurParams['frequency_unit'] = CRM_Utils_Array::value('frequency_unit', $params);
1518 $recurParams['frequency_interval'] = CRM_Utils_Array::value('frequency_interval', $params);
1519 $recurParams['installments'] = CRM_Utils_Array::value('installments', $params);
1520 $recurParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params);
1521
1522 $recurParams['is_test'] = 0;
1523 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1524 (isset($form->_mode) && ($form->_mode == 'test'))
1525 ) {
1526 $recurParams['is_test'] = 1;
1527 }
1528
1529 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1530 if (CRM_Utils_Array::value('receive_date', $params)) {
1531 $recurParams['start_date'] = $params['receive_date'];
1532 }
1533 $recurParams['invoice_id'] = CRM_Utils_Array::value('invoiceID', $params);
1534 $recurParams['contribution_status_id'] = 2;
1535 $recurParams['payment_processor_id'] = CRM_Utils_Array::value('payment_processor_id', $params);
1536 $recurParams['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params);
1537 // we need to add a unique trxn_id to avoid a unique key error
1538 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1539 $recurParams['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params, $params['invoiceID']);
1540 $recurParams['financial_type_id'] = $contributionType->id;
1541
1542 if (!$online || $form->_values['is_monetary']) {
1543 $recurParams['payment_instrument_id'] = 1;
1544 }
1545
1546 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1547 if ($online) {
1548 if (!array_key_exists('campaign_id', $params)) {
1549 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1550 }
1551 }
1552 $recurParams['campaign_id'] = $campaignId;
1553
1554 $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
1555 if (is_a($recurring, 'CRM_Core_Error')) {
1556 CRM_Core_Error::displaySessionError($result);
1557 $urlString = 'civicrm/contribute/transact';
1558 $urlParams = '_qf_Main_display=true';
1559 if ($className == 'CRM_Contribute_Form_Contribution') {
1560 $urlString = 'civicrm/contact/view/contribution';
1561 $urlParams = "action=add&cid={$form->_contactID}";
1562 if ($form->_mode) {
1563 $urlParams .= "&mode={$form->_mode}";
1564 }
1565 }
1566 CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
1567 }
1568
1569 return $recurring->id;
1570 }
1571
1572 /**
1573 * Create the Honor contact
1574 *
1575 * @return void
1576 * @access public
1577 */
1578 function createHonorContact() {
1579 $params = $this->controller->exportValues('Main');
1580
1581 // email is enough to create a contact
1582 if (! CRM_Utils_Array::value('honor_email', $params) &&
1583 // or we need first name AND last name
1584 (! CRM_Utils_Array::value('honor_first_name', $params)
1585 || ! CRM_Utils_Array::value('honor_last_name', $params))) {
1586 //don't create contact - possibly the form was left blank
1587 return null;
1588 }
1589
1590 //assign to template for email receipt
1591 $honor_block_is_active = $this->get('honor_block_is_active');
1592
1593 $this->assign('honor_block_is_active', $honor_block_is_active);
1594 $this->assign('honor_block_title', CRM_Utils_Array::value('honor_block_title', $this->_values));
1595
1596 $prefix = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id');
1597 $honorType = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'honor_type_id');
1598 $this->assign('honor_type', CRM_Utils_Array::value(CRM_Utils_Array::value('honor_type_id', $params), $honorType));
1599 $this->assign('honor_prefix', CRM_Utils_Array::value(CRM_Utils_Array::value('honor_prefix_id', $params), $prefix));
1600 $this->assign('honor_first_name', CRM_Utils_Array::value('honor_first_name', $params));
1601 $this->assign('honor_last_name', CRM_Utils_Array::value('honor_last_name', $params));
1602 $this->assign('honor_email', CRM_Utils_Array::value('honor_email', $params));
1603
1604 //create honoree contact
1605 return CRM_Contribute_BAO_Contribution::createHonorContact($params);
1606 }
1607
1608 /**
1609 * Function to add on behalf of organization and it's location
1610 *
1611 * @param $behalfOrganization array array of organization info
1612 * @param $contactID int individual contact id. One
1613 * who is doing the process of signup / contribution.
1614 *
1615 * @param $values array form values array
1616 * @param $params
1617 * @param null $fields
1618 *
1619 * @return void
1620 * @access public
1621 */
1622 static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1623 $isCurrentEmployer = FALSE;
1624 $orgID = NULL;
1625 if (CRM_Utils_Array::value('organization_id', $behalfOrganization) &&
1626 CRM_Utils_Array::value('org_option', $behalfOrganization)
1627 ) {
1628 $orgID = $behalfOrganization['organization_id'];
1629 unset($behalfOrganization['organization_id']);
1630 $isCurrentEmployer = TRUE;
1631 }
1632
1633 // formalities for creating / editing organization.
1634 $behalfOrganization['contact_type'] = 'Organization';
1635
1636 // get the relationship type id
1637 $relType = new CRM_Contact_DAO_RelationshipType();
1638 $relType->name_a_b = 'Employee of';
1639 $relType->find(TRUE);
1640 $relTypeId = $relType->id;
1641
1642 // keep relationship params ready
1643 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1644 $relParams['is_permission_a_b'] = 1;
1645 $relParams['is_active'] = 1;
1646
1647 if (!$orgID) {
1648 // check if matching organization contact exists
1649 $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization');
1650 $dedupeParams['check_permission'] = FALSE;
1651 $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1652
1653 // CRM-6243 says to pick the first org even if more than one match
1654 if (count($dupeIDs) >= 1) {
1655 $behalfOrganization['contact_id'] = $dupeIDs[0];
1656 // don't allow name edit
1657 unset($behalfOrganization['organization_name']);
1658 }
1659 }
1660 else {
1661 // if found permissioned related organization, allow location edit
1662 $behalfOrganization['contact_id'] = $orgID;
1663 // don't allow name edit
1664 unset($behalfOrganization['organization_name']);
1665 }
1666
1667 // handling for image url
1668 if (CRM_Utils_Array::value('image_URL', $behalfOrganization)) {
1669 CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
1670 }
1671
1672 // create organization, add location
1673 $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID,
1674 NULL, NULL, 'Organization'
1675 );
1676 // create relationship
1677 $relParams['contact_check'][$orgID] = 1;
1678 $cid = array('contact' => $contactID);
1679 CRM_Contact_BAO_Relationship::create($relParams, $cid);
1680
1681 // if multiple match - send a duplicate alert
1682 if ($dupeIDs && (count($dupeIDs) > 1)) {
1683 $values['onbehalf_dupe_alert'] = 1;
1684 // required for IPN
1685 $params['onbehalf_dupe_alert'] = 1;
1686 }
1687
1688 // make sure organization-contact-id is considered for recording
1689 // contribution/membership etc..
1690 if ($contactID != $orgID) {
1691 // take a note of contact-id, so we can send the
1692 // receipt to individual contact as well.
1693
1694 // required for mailing/template display ..etc
1695 $values['related_contact'] = $contactID;
1696 // required for IPN
1697 $params['related_contact'] = $contactID;
1698
1699 //make this employee of relationship as current
1700 //employer / employee relationship, CRM-3532
1701 if ($isCurrentEmployer &&
1702 ($orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1703 ) {
1704 $isCurrentEmployer = FALSE;
1705 }
1706
1707 if (!$isCurrentEmployer && $orgID) {
1708 //build current employer params
1709 $currentEmpParams[$contactID] = $orgID;
1710 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
1711 }
1712
1713 // contribution / signup will be done using this
1714 // organization id.
1715 $contactID = $orgID;
1716 }
1717 }
1718
1719 /**
1720 * Function used to save pcp / soft credit entry
1721 * This is used by contribution and also event pcps
1722 *
1723 * @param array $params associated array
1724 * @param object $contribution contribution object
1725 *
1726 * @static
1727 * @access public
1728 */
1729 static function processPcpSoft(&$params, &$contribution) {
1730 //add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1731 if (CRM_Utils_Array::value('soft_credit_to', $params)) {
1732 $contribSoftParams = array();
1733 foreach (array(
1734 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note', 'amount') as $val) {
1735 if (CRM_Utils_Array::value($val, $params)) {
1736 $contribSoftParams[$val] = $params[$val];
1737 }
1738 }
1739
1740 $contribSoftParams['contact_id'] = $params['soft_credit_to'];
1741 // add contribution id
1742 $contribSoftParams['contribution_id'] = $contribution->id;
1743 // add pcp id
1744 $contribSoftParams['pcp_id'] = $params['pcp_made_through_id'];
1745
1746 $softContribution = CRM_Contribute_BAO_ContributionSoft::add($contribSoftParams);
1747 }
1748 }
1749
1750 /**
1751 * Function used to se pcp related defaults / params
1752 * This is used by contribution and also event pcps
1753 *
1754 * @param object $page form object
1755 * @param array $params associated array
1756 *
1757 * @return array
1758 * @static
1759 * @access public
1760 */
1761 static function processPcp(&$page, $params) {
1762 $params['pcp_made_through_id'] = $page->_pcpId;
1763 $page->assign('pcpBlock', TRUE);
1764 if (CRM_Utils_Array::value('pcp_display_in_roll', $params) &&
1765 !CRM_Utils_Array::value('pcp_roll_nickname', $params)
1766 ) {
1767 $params['pcp_roll_nickname'] = ts('Anonymous');
1768 $params['pcp_is_anonymous'] = 1;
1769 }
1770 else {
1771 $params['pcp_is_anonymous'] = 0;
1772 }
1773 foreach (array(
1774 'pcp_display_in_roll',
1775 'pcp_is_anonymous',
1776 'pcp_roll_nickname',
1777 'pcp_personal_note'
1778 ) as $val) {
1779 if (CRM_Utils_Array::value($val, $params)) {
1780 $page->assign($val, $params[$val]);
1781 }
1782 }
1783
1784 return $params;
1785 }
1786 }