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