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