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