INFRA-132 - CRM/Contribute - Convert single-line @param to multi-line
[civicrm-core.git] / CRM / Contribute / Form / Contribution / Confirm.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * form to process actions on the group aspect of Custom Data
38 */
39class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_ContributionBase {
40
41 /**
100fef9d 42 * The id of the contact associated with this contribution
6a488035
TO
43 *
44 * @var int
6a488035
TO
45 */
46 public $_contactID;
47
1f1740fe
DL
48
49 /**
50 * The id of the contribution object that is created when the form is submitted
51 *
52 * @var int
1f1740fe
DL
53 */
54 public $_contributionID;
55
c8bde7ea
EM
56 /**
57 * Set the parameters to be passed to contribution create function
58 *
59 * @param array $params
014c4014 60 * @param int $contactID
100fef9d 61 * @param int $financialTypeID
c8bde7ea 62 * @param $online
100fef9d 63 * @param int $contributionPageId
c8bde7ea 64 * @param $nonDeductibleAmount
100fef9d 65 * @param int $campaignId
c8bde7ea 66 * @param $isMonetary
c8bde7ea
EM
67 * @param $pending
68 * @param $paymentProcessorOutcome
69 * @param $receiptDate
100fef9d 70 * @param int $recurringContributionID
c8bde7ea 71 * @param $isTest
100fef9d
CW
72 * @param int $addressID
73 * @param int $softCreditToID
74 * @param array $lineItems
c8bde7ea 75 *
c8bde7ea
EM
76 * @return array
77 */
78 public static function getContributionParams($params, $contactID, $financialTypeID, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending,
79 $paymentProcessorOutcome, $receiptDate, $recurringContributionID, $isTest, $addressID, $softCreditToID, $lineItems)
80 {
81 $contributionParams = array(
82 'contact_id' => $contactID,
83 'financial_type_id' => $financialTypeID,
84 'contribution_page_id' => $contributionPageId,
85 'receive_date' => (CRM_Utils_Array::value('receive_date', $params)) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'),
86 'non_deductible_amount' => $nonDeductibleAmount,
87 'total_amount' => $params['amount'],
17ab42dd 88 'tax_amount' => CRM_Utils_Array::value('tax_amount', $params),
c8bde7ea
EM
89 'amount_level' => CRM_Utils_Array::value('amount_level', $params),
90 'invoice_id' => $params['invoiceID'],
91 'currency' => $params['currencyID'],
92 'source' =>
93 (!$online || !empty($params['source'])) ?
94 CRM_Utils_Array::value('source', $params) :
95 CRM_Utils_Array::value('description', $params),
96 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
97 //configure cancel reason, cancel date and thankyou date
98 //from 'contribution' type profile if included
99 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0),
100 'cancel_date' =>
101 isset($params['cancel_date']) ?
102 CRM_Utils_Date::format($params['cancel_date']) :
103 NULL,
104 'thankyou_date' =>
105 isset($params['thankyou_date']) ?
106 CRM_Utils_Date::format($params['thankyou_date']) :
107 NULL,
108 'campaign_id' => $campaignId,
109 'is_test' => $isTest,
110 'address_id' => $addressID,
111 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
112 'soft_credit_to' => $softCreditToID,
b205ce09
PN
113 'line_item' => $lineItems,
114 'skipLineItem' => CRM_Utils_Array::value('skipLineItem', $params, 0)
c8bde7ea
EM
115 );
116 if (!$online && isset($params['thankyou_date'])) {
117 $contributionParam['thankyou_date'] = $params['thankyou_date'];
118 }
119 if (!$online || $isMonetary) {
120 if (empty($params['is_pay_later'])) {
121 $contributionParams['payment_instrument_id'] = 1;
122 }
123 }
a7a33651
EM
124 if ($paymentProcessorOutcome) {
125 $contributionParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $paymentProcessorOutcome);
126 }
c8bde7ea
EM
127 if (!$pending && $paymentProcessorOutcome) {
128 $contributionParams += array(
129 'fee_amount' => CRM_Utils_Array::value('fee_amount', $paymentProcessorOutcome),
130 'net_amount' => CRM_Utils_Array::value('net_amount', $paymentProcessorOutcome, $params['amount']),
131 'trxn_id' => $paymentProcessorOutcome['trxn_id'],
132 'receipt_date' => $receiptDate,
133 // also add financial_trxn details as part of fix for CRM-4724
134 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $paymentProcessorOutcome),
c8bde7ea
EM
135 );
136 }
137
138 // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
139 $contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contributionParams['non_deductible_amount'], ' '));
140 $contributionParams['total_amount'] = trim(CRM_Utils_Money::format($contributionParams['total_amount'], ' '));
141
142 if ($recurringContributionID) {
143 $contributionParams['contribution_recur_id'] = $recurringContributionID;
144 }
145
146 $contributionParams['contribution_status_id'] = $pending ? 2 : 1;
147 if (isset($contributionParams['invoice_id'])) {
148 $contributionParams['id'] = CRM_Core_DAO::getFieldValue(
149 'CRM_Contribute_DAO_Contribution',
150 $contributionParams['invoice_id'],
151 'id',
152 'invoice_id'
153 );
154 }
155
156 return $contributionParams;
157 }
158
6a488035 159 /**
100fef9d 160 * Set variables up before form is built
6a488035
TO
161 *
162 * @return void
6a488035
TO
163 */
164 public function preProcess() {
165 $config = CRM_Core_Config::singleton();
166 parent::preProcess();
cde484fd 167
6a488035
TO
168 // lineItem isn't set until Register postProcess
169 $this->_lineItem = $this->get('lineItem');
170 $this->_paymentProcessor = $this->get('paymentProcessor');
cde484fd 171
6a488035
TO
172 if ($this->_contributeMode == 'express') {
173 // rfp == redirect from paypal
174 $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean',
175 CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET'
176 );
177 if ($rfp) {
178 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
179 $expressParams = $payment->getExpressCheckoutDetails($this->get('token'));
180
181 $this->_params['payer'] = $expressParams['payer'];
182 $this->_params['payer_id'] = $expressParams['payer_id'];
183 $this->_params['payer_status'] = $expressParams['payer_status'];
184
185 CRM_Core_Payment_Form::mapParams($this->_bltID, $expressParams, $this->_params, FALSE);
cde484fd 186
6a488035 187 // fix state and country id if present
f0bf6c15 188 if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
6a488035
TO
189 $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
190 }
191 if (!empty($this->_params["billing_country_id-{$this->_bltID}"]) && $this->_params["billing_country_id-{$this->_bltID}"]) {
192 $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
193 }
194
195 // set a few other parameters for PayPal
196 $this->_params['token'] = $this->get('token');
197
198 $this->_params['amount'] = $this->get('amount');
199
200 if (!empty($this->_membershipBlock)){
201 $this->_params['selectMembership'] = $this->get('selectMembership');
202 }
203 // we use this here to incorporate any changes made by folks in hooks
204 $this->_params['currencyID'] = $config->defaultCurrency;
205
206 $this->_params['payment_action'] = 'Sale';
207
208 // also merge all the other values from the profile fields
209 $values = $this->controller->exportValues('Main');
210 $skipFields = array(
211 'amount', 'amount_other',
212 "billing_street_address-{$this->_bltID}",
213 "billing_city-{$this->_bltID}",
214 "billing_state_province_id-{$this->_bltID}",
215 "billing_postal_code-{$this->_bltID}",
216 "billing_country_id-{$this->_bltID}",
217 );
218 foreach ($values as $name => $value) {
219 // skip amount field
220 if (!in_array($name, $skipFields)) {
221 $this->_params[$name] = $value;
222 }
223 }
224 $this->set('getExpressCheckoutDetails', $this->_params);
225 }
226 else {
227 $this->_params = $this->get('getExpressCheckoutDetails');
228 }
229 }
230 else {
231 $this->_params = $this->controller->exportValues('Main');
232
233 if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
234 $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
235 }
236 if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) {
237 $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
238 }
239
240 if (isset($this->_params['credit_card_exp_date'])) {
241 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
242 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
243 }
5df36634
PJ
244
245 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
6a488035 246 $this->_params['amount'] = $this->get('amount');
d91b8b33 247 $this->_params['tax_amount'] = $this->get('tax_amount');
6a488035
TO
248
249 $this->_useForMember = $this->get('useForMember');
cde484fd 250
6a488035 251 if (isset($this->_params['amount'])) {
df6c4f28 252 $this->setFormAmountFields($this->_params['priceSetId']);
6a488035
TO
253 }
254 $this->_params['currencyID'] = $config->defaultCurrency;
255 $this->_params['payment_action'] = 'Sale';
256 }
257
258 $this->_params['is_pay_later'] = $this->get('is_pay_later');
259 $this->assign('is_pay_later', $this->_params['is_pay_later']);
260 if ($this->_params['is_pay_later']) {
261 $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
262 }
263 // if onbehalf-of-organization
a7488080 264 if (!empty($this->_params['hidden_onbehalf_profile'])) {
c8fa0a31 265 // CRM-15182
266 if (empty($this->_params['org_option']) && empty($this->_params['organization_id'])) {
a7488080 267 if (!empty($this->_params['onbehalfof_id'])) {
6a488035
TO
268 $this->_params['organization_id'] = $this->_params['onbehalfof_id'];
269 }
c8fa0a31 270 else {
271 $this->_params['organization_id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_params['onbehalf']['organization_name'], 'id', 'display_name');
272 }
6a488035
TO
273 }
274
275 $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name'];
276 $addressBlocks = array(
277 'street_address', 'city', 'state_province',
278 'postal_code', 'country', 'supplemental_address_1',
279 'supplemental_address_2', 'supplemental_address_3',
280 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'address_name',
281 );
282
283 $blocks = array('email', 'phone', 'im', 'url', 'openid');
284 foreach ($this->_params['onbehalf'] as $loc => $value) {
285 $field = $typeId = NULL;
286 if (strstr($loc, '-')) {
287 list($field, $locType) = explode('-', $loc);
288 }
289
290 if (in_array($field, $addressBlocks)) {
291 if ($locType == 'Primary') {
292 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
293 $locType = $defaultLocationType->id;
cde484fd
DL
294 }
295
6a488035
TO
296 if ($field == 'country') {
297 $value = CRM_Core_PseudoConstant::countryIsoCode($value);
298 }
299 elseif ($field == 'state_province') {
300 $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
301 }
cde484fd 302
6a488035
TO
303 $isPrimary = 1;
304 if (isset($this->_params['onbehalf_location']['address'])
305 && count($this->_params['onbehalf_location']['address']) > 0) {
306 $isPrimary = 0;
307 }
cde484fd 308
6a488035 309 $this->_params['onbehalf_location']['address'][$locType][$field] = $value;
a7488080 310 if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) {
6a488035
TO
311 $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
312 }
313 $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
314 }
315 elseif (in_array($field, $blocks)) {
316 if (!$typeId || is_numeric($typeId)) {
317 $blockName = $fieldName = $field;
318 $locationType = 'location_type_id';
319 if ( $locType == 'Primary' ) {
320 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
321 $locationValue = $defaultLocationType->id;
322 }
323 else {
324 $locationValue = $locType;
325 }
326 $locTypeId = '';
327 $phoneExtField = array();
328
329 if ($field == 'url') {
330 $blockName = 'website';
887e764d
PN
331 $locationType = 'website_type_id';
332 list($field, $locationValue) = explode('-', $loc);
6a488035
TO
333 }
334 elseif ($field == 'im') {
335 $fieldName = 'name';
336 $locTypeId = 'provider_id';
337 $typeId = $this->_params['onbehalf']["{$loc}-provider_id"];
338 }
339 elseif ($field == 'phone') {
340 list($field, $locType, $typeId) = explode('-', $loc);
341 $locTypeId = 'phone_type_id';
342
343 //check if extension field exists
344 $extField = str_replace('phone','phone_ext', $loc);
345 if (isset($this->_params['onbehalf'][$extField])) {
346 $phoneExtField = array('phone_ext' => $this->_params['onbehalf'][$extField]);
347 }
348 }
349
350 $isPrimary = 1;
351 if ( isset ($this->_params['onbehalf_location'][$blockName] )
352 && count( $this->_params['onbehalf_location'][$blockName] ) > 0 ) {
353 $isPrimary = 0;
354 }
355 if ($locationValue) {
356 $blockValues = array(
357 $fieldName => $value,
358 $locationType => $locationValue,
359 'is_primary' => $isPrimary,
360 );
361
362 if ($locTypeId) {
363 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
364 }
365 if (!empty($phoneExtField)) {
366 $blockValues = array_merge($blockValues, $phoneExtField);
367 }
368
369 $this->_params['onbehalf_location'][$blockName][] = $blockValues;
370 }
371 }
372 }
373 elseif (strstr($loc, 'custom')) {
374 if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) {
375 $value = $this->_params['onbehalf']["{$loc}_id"];
376 }
377 $this->_params['onbehalf_location']["{$loc}"] = $value;
378 }
379 else {
380 if ($loc == 'contact_sub_type') {
381 $this->_params['onbehalf_location'][$loc] = $value;
382 }
383 else {
384 $this->_params['onbehalf_location'][$field] = $value;
385 }
386 }
387 }
388 }
a7488080 389 elseif (!empty($this->_values['is_for_organization'])) {
6a488035
TO
390 // no on behalf of an organization, CRM-5519
391 // so reset loc blocks from main params.
392 foreach (array(
393 'phone', 'email', 'address') as $blk) {
394 if (isset($this->_params[$blk])) {
395 unset($this->_params[$blk]);
396 }
397 }
398 }
399
400 // if auto renew checkbox is set, initiate a open-ended recurring membership
8cc574cf
CW
401 if ((!empty($this->_params['selectMembership']) || !empty($this->_params['priceSetId'])) && !empty($this->_paymentProcessor['is_recur']) &&
402 CRM_Utils_Array::value('auto_renew', $this->_params) && empty($this->_params['is_recur']) && empty($this->_params['frequency_interval'])) {
6a488035
TO
403
404 $this->_params['is_recur'] = $this->_values['is_recur'] = 1;
405 // check if price set is not quick config
d80f2618 406 if (!empty($this->_params['priceSetId']) && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config')) {
9da8dc8c 407 list($this->_params['frequency_interval'], $this->_params['frequency_unit']) = CRM_Price_BAO_PriceSet::getRecurDetails($this->_params['priceSetId']);
6a488035
TO
408 }
409 else {
410 // FIXME: set interval and unit based on selected membership type
411 $this->_params['frequency_interval'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
412 $this->_params['selectMembership'], 'duration_interval'
413 );
414 $this->_params['frequency_unit'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
415 $this->_params['selectMembership'], 'duration_unit'
416 );
417 }
418 }
419
420 if ($this->_pcpId) {
421 $params = $this->processPcp($this, $this->_params);
422 $this->_params = $params;
423 }
424 $this->_params['invoiceID'] = $this->get('invoiceID');
425
426 //carry campaign from profile.
427 if (array_key_exists('contribution_campaign_id', $this->_params)) {
428 $this->_params['campaign_id'] = $this->_params['contribution_campaign_id'];
429 }
430
569df8ec
DG
431 // assign contribution page id to the template so we can add css class for it
432 $this->assign('contributionPageID', $this->_id);
433
6a488035
TO
434 $this->set('params', $this->_params);
435 }
436
437 /**
c490a46a 438 * Build the form object
6a488035
TO
439 *
440 * @return void
6a488035
TO
441 */
442 public function buildQuickForm() {
443 $this->assignToTemplate();
444
445 $params = $this->_params;
6a488035 446 // make sure we have values for it
8af73472 447 if ($this->_honor_block_is_active && !empty($params['soft_credit_type_id'])) {
133e2c99 448 $honorName = null;
449 $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
450
8af73472 451 $this->assign('honor_block_is_active', $this->_honor_block_is_active);
133e2c99 452 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
1421174e 453 CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($this, $params['honor'], $params['honoree_profile_id']);
6a488035 454
133e2c99 455 $fieldTypes = array('Contact');
456 $fieldTypes[] = CRM_Core_BAO_UFGroup::getContactType($params['honoree_profile_id']);
457 $this->buildCustom($params['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
6a488035
TO
458 }
459 $this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values));
460 $amount_block_is_active = $this->get('amount_block_is_active');
461 $this->assign('amount_block_is_active', $amount_block_is_active);
462
03b412ae
PB
463 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
464 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
465 if ($invoicing) {
466 $getTaxDetails = FALSE;
467 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
468 foreach ($this->_lineItem as $key => $value) {
469 foreach ($value as $v) {
470 if (isset($v['tax_rate'])) {
471 if ($v['tax_rate'] != '') {
472 $getTaxDetails = TRUE;
473 }
474 }
475 }
476 }
477 $this->assign('getTaxDetails', $getTaxDetails);
478 $this->assign('taxTerm', $taxTerm);
479 $this->assign('totalTaxAmount', $params['tax_amount']);
480 }
a7488080 481 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
6a488035
TO
482 $option = CRM_Utils_Array::value('options_' . $params['selectProduct'], $params);
483 $productID = $params['selectProduct'];
484 CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE,
485 $productID, $option
486 );
487 $this->set('productID', $productID);
488 $this->set('option', $option);
489 }
490 $config = CRM_Core_Config::singleton();
491 if (in_array('CiviMember', $config->enableComponents)) {
492 if (isset($params['selectMembership']) &&
493 $params['selectMembership'] != 'no_thanks'
494 ) {
495 CRM_Member_BAO_Membership::buildMembershipBlock($this,
496 $this->_id,
5b757295 497 $this->_membershipContactID,
6a488035
TO
498 FALSE,
499 $params['selectMembership'],
5b757295 500 FALSE
6a488035
TO
501 );
502 }
503 else {
504 $this->assign('membershipBlock', FALSE);
505 }
506 }
507 $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE);
508 $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE);
509
a7488080 510 if (!empty($params['hidden_onbehalf_profile'])) {
6a488035
TO
511 $ufJoinParams = array(
512 'module' => 'onBehalf',
513 'entity_table' => 'civicrm_contribution_page',
514 'entity_id' => $this->_id,
515 );
516 $OnBehalfProfile = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
517 $profileId = $OnBehalfProfile[0];
518
519 $fieldTypes = array('Contact', 'Organization');
520 $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
521 $fieldTypes = array_merge($fieldTypes, $contactSubType);
522 if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
523 $fieldTypes = array_merge($fieldTypes, array('Membership'));
524 }
525 else {
526 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
527 }
528
133e2c99 529 $this->buildCustom($profileId, 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
6a488035
TO
530 }
531
532 $this->_separateMembershipPayment = $this->get('separateMembershipPayment');
533 $this->assign('is_separate_payment', $this->_separateMembershipPayment);
9da8dc8c 534 if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
6a488035
TO
535 $this->assign('lineItem', $this->_lineItem);
536 } else {
537 $this->assign('is_quick_config', 1);
538 $this->_params['is_quick_config'] = 1;
539 }
540 $this->assign('priceSetID', $this->_priceSetId);
541 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(false, null, 'name');
f92fc7eb
CW
542 if ($this->_paymentProcessor &&
543 $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('Google_Checkout', $paymentProcessorType)
6a488035
TO
544 && !$this->_params['is_pay_later'] && !($this->_amount == 0)
545 ) {
546 $this->_checkoutButtonName = $this->getButtonName('next', 'checkout');
547 $this->add('image',
548 $this->_checkoutButtonName,
549 $this->_paymentProcessor['url_button'],
97e557d7 550 array('class' => 'crm-form-submit')
6a488035
TO
551 );
552
553 $this->addButtons(array(
554 array(
555 'type' => 'back',
556 'name' => ts('<< Go Back'),
557 ),
558 )
559 );
560 }
561 else {
562 if ($this->_contributeMode == 'notify' || !$this->_values['is_monetary'] ||
563 $this->_amount <= 0.0 || $this->_params['is_pay_later'] ||
564 ($this->_separateMembershipPayment && $this->_amount <= 0.0)
565 ) {
566 $contribButton = ts('Continue >>');
567 $this->assign('button', ts('Continue'));
568 }
569 else {
570 $contribButton = ts('Make Contribution');
571 $this->assign('button', ts('Make Contribution'));
572 }
573 $this->addButtons(array(
574 array(
575 'type' => 'next',
576 'name' => $contribButton,
577 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
578 'isDefault' => TRUE,
c6edd786 579 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
6a488035
TO
580 ),
581 array(
582 'type' => 'back',
583 'name' => ts('Go Back'),
584 ),
585 )
586 );
587 }
588
589 $defaults = array();
9c80939e 590 $fields = array_fill_keys(array_keys($this->_fields), 1);
6a488035
TO
591 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
592
593 $contact = $this->_params;
594 foreach ($fields as $name => $dontCare) {
9c80939e
CW
595 // Recursively set defaults for nested fields
596 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' || $name == 'honor')) {
597 foreach ($contact[$name] as $fieldName => $fieldValue) {
e8d56359 598 if (is_array($fieldValue) && !in_array($this->_fields[$name][$fieldName]['html_type'], array('Multi-Select','AdvMulti-Select'))) {
38b95e0f 599 foreach ($fieldValue as $key => $value) {
600 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
601 }
602 }
603 else {
604 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
605 }
9c80939e
CW
606 }
607 }
608 elseif (isset($contact[$name])) {
6a488035
TO
609 $defaults[$name] = $contact[$name];
610 if (substr($name, 0, 7) == 'custom_') {
611 $timeField = "{$name}_time";
612 if (isset($contact[$timeField])) {
613 $defaults[$timeField] = $contact[$timeField];
614 }
615 if (isset($contact["{$name}_id"])) {
616 $defaults["{$name}_id"] = $contact["{$name}_id"];
617 }
618 }
8cc574cf 619 elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting')) && !empty($contact[$name . '_custom'])) {
6a488035
TO
620 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
621 }
622 }
623 }
624
625 $this->assign('useForMember', $this->get('useForMember'));
626
6a488035
TO
627 $this->setDefaults($defaults);
628
629 $this->freeze();
630 }
631
632 /**
100fef9d 633 * Overwrite action, since we are only showing elements in frozen mode
6a488035
TO
634 * no help display needed
635 *
636 * @return int
6a488035 637 */
00be9182 638 public function getAction() {
6a488035
TO
639 if ($this->_action & CRM_Core_Action::PREVIEW) {
640 return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
641 }
642 else {
643 return CRM_Core_Action::VIEW;
644 }
645 }
646
647 /**
c490a46a 648 * Set default values for the form. Note that in edit/view mode
6a488035
TO
649 * the default values are retrieved from the database
650 *
6a488035
TO
651 *
652 * @return void
653 */
00be9182 654 public function setDefaultValues() {}
6a488035
TO
655
656 /**
657 * Process the form
658 *
659 * @return void
6a488035
TO
660 */
661 public function postProcess() {
da8d9879 662 $contactID = $this->getContactID();
cc789d46
EM
663 $isPayLater = $this->_params['is_pay_later'];
664 if ($this->_params['payment_processor'] == 0) {
665 $this->_params['is_pay_later'] = $isPayLater = TRUE;
666 }
6a488035
TO
667 // add a description field at the very beginning
668 $this->_params['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
669
670 // also add accounting code
671 $this->_params['accountingCode'] = CRM_Utils_Array::value('accountingCode',
672 $this->_values
673 );
674
675 // fix currency ID
dbddfb08 676 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
6a488035 677
6a488035
TO
678 //carry payment processor id.
679 if ($paymentProcessorId = CRM_Utils_Array::value('id', $this->_paymentProcessor)) {
680 $this->_params['payment_processor_id'] = $paymentProcessorId;
6a488035 681 }
a7488080 682 if (!empty($params['image_URL'])) {
6a488035
TO
683 CRM_Contact_BAO_Contact::processImageParams($params);
684 }
e9599dfa 685 $premiumParams = $membershipParams = $params = $this->_params;
99fffb1f 686 $fields = array('email-Primary' => 1);
6a488035
TO
687
688 // get the add to groups
689 $addToGroups = array();
690
691 // now set the values for the billing location.
692 foreach ($this->_fields as $name => $value) {
693 $fields[$name] = 1;
694
695 // get the add to groups for uf fields
a7488080 696 if (!empty($value['add_to_group_id'])) {
6a488035
TO
697 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
698 }
699 }
700
701 if (!array_key_exists('first_name', $fields)) {
702 $nameFields = array('first_name', 'middle_name', 'last_name');
703 foreach ($nameFields as $name) {
704 $fields[$name] = 1;
705 if (array_key_exists("billing_$name", $params)) {
706 $params[$name] = $params["billing_{$name}"];
707 $params['preserveDBName'] = TRUE;
708 }
709 }
710 }
711
712 // billing email address
713 $fields["email-{$this->_bltID}"] = 1;
714
715 //unset the billing parameters if it is pay later mode
716 //to avoid creation of billing location
cc789d46 717 if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater) {
6a488035
TO
718 $billingFields = array(
719 'billing_first_name',
720 'billing_middle_name',
721 'billing_last_name',
722 "billing_street_address-{$this->_bltID}",
723 "billing_city-{$this->_bltID}",
724 "billing_state_province-{$this->_bltID}",
725 "billing_state_province_id-{$this->_bltID}",
726 "billing_postal_code-{$this->_bltID}",
727 "billing_country-{$this->_bltID}",
728 "billing_country_id-{$this->_bltID}",
729 );
730
731 foreach ($billingFields as $value) {
732 unset($params[$value]);
733 unset($fields[$value]);
734 }
735 }
736
737 // if onbehalf-of-organization contribution, take out
738 // organization params in a separate variable, to make sure
739 // normal behavior is continued. And use that variable to
740 // process on-behalf-of functionality.
a7488080 741 if (!empty($this->_params['hidden_onbehalf_profile'])) {
6a488035
TO
742 $behalfOrganization = array();
743 $orgFields = array('organization_name', 'organization_id', 'org_option');
744 foreach ($orgFields as $fld) {
745 if (array_key_exists($fld, $params)) {
746 $behalfOrganization[$fld] = $params[$fld];
747 unset($params[$fld]);
748 }
749 }
750
751 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
752 foreach ($params['onbehalf'] as $fld => $values) {
753 if (strstr($fld, 'custom_')) {
754 $behalfOrganization[$fld] = $values;
cde484fd 755 }
6a488035
TO
756 elseif (!(strstr($fld, '-'))) {
757 if (in_array($fld, array(
758 'contribution_campaign_id', 'member_campaign_id'))) {
759 $fld = 'campaign_id';
760 }
761 else {
762 $behalfOrganization[$fld] = $values;
cde484fd 763 }
6a488035
TO
764 $this->_params[$fld] = $values;
765 }
766 }
767 }
768
769 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
770 foreach ($params['onbehalf_location'] as $block => $vals) {
771 //fix for custom data (of type checkbox, multi-select)
772 if ( substr($block, 0, 7) == 'custom_' ) {
773 continue;
774 }
775 // fix the index of block elements
776 if (is_array($vals) ) {
777 foreach ( $vals as $key => $val ) {
778 //dont adjust the index of address block as
779 //it's index is WRT to location type
780 $newKey = ($block == 'address') ? $key : ++$key;
781 $behalfOrganization[$block][$newKey] = $val;
782 }
783 }
784 }
785 unset($params['onbehalf_location']);
786 }
a7488080 787 if (!empty($params['onbehalf[image_URL]'])) {
6a488035
TO
788 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
789 }
790 }
791
792 // check for profile double opt-in and get groups to be subscribed
793 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
794
795 // since we are directly adding contact to group lets unset it from mailing
796 if (!empty($addToGroups)) {
797 foreach ($addToGroups as $groupId) {
798 if (isset($subscribeGroupIds[$groupId])) {
799 unset($subscribeGroupIds[$groupId]);
800 }
801 }
802 }
803
804 foreach ($addToGroups as $k) {
805 if (array_key_exists($k, $subscribeGroupIds)) {
806 unset($addToGroups[$k]);
807 }
808 }
809
da8d9879 810 if (empty($contactID)) {
6a488035 811 $dupeParams = $params;
a7488080 812 if (!empty($dupeParams['onbehalf'])) {
6a488035
TO
813 unset($dupeParams['onbehalf']);
814 }
815
816 $dedupeParams = CRM_Dedupe_Finder::formatParams($dupeParams, 'Individual');
817 $dedupeParams['check_permission'] = FALSE;
818 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
819
820 // if we find more than one contact, use the first one
99fffb1f 821 $contactID = CRM_Utils_Array::value(0, $ids);
6a488035
TO
822
823 // Fetch default greeting id's if creating a contact
99fffb1f 824 if (!$contactID) {
6a488035
TO
825 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
826 if (!isset($params[$greeting])) {
827 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
828 }
829 }
830 }
99fffb1f 831 $contactType = NULL;
6a488035
TO
832 }
833 else {
99fffb1f 834 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
6a488035 835 }
99fffb1f
EM
836 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
837 $params,
838 $fields,
839 $contactID,
840 $addToGroups,
841 NULL,
842 $contactType,
843 TRUE
844 );
6a488035
TO
845
846 // Make the contact ID associated with the contribution available at the Class level.
847 // Also make available to the session.
596bff78 848 //@todo consider handling this in $this->getContactID();
6a488035
TO
849 $this->set('contactID', $contactID);
850 $this->_contactID = $contactID;
851
852 //get email primary first if exist
b288b9c2
EM
853 $subscriptionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
854 if (!$subscriptionEmail['email']) {
855 $subscriptionEmail['email'] = CRM_Utils_Array::value("email-{$this->_bltID}", $params);
6a488035
TO
856 }
857 // subscribing contact to groups
b288b9c2
EM
858 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
859 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
6a488035
TO
860 }
861
862 // If onbehalf-of-organization contribution / signup, add organization
863 // and it's location.
864 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
865 $ufFields = array();
866 foreach ($this->_fields['onbehalf'] as $name => $value) {
867 $ufFields[$name] = 1;
868 }
869 self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values,
870 $this->_params, $ufFields
871 );
6fe8deba 872 } else if (!empty($this->_membershipContactID) && $contactID != $this->_membershipContactID) {
51fa20cb 873 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
51e89def
DS
874 // store current user id as related contact for later use for mailing / activity..
875 $this->_values['related_contact'] = $contactID;
876 $this->_params['related_contact'] = $contactID;
877 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
878 $contactID = $this->_membershipContactID;
879 }
880
6a488035
TO
881 // lets store the contactID in the session
882 // for things like tell a friend
883 $session = CRM_Core_Session::singleton();
884 if (!$session->get('userID')) {
885 $session->set('transaction.userID', $contactID);
886 }
887 else {
888 $session->set('transaction.userID', NULL);
889 }
890
891 $this->_useForMember = $this->get('useForMember');
892
893 // store the fact that this is a membership and membership type is selected
894 $processMembership = FALSE;
8cc574cf 895 if ((!empty($membershipParams['selectMembership']) &&
6a488035
TO
896 $membershipParams['selectMembership'] != 'no_thanks'
897 ) ||
898 $this->_useForMember
899 ) {
900 $processMembership = TRUE;
901
902 if (!$this->_useForMember) {
903 $this->assign('membership_assign', TRUE);
904 $this->set('membershipTypeID', $this->_params['selectMembership']);
905 }
906
907 if ($this->_action & CRM_Core_Action::PREVIEW) {
908 $membershipParams['is_test'] = 1;
909 }
910 if ($this->_params['is_pay_later']) {
911 $membershipParams['is_pay_later'] = 1;
912 }
913 }
914
915 if ($processMembership) {
916 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE);
917
918 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
919 if (isset($this->_params['related_contact'])) {
920 $membershipParams['cms_contactID'] = $this->_params['related_contact'];
921 }
922 else {
923 $membershipParams['cms_contactID'] = $contactID;
924 }
925
f64a217a 926 //inherit campaign from contribution page.
6a488035
TO
927 if (!array_key_exists('campaign_id', $membershipParams)) {
928 $membershipParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
929 }
930
931 if (!empty($membershipParams['onbehalf']) &&
8cc574cf 932 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
6a488035
TO
933 $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
934 }
935
936 $customFieldsFormatted = $fieldTypes = array();
937 if (!empty($membershipParams['onbehalf']) &&
938 is_array($membershipParams['onbehalf'])) {
939 foreach ($membershipParams['onbehalf'] as $key => $value) {
940 if (strstr($key, 'custom_')) {
941 $customFieldId = explode('_', $key);
942 CRM_Core_BAO_CustomField::formatCustomField(
943 $customFieldId[1],
944 $customFieldsFormatted,
945 $value,
946 'Membership',
947 NULL,
948 $contactID
949 );
950 }
951 }
952 $fieldTypes = array('Contact', 'Organization', 'Membership');
953 }
954
955 $priceFieldIds = $this->get('memberPriceFieldIDS');
956
957 if (!empty($priceFieldIds)) {
9da8dc8c 958 $contributionTypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
6a488035
TO
959 unset($priceFieldIds['id']);
960 $membershipTypeIds = array();
961 $membershipTypeTerms = array();
962 foreach ($priceFieldIds as $priceFieldId) {
9da8dc8c 963 if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
6a488035 964 $membershipTypeIds[] = $id;
dbddfb08
EM
965 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
966 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
6a488035 967 $term = 1;
9da8dc8c 968 if ($term = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
6a488035
TO
969 $membershipTypeTerms[$id] = ($term > 1) ? $term : 1;
970 }
971 else {
972 $membershipTypeTerms[$id] = 1;
973 }
974 }
975 }
976 $membershipParams['selectMembership'] = $membershipTypeIds;
9ce8bcfc 977 $membershipParams['financial_type_id'] = $contributionTypeID;
6a488035
TO
978 $membershipParams['types_terms'] = $membershipTypeTerms;
979 }
a7488080 980 if (!empty($membershipParams['selectMembership'])) {
9ce8bcfc 981 // CRM-12233
5624f515 982 $membershipLineItems = array();
9ce8bcfc
PN
983 if ($this->_separateMembershipPayment && $this->_values['amount_block_is_active']) {
984 foreach ($this->_values['fee'] as $key => $feeValues) {
5624f515 985 if ($feeValues['name'] == 'membership_amount') {
9ce8bcfc 986 $fieldId = $this->_params['price_' . $key];
5624f515 987 $membershipLineItems[$this->_priceSetId][$fieldId] = $this->_lineItem[$this->_priceSetId][$fieldId];
9ce8bcfc
PN
988 unset($this->_lineItem[$this->_priceSetId][$fieldId]);
989 break;
990 }
991 }
992 }
cc789d46 993 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater);
fa9d0451
EM
994 if (!$this->_amount > 0.0 || !$membershipParams['amount']) {
995 // we need to explicitly create a CMS user in case of free memberships
996 // since it is done under processConfirm for paid memberships
997 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams,
998 $membershipParams['cms_contactID'],
999 'email-' . $this->_bltID
1000 );
1001 }
9ce8bcfc 1002 }
6a488035
TO
1003 }
1004 else {
1005 // at this point we've created a contact and stored its address etc
1006 // all the payment processors expect the name and address to be in the
1007 // so we copy stuff over to first_name etc.
1008 $paymentParams = $this->_params;
157b21d8 1009 $contributionTypeId = $this->_values['financial_type_id'];
6a488035
TO
1010
1011 $fieldTypes = array();
1012 if (!empty($paymentParams['onbehalf']) &&
1013 is_array($paymentParams['onbehalf'])
1014 ) {
1015 foreach ($paymentParams['onbehalf'] as $key => $value) {
1016 if (strstr($key, 'custom_')) {
1017 $this->_params[$key] = $value;
1018 }
1019 }
1020 $fieldTypes = array('Contact', 'Organization', 'Contribution');
1021 }
cc789d46 1022 $financialTypeID = $this->wrangleFinancialTypeID($contributionTypeId);
6a488035
TO
1023
1024 CRM_Contribute_BAO_Contribution_Utils::processConfirm($this, $paymentParams,
1025 $premiumParams, $contactID,
cc789d46 1026 $financialTypeID,
6a488035 1027 'contribution',
cc789d46
EM
1028 $fieldTypes,
1029 ($this->_mode == 'test') ? 1 : 0,
1030 $isPayLater
1031 );
1032 }
1033 }
1034
1035 /**
1036 * This wrangling of the financialType ID was happening in a shared function rather than in the form it relates to & hence has been moved to that form
1037 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
1038 *
1039 * Comments from previous refactor indicate doubt as to what was going on
100fef9d 1040 * @param int $contributionTypeId
cc789d46
EM
1041 *
1042 * @return null|string
1043 */
00be9182 1044 public function wrangleFinancialTypeID($contributionTypeId) {
cc789d46
EM
1045 if (isset($paymentParams['financial_type'])) {
1046 $contributionTypeId = $paymentParams['financial_type'];
1047 }
1048 elseif (!empty($this->_values['pledge_id'])) {
1049 $contributionTypeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
1050 $this->_values['pledge_id'],
1051 'financial_type_id'
6a488035
TO
1052 );
1053 }
cc789d46 1054 return $contributionTypeId;
6a488035
TO
1055 }
1056
1057 /**
1058 * Process the form
1059 *
100fef9d 1060 * @param array $premiumParams
cd6994fc
E
1061 * @param $contribution
1062 *
6a488035 1063 * @return void
6a488035
TO
1064 */
1065 public function postProcessPremium($premiumParams, $contribution) {
62c4420e 1066 $hour = $minute = $second = 0;
6a488035
TO
1067 // assigning Premium information to receipt tpl
1068 $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
1069 if ($selectProduct &&
1070 $selectProduct != 'no_thanks'
1071 ) {
1072 $startDate = $endDate = "";
1073 $this->assign('selectPremium', TRUE);
1074 $productDAO = new CRM_Contribute_DAO_Product();
1075 $productDAO->id = $selectProduct;
1076 $productDAO->find(TRUE);
1077 $this->assign('product_name', $productDAO->name);
1078 $this->assign('price', $productDAO->price);
1079 $this->assign('sku', $productDAO->sku);
1080 $this->assign('option', CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams));
1081
1082 $periodType = $productDAO->period_type;
cde484fd 1083
6a488035
TO
1084 if ($periodType) {
1085 $fixed_period_start_day = $productDAO->fixed_period_start_day;
1086 $duration_unit = $productDAO->duration_unit;
1087 $duration_interval = $productDAO->duration_interval;
1088 if ($periodType == 'rolling') {
1089 $startDate = date('Y-m-d');
1090 }
1091 elseif ($periodType == 'fixed') {
1092 if ($fixed_period_start_day) {
1093 $date = explode('-', date('Y-m-d'));
1094 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
1095 $day = substr($fixed_period_start_day, -2) . "<br>";
1096 $year = $date[0];
1097 $startDate = $year . '-' . $month . '-' . $day;
1098 }
1099 else {
1100 $startDate = date('Y-m-d');
1101 }
1102 }
1103
1104 $date = explode('-', $startDate);
1105 $year = $date[0];
1106 $month = $date[1];
1107 $day = $date[2];
1108
1109 switch ($duration_unit) {
1110 case 'year':
1111 $year = $year + $duration_interval;
1112 break;
1113
1114 case 'month':
1115 $month = $month + $duration_interval;
1116 break;
1117
1118 case 'day':
1119 $day = $day + $duration_interval;
1120 break;
1121
1122 case 'week':
1123 $day = $day + ($duration_interval * 7);
1124 }
1125 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
1126 $this->assign('start_date', $startDate);
1127 $this->assign('end_date', $endDate);
1128 }
1129
1130 $dao = new CRM_Contribute_DAO_Premium();
1131 $dao->entity_table = 'civicrm_contribution_page';
1132 $dao->entity_id = $this->_id;
1133 $dao->find(TRUE);
1134 $this->assign('contact_phone', $dao->premiums_contact_phone);
1135 $this->assign('contact_email', $dao->premiums_contact_email);
1136
1137 //create Premium record
1138 $params = array(
1139 'product_id' => $premiumParams['selectProduct'],
1140 'contribution_id' => $contribution->id,
1141 'product_option' => CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams),
1142 'quantity' => 1,
1143 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
1144 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
1145 );
a7488080 1146 if (!empty($premiumParams['selectProduct'])){
6a488035
TO
1147 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
1148 $daoPremiumsProduct->product_id = $premiumParams['selectProduct'];
1149 $daoPremiumsProduct->premiums_id = $dao->id;
1150 $daoPremiumsProduct->find(true);
1151 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id;
1152 }
1153 //Fixed For CRM-3901
1154 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1155 $daoContrProd->contribution_id = $contribution->id;
1156 if ($daoContrProd->find(TRUE)) {
1157 $params['id'] = $daoContrProd->id;
1158 }
cde484fd 1159
6a488035 1160 CRM_Contribute_BAO_Contribution::addPremium($params);
8cc574cf 1161 if ($productDAO->cost && !empty($params['financial_type_id'])) {
6a488035
TO
1162 $trxnParams = array(
1163 'cost' => $productDAO->cost,
1164 'currency' => $productDAO->currency,
1165 'financial_type_id' => $params['financial_type_id'],
1166 'contributionId' => $contribution->id
1167 );
1168 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
1169 }
1170 }
1171 elseif ($selectProduct == 'no_thanks') {
1172 //Fixed For CRM-3901
1173 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1174 $daoContrProd->contribution_id = $contribution->id;
1175 if ($daoContrProd->find(TRUE)) {
1176 $daoContrProd->delete();
1177 }
1178 }
1179 }
1180
1181 /**
1182 * Process the contribution
1183 *
c490a46a 1184 * @param CRM_Core_Form $form
4ce4a928
EM
1185 * @param array $params
1186 * @param array $result
014c4014 1187 * @param int $contactID
a1a94e61 1188 * @param CRM_Financial_DAO_FinancialType $financialType
cd6994fc
E
1189 * @param bool $pending
1190 * @param bool $online
1191 *
a1a94e61
EM
1192 * @param bool $isTest
1193 * @param array $lineItems
1194 *
4ce4a928 1195 * @throws Exception
6a488035 1196 * @return CRM_Contribute_DAO_Contribution
6a488035 1197 */
1f1740fe
DL
1198 static function processContribution(
1199 &$form,
6a488035
TO
1200 $params,
1201 $result,
1202 $contactID,
637b4757 1203 $financialType,
4ce4a928 1204 $pending,
4bd318e0
EM
1205 $online,
1206 $isTest,
1207 $lineItems
6a488035
TO
1208 ) {
1209 $transaction = new CRM_Core_Transaction();
4625312e 1210 $contribSoftContactId = $addressID = NULL;
6a488035
TO
1211
1212 // add these values for the recurringContrib function ,CRM-10188
637b4757 1213 $params['financial_type_id'] = $financialType->id;
c8bde7ea
EM
1214
1215 //create an contribution address
5785931e 1216 if ($form->_contributeMode != 'notify' && empty($params['is_pay_later']) && !empty($form->_values['is_monetary'])) {
c8bde7ea
EM
1217 $addressID = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
1218 }
1219
e34dd94b 1220 //@todo - this is being set from the form to resolve CRM-10188 - an
1221 // eNotice caused by it not being set @ the front end
1222 // however, we then get it being over-written with null for backend contributions
1223 // a better fix would be to set the values in the respective forms rather than require
1224 // a function being shared by two forms to deal with their respective values
1225 // moving it to the BAO & not taking the $form as a param would make sense here.
396e62d8 1226 if(!isset($params['is_email_receipt']) && !empty($form->_values['is_email_receipt'])){
e34dd94b 1227 $params['is_email_receipt'] = CRM_Utils_Array::value( 'is_email_receipt', $form->_values );
1228 }
637b4757 1229 $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType, $online);
6a488035 1230
6a488035
TO
1231 // CRM-11885
1232 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
1233 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
1234 $nonDeductibleAmount = $params['non_deductible_amount'];
1235 }
1236 // if non_deductible_amount does NOT exist - then calculate it depending on:
1237 // $contributionType->is_deductible and whether there is a product (premium).
1238 else {
1239 //if ($contributionType->is_deductible && $deductibleMode) {
637b4757 1240 if ($financialType->is_deductible) {
6a488035
TO
1241 if ($online && isset($params['selectProduct'])) {
1242 $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
1243 }
1244 if (!$online && isset($params['product_name'][0])) {
1245 $selectProduct = $params['product_name'][0];
1246 }
1247 // if there is a product - compare the value to the contribution amount
1248 if (isset($selectProduct) &&
1249 $selectProduct != 'no_thanks'
1250 ) {
1251 $productDAO = new CRM_Contribute_DAO_Product();
1252 $productDAO->id = $selectProduct;
1253 $productDAO->find(TRUE);
1254 // product value exceeds contribution amount
1255 if ($params['amount'] < $productDAO->price) {
1256 $nonDeductibleAmount = $params['amount'];
1257 }
1258 // product value does NOT exceed contribution amount
1259 else {
1260 $nonDeductibleAmount = $productDAO->price;
1261 }
1262 }
1263 // contribution is deductible - but there is no product
1264 else {
1265 $nonDeductibleAmount = '0.00';
1266 }
1267 }
1268 // contribution is NOT deductible
1269 else {
1270 $nonDeductibleAmount = $params['amount'];
1271 }
1272 }
1273
1274 $now = date('YmdHis');
1275 $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
a7488080 1276 if (!empty($form->_values['is_email_receipt'])) {
6a488035
TO
1277 $receiptDate = $now;
1278 }
1279
1280 //get the contrib page id.
dbddfb08 1281 $contributionPageId = NULL;
6a488035
TO
1282 if ($online) {
1283 $contributionPageId = $form->_id;
1284 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1285 if (!array_key_exists('campaign_id', $params)) {
1286 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1287 }
1288 }
1289 else {
1290 //also for offline we do support - CRM-7290
1291 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
1292 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1293 }
1294
6a488035 1295 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
8cc574cf 1296 if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
6a488035 1297 // if its due to pcp
a7488080 1298 if (!empty($params['pcp_made_through_id'])) {
6a488035
TO
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
c8bde7ea 1311 $params['soft_credit_to'] = $contribSoftContactId;
6a488035
TO
1312 }
1313
92acf33d 1314 if (isset($params['amount'])) {
396e62d8 1315 $isMonetary = NULL;
1316 if (!empty($form->_values['is_monetary'])) {
1317 $isMonetary = $form->_values['is_monetary'];
1318 }
c8bde7ea 1319 $contribParams = self::getContributionParams(
396e62d8 1320 $params, $contactID, $financialType->id, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending, $result, $receiptDate,
c8bde7ea
EM
1321 $recurringContributionID, $isTest, $addressID, $contribSoftContactId, $lineItems
1322 );
1323 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
24f81279 1324
03b412ae
PB
1325 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
1326 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1327 if ($invoicing) {
1328 $totalTaxAmount = 0;
1329 $dataArray = array();
1330 foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
1331 foreach ($lineItemValue as $key => $value) {
1332 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1333 if (isset($dataArray[$value['tax_rate']])) {
1334 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1335 }
1336 else {
1337 $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1338 }
79d001a2
PB
1339 }
1340 }
1341 }
03b412ae
PB
1342 $smarty = CRM_Core_Smarty::singleton();
1343 $smarty->assign('dataArray', $dataArray);
1344 $smarty->assign('totalTaxAmount', $params['tax_amount']);
79d001a2 1345 }
9879aeb8
DL
1346 if (is_a($contribution, 'CRM_Core_Error')) {
1347 $message = CRM_Core_Error::getMessages($contribution);
1348 CRM_Core_Error::fatal($message);
1349 }
1f1740fe
DL
1350
1351 // lets store it in the form variable so postProcess hook can get to this and use it
1352 $form->_contributionID = $contribution->id;
6a488035 1353 }
cde484fd 1354
1421174e 1355 //CRM-13981, processing honor contact into soft-credit contribution
1356 CRM_Contact_Form_ProfileContact::postProcess($form);
1357
6a488035
TO
1358 // process soft credit / pcp pages
1359 CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
cde484fd 1360
6a488035 1361 //handle pledge stuff.
8cc574cf
CW
1362 if (empty($form->_params['separate_membership_payment']) && !empty($form->_values['pledge_block_id']) &&
1363 (!empty($form->_params['is_pledge']) || !empty($form->_values['pledge_id']))
6a488035
TO
1364 ) {
1365
a7488080 1366 if (!empty($form->_values['pledge_id'])) {
6a488035
TO
1367
1368 //when user doing pledge payments.
1369 //update the schedule when payment(s) are made
1370 foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
1371 $scheduledAmount = CRM_Core_DAO::getFieldValue(
1372 'CRM_Pledge_DAO_PledgePayment',
1373 $paymentId,
1374 'scheduled_amount',
1375 'id'
1376 );
1377
1378 $pledgePaymentParams = array(
1379 'id' => $paymentId,
1380 'contribution_id' => $contribution->id,
1381 'status_id' => $contribution->contribution_status_id,
1382 'actual_amount' => $scheduledAmount,
1383 );
1384
1385
1386 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
1387 }
1388
1389 //update pledge status according to the new payment statuses
1390 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']);
1391 }
1392 else {
1393 //when user creating pledge record.
1394 $pledgeParams = array();
1395 $pledgeParams['contact_id'] = $contribution->contact_id;
1396 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
1397 $pledgeParams['contribution_id'] = $contribution->id;
1398 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
1399 $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
1400 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
1401 $pledgeParams['installments'] = $params['pledge_installments'];
1402 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
1403 if ($pledgeParams['frequency_unit'] == 'month') {
1404 $pledgeParams['frequency_day'] = intval(date("d"));
1405 }
1406 else {
1407 $pledgeParams['frequency_day'] = 1;
1408 }
1409 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
1410 $pledgeParams['status_id'] = $contribution->contribution_status_id;
1411 $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
1412 $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
1413 $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
1414 $pledgeParams['is_test'] = $contribution->is_test;
1415 $pledgeParams['acknowledge_date'] = date('Ymd');
1416 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
1417
1418 //inherit campaign from contirb page.
1419 $pledgeParams['campaign_id'] = $campaignId;
1420
1421 $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
1422
1423 $form->_params['pledge_id'] = $pledge->id;
1424
1425 //send acknowledgment email. only when pledge is created
1426 if ($pledge->id) {
1427 //build params to send acknowledgment.
1428 $pledgeParams['id'] = $pledge->id;
1429 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
1430 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
1431
1432 //scheduled amount will be same as installment_amount.
1433 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
1434
1435 //get total pledge amount.
1436 $pledgeParams['total_pledge_amount'] = $pledge->amount;
1437
1438 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
1439 }
1440 }
1441 }
1442
1443 if ($online && $contribution) {
1444 CRM_Core_BAO_CustomValueTable::postProcess($form->_params,
1445 CRM_Core_DAO::$_nullArray,
1446 'civicrm_contribution',
1447 $contribution->id,
1448 'Contribution'
1449 );
1450 }
1451 elseif ($contribution) {
1452 //handle custom data.
1453 $params['contribution_id'] = $contribution->id;
a7488080 1454 if (!empty($params['custom']) &&
6a488035
TO
1455 is_array($params['custom']) &&
1456 !is_a($contribution, 'CRM_Core_Error')
1457 ) {
1458 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
1459 }
1460 }
1461 // Save note
1462 if ($contribution && !empty($params['contribution_note'])) {
1463 $noteParams = array(
1464 'entity_table' => 'civicrm_contribution',
1465 'note' => $params['contribution_note'],
1466 'entity_id' => $contribution->id,
1467 'contact_id' => $contribution->contact_id,
1468 'modified_date' => date('Ymd'),
1469 );
1470
1471 CRM_Core_BAO_Note::add($noteParams, array());
1472 }
1473
1474
1475 if (isset($params['related_contact'])) {
1476 $contactID = $params['related_contact'];
1477 }
1478 elseif (isset($params['cms_contactID'])) {
1479 $contactID = $params['cms_contactID'];
1480 }
cde484fd 1481
6a488035
TO
1482 //create contribution activity w/ individual and target
1483 //activity w/ organisation contact id when onbelf, CRM-4027
1484 $targetContactID = NULL;
a7488080 1485 if (!empty($params['hidden_onbehalf_profile'])) {
6a488035
TO
1486 $targetContactID = $contribution->contact_id;
1487 $contribution->contact_id = $contactID;
1488 }
1489
1490 // create an activity record
1491 if ($contribution) {
9879aeb8 1492 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
6a488035
TO
1493 }
1494
1495 $transaction->commit();
4ab1a3a3 1496 // CRM-13074 - create the CMSUser after the transaction is completed as it
1497 // is not appropriate to delete a valid contribution if a user create problem occurs
1498 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params,
1499 $contactID,
1500 'email-' . $form->_bltID
1501 );
6a488035
TO
1502 return $contribution;
1503 }
1504
1505 /**
1506 * Create the recurring contribution record
1507 *
03110609
EM
1508 * @param CRM_Core_Form $form
1509 * @param array $params
014c4014 1510 * @param int $contactID
03110609
EM
1511 * @param string $contributionType
1512 * @param bool $online
1513 *
1514 * @return mixed
6a488035 1515 */
00be9182 1516 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
6a488035
TO
1517 // return if this page is not set for recurring
1518 // or the user has not chosen the recurring option
1519
1520 //this is online case validation.
8cc574cf 1521 if ((empty($form->_values['is_recur']) && $online) || empty($params['is_recur'])) {
6a488035
TO
1522 return NULL;
1523 }
1524
dbddfb08 1525 $recurParams = array('contact_id' => $contactID);
6a488035
TO
1526 $recurParams['amount'] = CRM_Utils_Array::value('amount', $params);
1527 $recurParams['auto_renew'] = CRM_Utils_Array::value('auto_renew', $params);
1528 $recurParams['frequency_unit'] = CRM_Utils_Array::value('frequency_unit', $params);
1529 $recurParams['frequency_interval'] = CRM_Utils_Array::value('frequency_interval', $params);
1530 $recurParams['installments'] = CRM_Utils_Array::value('installments', $params);
1531 $recurParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params);
1532
d8a20b17
FG
1533 // CRM-14354: For an auto-renewing membership with an additional contribution,
1534 // if separate payments is not enabled, make sure only the membership fee recurs
396e62d8 1535 if (!empty($form->_membershipBlock)
1536 && $form->_membershipBlock['is_separate_payment'] === '0'
d8a20b17
FG
1537 && isset($params['selectMembership'])
1538 && $form->_values['is_allow_other_amount'] == '1'
1539 ) {
1540 $recurParams['amount'] = $form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'];
1541 }
1542
6a488035
TO
1543 $recurParams['is_test'] = 0;
1544 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1545 (isset($form->_mode) && ($form->_mode == 'test'))
1546 ) {
1547 $recurParams['is_test'] = 1;
1548 }
1549
1550 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
a7488080 1551 if (!empty($params['receive_date'])) {
6a488035
TO
1552 $recurParams['start_date'] = $params['receive_date'];
1553 }
1554 $recurParams['invoice_id'] = CRM_Utils_Array::value('invoiceID', $params);
4f8dce1b 1555 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
6a488035
TO
1556 $recurParams['payment_processor_id'] = CRM_Utils_Array::value('payment_processor_id', $params);
1557 $recurParams['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params);
1558 // we need to add a unique trxn_id to avoid a unique key error
1559 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1560 $recurParams['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params, $params['invoiceID']);
1561 $recurParams['financial_type_id'] = $contributionType->id;
1562
1563 if (!$online || $form->_values['is_monetary']) {
1564 $recurParams['payment_instrument_id'] = 1;
1565 }
1566
1567 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1568 if ($online) {
1569 if (!array_key_exists('campaign_id', $params)) {
1570 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1571 }
1572 }
1573 $recurParams['campaign_id'] = $campaignId;
1574
1575 $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
1576 if (is_a($recurring, 'CRM_Core_Error')) {
bd0bfdec 1577 CRM_Core_Error::displaySessionError($recurring);
6a488035
TO
1578 $urlString = 'civicrm/contribute/transact';
1579 $urlParams = '_qf_Main_display=true';
e8ab1184 1580 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
6a488035
TO
1581 $urlString = 'civicrm/contact/view/contribution';
1582 $urlParams = "action=add&cid={$form->_contactID}";
1583 if ($form->_mode) {
1584 $urlParams .= "&mode={$form->_mode}";
1585 }
1586 }
1587 CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
1588 }
1589
1590 return $recurring->id;
1591 }
1592
6a488035 1593 /**
100fef9d 1594 * Add on behalf of organization and it's location
6a488035 1595 *
014c4014
TO
1596 * @param $behalfOrganization
1597 * Array array of organization info.
1598 * @param $contactID
1599 * Int individual contact id. One.
6a488035
TO
1600 * who is doing the process of signup / contribution.
1601 *
014c4014
TO
1602 * @param $values
1603 * Array form values array.
c490a46a 1604 * @param array $params
cd6994fc
E
1605 * @param null $fields
1606 *
6a488035 1607 * @return void
6a488035 1608 */
00be9182 1609 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
6a488035 1610 $isCurrentEmployer = FALSE;
dbddfb08 1611 $dupeIDs = array();
6a488035 1612 $orgID = NULL;
96904d4d 1613 if (!empty($behalfOrganization['organization_id']) && empty($behalfOrganization['org_option'])) {
6a488035
TO
1614 $orgID = $behalfOrganization['organization_id'];
1615 unset($behalfOrganization['organization_id']);
1616 $isCurrentEmployer = TRUE;
1617 }
1618
1619 // formalities for creating / editing organization.
1620 $behalfOrganization['contact_type'] = 'Organization';
1621
1622 // get the relationship type id
1623 $relType = new CRM_Contact_DAO_RelationshipType();
1624 $relType->name_a_b = 'Employee of';
1625 $relType->find(TRUE);
1626 $relTypeId = $relType->id;
1627
1628 // keep relationship params ready
1629 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1630 $relParams['is_permission_a_b'] = 1;
1631 $relParams['is_active'] = 1;
1632
1633 if (!$orgID) {
1634 // check if matching organization contact exists
1635 $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization');
1636 $dedupeParams['check_permission'] = FALSE;
1637 $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1638
1639 // CRM-6243 says to pick the first org even if more than one match
1640 if (count($dupeIDs) >= 1) {
34eea47c 1641 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
6a488035
TO
1642 // don't allow name edit
1643 unset($behalfOrganization['organization_name']);
1644 }
1645 }
1646 else {
1647 // if found permissioned related organization, allow location edit
1648 $behalfOrganization['contact_id'] = $orgID;
1649 // don't allow name edit
1650 unset($behalfOrganization['organization_name']);
1651 }
1652
1653 // handling for image url
a7488080 1654 if (!empty($behalfOrganization['image_URL'])) {
6a488035
TO
1655 CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
1656 }
1657
1658 // create organization, add location
1659 $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID,
1660 NULL, NULL, 'Organization'
1661 );
1662 // create relationship
1663 $relParams['contact_check'][$orgID] = 1;
1664 $cid = array('contact' => $contactID);
7ecf6275 1665 CRM_Contact_BAO_Relationship::createMultiple($relParams, $cid);
6a488035
TO
1666
1667 // if multiple match - send a duplicate alert
1668 if ($dupeIDs && (count($dupeIDs) > 1)) {
1669 $values['onbehalf_dupe_alert'] = 1;
1670 // required for IPN
1671 $params['onbehalf_dupe_alert'] = 1;
1672 }
1673
1674 // make sure organization-contact-id is considered for recording
1675 // contribution/membership etc..
1676 if ($contactID != $orgID) {
1677 // take a note of contact-id, so we can send the
1678 // receipt to individual contact as well.
1679
1680 // required for mailing/template display ..etc
1681 $values['related_contact'] = $contactID;
1682 // required for IPN
1683 $params['related_contact'] = $contactID;
1684
1685 //make this employee of relationship as current
1686 //employer / employee relationship, CRM-3532
1687 if ($isCurrentEmployer &&
1688 ($orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1689 ) {
1690 $isCurrentEmployer = FALSE;
1691 }
1692
1693 if (!$isCurrentEmployer && $orgID) {
1694 //build current employer params
1695 $currentEmpParams[$contactID] = $orgID;
1696 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
1697 }
1698
1699 // contribution / signup will be done using this
1700 // organization id.
1701 $contactID = $orgID;
1702 }
1703 }
1704
1705 /**
1706 * Function used to save pcp / soft credit entry
1707 * This is used by contribution and also event pcps
1708 *
014c4014
TO
1709 * @param array $params
1710 * Associated array.
1711 * @param object $contribution
1712 * Contribution object.
6a488035
TO
1713 *
1714 * @static
6a488035 1715 */
00be9182 1716 public static function processPcpSoft(&$params, &$contribution) {
6a488035 1717 //add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
a7488080 1718 if (!empty($params['soft_credit_to'])) {
dbddfb08 1719 $contributionSoftParams = array();
6a488035
TO
1720 foreach (array(
1721 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note', 'amount') as $val) {
a7488080 1722 if (!empty($params[$val])) {
dbddfb08 1723 $contributionSoftParams[$val] = $params[$val];
6a488035
TO
1724 }
1725 }
1726
dbddfb08 1727 $contributionSoftParams['contact_id'] = $params['soft_credit_to'];
6a488035 1728 // add contribution id
dbddfb08 1729 $contributionSoftParams['contribution_id'] = $contribution->id;
6a488035 1730 // add pcp id
dbddfb08 1731 $contributionSoftParams['pcp_id'] = $params['pcp_made_through_id'];
6a488035 1732
dbddfb08 1733 $contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
51fa20cb 1734
dbddfb08 1735 CRM_Contribute_BAO_ContributionSoft::add($contributionSoftParams);
6a488035
TO
1736 }
1737 }
1738
1739 /**
1740 * Function used to se pcp related defaults / params
1741 * This is used by contribution and also event pcps
1742 *
014c4014
TO
1743 * @param CRM_Core_Form $page
1744 * Form object.
1745 * @param array $params
1746 * Associated array.
6a488035 1747 *
cd6994fc 1748 * @return array
6a488035 1749 * @static
6a488035 1750 */
00be9182 1751 public static function processPcp(&$page, $params) {
547206bc 1752 $params['pcp_made_through_id'] = $page->_pcpId;
6a488035 1753 $page->assign('pcpBlock', TRUE);
8cc574cf 1754 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
6a488035
TO
1755 $params['pcp_roll_nickname'] = ts('Anonymous');
1756 $params['pcp_is_anonymous'] = 1;
1757 }
1758 else {
1759 $params['pcp_is_anonymous'] = 0;
1760 }
1761 foreach (array(
547206bc 1762 'pcp_display_in_roll',
1763 'pcp_is_anonymous',
1764 'pcp_roll_nickname',
1765 'pcp_personal_note'
1766 ) as $val) {
a7488080 1767 if (!empty($params[$val])) {
6a488035
TO
1768 $page->assign($val, $params[$val]);
1769 }
1770 }
1771
1772 return $params;
1773 }
705b4205
EM
1774
1775 /**
5624f515 1776 * @param array $membershipParams
014c4014 1777 * @param int $contactID
5624f515
EM
1778 * @param array $customFieldsFormatted
1779 * @param array $fieldTypes
1780 * @param array $premiumParams
014c4014
TO
1781 * @param array $membershipLineItems
1782 * Line items specifically relating to memberships.
cc789d46 1783 * @param $isPayLater
705b4205 1784 */
cc789d46 1785 public function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater) {
705b4205 1786 try {
d25e4224
DG
1787 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1788 $membershipTypes = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIDs);
5624f515
EM
1789 $membershipType = empty($membershipTypes) ? array() : reset($membershipTypes);
1790 $this->assign('membership_name', CRM_Utils_Array::value('name', $membershipType));
1791
fa9d0451 1792 $isPaidMembership = FALSE;
553991dd 1793 if($this->_amount >= 0.0 && isset($membershipParams['amount'])) {
fa9d0451
EM
1794 //amount must be greater than zero for
1795 //adding contribution record to contribution table.
1796 //this condition arises when separate membership payment is
1797 //enabled and contribution amount is not selected. fix for CRM-3010
1798 $isPaidMembership = TRUE;
1799 }
fb49fa48 1800 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id, $this->_values['amount_block_is_active']);
fa9d0451 1801
c98997b9 1802 if ($this->_values['amount_block_is_active']) {
246e7293 1803 $contributionTypeId = $this->_values['financial_type_id'];
236a2274
EM
1804 }
1805 else {
5624f515 1806 $contributionTypeId = CRM_Utils_Array::value('financial_type_id', $membershipType, CRM_Utils_Array::value('financial_type_id' ,$membershipParams));
236a2274
EM
1807 }
1808
705b4205 1809 CRM_Member_BAO_Membership::postProcessMembership($membershipParams, $contactID,
d25e4224 1810 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId, $isProcessSeparateMembershipTransaction, $contributionTypeId,
cc789d46 1811 $membershipLineItems, $isPayLater
705b4205
EM
1812 );
1813 $this->assign('membership_assign', TRUE);
1814 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1815 }
1816 catch (CRM_Core_Exception $e) {
1817 CRM_Core_Session::singleton()->setStatus($e->getMessage());
1818 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
1819 }
1820 }
fb49fa48
EM
1821
1822 /**
1823 * Are we going to do 2 financial transactions?
1824 * ie the membership block supports a separate transactions AND the contribution form has been configured for a contribution
1825 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1826 *
1827 *
014c4014 1828 * @param int $formID
fb49fa48
EM
1829 * @param bool $amountBlockActiveOnForm
1830 *
1831 * @return bool
1832 */
1833 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1834 $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($formID);
1835 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1836 return TRUE;
1837 }
1838 return FALSE;
1839 }
df6c4f28
EM
1840
1841 /**
1842 * This function sets the fields
1843 * - $this->_params['amount_level']
1844 * - $this->_params['selectMembership']
1845 * And under certain circumstances sets
1846 * $this->_params['amount'] = null;
1847 *
100fef9d 1848 * @param int $priceSetID
df6c4f28 1849 *
df6c4f28
EM
1850 */
1851 public function setFormAmountFields($priceSetID) {
1852 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config');
1853 $priceField = new CRM_Price_DAO_PriceField();
1854 $priceField->price_set_id = $priceSetID;
1855 $priceField->orderBy('weight');
1856 $priceField->find();
06b4ee3e 1857 $paramWeDoNotUnderstand = NULL;
df6c4f28
EM
1858
1859 while ($priceField->fetch()) {
df6c4f28
EM
1860 if ($priceField->name == "contribution_amount") {
1861 $paramWeDoNotUnderstand = $priceField->id;
1862 }
1863 if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) {
1864 if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') {
1865 $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1866 $this->_params["price_{$priceField->id}"], 'label');
1867 }
1868 if ($priceField->name == "membership_amount") {
1869 $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1870 $this->_params["price_{$priceField->id}"], 'membership_type_id');
1871 }
1872 } // if separate payment we set contribution amount to be null, so that it will not show contribution amount same as membership amount.
1873 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1874 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1875 // so we should merge them together
1876 // the quick config seems like a red-herring - if this is about a separate membership payment then there
f64a217a 1877 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
df6c4f28
EM
1878 elseif (
1879 CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock)
1880 && !empty($this->_values['fee'][$priceField->id])
1881 && ($this->_values['fee'][$priceField->id]['name'] == "other_amount")
1882 && CRM_Utils_Array::value("price_{$paramWeDoNotUnderstand}", $this->_params) < 1
1883 && empty($this->_params["price_{$priceField->id}"])
1884 ) {
1885 $this->_params['amount'] = null;
1886 }
1887
1888 // Fix for CRM-14375 - If we are using separate payments and "no
1889 // thank you" is selected for the additional contribution, set
1890 // contribution amount to be null, so that it will not show
1891 // contribution amount same as membership amount.
1892 //@todo - merge with section above
1893 if ($this->_membershipBlock['is_separate_payment']
3c0201c9 1894 && !empty($this->_values['fee'][$priceField->id])
df6c4f28
EM
1895 && CRM_Utils_Array::value('name', $this->_values['fee'][$priceField->id]) == 'contribution_amount'
1896 && CRM_Utils_Array::value("price_{$priceField->id}", $this->_params) == '-1'
1897 ) {
1898 $this->_params['amount'] = null;
1899 }
1900 }
1901 }
be26f3e0 1902
03110609
EM
1903 /**
1904 * @param array $params
1905 *
1906 * @throws CiviCRM_API3_Exception
1907 */
00be9182 1908 public static function submit($params) {
be26f3e0
EM
1909 $form = new CRM_Contribute_Form_Contribution_Confirm();
1910 $form->_id = $params['id'];
e6fa4056
EM
1911 if (!empty($params['contact_id'])) {
1912 $form->_contactID = $params['contact_id'];
1913 }
f64a217a
EM
1914 CRM_Contribute_BAO_ContributionPage::setValues($form->_id, $form->_values);
1915 $form->_separateMembershipPayment = CRM_Contribute_BAO_ContributionPage::getIsMembershipPayment($form->_id);
be26f3e0
EM
1916 //this way the mocked up controller ignores the session stuff
1917 $_SERVER['REQUEST_METHOD'] = 'GET';
1918 $form->controller = new CRM_Contribute_Controller_Contribution();
1919 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1920 $paramsProcessedForForm = $form->_params = self::getFormParams($params['id'], $params);
f64a217a 1921 $form->_amount = $params['amount'];
be26f3e0
EM
1922 $priceSetID = $form->_params['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1923 $priceFields = CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
f64a217a
EM
1924 $priceSetFields = reset($priceFields);
1925 $form->_values['fee'] = $priceSetFields['fields'];
5624f515 1926 $form->_priceSetId = $priceSetID;
be26f3e0 1927 $form->setFormAmountFields($priceSetID);
d25e4224
DG
1928 if (!empty($params['payment_processor'])) {
1929 $form->_paymentProcessor = civicrm_api3('payment_processor', 'getsingle', array('id' => $params['payment_processor']));
e6fa4056
EM
1930 if ($form->_paymentProcessor['billing_mode'] ==1) {
1931 $form->_contributeMode = 'direct';
1932 }
1933 else {
1934 $form->_contributeMode = 'notify';
1935 }
d25e4224 1936 }
07102c2c
EM
1937 else {
1938 $form->_params['payment_processor'] = 0;
1939 }
be26f3e0
EM
1940 $priceFields = $priceFields[$priceSetID]['fields'];
1941 CRM_Price_BAO_PriceSet::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1942 $form->_lineItem = array($priceSetID => $lineItems);
1943 $form->postProcess();
1944 }
1945
1946 /**
1947 * Helper function for static submit function - set relevant params - help us to build up an array that we can pass in
100fef9d 1948 * @param int $id
be26f3e0
EM
1949 * @param array $params
1950 *
1951 * @return array
1952 * @throws CiviCRM_API3_Exception
1953 */
00be9182 1954 public static function getFormParams($id, array $params) {
be26f3e0 1955 if(!isset($params['is_pay_later'])) {
d25e4224
DG
1956 if (!empty($params['payment_processor'])) {
1957 $params['is_pay_later'] = 0;
1958 }
1959 else {
1960 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1961 'id' => $id,
1962 'return' => 'is_pay_later'
1963 ));
1964 }
be26f3e0
EM
1965 }
1966 if(empty($params['price_set_id'])) {
1967 $params['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id']);
1968 }
1969 return $params;
1970 }
6a488035 1971}