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