Merge pull request #6093 from eileenmcnaughton/master
[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
TO
48 public $_paymentProcessors;
49 protected $_defaults;
50
51 public $_membershipTypeValues;
52
53 public $_useForMember;
54
dde5a0ef 55 /**
100fef9d 56 * 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
57 * @var array
58 */
59 public $_paymentFields = array();
60
e50ee6a3 61 protected $_paymentProcessorID;
7c8cc461 62 protected $_snippet;
6a488035
TO
63
64 /**
fe482240 65 * Set variables up before form is built.
6a488035
TO
66 */
67 public function preProcess() {
68 parent::preProcess();
69
7bf9cde2 70 self::preProcessPaymentOptions($this);
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);
316 if ($opMemTypeId &&
317 in_array($opMemTypeId, $this->_currentMemberships) &&
318 !in_array($opMemTypeId, $selectedCurrentMemTypes)
319 ) {
320 if ($val['html_type'] == 'CheckBox') {
321 $this->_defaults["price_{$key}"][$keys] = 1;
322 }
323 else {
324 $this->_defaults["price_{$key}"] = $keys;
325 }
326 $selectedCurrentMemTypes[] = $values['membership_type_id'];
327 }
a7488080 328 elseif (!empty($values['is_default']) &&
6a488035
TO
329 !$opMemTypeId &&
330 (!isset($this->_defaults["price_{$key}"]) ||
331 ($val['html_type'] == 'CheckBox' && !isset($this->_defaults["price_{$key}"][$keys]))
332 )
333 ) {
334 if ($val['html_type'] == 'CheckBox') {
335 $this->_defaults["price_{$key}"][$keys] = 1;
336 }
337 else {
338 $this->_defaults["price_{$key}"] = $keys;
339 }
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);
e02d7e96
EM
380 // Return if we are in an ajax - this is probably redundant now as
381 // processor does not call this form for a snippet anymore - but unsure about
382 // cdType
7c8cc461
CW
383 if ($this->_snippet) {
384 return;
385 }
6a488035
TO
386 }
387
388 $config = CRM_Core_Config::singleton();
78f0ee1b 389
37326fa1
DG
390 $contactID = $this->getContactID();
391 if ($contactID) {
392 $this->assign('contact_id', $contactID);
f498a273 393 $this->assign('display_name', CRM_Contact_BAO_Contact::displayName($contactID));
37326fa1
DG
394 }
395
6a488035 396 if ($this->_onbehalf) {
061a96be 397 CRM_Contribute_Form_Contribution_OnBehalfOf::buildQuickForm($this);
ab234a8a
CW
398 // Return if we are in an ajax callback
399 if ($this->_snippet) {
400 return;
401 }
6a488035
TO
402 }
403
404 $this->applyFilter('__ALL__', 'trim');
405 $this->add('text', "email-{$this->_bltID}",
406 ts('Email Address'),
407 array('size' => 30, 'maxlength' => 60, 'class' => 'email'),
408 TRUE
409 );
410 $this->addRule("email-{$this->_bltID}", ts('Email is not valid.'), 'email');
6a488035 411 $pps = array();
67399793 412 //@todo - this should be replaced by a check as to whether billing fields are set
596bff78 413 $onlinePaymentProcessorEnabled = FALSE;
6a488035 414 if (!empty($this->_paymentProcessors)) {
596bff78 415 foreach ($this->_paymentProcessors as $key => $name) {
22e263ad 416 if ($name['billing_mode'] == 1) {
596bff78 417 $onlinePaymentProcessorEnabled = TRUE;
418 }
6a488035
TO
419 $pps[$key] = $name['name'];
420 }
421 }
a7488080 422 if (!empty($this->_values['is_pay_later'])) {
6a488035
TO
423 $pps[0] = $this->_values['pay_later_text'];
424 }
425
426 if (count($pps) > 1) {
e02d7e96 427 $this->addRadio('payment_processor_id', ts('Payment Method'), $pps,
6a488035
TO
428 NULL, "&nbsp;", TRUE
429 );
430 }
431 elseif (!empty($pps)) {
432 $key = array_keys($pps);
433 $key = array_pop($key);
e02d7e96 434 $this->addElement('hidden', 'payment_processor_id', $key);
6a488035
TO
435 if ($key === 0) {
436 $this->assign('is_pay_later', $this->_values['is_pay_later']);
437 $this->assign('pay_later_text', $this->_values['pay_later_text']);
438 }
439 }
596bff78 440
441 $contactID = $this->getContactID();
aa288d3f 442 if ($this->getContactID() === 0) {
596bff78 443 $this->addCidZeroOptions($onlinePaymentProcessorEnabled);
444 }
aa288d3f 445
6a488035
TO
446 //build pledge block.
447 $this->_useForMember = 0;
448 //don't build membership block when pledge_id is passed
a7488080 449 if (empty($this->_values['pledge_id'])) {
6a488035
TO
450 $this->_separateMembershipPayment = FALSE;
451 if (in_array('CiviMember', $config->enableComponents)) {
452 $isTest = 0;
453 if ($this->_action & CRM_Core_Action::PREVIEW) {
454 $isTest = 1;
455 }
456
457 if ($this->_priceSetId &&
458 (CRM_Core_Component::getComponentID('CiviMember') == CRM_Utils_Array::value('extends', $this->_priceSet))
459 ) {
460 $this->_useForMember = 1;
461 $this->set('useForMember', $this->_useForMember);
462 }
463
464 $this->_separateMembershipPayment = CRM_Member_BAO_Membership::buildMembershipBlock($this,
465 $this->_id,
5b757295 466 $this->_membershipContactID,
6a488035 467 TRUE, NULL, FALSE,
5b757295 468 $isTest
6a488035
TO
469 );
470 }
471 $this->set('separateMembershipPayment', $this->_separateMembershipPayment);
472 }
473 $this->assign('useForMember', $this->_useForMember);
474 // If we configured price set for contribution page
475 // we are not allow membership signup as well as any
476 // other contribution amount field, CRM-5095
477 if (isset($this->_priceSetId) && $this->_priceSetId) {
478 $this->add('hidden', 'priceSetId', $this->_priceSetId);
479 // build price set form.
480 $this->set('priceSetId', $this->_priceSetId);
9da8dc8c 481 CRM_Price_BAO_PriceSet::buildPriceSet($this);
6a488035 482 if ($this->_values['is_monetary'] &&
353ffa53
TO
483 $this->_values['is_recur'] && empty($this->_values['pledge_id'])
484 ) {
6a488035
TO
485 self::buildRecur($this);
486 }
487 }
6a488035
TO
488
489 if ($this->_priceSetId) {
9da8dc8c 490 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
6a488035
TO
491 if ($is_quick_config) {
492 $this->_useForMember = 0;
493 $this->set('useForMember', $this->_useForMember);
494 }
495 }
496
497 if ($this->_values['is_for_organization']) {
498 $this->buildOnBehalfOrganization();
499 }
500
501 //we allow premium for pledge during pledge creation only.
a7488080 502 if (empty($this->_values['pledge_id'])) {
6a488035
TO
503 CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, TRUE);
504 }
505
133e2c99 506 //add honor block
8af73472 507 if ($this->_honor_block_is_active) {
133e2c99 508 $this->assign('honor_block_is_active', TRUE);
133e2c99 509
510 //build soft-credit section
511 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
512 //build honoree profile section
513 CRM_Contact_Form_ProfileContact::buildQuickForm($this);
6a488035
TO
514 }
515
6a488035
TO
516 //don't build pledge block when mid is passed
517 if (!$this->_mid) {
518 $config = CRM_Core_Config::singleton();
8cc574cf 519 if (in_array('CiviPledge', $config->enableComponents) && !empty($this->_values['pledge_block_id'])) {
6a488035
TO
520 CRM_Pledge_BAO_PledgeBlock::buildPledgeBlock($this);
521 }
522 }
523
6a488035 524 //to create an cms user
1fcf2d71 525 if (!$this->_contactID) {
6a488035
TO
526 $createCMSUser = FALSE;
527
528 if ($this->_values['custom_pre_id']) {
529 $profileID = $this->_values['custom_pre_id'];
530 $createCMSUser = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_cms_user');
531 }
532
533 if (!$createCMSUser &&
534 $this->_values['custom_post_id']
535 ) {
536 if (!is_array($this->_values['custom_post_id'])) {
537 $profileIDs = array($this->_values['custom_post_id']);
538 }
539 else {
540 $profileIDs = $this->_values['custom_post_id'];
541 }
542 foreach ($profileIDs as $pid) {
543 if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $pid, 'is_cms_user')) {
544 $profileID = $pid;
545 $createCMSUser = TRUE;
546 break;
547 }
548 }
549 }
550
551 if ($createCMSUser) {
552 CRM_Core_BAO_CMSUser::buildForm($this, $profileID, TRUE);
553 }
554 }
555 if ($this->_pcpId) {
556 if ($pcpSupporter = CRM_PCP_BAO_PCP::displayName($this->_pcpId)) {
b942a32a 557 $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
558 // 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.
559 $text = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute');
22e263ad 560 if (!empty($text)) {
b942a32a 561 $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
562 }
563 $this->assign('pcpSupporterText', $pcp_supporter_text);
6a488035 564 }
31ed2806
JM
565 $prms = array('id' => $this->_pcpId);
566 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
567 if ($pcpInfo['is_honor_roll']) {
4d327c2d 568 $this->assign('isHonor', TRUE);
31ed2806
JM
569 $this->add('checkbox', 'pcp_display_in_roll', ts('Show my contribution in the public honor roll'), NULL, NULL,
570 array('onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );")
571 );
572 $extraOption = array('onclick' => "return pcpAnonymous( );");
353ffa53
TO
573 $elements = array();
574 $elements[] = &$this->createElement('radio', NULL, '', ts('Include my name and message'), 0, $extraOption);
575 $elements[] = &$this->createElement('radio', NULL, '', ts('List my contribution anonymously'), 1, $extraOption);
31ed2806 576 $this->addGroup($elements, 'pcp_is_anonymous', NULL, '&nbsp;&nbsp;&nbsp;');
31ed2806
JM
577
578 $this->add('text', 'pcp_roll_nickname', ts('Name'), array('maxlength' => 30));
579 $this->add('textarea', 'pcp_personal_note', ts('Personal Note'), array('style' => 'height: 3em; width: 40em;'));
580 }
6a488035
TO
581 }
582
583 //we have to load confirm contribution button in template
584 //when multiple payment processor as the user
585 //can toggle with payment processor selection
586 $billingModePaymentProcessors = 0;
481a74f4 587 if (!empty($this->_paymentProcessors)) {
6a488035
TO
588 foreach ($this->_paymentProcessors as $key => $values) {
589 if ($values['billing_mode'] == CRM_Core_Payment::BILLING_MODE_BUTTON) {
590 $billingModePaymentProcessors++;
591 }
592 }
593 }
594
595 if ($billingModePaymentProcessors && count($this->_paymentProcessors) == $billingModePaymentProcessors) {
596 $allAreBillingModeProcessors = TRUE;
0db6c3e1
TO
597 }
598 else {
6a488035
TO
599 $allAreBillingModeProcessors = FALSE;
600 }
601
602 if (!($allAreBillingModeProcessors && !$this->_values['is_pay_later'])) {
61189839
CW
603 $submitButton = array(
604 'type' => 'upload',
c0321a2d 605 'name' => CRM_Utils_Array::value('is_confirm_enabled', $this->_values) ? ts('Confirm Contribution') : ts('Contribute'),
61189839
CW
606 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
607 'isDefault' => TRUE,
6a488035 608 );
61189839
CW
609 // Add submit-once behavior when confirm page disabled
610 if (empty($this->_values['is_confirm_enabled'])) {
611 $submitButton['js'] = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
612 }
613 $this->addButtons(array($submitButton));
6a488035
TO
614 }
615
616 $this->addFormRule(array('CRM_Contribute_Form_Contribution_Main', 'formRule'), $this);
6a488035
TO
617 }
618
6a488035 619 /**
100fef9d 620 * Build elements to enable pay on behalf of an organization.
6a488035 621 */
00be9182 622 public function buildOnBehalfOrganization() {
6a488035
TO
623 if ($this->_membershipContactID) {
624 $entityBlock = array('contact_id' => $this->_membershipContactID);
625 CRM_Core_BAO_Location::getValues($entityBlock, $this->_defaults);
626 }
627
78f0ee1b 628 if (!$this->_onBehalfRequired) {
6a488035
TO
629 $this->addElement('checkbox', 'is_for_organization',
630 $this->_values['for_organization'],
631 NULL, array('onclick' => "showOnBehalf( );")
632 );
633 }
6a488035
TO
634
635 $this->assign('is_for_organization', TRUE);
636 $this->assign('urlPath', 'civicrm/contribute/transact');
637 }
638
639 /**
fe482240 640 * Build elements to collect information for recurring contributions.
6a488035 641 *
03110609
EM
642 *
643 * @param CRM_Core_Form $form
6a488035 644 */
a5aef36c 645 public static function buildRecur(&$form) {
6a488035
TO
646 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur');
647 $className = get_class($form);
648
a5aef36c 649 $form->assign('is_recur_interval', CRM_Utils_Array::value('is_recur_interval', $form->_values));
650 $form->assign('is_recur_installments', CRM_Utils_Array::value('is_recur_installments', $form->_values));
6a488035
TO
651
652 $form->add('checkbox', 'is_recur', ts('I want to contribute this amount'), NULL);
653
a7488080 654 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
6a488035
TO
655 $form->add('text', 'frequency_interval', ts('Every'), $attributes['frequency_interval']);
656 $form->addRule('frequency_interval', ts('Frequency must be a whole number (EXAMPLE: Every 3 months).'), 'integer');
657 }
658 else {
659 // make sure frequency_interval is submitted as 1 if given no choice to user.
660 $form->add('hidden', 'frequency_interval', 1);
661 }
662
663 $frUnits = CRM_Utils_Array::value('recur_frequency_unit', $form->_values);
664 if (empty($frUnits) &&
665 $className == 'CRM_Contribute_Form_Contribution'
666 ) {
667 $frUnits = implode(CRM_Core_DAO::VALUE_SEPARATOR,
668 CRM_Core_OptionGroup::values('recur_frequency_units')
669 );
670 }
671
672 $unitVals = explode(CRM_Core_DAO::VALUE_SEPARATOR, $frUnits);
673
674 // CRM 10860, display text instead of a dropdown if there's only 1 frequency unit
317fceb4 675 if (count($unitVals) == 1) {
874c9be7 676 $form->assign('one_frequency_unit', TRUE);
6a488035
TO
677 $unit = $unitVals[0];
678 $form->add('hidden', 'frequency_unit', $unit);
a7488080 679 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
6a488035
TO
680 $unit .= "(s)";
681 }
a5aef36c 682 $form->assign('frequency_unit', $unit);
0db6c3e1
TO
683 }
684 else {
874c9be7 685 $form->assign('one_frequency_unit', FALSE);
6a488035 686 $units = array();
728ebde6 687 $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units', FALSE, FALSE, TRUE);
6a488035
TO
688 foreach ($unitVals as $key => $val) {
689 if (array_key_exists($val, $frequencyUnits)) {
690 $units[$val] = $frequencyUnits[$val];
a7488080 691 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
6a488035
TO
692 $units[$val] = "{$frequencyUnits[$val]}(s)";
693 }
694 }
695 }
696 $frequencyUnit = &$form->add('select', 'frequency_unit', NULL, $units);
697 }
698
6a488035
TO
699 // FIXME: Ideally we should freeze select box if there is only
700 // one option but looks there is some problem /w QF freeze.
701 //if ( count( $units ) == 1 ) {
702 //$frequencyUnit->freeze( );
703 //}
704
705 $form->add('text', 'installments', ts('installments'),
706 $attributes['installments']
707 );
708 $form->addRule('installments', ts('Number of installments must be a whole number.'), 'integer');
709 }
710
711 /**
fe482240 712 * Global form rule.
6a488035 713 *
014c4014
TO
714 * @param array $fields
715 * The input form values.
716 * @param array $files
717 * The uploaded files if any.
d90a1a52 718 * @param CRM_Core_Form $self
2a6da8d7 719 *
72b3a70c
CW
720 * @return bool|array
721 * true if no errors, else array of errors
6a488035 722 */
00be9182 723 public static function formRule($fields, $files, $self) {
6a488035 724 $errors = array();
aefd7f6b 725 $amount = self::computeAmount($fields, $self->_values);
6a488035 726
8cc574cf 727 if ((!empty($fields['selectMembership']) &&
6a488035
TO
728 $fields['selectMembership'] != 'no_thanks'
729 ) ||
8cc574cf 730 (!empty($fields['priceSetId']) &&
6a488035
TO
731 $self->_useForMember
732 )
733 ) {
4005a2ae 734 $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, FALSE, TRUE);
6a488035
TO
735
736 $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization();
737
738 $unallowedOrgs = array();
739 foreach (array_keys($lifeMember) as $memTypeId) {
740 $unallowedOrgs[] = $membershipOrgDetails[$memTypeId];
741 }
742 }
743
744 //check for atleast one pricefields should be selected
a7488080 745 if (!empty($fields['priceSetId'])) {
9da8dc8c 746 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
747 $priceField->price_set_id = $fields['priceSetId'];
748 $priceField->orderBy('weight');
749 $priceField->find();
750
751 $check = array();
752 $membershipIsActive = TRUE;
753 $previousId = $otherAmount = FALSE;
754 while ($priceField->fetch()) {
755
756 if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) {
757 $previousId = $priceField->id;
481a74f4 758 if ($priceField->name == 'membership_amount' && !$priceField->is_active) {
6a488035
TO
759 $membershipIsActive = FALSE;
760 }
761 }
762 if ($priceField->name == 'other_amount') {
8cc574cf 763 if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) &&
353ffa53
TO
764 array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])
765 ) {
6a488035
TO
766 $otherAmount = $priceField->id;
767 }
768 elseif (!empty($fields["price_{$priceField->id}"])) {
ef88f444 769 $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]);
353ffa53
TO
770 $min = CRM_Utils_Array::value('min_amount', $self->_values);
771 $max = CRM_Utils_Array::value('max_amount', $self->_values);
6a488035
TO
772 if ($min && $otherAmountVal < $min) {
773 $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1',
353ffa53 774 array(1 => $min)
6a488035
TO
775 );
776 }
777 if ($max && $otherAmountVal > $max) {
778 $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.',
353ffa53 779 array(1 => $max)
6a488035
TO
780 );
781 }
782 }
783 }
784 if (!empty($fields["price_{$priceField->id}"]) || ($previousId == $priceField->id && isset($fields["price_{$previousId}"])
353ffa53
TO
785 && empty($fields["price_{$previousId}"]))
786 ) {
6a488035
TO
787 $check[] = $priceField->id;
788 }
789 }
790
b5a62499
PN
791 $currentMemberships = NULL;
792 if ($membershipIsActive) {
793 $is_test = $self->_mode != 'live' ? 1 : 0;
794 $memContactID = $self->_membershipContactID;
7f7fa13a
EM
795
796 // For anonymous user check using dedupe rule
b5a62499
PN
797 // if user has Cancelled Membership
798 if (!$memContactID) {
799 $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
800 $dedupeParams['check_permission'] = FALSE;
801 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
802 // if we find more than one contact, use the first one
803 $memContactID = CRM_Utils_Array::value(0, $ids);
804 }
805 $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID,
806 $is_test
807 );
7f7fa13a 808
b5a62499
PN
809 $errorText = 'Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.';
810 foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
811 if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array::value('price_' . $fieldKey, $fields)) {
812 if (!is_array($fields['price_' . $fieldKey])) {
7f7fa13a 813 if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]])
353ffa53
TO
814 && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)
815 ) {
3a96b63b 816 $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'])));
b5a62499
PN
817 }
818 }
819 else {
820 foreach ($fields['price_' . $fieldKey] as $key => $ignore) {
7f7fa13a 821 if (array_key_exists('membership_type_id', $fieldValue['options'][$key])
353ffa53
TO
822 && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)
823 ) {
b5a62499
PN
824 $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$key]['membership_type_id'])));
825 }
826 }
827 }
828 }
829 }
830 }
7f7fa13a 831
9ce8bcfc 832 // CRM-12233
665e5ec7 833 if ($membershipIsActive && !$self->_membershipBlock['is_required']
353ffa53
TO
834 && $self->_values['amount_block_is_active']
835 ) {
9ce8bcfc
PN
836 $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL;
837 foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
41f27e49 838 // if 'No thank you' membership is selected then set $membershipFieldId
9ce8bcfc
PN
839 if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) {
840 $membershipFieldId = $fieldKey;
841 }
842 elseif ($membershipFieldId) {
843 if ($fieldValue['name'] == 'other_amount') {
844 $otherFieldId = $fieldKey;
845 }
846 elseif ($fieldValue['name'] == 'contribution_amount') {
847 $contributionFieldId = $fieldKey;
848 }
665e5ec7 849
9ce8bcfc
PN
850 if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') {
851 $errorKey = $fieldKey;
852 }
853 }
854 }
41f27e49 855 // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error
8cc574cf 856 if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) {
1cd7e100 857 $errors["price_{$errorKey}"] = ts('Additional Contribution is required.');
9ce8bcfc
PN
858 }
859 }
6a488035
TO
860 if (empty($check)) {
861 if ($self->_useForMember == 1 && $membershipIsActive) {
862 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
863 }
864 else {
865 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
866 }
867 }
22e263ad 868 if ($otherAmount && !empty($check)) {
6a488035
TO
869 $errors["price_{$otherAmount}"] = ts('Amount is required field.');
870 }
871
872 if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) {
873 $priceFieldIDS = array();
874 $priceFieldMemTypes = array();
875
876 foreach ($self->_priceSet['fields'] as $priceId => $value) {
8cc574cf 877 if (!empty($fields['price_' . $priceId]) || ($self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required']))) {
a7488080 878 if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) {
6a488035
TO
879 foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
880 if ($isSet) {
881 $priceFieldIDS[] = $priceFldVal;
882 }
883 }
884 }
8cc574cf 885 elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) {
6a488035
TO
886 // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
887 // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
888 $priceFieldIDS[] = $fields['price_' . $priceId];
889 }
890
a7488080 891 if (!empty($value['options'])) {
6a488035 892 foreach ($value['options'] as $val) {
88c6259e 893 if (!empty($val['membership_type_id']) && (
fb4aa4d9 894 ($fields['price_' . $priceId] == $val['id']) ||
895 (isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))
896 )
897 ) {
6a488035
TO
898 $priceFieldMemTypes[] = $val['membership_type_id'];
899 }
900 }
901 }
902 }
903 }
904
905 if (!empty($lifeMember)) {
906 foreach ($priceFieldIDS as $priceFieldId) {
9da8dc8c 907 if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) &&
6a488035
TO
908 in_array($membershipOrgDetails[$id], $unallowedOrgs)
909 ) {
910 $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
911 break;
912 }
913 }
914 }
915
916 if (!empty($priceFieldIDS)) {
917 $ids = implode(',', $priceFieldIDS);
918
919 $priceFieldIDS['id'] = $fields['priceSetId'];
920 $self->set('memberPriceFieldIDS', $priceFieldIDS);
9da8dc8c 921 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
b44e3f84
DS
922 foreach ($count as $id => $occurrence) {
923 if ($occurrence > 1) {
6a488035
TO
924 $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.');
925 }
926 }
927 }
928
929 if (empty($priceFieldMemTypes)) {
930 $errors['_qf_default'] = ts('Please select at least one membership option.');
931 }
932 }
933
9da8dc8c 934 CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'],
6a488035
TO
935 $fields, $lineItem
936 );
665e5ec7 937
6a488035
TO
938 if ($fields['amount'] < 0) {
939 $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
940 }
941 $amount = $fields['amount'];
942 }
943
944 if (isset($fields['selectProduct']) &&
353ffa53
TO
945 $fields['selectProduct'] != 'no_thanks'
946 ) {
6a488035
TO
947 $productDAO = new CRM_Contribute_DAO_Product();
948 $productDAO->id = $fields['selectProduct'];
949 $productDAO->find(TRUE);
950 $min_amount = $productDAO->min_contribution;
951
952 if ($amount < $min_amount) {
953 $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount)));
954 CRM_Core_Session::setStatus($errors['selectProduct']);
955 }
956 }
957
577d1236
WA
958 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
959 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
6a488035 960
a7488080 961 if (!empty($fields['is_recur']) &&
e02d7e96 962 CRM_Utils_Array::value('payment_processor_id', $fields) == 0
353ffa53 963 ) {
6a488035
TO
964 $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
965 }
966
a7488080 967 if (!empty($fields['is_for_organization']) &&
6a488035
TO
968 !property_exists($self, 'organizationName')
969 ) {
970
a7488080
CW
971 if (empty($fields['onbehalf']['organization_name'])) {
972 if (!empty($fields['org_option']) && !$fields['onbehalfof_id']) {
6a488035
TO
973 $errors['organization_id'] = ts('Please select an organization or enter a new one.');
974 }
a7488080 975 elseif (empty($fields['org_option'])) {
6a488035
TO
976 $errors['onbehalf']['organization_name'] = ts('Please enter the organization name.');
977 }
978 }
979
980 foreach ($fields['onbehalf'] as $key => $value) {
981 if (strstr($key, 'email')) {
982 $emailLocType = explode('-', $key);
983 }
984 }
a7488080 985 if (empty($fields['onbehalf']["email-{$emailLocType[1]}"])) {
6a488035
TO
986 $errors['onbehalf']["email-{$emailLocType[1]}"] = ts('Organization email is required.');
987 }
988 }
989
990 // validate PCP fields - if not anonymous, we need a nick name value
8cc574cf 991 if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) &&
6a488035
TO
992 (CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0) &&
993 CRM_Utils_Array::value('pcp_roll_nickname', $fields) == ''
994 ) {
995 $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
996 }
997
998 // return if this is express mode
999 $config = CRM_Core_Config::singleton();
f92fc7eb
CW
1000 if ($self->_paymentProcessor &&
1001 $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON
1002 ) {
8cc574cf 1003 if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) ||
6a488035
TO
1004 CRM_Utils_Array::value($self->_expressButtonName, $fields)
1005 ) {
1006 return $errors;
1007 }
1008 }
1009
1010 //validate the pledge fields.
a7488080 1011 if (!empty($self->_values['pledge_block_id'])) {
6a488035 1012 //validation for pledge payment.
a7488080 1013 if (!empty($self->_values['pledge_id'])) {
6a488035
TO
1014 if (empty($fields['pledge_amount'])) {
1015 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
1016 }
1017 }
a7488080 1018 elseif (!empty($fields['is_pledge'])) {
6a488035 1019 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) {
917a9954 1020 $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.');
6a488035
TO
1021 }
1022 else {
1023 if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) {
1024 $errors['pledge_installments'] = ts('Pledge Installments is required field.');
1025 }
1026 elseif (CRM_Utils_array::value('pledge_installments', $fields) == 1) {
1027 $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.');
1028 }
1029 elseif (CRM_Utils_array::value('pledge_installments', $fields) == 0) {
1030 $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
1031 }
1032 }
1033
1034 //validation for Pledge Frequency Interval.
1035 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) {
1036 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
1037 }
1038 else {
1039 if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) {
1040 $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
1041 }
1042 elseif (CRM_Utils_array::value('pledge_frequency_interval', $fields) == 0) {
1043 $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
1044 }
1045 }
1046 }
1047 }
1048
1049 // also return if paylater mode
e02d7e96 1050 if (CRM_Utils_Array::value('payment_processor_id', $fields) == 0 && $self->_isBillingAddressRequiredForPayLater == 0) {
6a488035
TO
1051 return empty($errors) ? TRUE : $errors;
1052 }
1053
1054 // if the user has chosen a free membership or the amount is less than zero
1055 // i.e. we skip calling the payment processor and hence dont need credit card
1056 // info
f92fc7eb 1057 if ((float) $amount <= 0.0) {
6a488035
TO
1058 return $errors;
1059 }
1060
7cb3d4f0
CW
1061 if (!empty($self->_paymentFields)) {
1062 CRM_Core_Form::validateMandatoryFields($self->_paymentFields, $fields, $errors);
6a488035 1063 }
e02d7e96 1064 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
6a488035 1065
6a488035
TO
1066 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1067 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
1068 $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
1069 if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) {
1070 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
353ffa53 1071 array(1 => ucwords(str_replace('_', " ", $greeting)))
6a488035
TO
1072 );
1073 }
1074 }
1075 }
1076
1077 return empty($errors) ? TRUE : $errors;
1078 }
1079
186c9c17 1080 /**
aefd7f6b
EM
1081 * Compute amount to be paid.
1082 *
c490a46a 1083 * @param array $params
aefd7f6b 1084 * @param array $formValues
186c9c17
EM
1085 *
1086 * @return int|mixed|null|string
1087 */
aefd7f6b 1088 public static function computeAmount($params, $formValues) {
99b93cf8 1089 $amount = 0;
aefd7f6b 1090 // First clean up the other amount field if present.
6a488035
TO
1091 if (isset($params['amount_other'])) {
1092 $params['amount_other'] = CRM_Utils_Rule::cleanMoney($params['amount_other']);
1093 }
1094
8cc574cf 1095 if (CRM_Utils_Array::value('amount', $params) == 'amount_other_radio' || !empty($params['amount_other'])) {
6a488035
TO
1096 $amount = $params['amount_other'];
1097 }
1098 elseif (!empty($params['pledge_amount'])) {
6a488035
TO
1099 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
1100 $amount += CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount');
1101 }
1102 }
1103 else {
aefd7f6b 1104 if (!empty($formValues['amount'])) {
6a488035
TO
1105 $amountID = CRM_Utils_Array::value('amount', $params);
1106
1107 if ($amountID) {
aefd7f6b
EM
1108 $params['amount_level'] = CRM_Utils_Array::value('label', $formValues[$amountID]);
1109 $amount = CRM_Utils_Array::value('value', $formValues[$amountID]);
6a488035
TO
1110 }
1111 }
1112 }
1113 return $amount;
1114 }
1115
1116 /**
fe482240 1117 * Process the form submission.
6a488035
TO
1118 */
1119 public function postProcess() {
1120 $config = CRM_Core_Config::singleton();
6a488035
TO
1121 // we first reset the confirm page so it accepts new values
1122 $this->controller->resetPage('Confirm');
1123
1124 // get the submitted form values.
1125 $params = $this->controller->exportValues($this->_name);
da8d9879 1126
4625312e
EM
1127 //carry campaign from profile.
1128 if (array_key_exists('contribution_campaign_id', $params)) {
1129 $params['campaign_id'] = $params['contribution_campaign_id'];
1130 }
1131
1132 if (!empty($params['onbehalfof_id'])) {
1133 $params['organization_id'] = $params['onbehalfof_id'];
1134 }
1135
1136 $params['currencyID'] = $config->defaultCurrency;
1137
a7488080 1138 if (!empty($params['priceSetId'])) {
9da8dc8c 1139 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
6a488035 1140 if ($is_quick_config) {
9da8dc8c 1141 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
1142 $priceField->price_set_id = $params['priceSetId'];
1143 $priceField->orderBy('weight');
1144 $priceField->find();
1145
1d9d37c7 1146 $priceOptions = array();
6a488035 1147 while ($priceField->fetch()) {
1d9d37c7
FG
1148 CRM_Price_BAO_PriceFieldValue::getValues($priceField->id, $priceOptions);
1149 if ($selectedPriceOptionID = CRM_Utils_Array::value("price_{$priceField->id}", $params)) {
1150 switch ($priceField->name) {
1151 case 'membership_amount':
1152 $this->_params['selectMembership'] = $params['selectMembership'] = CRM_Utils_Array::value('membership_type_id', $priceOptions[$selectedPriceOptionID]);
1153 $this->set('selectMembership', $params['selectMembership']);
1154 if (CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) == 0) {
1155 $this->_values['amount'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
1156 }
1157 break;
1158
1159 case 'contribution_amount':
1160 $params['amount'] = $selectedPriceOptionID;
1161 $this->_values['amount'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
1162 $this->_values[$selectedPriceOptionID]['value'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
1163 $this->_values[$selectedPriceOptionID]['label'] = CRM_Utils_Array::value('label', $priceOptions[$selectedPriceOptionID]);
1164 $this->_values[$selectedPriceOptionID]['amount_id'] = CRM_Utils_Array::value('id', $priceOptions[$selectedPriceOptionID]);
1165 $this->_values[$selectedPriceOptionID]['weight'] = CRM_Utils_Array::value('weight', $priceOptions[$selectedPriceOptionID]);
1166 break;
1167
1168 case 'other_amount':
1169 $params['amount_other'] = $selectedPriceOptionID;
1170 break;
6a488035
TO
1171 }
1172 }
6a488035
TO
1173 }
1174 }
1175 }
1176
1177 if (($this->_values['is_pay_later'] &&
1178 empty($this->_paymentProcessor) &&
1179 !array_key_exists('hidden_processor', $params)) ||
e02d7e96 1180 (!empty($params['payment_processor_id']) && $params['payment_processor_id'] == 0)
353ffa53 1181 ) {
6a488035
TO
1182 $params['is_pay_later'] = 1;
1183 }
1184 else {
1185 $params['is_pay_later'] = 0;
1186 }
1187
1188 $this->set('is_pay_later', $params['is_pay_later']);
1189 // assign pay later stuff
1190 $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
1191 $this->assign('is_pay_later', $params['is_pay_later']);
1192 if ($params['is_pay_later']) {
1193 $this->assign('pay_later_text', $this->_values['pay_later_text']);
1194 $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
1195 }
1196
8bff2456 1197 // from here on down, $params['amount'] holds a monetary value (or null) rather than an option ID
aefd7f6b 1198 $params['amount'] = self::computeAmount($params, $this->_values);
6a488035
TO
1199 $params['separate_amount'] = $params['amount'];
1200 $memFee = NULL;
a7488080 1201 if (!empty($params['selectMembership'])) {
6a488035
TO
1202 if (!empty($this->_membershipTypeValues)) {
1203 $membershipTypeValues = $this->_membershipTypeValues[$params['selectMembership']];
1204 }
1205 else {
1206 $membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this,
1207 $params['selectMembership']
1208 );
1209 }
1210 $memFee = $membershipTypeValues['minimum_fee'];
1211 if (!$params['amount'] && !$this->_separateMembershipPayment) {
1212 $params['amount'] = $memFee ? $memFee : 0;
1213 }
1214 }
e6d4f555 1215 //If the membership & contribution is used in contribution page & not separate payment
9ce8bcfc
PN
1216 $fieldId = $memPresent = $membershipLabel = $fieldOption = $is_quick_config = NULL;
1217 $proceFieldAmount = 0;
8af73472 1218 if (property_exists($this, '_separateMembershipPayment') && $this->_separateMembershipPayment == 0) {
9da8dc8c 1219 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
6a488035
TO
1220 if ($is_quick_config) {
1221 foreach ($this->_priceSet['fields'] as $fieldKey => $fieldVal) {
874c9be7 1222 if ($fieldVal['name'] == 'membership_amount' && !empty($params['price_' . $fieldKey])) {
353ffa53 1223 $fieldId = $fieldVal['id'];
6a488035 1224 $fieldOption = $params['price_' . $fieldId];
9ce8bcfc 1225 $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
353ffa53 1226 $memPresent = TRUE;
6a488035
TO
1227 }
1228 else {
a7488080 1229 if (!empty($params['price_' . $fieldKey]) && $memPresent && ($fieldVal['name'] == 'other_amount' || $fieldVal['name'] == 'contribution_amount')) {
6a488035
TO
1230 $fieldId = $fieldVal['id'];
1231 if ($fieldVal['name'] == 'other_amount') {
9ce8bcfc 1232 $proceFieldAmount += $this->_submitValues['price_' . $fieldId];
6a488035 1233 }
abcf506a 1234 elseif ($fieldVal['name'] == 'contribution_amount' && $this->_submitValues['price_' . $fieldId] > 0) {
9ce8bcfc 1235 $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
ce9024ca 1236 }
6a488035
TO
1237 unset($params['price_' . $fieldId]);
1238 break;
1239 }
1240 }
1241 }
1242 }
1243 }
874c9be7 1244
6a488035
TO
1245 if (!isset($params['amount_other'])) {
1246 $this->set('amount_level', CRM_Utils_Array::value('amount_level', $params));
1247 }
1248
1249 if ($priceSetId = CRM_Utils_Array::value('priceSetId', $params)) {
1250 $lineItem = array();
481a74f4
TO
1251 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1252 if ($is_quick_config) {
1253 foreach ($this->_values['fee'] as $key => & $val) {
387fd5aa 1254 if ($val['name'] == 'other_amount' && $val['html_type'] == 'Text' && !empty($params['price_' . $key])) {
aefd7f6b
EM
1255 // Clean out any currency symbols.
1256 $params['price_' . $key] = CRM_Utils_Rule::cleanMoney($params['price_' . $key]);
353ffa53 1257 if ($params['price_' . $key] != 0) {
481a74f4 1258 foreach ($val['options'] as $optionKey => & $options) {
353ffa53 1259 $options['amount'] = CRM_Utils_Array::value('price_' . $key, $params);
ef88f444
PC
1260 break;
1261 }
6a488035 1262 }
92fcb95f 1263 $params['price_' . $key] = 1;
6a488035
TO
1264 break;
1265 }
1266 }
1267 }
6a488035
TO
1268 $component = '';
1269 if ($this->_membershipBlock) {
1270 $component = 'membership';
1271 }
ef88f444 1272
9da8dc8c 1273 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[$priceSetId], $component);
dc428161 1274 if ($params['tax_amount']) {
1275 $this->set('tax_amount', $params['tax_amount']);
1276 }
6a488035
TO
1277
1278 if ($proceFieldAmount) {
6a488035 1279 $lineItem[$params['priceSetId']][$fieldOption]['unit_price'] = $proceFieldAmount;
c40e1ff4 1280 $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount;
dc428161 1281 if (isset($lineItem[$params['priceSetId']][$fieldOption]['tax_amount'])) {
1282 $proceFieldAmount += $lineItem[$params['priceSetId']][$fieldOption]['tax_amount'];
1283 }
6a488035 1284 if (!$this->_membershipBlock['is_separate_payment']) {
aefd7f6b
EM
1285 //require when separate membership not used
1286 $params['amount'] = $proceFieldAmount;
6a488035
TO
1287 }
1288 }
1289 $this->set('lineItem', $lineItem);
1290 }
1291
8cc574cf 1292 if ($this->_membershipBlock['is_separate_payment'] && !empty($params['separate_amount'])) {
6a488035 1293 $this->set('amount', $params['separate_amount']);
0db6c3e1
TO
1294 }
1295 else {
6a488035
TO
1296 $this->set('amount', $params['amount']);
1297 }
1298
1299 // generate and set an invoiceID for this transaction
1300 $invoiceID = md5(uniqid(rand(), TRUE));
1301 $this->set('invoiceID', $invoiceID);
1302
e6d4f555 1303 // required only if is_monetary and valid positive amount
6a488035
TO
1304 if ($this->_values['is_monetary'] &&
1305 is_array($this->_paymentProcessor) &&
1306 ((float ) $params['amount'] > 0.0 || $memFee > 0.0)
1307 ) {
1308
1309 // default mode is direct
1310 $this->set('contributeMode', 'direct');
1311
f92fc7eb
CW
1312 if ($this->_paymentProcessor &&
1313 $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON
1314 ) {
6a488035
TO
1315 //get the button name
1316 $buttonName = $this->controller->getButtonName();
1317 if (in_array($buttonName,
1318 array($this->_expressButtonName, $this->_expressButtonName . '_x', $this->_expressButtonName . '_y')
353ffa53
TO
1319 ) && empty($params['is_pay_later'])
1320 ) {
aefd7f6b 1321 $this->handlePaypalExpress($invoiceID, $params);
6a488035
TO
1322 }
1323 }
f92fc7eb
CW
1324 elseif ($this->_paymentProcessor &&
1325 $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY
1326 ) {
6a488035
TO
1327 $this->set('contributeMode', 'notify');
1328 }
1329 }
1330
1331 // should we skip the confirm page?
a7488080 1332 if (empty($this->_values['is_confirm_enabled'])) {
94fe3c35
DL
1333 // call the post process hook for the main page before we switch to confirm
1334 $this->postProcessHook();
1335
6a488035
TO
1336 // build the confirm page
1337 $confirmForm = &$this->controller->_pages['Confirm'];
1338 $confirmForm->preProcess();
1339 $confirmForm->buildQuickForm();
1340
1341 // the confirmation page is valid
1342 $data = &$this->controller->container();
1343 $data['valid']['Confirm'] = 1;
1344
1345 // confirm the contribution
94fe3c35
DL
1346 // mainProcess calls the hook also
1347 $confirmForm->mainProcess();
6a488035
TO
1348 $qfKey = $this->controller->_key;
1349
1350 // redirect to thank you page
1351 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey=$qfKey", TRUE, NULL, FALSE));
1352 }
874c9be7 1353
6a488035 1354 }
7bf9cde2
CW
1355
1356 /**
7fe37828
EM
1357 * Handle Payment Processor switching for contribution and event registration forms.
1358 *
cc789d46 1359 * @param CRM_Contribute_Form_Contribution_Main|CRM_Event_Form_Registration_Register $form
03110609 1360 * @param bool $noFees
7bf9cde2 1361 */
00be9182 1362 public static function preProcessPaymentOptions(&$form, $noFees = FALSE) {
7bf9cde2 1363 $form->_snippet = CRM_Utils_Array::value('snippet', $_GET);
7bf9cde2 1364
b6a469c5 1365 $form->_paymentProcessors = $noFees ? array() : $form->get('paymentProcessors');
e50ee6a3 1366 $form->_paymentProcessorID = NULL;
b6a469c5 1367 if ($form->_paymentProcessors) {
e02d7e96
EM
1368 if (!empty($form->_submitValues)) {
1369 $form->_paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $form->_submitValues);
e50ee6a3
EM
1370 $form->_paymentProcessor = CRM_Utils_Array::value($form->_paymentProcessorID, $form->_paymentProcessors);
1371 $form->set('type', $form->_paymentProcessorID);
f92fc7eb
CW
1372 $form->set('mode', $form->_mode);
1373 $form->set('paymentProcessor', $form->_paymentProcessor);
7bf9cde2
CW
1374 }
1375 // Set default payment processor
1376 else {
b6a469c5
CW
1377 foreach ($form->_paymentProcessors as $values) {
1378 if (!empty($values['is_default']) || count($form->_paymentProcessors) == 1) {
e50ee6a3 1379 $form->_paymentProcessorID = $values['id'];
f92fc7eb 1380 break;
7bf9cde2
CW
1381 }
1382 }
1383 }
e50ee6a3 1384 if ($form->_paymentProcessorID) {
7bf9cde2
CW
1385 CRM_Core_Payment_ProcessorForm::preProcess($form);
1386 }
67399793
EM
1387 else {
1388 $form->_paymentProcessor = array();
1389 }
bc44463a 1390 CRM_Financial_Form_Payment::addCreditCardJs();
7bf9cde2 1391 }
e50ee6a3 1392 $form->assign('paymentProcessorID', $form->_paymentProcessorID);
7bf9cde2 1393 }
96025800 1394
aefd7f6b
EM
1395 /**
1396 * @param $invoiceID
1397 * @param $params
1398 *
1399 * @return mixed
1400 */
1401 protected function handlePaypalExpress($invoiceID, $params) {
1402 $this->set('contributeMode', 'express');
1403
1404 $params['invoiceID'] = $invoiceID;
1405 $params['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
1406
1407 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
1408 $token = $payment->setExpressCheckout($params);
1409 if (is_a($token, 'CRM_Core_Error')) {
1410 CRM_Core_Error::displaySessionError($token);
1411 CRM_Utils_System::redirect($params['cancelURL']);
1412 }
1413
1414 $this->set('token', $token);
1415 $paymentURL = $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token";
1416 CRM_Utils_System::redirect($paymentURL);
1417 }
1418
6a488035 1419}