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