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