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