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