Merge pull request #6905 from mattwire/CRM-17346
[civicrm-core.git] / CRM / Contribute / Form / Contribution / Main.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
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 * This class generates form components for processing a Contribution.
36 */
37 class CRM_Contribute_Form_Contribution_Main extends CRM_Contribute_Form_ContributionBase {
38
39 /**
40 * Define default MembershipType Id.
41 */
42 public $_defaultMemTypeId;
43
44 public $_paymentProcessors;
45
46 public $_membershipTypeValues;
47
48 public $_useForMember;
49
50 /**
51 * Array of payment related fields to potentially display on this form (generally credit card or debit card fields). This is rendered via billingBlock.tpl
52 * @var array
53 */
54 public $_paymentFields = array();
55
56 protected $_paymentProcessorID;
57 protected $_snippet;
58
59 /**
60 * Set variables up before form is built.
61 */
62 public function preProcess() {
63 parent::preProcess();
64
65 $this->_paymentProcessors = $this->get('paymentProcessors');
66 $this->preProcessPaymentOptions();
67
68 // Make the contributionPageID available to the template
69 $this->assign('contributionPageID', $this->_id);
70 $this->assign('isShare', CRM_Utils_Array::value('is_share', $this->_values));
71 $this->assign('isConfirmEnabled', CRM_Utils_Array::value('is_confirm_enabled', $this->_values));
72
73 $this->assign('reset', CRM_Utils_Request::retrieve('reset', 'Boolean', CRM_Core_DAO::$_nullObject));
74 $this->assign('mainDisplay', CRM_Utils_Request::retrieve('_qf_Main_display', 'Boolean',
75 CRM_Core_DAO::$_nullObject));
76
77 if (!empty($this->_pcpInfo['id']) && !empty($this->_pcpInfo['intro_text'])) {
78 $this->assign('intro_text', $this->_pcpInfo['intro_text']);
79 }
80 elseif (!empty($this->_values['intro_text'])) {
81 $this->assign('intro_text', $this->_values['intro_text']);
82 }
83
84 $qParams = "reset=1&amp;id={$this->_id}";
85 if ($pcpId = CRM_Utils_Array::value('pcp_id', $this->_pcpInfo)) {
86 $qParams .= "&amp;pcpId={$pcpId}";
87 }
88 $this->assign('qParams', $qParams);
89
90 if (!empty($this->_values['footer_text'])) {
91 $this->assign('footer_text', $this->_values['footer_text']);
92 }
93 }
94
95 /**
96 * Set the default values.
97 */
98 public function setDefaultValues() {
99 // check if the user is registered and we have a contact ID
100 $contactID = $this->getContactID();
101
102 if (!empty($contactID)) {
103 $fields = array();
104 $removeCustomFieldTypes = array('Contribution', 'Membership');
105 $contribFields = CRM_Contribute_BAO_Contribution::getContributionFields();
106
107 // remove component related fields
108 foreach ($this->_fields as $name => $dontCare) {
109 //don't set custom data Used for Contribution (CRM-1344)
110 if (substr($name, 0, 7) == 'custom_') {
111 $id = substr($name, 7);
112 if (!CRM_Core_BAO_CustomGroup::checkCustomField($id, $removeCustomFieldTypes)) {
113 continue;
114 }
115 // ignore component fields
116 }
117 elseif (array_key_exists($name, $contribFields) || (substr($name, 0, 11) == 'membership_') || (substr($name, 0, 13) == 'contribution_')) {
118 continue;
119 }
120 $fields[$name] = 1;
121 }
122
123 if (!empty($fields)) {
124 CRM_Core_BAO_UFGroup::setProfileDefaults($contactID, $fields, $this->_defaults);
125 }
126
127 $billingDefaults = $this->getProfileDefaults('Billing', $contactID);
128 $this->_defaults = array_merge($this->_defaults, $billingDefaults);
129 }
130
131 //set custom field defaults set by admin if value is not set
132 if (!empty($this->_fields)) {
133 //load default campaign from page.
134 if (array_key_exists('contribution_campaign_id', $this->_fields)) {
135 $this->_defaults['contribution_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
136 }
137
138 //set custom field defaults
139 foreach ($this->_fields as $name => $field) {
140 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
141 if (!isset($this->_defaults[$name])) {
142 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults,
143 NULL, CRM_Profile_Form::MODE_REGISTER
144 );
145 }
146 }
147 }
148 }
149
150 /*
151 * hack to simplify credit card entry for testing
152 *
153 * $this->_defaults['credit_card_type'] = 'Visa';
154 * $this->_defaults['amount'] = 168;
155 * $this->_defaults['credit_card_number'] = '4111111111111111';
156 * $this->_defaults['cvv2'] = '000';
157 * $this->_defaults['credit_card_exp_date'] = array('Y' => date('Y')+1, 'M' => '05');
158 * // hack to simplify direct debit entry for testing
159 * $this->_defaults['account_holder'] = 'Max Müller';
160 * $this->_defaults['bank_account_number'] = '12345678';
161 * $this->_defaults['bank_identification_number'] = '12030000';
162 * $this->_defaults['bank_name'] = 'Bankname';
163 */
164
165 //build set default for pledge overdue payment.
166 if (!empty($this->_values['pledge_id'])) {
167 //used to record completed pledge payment ids used later for honor default
168 $completedContributionIds = array();
169 $pledgePayments = CRM_Pledge_BAO_PledgePayment::getPledgePayments($this->_values['pledge_id']);
170
171 $duePayment = FALSE;
172 foreach ($pledgePayments as $payId => $value) {
173 if ($value['status'] == 'Overdue') {
174 $this->_defaults['pledge_amount'][$payId] = 1;
175 }
176 elseif (!$duePayment && $value['status'] == 'Pending') {
177 $this->_defaults['pledge_amount'][$payId] = 1;
178 $duePayment = TRUE;
179 }
180 elseif ($value['status'] == 'Completed' && $value['contribution_id']) {
181 $completedContributionIds[] = $value['contribution_id'];
182 }
183 }
184
185 if (count($completedContributionIds)) {
186 $softCredit = array();
187 foreach ($completedContributionIds as $id) {
188 $softCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id);
189 }
190 if (isset($softCredit['soft_credit'])) {
191 $this->_defaults['soft_credit_type_id'] = $softCredit['soft_credit'][1]['soft_credit_type'];
192
193 //since honoree profile fieldname of fields are prefixed with 'honor'
194 //we need to reformat the fieldname to append prefix during setting default values
195 CRM_Core_BAO_UFGroup::setProfileDefaults(
196 $softCredit['soft_credit'][1]['contact_id'],
197 CRM_Core_BAO_UFGroup::getFields($this->_honoreeProfileId),
198 $defaults
199 );
200 foreach ($defaults as $fieldName => $value) {
201 $this->_defaults['honor[' . $fieldName . ']'] = $value;
202 }
203 }
204 }
205 }
206 elseif (!empty($this->_values['pledge_block_id'])) {
207 //set default to one time contribution.
208 $this->_defaults['is_pledge'] = 0;
209 }
210
211 // to process Custom data that are appended to URL
212 $getDefaults = CRM_Core_BAO_CustomGroup::extractGetParams($this, "'Contact', 'Individual', 'Contribution'");
213 $this->_defaults = array_merge($this->_defaults, $getDefaults);
214
215 $config = CRM_Core_Config::singleton();
216 // set default country from config if no country set
217 if (empty($this->_defaults["billing_country_id-{$this->_bltID}"])) {
218 $this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
219 }
220
221 // set default state/province from config if no state/province set
222 if (empty($this->_defaults["billing_state_province_id-{$this->_bltID}"])) {
223 $this->_defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
224 }
225
226 if ($this->_priceSetId) {
227 if (($this->_useForMember && !empty($this->_currentMemberships)) || $this->_defaultMemTypeId) {
228 $selectedCurrentMemTypes = array();
229 foreach ($this->_priceSet['fields'] as $key => $val) {
230 foreach ($val['options'] as $keys => $values) {
231 $opMemTypeId = CRM_Utils_Array::value('membership_type_id', $values);
232 $priceFieldName = 'price_' . $values['price_field_id'];
233 $priceFieldValue = CRM_Price_BAO_PriceSet::getPriceFieldValueFromURL($this, $priceFieldName);
234 if (!empty($priceFieldValue)) {
235 CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $this->_defaults);
236 // break here to prevent overwriting of default due to 'is_default'
237 // option configuration or setting of current membership or
238 // membership for related organization.
239 // The value sent via URL get's higher priority.
240 break;
241 }
242 elseif ($opMemTypeId &&
243 in_array($opMemTypeId, $this->_currentMemberships) &&
244 !in_array($opMemTypeId, $selectedCurrentMemTypes)
245 ) {
246 CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults);
247 $selectedCurrentMemTypes[] = $values['membership_type_id'];
248 }
249 elseif (!empty($values['is_default']) &&
250 !$opMemTypeId &&
251 (!isset($this->_defaults[$priceFieldName]) ||
252 ($val['html_type'] == 'CheckBox' &&
253 !isset($this->_defaults[$priceFieldName][$keys]))
254 )) {
255 CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults);
256 }
257 }
258 }
259 }
260 else {
261 CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $this->_defaults);
262 }
263 }
264
265 if (!empty($this->_paymentProcessors)) {
266 foreach ($this->_paymentProcessors as $pid => $value) {
267 if (!empty($value['is_default'])) {
268 $this->_defaults['payment_processor_id'] = $pid;
269 }
270 }
271 }
272
273 return $this->_defaults;
274 }
275
276 /**
277 * Build the form object.
278 */
279 public function buildQuickForm() {
280 // build profiles first so that we can determine address fields etc
281 // and then show copy address checkbox
282 $this->buildCustom($this->_values['custom_pre_id'], 'customPre');
283 $this->buildCustom($this->_values['custom_post_id'], 'customPost');
284
285 $this->buildComponentForm($this->_id, $this);
286
287 if (!empty($this->_fields) && !empty($this->_values['custom_pre_id'])) {
288 $profileAddressFields = array();
289 foreach ($this->_fields as $key => $value) {
290 CRM_Core_BAO_UFField::assignAddressField($key, $profileAddressFields, array('uf_group_id' => $this->_values['custom_pre_id']));
291 }
292 $this->set('profileAddressFields', $profileAddressFields);
293 }
294
295 // Build payment processor form
296 CRM_Core_Payment_ProcessorForm::buildQuickForm($this);
297
298 $config = CRM_Core_Config::singleton();
299
300 $contactID = $this->getContactID();
301 if ($contactID) {
302 $this->assign('contact_id', $contactID);
303 $this->assign('display_name', CRM_Contact_BAO_Contact::displayName($contactID));
304 }
305
306 $this->applyFilter('__ALL__', 'trim');
307 $this->add('text', "email-{$this->_bltID}",
308 ts('Email Address'),
309 array('size' => 30, 'maxlength' => 60, 'class' => 'email'),
310 TRUE
311 );
312 $this->addRule("email-{$this->_bltID}", ts('Email is not valid.'), 'email');
313 $pps = array();
314 //@todo - this should be replaced by a check as to whether billing fields are set
315 $onlinePaymentProcessorEnabled = FALSE;
316 if (!empty($this->_paymentProcessors)) {
317 foreach ($this->_paymentProcessors as $key => $name) {
318 if ($name['billing_mode'] == 1) {
319 $onlinePaymentProcessorEnabled = TRUE;
320 }
321 $pps[$key] = $name['name'];
322 }
323 }
324 if (!empty($this->_values['is_pay_later'])) {
325 $pps[0] = $this->_values['pay_later_text'];
326 }
327
328 if (count($pps) > 1) {
329 $this->addRadio('payment_processor_id', ts('Payment Method'), $pps,
330 NULL, "&nbsp;", TRUE
331 );
332 }
333 elseif (!empty($pps)) {
334 $key = array_keys($pps);
335 $key = array_pop($key);
336 $this->addElement('hidden', 'payment_processor_id', $key);
337 if ($key === 0) {
338 $this->assign('is_pay_later', $this->_values['is_pay_later']);
339 $this->assign('pay_later_text', $this->_values['pay_later_text']);
340 }
341 }
342
343 $contactID = $this->getContactID();
344 if ($this->getContactID() === 0) {
345 $this->addCidZeroOptions($onlinePaymentProcessorEnabled);
346 }
347
348 //build pledge block.
349 $this->_useForMember = 0;
350 //don't build membership block when pledge_id is passed
351 if (empty($this->_values['pledge_id'])) {
352 $this->_separateMembershipPayment = FALSE;
353 if (in_array('CiviMember', $config->enableComponents)) {
354 $isTest = 0;
355 if ($this->_action & CRM_Core_Action::PREVIEW) {
356 $isTest = 1;
357 }
358
359 if ($this->_priceSetId &&
360 (CRM_Core_Component::getComponentID('CiviMember') == CRM_Utils_Array::value('extends', $this->_priceSet))
361 ) {
362 $this->_useForMember = 1;
363 $this->set('useForMember', $this->_useForMember);
364 }
365
366 $this->_separateMembershipPayment = $this->buildMembershipBlock(
367 $this->_membershipContactID,
368 TRUE, NULL, FALSE,
369 $isTest
370 );
371 }
372 $this->set('separateMembershipPayment', $this->_separateMembershipPayment);
373 }
374 $this->assign('useForMember', $this->_useForMember);
375 // If we configured price set for contribution page
376 // we are not allow membership signup as well as any
377 // other contribution amount field, CRM-5095
378 if (isset($this->_priceSetId) && $this->_priceSetId) {
379 $this->add('hidden', 'priceSetId', $this->_priceSetId);
380 // build price set form.
381 $this->set('priceSetId', $this->_priceSetId);
382 CRM_Price_BAO_PriceSet::buildPriceSet($this);
383 if ($this->_values['is_monetary'] &&
384 $this->_values['is_recur'] && empty($this->_values['pledge_id'])
385 ) {
386 self::buildRecur($this);
387 }
388 }
389
390 if ($this->_priceSetId) {
391 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
392 if ($is_quick_config) {
393 $this->_useForMember = 0;
394 $this->set('useForMember', $this->_useForMember);
395 }
396 }
397
398 //we allow premium for pledge during pledge creation only.
399 if (empty($this->_values['pledge_id'])) {
400 CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, TRUE);
401 }
402
403 //don't build pledge block when mid is passed
404 if (!$this->_mid) {
405 $config = CRM_Core_Config::singleton();
406 if (in_array('CiviPledge', $config->enableComponents) && !empty($this->_values['pledge_block_id'])) {
407 CRM_Pledge_BAO_PledgeBlock::buildPledgeBlock($this);
408 }
409 }
410
411 //to create an cms user
412 if (!$this->_contactID) {
413 $createCMSUser = FALSE;
414
415 if ($this->_values['custom_pre_id']) {
416 $profileID = $this->_values['custom_pre_id'];
417 $createCMSUser = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_cms_user');
418 }
419
420 if (!$createCMSUser &&
421 $this->_values['custom_post_id']
422 ) {
423 if (!is_array($this->_values['custom_post_id'])) {
424 $profileIDs = array($this->_values['custom_post_id']);
425 }
426 else {
427 $profileIDs = $this->_values['custom_post_id'];
428 }
429 foreach ($profileIDs as $pid) {
430 if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $pid, 'is_cms_user')) {
431 $profileID = $pid;
432 $createCMSUser = TRUE;
433 break;
434 }
435 }
436 }
437
438 if ($createCMSUser) {
439 CRM_Core_BAO_CMSUser::buildForm($this, $profileID, TRUE);
440 }
441 }
442 if ($this->_pcpId) {
443 if ($pcpSupporter = CRM_PCP_BAO_PCP::displayName($this->_pcpId)) {
444 $pcp_supporter_text = ts('This contribution is being made thanks to the effort of <strong>%1</strong>, who supports our campaign.', array(1 => $pcpSupporter));
445 // Only tell people that can also create a PCP if the contribution page has a non-empty value in the "Create Personal Campaign Page link" field.
446 $text = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute');
447 if (!empty($text)) {
448 $pcp_supporter_text .= ts("You can support it as well - once you complete the donation, you will be able to create your own Personal Campaign Page!");
449 }
450 $this->assign('pcpSupporterText', $pcp_supporter_text);
451 }
452 $prms = array('id' => $this->_pcpId);
453 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
454 if ($pcpInfo['is_honor_roll']) {
455 $this->assign('isHonor', TRUE);
456 $this->add('checkbox', 'pcp_display_in_roll', ts('Show my contribution in the public honor roll'), NULL, NULL,
457 array('onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );")
458 );
459 $extraOption = array('onclick' => "return pcpAnonymous( );");
460 $elements = array();
461 $elements[] = &$this->createElement('radio', NULL, '', ts('Include my name and message'), 0, $extraOption);
462 $elements[] = &$this->createElement('radio', NULL, '', ts('List my contribution anonymously'), 1, $extraOption);
463 $this->addGroup($elements, 'pcp_is_anonymous', NULL, '&nbsp;&nbsp;&nbsp;');
464
465 $this->add('text', 'pcp_roll_nickname', ts('Name'), array('maxlength' => 30));
466 $this->add('textarea', 'pcp_personal_note', ts('Personal Note'), array('style' => 'height: 3em; width: 40em;'));
467 }
468 }
469 if (empty($this->_values['fee'])) {
470 CRM_Core_Error::fatal(ts('This page does not have any price fields configured or you may not have permission for them. Please contact the site administrator for more details.'));
471 }
472
473 //we have to load confirm contribution button in template
474 //when multiple payment processor as the user
475 //can toggle with payment processor selection
476 $billingModePaymentProcessors = 0;
477 if (!empty($this->_paymentProcessors)) {
478 foreach ($this->_paymentProcessors as $key => $values) {
479 if ($values['billing_mode'] == CRM_Core_Payment::BILLING_MODE_BUTTON) {
480 $billingModePaymentProcessors++;
481 }
482 }
483 }
484
485 if ($billingModePaymentProcessors && count($this->_paymentProcessors) == $billingModePaymentProcessors) {
486 $allAreBillingModeProcessors = TRUE;
487 }
488 else {
489 $allAreBillingModeProcessors = FALSE;
490 }
491
492 if (!($allAreBillingModeProcessors && !$this->_values['is_pay_later'])) {
493 $submitButton = array(
494 'type' => 'upload',
495 'name' => CRM_Utils_Array::value('is_confirm_enabled', $this->_values) ? ts('Confirm Contribution') : ts('Contribute'),
496 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
497 'isDefault' => TRUE,
498 );
499 // Add submit-once behavior when confirm page disabled
500 if (empty($this->_values['is_confirm_enabled'])) {
501 $submitButton['js'] = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
502 }
503 $this->addButtons(array($submitButton));
504 }
505
506 $this->addFormRule(array('CRM_Contribute_Form_Contribution_Main', 'formRule'), $this);
507 }
508
509 /**
510 * Build elements to collect information for recurring contributions.
511 *
512 *
513 * @param CRM_Core_Form $form
514 */
515 public static function buildRecur(&$form) {
516 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur');
517 $className = get_class($form);
518
519 $form->assign('is_recur_interval', CRM_Utils_Array::value('is_recur_interval', $form->_values));
520 $form->assign('is_recur_installments', CRM_Utils_Array::value('is_recur_installments', $form->_values));
521
522 $form->add('checkbox', 'is_recur', ts('I want to contribute this amount'), NULL);
523
524 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
525 $form->add('text', 'frequency_interval', ts('Every'), $attributes['frequency_interval']);
526 $form->addRule('frequency_interval', ts('Frequency must be a whole number (EXAMPLE: Every 3 months).'), 'integer');
527 }
528 else {
529 // make sure frequency_interval is submitted as 1 if given no choice to user.
530 $form->add('hidden', 'frequency_interval', 1);
531 }
532
533 $frUnits = CRM_Utils_Array::value('recur_frequency_unit', $form->_values);
534 if (empty($frUnits) &&
535 $className == 'CRM_Contribute_Form_Contribution'
536 ) {
537 $frUnits = implode(CRM_Core_DAO::VALUE_SEPARATOR,
538 CRM_Core_OptionGroup::values('recur_frequency_units')
539 );
540 }
541
542 $unitVals = explode(CRM_Core_DAO::VALUE_SEPARATOR, $frUnits);
543
544 // CRM 10860, display text instead of a dropdown if there's only 1 frequency unit
545 if (count($unitVals) == 1) {
546 $form->assign('one_frequency_unit', TRUE);
547 $unit = $unitVals[0];
548 $form->add('hidden', 'frequency_unit', $unit);
549 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
550 $unit .= "(s)";
551 }
552 $form->assign('frequency_unit', $unit);
553 }
554 else {
555 $form->assign('one_frequency_unit', FALSE);
556 $units = array();
557 $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units', FALSE, FALSE, TRUE);
558 foreach ($unitVals as $key => $val) {
559 if (array_key_exists($val, $frequencyUnits)) {
560 $units[$val] = $frequencyUnits[$val];
561 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
562 $units[$val] = "{$frequencyUnits[$val]}(s)";
563 }
564 }
565 }
566 $frequencyUnit = &$form->add('select', 'frequency_unit', NULL, $units);
567 }
568
569 // FIXME: Ideally we should freeze select box if there is only
570 // one option but looks there is some problem /w QF freeze.
571 //if ( count( $units ) == 1 ) {
572 //$frequencyUnit->freeze( );
573 //}
574
575 $form->add('text', 'installments', ts('installments'),
576 $attributes['installments']
577 );
578 $form->addRule('installments', ts('Number of installments must be a whole number.'), 'integer');
579 }
580
581 /**
582 * Global form rule.
583 *
584 * @param array $fields
585 * The input form values.
586 * @param array $files
587 * The uploaded files if any.
588 * @param CRM_Core_Form $self
589 *
590 * @return bool|array
591 * true if no errors, else array of errors
592 */
593 public static function formRule($fields, $files, $self) {
594 $errors = array();
595 $amount = self::computeAmount($fields, $self->_values);
596
597 if ((!empty($fields['selectMembership']) &&
598 $fields['selectMembership'] != 'no_thanks'
599 ) ||
600 (!empty($fields['priceSetId']) &&
601 $self->_useForMember
602 )
603 ) {
604 $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, FALSE, TRUE);
605
606 $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization();
607
608 $unallowedOrgs = array();
609 foreach (array_keys($lifeMember) as $memTypeId) {
610 $unallowedOrgs[] = $membershipOrgDetails[$memTypeId];
611 }
612 }
613
614 //check for atleast one pricefields should be selected
615 if (!empty($fields['priceSetId'])) {
616 $priceField = new CRM_Price_DAO_PriceField();
617 $priceField->price_set_id = $fields['priceSetId'];
618 $priceField->orderBy('weight');
619 $priceField->find();
620
621 $check = array();
622 $membershipIsActive = TRUE;
623 $previousId = $otherAmount = FALSE;
624 while ($priceField->fetch()) {
625
626 if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) {
627 $previousId = $priceField->id;
628 if ($priceField->name == 'membership_amount' && !$priceField->is_active) {
629 $membershipIsActive = FALSE;
630 }
631 }
632 if ($priceField->name == 'other_amount') {
633 if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) &&
634 array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])
635 ) {
636 $otherAmount = $priceField->id;
637 }
638 elseif (!empty($fields["price_{$priceField->id}"])) {
639 $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]);
640 $min = CRM_Utils_Array::value('min_amount', $self->_values);
641 $max = CRM_Utils_Array::value('max_amount', $self->_values);
642 if ($min && $otherAmountVal < $min) {
643 $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1',
644 array(1 => $min)
645 );
646 }
647 if ($max && $otherAmountVal > $max) {
648 $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.',
649 array(1 => $max)
650 );
651 }
652 }
653 }
654 if (!empty($fields["price_{$priceField->id}"]) || ($previousId == $priceField->id && isset($fields["price_{$previousId}"])
655 && empty($fields["price_{$previousId}"]))
656 ) {
657 $check[] = $priceField->id;
658 }
659 }
660
661 $currentMemberships = NULL;
662 if ($membershipIsActive) {
663 $is_test = $self->_mode != 'live' ? 1 : 0;
664 $memContactID = $self->_membershipContactID;
665
666 // For anonymous user check using dedupe rule
667 // if user has Cancelled Membership
668 if (!$memContactID) {
669 $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
670 $dedupeParams['check_permission'] = FALSE;
671 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
672 // if we find more than one contact, use the first one
673 $memContactID = CRM_Utils_Array::value(0, $ids);
674 }
675 $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID,
676 $is_test
677 );
678
679 $errorText = 'Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.';
680 foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
681 if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array::value('price_' . $fieldKey, $fields)) {
682 if (!is_array($fields['price_' . $fieldKey])) {
683 if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]])
684 && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)
685 ) {
686 $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'])));
687 }
688 }
689 else {
690 foreach ($fields['price_' . $fieldKey] as $key => $ignore) {
691 if (array_key_exists('membership_type_id', $fieldValue['options'][$key])
692 && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)
693 ) {
694 $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$key]['membership_type_id'])));
695 }
696 }
697 }
698 }
699 }
700 }
701
702 // CRM-12233
703 if ($membershipIsActive && !$self->_membershipBlock['is_required']
704 && $self->_values['amount_block_is_active']
705 ) {
706 $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL;
707 foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
708 // if 'No thank you' membership is selected then set $membershipFieldId
709 if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) {
710 $membershipFieldId = $fieldKey;
711 }
712 elseif ($membershipFieldId) {
713 if ($fieldValue['name'] == 'other_amount') {
714 $otherFieldId = $fieldKey;
715 }
716 elseif ($fieldValue['name'] == 'contribution_amount') {
717 $contributionFieldId = $fieldKey;
718 }
719
720 if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') {
721 $errorKey = $fieldKey;
722 }
723 }
724 }
725 // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error
726 if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) {
727 $errors["price_{$errorKey}"] = ts('Additional Contribution is required.');
728 }
729 }
730 if (empty($check)) {
731 if ($self->_useForMember == 1 && $membershipIsActive) {
732 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
733 }
734 else {
735 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
736 }
737 }
738 if ($otherAmount && !empty($check)) {
739 $errors["price_{$otherAmount}"] = ts('Amount is required field.');
740 }
741
742 if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) {
743 $priceFieldIDS = array();
744 $priceFieldMemTypes = array();
745
746 foreach ($self->_priceSet['fields'] as $priceId => $value) {
747 if (!empty($fields['price_' . $priceId]) || ($self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required']))) {
748 if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) {
749 foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
750 if ($isSet) {
751 $priceFieldIDS[] = $priceFldVal;
752 }
753 }
754 }
755 elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) {
756 // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
757 // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
758 $priceFieldIDS[] = $fields['price_' . $priceId];
759 }
760
761 if (!empty($value['options'])) {
762 foreach ($value['options'] as $val) {
763 if (!empty($val['membership_type_id']) && (
764 ($fields['price_' . $priceId] == $val['id']) ||
765 (isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))
766 )
767 ) {
768 $priceFieldMemTypes[] = $val['membership_type_id'];
769 }
770 }
771 }
772 }
773 }
774
775 if (!empty($lifeMember)) {
776 foreach ($priceFieldIDS as $priceFieldId) {
777 if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) &&
778 in_array($membershipOrgDetails[$id], $unallowedOrgs)
779 ) {
780 $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
781 break;
782 }
783 }
784 }
785
786 if (!empty($priceFieldIDS)) {
787 $ids = implode(',', $priceFieldIDS);
788
789 $priceFieldIDS['id'] = $fields['priceSetId'];
790 $self->set('memberPriceFieldIDS', $priceFieldIDS);
791 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
792 foreach ($count as $id => $occurrence) {
793 if ($occurrence > 1) {
794 $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.');
795 }
796 }
797 }
798
799 if (empty($priceFieldMemTypes)) {
800 $errors['_qf_default'] = ts('Please select at least one membership option.');
801 }
802 }
803
804 CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'],
805 $fields, $lineItem
806 );
807
808 if ($fields['amount'] < 0) {
809 $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
810 }
811 $amount = $fields['amount'];
812 }
813
814 if (isset($fields['selectProduct']) &&
815 $fields['selectProduct'] != 'no_thanks'
816 ) {
817 $productDAO = new CRM_Contribute_DAO_Product();
818 $productDAO->id = $fields['selectProduct'];
819 $productDAO->find(TRUE);
820 $min_amount = $productDAO->min_contribution;
821
822 if ($amount < $min_amount) {
823 $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount)));
824 CRM_Core_Session::setStatus($errors['selectProduct']);
825 }
826 }
827
828 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
829 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
830
831 if (!empty($fields['is_recur']) &&
832 CRM_Utils_Array::value('payment_processor_id', $fields) == 0
833 ) {
834 $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
835 }
836
837 // validate PCP fields - if not anonymous, we need a nick name value
838 if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) &&
839 (CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0) &&
840 CRM_Utils_Array::value('pcp_roll_nickname', $fields) == ''
841 ) {
842 $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
843 }
844
845 // return if this is express mode
846 $config = CRM_Core_Config::singleton();
847 if ($self->_paymentProcessor &&
848 $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON
849 ) {
850 if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) ||
851 CRM_Utils_Array::value($self->_expressButtonName, $fields)
852 ) {
853 return $errors;
854 }
855 }
856
857 //validate the pledge fields.
858 if (!empty($self->_values['pledge_block_id'])) {
859 //validation for pledge payment.
860 if (!empty($self->_values['pledge_id'])) {
861 if (empty($fields['pledge_amount'])) {
862 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
863 }
864 }
865 elseif (!empty($fields['is_pledge'])) {
866 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) {
867 $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.');
868 }
869 else {
870 if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) {
871 $errors['pledge_installments'] = ts('Pledge Installments is required field.');
872 }
873 elseif (CRM_Utils_array::value('pledge_installments', $fields) == 1) {
874 $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.');
875 }
876 elseif (CRM_Utils_array::value('pledge_installments', $fields) == 0) {
877 $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
878 }
879 }
880
881 //validation for Pledge Frequency Interval.
882 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) {
883 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
884 }
885 else {
886 if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) {
887 $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
888 }
889 elseif (CRM_Utils_array::value('pledge_frequency_interval', $fields) == 0) {
890 $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
891 }
892 }
893 }
894 }
895
896 // also return if paylater mode
897 if (CRM_Utils_Array::value('payment_processor_id', $fields) == 0 && $self->_isBillingAddressRequiredForPayLater == 0) {
898 return empty($errors) ? TRUE : $errors;
899 }
900
901 // if the user has chosen a free membership or the amount is less than zero
902 // i.e. we skip calling the payment processor and hence dont need credit card
903 // info
904 if ((float) $amount <= 0.0) {
905 return $errors;
906 }
907
908 if (!empty($self->_paymentFields)) {
909 CRM_Core_Form::validateMandatoryFields($self->_paymentFields, $fields, $errors);
910 }
911 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
912
913 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
914 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
915 $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
916 if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) {
917 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
918 array(1 => ucwords(str_replace('_', " ", $greeting)))
919 );
920 }
921 }
922 }
923
924 return empty($errors) ? TRUE : $errors;
925 }
926
927 /**
928 * Compute amount to be paid.
929 *
930 * @param array $params
931 * @param array $formValues
932 *
933 * @return int|mixed|null|string
934 */
935 public static function computeAmount($params, $formValues) {
936 $amount = 0;
937 // First clean up the other amount field if present.
938 if (isset($params['amount_other'])) {
939 $params['amount_other'] = CRM_Utils_Rule::cleanMoney($params['amount_other']);
940 }
941
942 if (CRM_Utils_Array::value('amount', $params) == 'amount_other_radio' || !empty($params['amount_other'])) {
943 $amount = $params['amount_other'];
944 }
945 elseif (!empty($params['pledge_amount'])) {
946 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
947 $amount += CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount');
948 }
949 }
950 else {
951 if (!empty($formValues['amount'])) {
952 $amountID = CRM_Utils_Array::value('amount', $params);
953
954 if ($amountID) {
955 $params['amount_level'] = CRM_Utils_Array::value('label', $formValues[$amountID]);
956 $amount = CRM_Utils_Array::value('value', $formValues[$amountID]);
957 }
958 }
959 }
960 return $amount;
961 }
962
963 /**
964 * Process the form submission.
965 */
966 public function postProcess() {
967 // we first reset the confirm page so it accepts new values
968 $this->controller->resetPage('Confirm');
969
970 // get the submitted form values.
971 $params = $this->controller->exportValues($this->_name);
972 $this->submit($params);
973
974 if (empty($this->_values['is_confirm_enabled'])) {
975 $this->skipToThankYouPage();
976 }
977
978 }
979
980 /**
981 * Submit function.
982 *
983 * This is the guts of the postProcess made also accessible to the test suite.
984 *
985 * @param array $params
986 * Submitted values.
987 */
988 public function submit($params) {
989 //carry campaign from profile.
990 if (array_key_exists('contribution_campaign_id', $params)) {
991 $params['campaign_id'] = $params['contribution_campaign_id'];
992 }
993
994 $params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
995
996 if (!empty($params['priceSetId'])) {
997 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
998 if ($is_quick_config) {
999 $priceField = new CRM_Price_DAO_PriceField();
1000 $priceField->price_set_id = $params['priceSetId'];
1001 $priceField->orderBy('weight');
1002 $priceField->find();
1003
1004 $priceOptions = array();
1005 while ($priceField->fetch()) {
1006 CRM_Price_BAO_PriceFieldValue::getValues($priceField->id, $priceOptions);
1007 if ($selectedPriceOptionID = CRM_Utils_Array::value("price_{$priceField->id}", $params)) {
1008 switch ($priceField->name) {
1009 case 'membership_amount':
1010 $this->_params['selectMembership'] = $params['selectMembership'] = CRM_Utils_Array::value('membership_type_id', $priceOptions[$selectedPriceOptionID]);
1011 $this->set('selectMembership', $params['selectMembership']);
1012 if (CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) == 0) {
1013 $this->_values['amount'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
1014 }
1015 break;
1016
1017 case 'contribution_amount':
1018 $params['amount'] = $selectedPriceOptionID;
1019 $this->_values['amount'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
1020 $this->_values[$selectedPriceOptionID]['value'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
1021 $this->_values[$selectedPriceOptionID]['label'] = CRM_Utils_Array::value('label', $priceOptions[$selectedPriceOptionID]);
1022 $this->_values[$selectedPriceOptionID]['amount_id'] = CRM_Utils_Array::value('id', $priceOptions[$selectedPriceOptionID]);
1023 $this->_values[$selectedPriceOptionID]['weight'] = CRM_Utils_Array::value('weight', $priceOptions[$selectedPriceOptionID]);
1024 break;
1025
1026 case 'other_amount':
1027 $params['amount_other'] = $selectedPriceOptionID;
1028 break;
1029 }
1030 }
1031 }
1032 }
1033 }
1034
1035 if (($this->_values['is_pay_later'] &&
1036 empty($this->_paymentProcessor) &&
1037 !array_key_exists('hidden_processor', $params)) ||
1038 (!empty($params['payment_processor_id']) && $params['payment_processor_id'] == 0)
1039 ) {
1040 $params['is_pay_later'] = 1;
1041 }
1042 else {
1043 $params['is_pay_later'] = 0;
1044 }
1045
1046 // Would be nice to someday understand the point of this set.
1047 $this->set('is_pay_later', $params['is_pay_later']);
1048 // assign pay later stuff
1049 $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
1050 $this->assign('is_pay_later', $params['is_pay_later']);
1051 if ($params['is_pay_later']) {
1052 $this->assign('pay_later_text', $this->_values['pay_later_text']);
1053 $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
1054 }
1055
1056 // from here on down, $params['amount'] holds a monetary value (or null) rather than an option ID
1057 $params['amount'] = self::computeAmount($params, $this->_values);
1058 $params['separate_amount'] = $params['amount'];
1059 $memFee = NULL;
1060 if (!empty($params['selectMembership'])) {
1061 if (empty($this->_membershipTypeValues)) {
1062 $this->_membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this,
1063 (array) $params['selectMembership']
1064 );
1065 }
1066 $membershipTypeValues = $this->_membershipTypeValues[$params['selectMembership']];
1067 $memFee = $membershipTypeValues['minimum_fee'];
1068 if (!$params['amount'] && !$this->_separateMembershipPayment) {
1069 $params['amount'] = $memFee ? $memFee : 0;
1070 }
1071 }
1072 //If the membership & contribution is used in contribution page & not separate payment
1073 $fieldId = $memPresent = $membershipLabel = $fieldOption = $is_quick_config = NULL;
1074 $proceFieldAmount = 0;
1075 if (property_exists($this, '_separateMembershipPayment') && $this->_separateMembershipPayment == 0) {
1076 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
1077 if ($is_quick_config) {
1078 foreach ($this->_priceSet['fields'] as $fieldKey => $fieldVal) {
1079 if ($fieldVal['name'] == 'membership_amount' && !empty($params['price_' . $fieldKey])) {
1080 $fieldId = $fieldVal['id'];
1081 $fieldOption = $params['price_' . $fieldId];
1082 $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
1083 $memPresent = TRUE;
1084 }
1085 else {
1086 if (!empty($params['price_' . $fieldKey]) && $memPresent && ($fieldVal['name'] == 'other_amount' || $fieldVal['name'] == 'contribution_amount')) {
1087 $fieldId = $fieldVal['id'];
1088 if ($fieldVal['name'] == 'other_amount') {
1089 $proceFieldAmount += $this->_submitValues['price_' . $fieldId];
1090 }
1091 elseif ($fieldVal['name'] == 'contribution_amount' && $this->_submitValues['price_' . $fieldId] > 0) {
1092 $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
1093 }
1094 unset($params['price_' . $fieldId]);
1095 break;
1096 }
1097 }
1098 }
1099 }
1100 }
1101
1102 if (!isset($params['amount_other'])) {
1103 $this->set('amount_level', CRM_Utils_Array::value('amount_level', $params));
1104 }
1105
1106 if ($priceSetId = CRM_Utils_Array::value('priceSetId', $params)) {
1107 $lineItem = array();
1108 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1109 if ($is_quick_config) {
1110 foreach ($this->_values['fee'] as $key => & $val) {
1111 if ($val['name'] == 'other_amount' && $val['html_type'] == 'Text' && !empty($params['price_' . $key])) {
1112 // Clean out any currency symbols.
1113 $params['price_' . $key] = CRM_Utils_Rule::cleanMoney($params['price_' . $key]);
1114 if ($params['price_' . $key] != 0) {
1115 foreach ($val['options'] as $optionKey => & $options) {
1116 $options['amount'] = CRM_Utils_Array::value('price_' . $key, $params);
1117 break;
1118 }
1119 }
1120 $params['price_' . $key] = 1;
1121 break;
1122 }
1123 }
1124 }
1125 $component = '';
1126 if ($this->_membershipBlock) {
1127 $component = 'membership';
1128 }
1129
1130 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[$priceSetId], $component);
1131 if ($params['tax_amount']) {
1132 $this->set('tax_amount', $params['tax_amount']);
1133 }
1134
1135 if ($proceFieldAmount) {
1136 $lineItem[$params['priceSetId']][$fieldOption]['unit_price'] = $proceFieldAmount;
1137 $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount;
1138 if (isset($lineItem[$params['priceSetId']][$fieldOption]['tax_amount'])) {
1139 $proceFieldAmount += $lineItem[$params['priceSetId']][$fieldOption]['tax_amount'];
1140 }
1141 if (!$this->_membershipBlock['is_separate_payment']) {
1142 //require when separate membership not used
1143 $params['amount'] = $proceFieldAmount;
1144 }
1145 }
1146 $this->set('lineItem', $lineItem);
1147 }
1148
1149 if ($this->_membershipBlock['is_separate_payment'] && !empty($params['separate_amount'])) {
1150 $this->set('amount', $params['separate_amount']);
1151 }
1152 else {
1153 $this->set('amount', $params['amount']);
1154 }
1155
1156 // generate and set an invoiceID for this transaction
1157 $invoiceID = md5(uniqid(rand(), TRUE));
1158 $this->set('invoiceID', $invoiceID);
1159 $params['invoiceID'] = $invoiceID;
1160 $params['description'] = ts('Online Contribution') . ': ' . ((!empty($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']));
1161 $params['button'] = $this->controller->getButtonName();
1162 // required only if is_monetary and valid positive amount
1163 // @todo it seems impossible for $memFee to be greater than 0 & $params['amount'] not to
1164 // be & by requiring $memFee down here we make it harder to do a sensible refactoring of the function
1165 // above (ie. extract the amount in a small function).
1166 if ($this->_values['is_monetary'] &&
1167 is_array($this->_paymentProcessor) &&
1168 ((float ) $params['amount'] > 0.0 || $memFee > 0.0)
1169 ) {
1170 $this->setContributeMode();
1171 // Really this setting of $this->_params & params within it should be done earlier on in the function
1172 // probably the values determined here should be reused in confirm postProcess as there is no opportunity to alter anything
1173 // on the confirm page. However as we are dealing with a stable release we go as close to where it is used
1174 // as possible.
1175 // In general the form has a lack of clarity of the logic of why things are set on the form in some cases &
1176 // the logic around when $this->_params is used compared to other params arrays.
1177 $this->_params = array_merge($params, $this->_params);
1178 $this->setRecurringMembershipParams();
1179 if ($this->_paymentProcessor &&
1180 $this->_paymentProcessor['object']->supports('preApproval')
1181 ) {
1182 $this->handlePreApproval($this->_params);
1183 }
1184 }
1185 }
1186
1187 /**
1188 * Assign the billing mode to the template.
1189 *
1190 * This is required for legacy support for contributeMode in templates.
1191 *
1192 * The goal is to remove this parameter & use more relevant parameters.
1193 */
1194 protected function setContributeMode() {
1195 switch ($this->_paymentProcessor['billing_mode']) {
1196 case CRM_Core_Payment::BILLING_MODE_FORM:
1197 $this->set('contributeMode', 'direct');
1198 break;
1199
1200 case CRM_Core_Payment::BILLING_MODE_BUTTON:
1201 $this->set('contributeMode', 'express');
1202 break;
1203
1204 case CRM_Core_Payment::BILLING_MODE_NOTIFY:
1205 $this->set('contributeMode', 'notify');
1206 break;
1207 }
1208
1209 }
1210
1211 /**
1212 * Process confirm function and pass browser to the thank you page.
1213 */
1214 protected function skipToThankYouPage() {
1215 // call the post process hook for the main page before we switch to confirm
1216 $this->postProcessHook();
1217
1218 // build the confirm page
1219 $confirmForm = &$this->controller->_pages['Confirm'];
1220 $confirmForm->preProcess();
1221 $confirmForm->buildQuickForm();
1222
1223 // the confirmation page is valid
1224 $data = &$this->controller->container();
1225 $data['valid']['Confirm'] = 1;
1226
1227 // confirm the contribution
1228 // mainProcess calls the hook also
1229 $confirmForm->mainProcess();
1230 $qfKey = $this->controller->_key;
1231
1232 // redirect to thank you page
1233 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey=$qfKey", TRUE, NULL, FALSE));
1234 }
1235
1236 /**
1237 * Function for unit tests on the postProcess function.
1238 *
1239 * @param array $params
1240 */
1241 public function testSubmit($params) {
1242 $_SERVER['REQUEST_METHOD'] = 'GET';
1243 $this->controller = new CRM_Contribute_Controller_Contribution();
1244 $this->submit($params);
1245 }
1246
1247 }