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