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