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