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