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