f7d23bb356786da7edb2bf11932a0ce86f886330
[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 */
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 /**
60 * Array of payment related fields to potentially display on this form (generally credit card or debit card fields). This is rendered via billingBlock.tpl
61 * @var array
62 */
63 public $_paymentFields = array();
64
65 protected $_paymentProcessorID;
66 protected $_snippet;
67
68 /**
69 * Set variables up before form is built
70 *
71 * @return void
72 */
73 public function preProcess() {
74 parent::preProcess();
75
76 self::preProcessPaymentOptions($this);
77
78 // Make the contributionPageID avilable to the template
79 $this->assign('contributionPageID', $this->_id);
80 $this->assign('isShare', CRM_Utils_Array::value('is_share', $this->_values));
81 $this->assign('isConfirmEnabled', CRM_Utils_Array::value('is_confirm_enabled', $this->_values));
82
83 // make sure we have right permission to edit this user
84 $csContactID = $this->getContactID();
85 $reset = CRM_Utils_Request::retrieve('reset', 'Boolean', CRM_Core_DAO::$_nullObject);
86 $mainDisplay = CRM_Utils_Request::retrieve('_qf_Main_display', 'Boolean', CRM_Core_DAO::$_nullObject);
87
88 if ($reset) {
89 $this->assign('reset', $reset);
90 }
91
92 if ($mainDisplay) {
93 $this->assign('mainDisplay', $mainDisplay);
94 }
95
96 // Possible values for 'is_for_organization':
97 // * 0 - org profile disabled
98 // * 1 - org profile optional
99 // * 2 - org profile required
100 $this->_onbehalf = FALSE;
101 if (!empty($this->_values['is_for_organization'])) {
102 if ($this->_values['is_for_organization'] == 2) {
103 $this->_onBehalfRequired = TRUE;
104 }
105 // Add organization profile if 1 of the following are true:
106 // If the org profile is required
107 if ($this->_onBehalfRequired ||
108 // Or we are building the form for the first time
109 empty($_POST) ||
110 // Or the user has submitted the form and checked the "On Behalf" checkbox
111 !empty($_POST['is_for_organization'])
112 ) {
113 $this->_onbehalf = TRUE;
114 CRM_Contribute_Form_Contribution_OnBehalfOf::preProcess($this);
115 }
116 }
117 $this->assign('onBehalfRequired', $this->_onBehalfRequired);
118
119 if ($this->_honor_block_is_active) {
120 CRM_Contact_Form_ProfileContact::preprocess($this);
121 }
122
123 if ($this->_snippet) {
124 $this->assign('isOnBehalfCallback', CRM_Utils_Array::value('onbehalf', $_GET, FALSE));
125 return;
126 }
127
128 if (!empty($this->_pcpInfo['id']) && !empty($this->_pcpInfo['intro_text'])) {
129 $this->assign('intro_text', $this->_pcpInfo['intro_text']);
130 }
131 elseif (!empty($this->_values['intro_text'])) {
132 $this->assign('intro_text', $this->_values['intro_text']);
133 }
134
135 $qParams = "reset=1&amp;id={$this->_id}";
136 if ($pcpId = CRM_Utils_Array::value('pcp_id', $this->_pcpInfo)) {
137 $qParams .= "&amp;pcpId={$pcpId}";
138 }
139 $this->assign('qParams', $qParams);
140
141 if (!empty($this->_values['footer_text'])) {
142 $this->assign('footer_text', $this->_values['footer_text']);
143 }
144
145 //CRM-5001
146 if (!empty($this->_values['is_for_organization'])) {
147 $msg = ts('Mixed profile not allowed for on behalf of registration/sign up.');
148 $ufJoinParams = array(
149 'module' => 'onBehalf',
150 'entity_table' => 'civicrm_contribution_page',
151 'entity_id' => $this->_id,
152 );
153 $onBehalfProfileIDs = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
154 // getUFGroupIDs returns an array with the first item being the ID we need
155 $onBehalfProfileID = $onBehalfProfileIDs[0];
156 if ($onBehalfProfileID) {
157 $onBehalfProfile = CRM_Core_BAO_UFGroup::profileGroups($onBehalfProfileID);
158 foreach (array(
159 'Individual', 'Organization', 'Household') as $contactType) {
160 if (in_array($contactType, $onBehalfProfile) &&
161 (in_array('Membership', $onBehalfProfile) ||
162 in_array('Contribution', $onBehalfProfile)
163 )
164 ) {
165 CRM_Core_Error::fatal($msg);
166 }
167 }
168 }
169
170 if ($postID = CRM_Utils_Array::value('custom_post_id', $this->_values)) {
171 $postProfile = CRM_Core_BAO_UFGroup::profileGroups($postID);
172 foreach (array(
173 'Individual', 'Organization', 'Household') as $contactType) {
174 if (in_array($contactType, $postProfile) &&
175 (in_array('Membership', $postProfile) ||
176 in_array('Contribution', $postProfile)
177 )
178 ) {
179 CRM_Core_Error::fatal($msg);
180 }
181 }
182 }
183 }
184 }
185
186 /**
187 * Set the default values
188 *
189 * @return void
190 */
191 /**
192 *
193 */
194 public function setDefaultValues() {
195 // check if the user is registered and we have a contact ID
196 $contactID = $this->getContactID();
197
198 if (!empty($contactID)) {
199 $fields = array();
200 $removeCustomFieldTypes = array('Contribution', 'Membership');
201 $contribFields = CRM_Contribute_BAO_Contribution::getContributionFields();
202
203 // remove component related fields
204 foreach ($this->_fields as $name => $dontCare) {
205 //don't set custom data Used for Contribution (CRM-1344)
206 if (substr($name, 0, 7) == 'custom_') {
207 $id = substr($name, 7);
208 if (!CRM_Core_BAO_CustomGroup::checkCustomField($id, $removeCustomFieldTypes)) {
209 continue;
210 }
211 // ignore component fields
212 }
213 elseif (array_key_exists($name, $contribFields) || (substr($name, 0, 11) == 'membership_') || (substr($name, 0, 13) == 'contribution_')) {
214 continue;
215 }
216 $fields[$name] = 1;
217 }
218
219 if (!empty($fields)) {
220 CRM_Core_BAO_UFGroup::setProfileDefaults($contactID, $fields, $this->_defaults);
221 }
222
223 $billingDefaults = $this->getProfileDefaults('Billing', $contactID);
224 $this->_defaults = array_merge($this->_defaults, $billingDefaults);
225 }
226
227 //set custom field defaults set by admin if value is not set
228 if (!empty($this->_fields)) {
229 //load default campaign from page.
230 if (array_key_exists('contribution_campaign_id', $this->_fields)) {
231 $this->_defaults['contribution_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
232 }
233
234 //set custom field defaults
235 foreach ($this->_fields as $name => $field) {
236 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
237 if (!isset($this->_defaults[$name])) {
238 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults,
239 NULL, CRM_Profile_Form::MODE_REGISTER
240 );
241 }
242 }
243 }
244 }
245
246 // // hack to simplify credit card entry for testing
247 // $this->_defaults['credit_card_type'] = 'Visa';
248 // $this->_defaults['amount'] = 168;
249 // $this->_defaults['credit_card_number'] = '4111111111111111';
250 // $this->_defaults['cvv2'] = '000';
251 // $this->_defaults['credit_card_exp_date'] = array('Y' => date('Y')+1, 'M' => '05');
252
253 // // hack to simplify direct debit entry for testing
254 // $this->_defaults['account_holder'] = 'Max Müller';
255 // $this->_defaults['bank_account_number'] = '12345678';
256 // $this->_defaults['bank_identification_number'] = '12030000';
257 // $this->_defaults['bank_name'] = 'Bankname';
258
259 //build set default for pledge overdue payment.
260 if (!empty($this->_values['pledge_id'])) {
261 //get all pledge payment records of current pledge id.
262 $pledgePayments = array();
263
264 //used to record completed pledge payment ids used later for honor default
265 $completedContributionIds = array();
266
267 $pledgePayments = CRM_Pledge_BAO_PledgePayment::getPledgePayments($this->_values['pledge_id']);
268
269 $duePayment = FALSE;
270 foreach ($pledgePayments as $payId => $value) {
271 if ($value['status'] == 'Overdue') {
272 $this->_defaults['pledge_amount'][$payId] = 1;
273 }
274 elseif (!$duePayment && $value['status'] == 'Pending') {
275 $this->_defaults['pledge_amount'][$payId] = 1;
276 $duePayment = TRUE;
277 }
278 elseif ($value['status'] == 'Completed' && $value['contribution_id']) {
279 $completedContributionIds[] = $value['contribution_id'];
280 }
281 }
282
283 if ($this->_honor_block_is_active && count($completedContributionIds)) {
284 $softCredit = array();
285 foreach ($completedContributionIds as $id) {
286 $softCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id);
287 }
288 if (isset($softCredit['soft_credit'])) {
289 $this->_defaults['soft_credit_type_id'] = $softCredit['soft_credit'][1]['soft_credit_type'];
290
291 //since honoree profile fieldname of fields are prefixed with 'honor'
292 //we need to reformat the fieldname to append prefix during setting default values
293 CRM_Core_BAO_UFGroup::setProfileDefaults(
294 $softCredit['soft_credit'][1]['contact_id'],
295 CRM_Core_BAO_UFGroup::getFields($this->_honoreeProfileId),
296 $defaults
297 );
298 foreach ($defaults as $fieldName => $value) {
299 $this->_defaults['honor[' . $fieldName . ']'] = $value;
300 }
301 }
302 }
303 }
304 elseif (!empty($this->_values['pledge_block_id'])) {
305 //set default to one time contribution.
306 $this->_defaults['is_pledge'] = 0;
307 }
308
309 // to process Custom data that are appended to URL
310 $getDefaults = CRM_Core_BAO_CustomGroup::extractGetParams($this, "'Contact', 'Individual', 'Contribution'");
311 $this->_defaults = array_merge($this->_defaults, $getDefaults);
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 * Build the form object
376 *
377 * @return void
378 */
379 public function buildQuickForm() {
380 // build profiles first so that we can determine address fields etc
381 // and then show copy address checkbox
382 $this->buildCustom($this->_values['custom_pre_id'], 'customPre');
383 $this->buildCustom($this->_values['custom_post_id'], 'customPost');
384
385 if (!empty($this->_fields) && !empty($this->_values['custom_pre_id'])) {
386 $profileAddressFields = array();
387 foreach ($this->_fields as $key => $value) {
388 CRM_Core_BAO_UFField::assignAddressField($key, $profileAddressFields, array('uf_group_id' => $this->_values['custom_pre_id']));
389 }
390 $this->set('profileAddressFields', $profileAddressFields);
391 }
392
393 // Build payment processor form
394 if (empty($_GET['onbehalf'])) {
395 CRM_Core_Payment_ProcessorForm::buildQuickForm($this);
396 // Return if we are in an ajax callback
397 if ($this->_snippet) {
398 return;
399 }
400 }
401
402 $config = CRM_Core_Config::singleton();
403
404 if ($this->_onbehalf) {
405 CRM_Contribute_Form_Contribution_OnBehalfOf::buildQuickForm($this);
406 // Return if we are in an ajax callback
407 if ($this->_snippet) {
408 return;
409 }
410 }
411
412 $this->applyFilter('__ALL__', 'trim');
413 $this->add('text', "email-{$this->_bltID}",
414 ts('Email Address'),
415 array('size' => 30, 'maxlength' => 60, 'class' => 'email'),
416 TRUE
417 );
418 $this->addRule("email-{$this->_bltID}", ts('Email is not valid.'), 'email');
419 $pps = array();
420 //@todo - this should be replaced by a check as to whether billing fields are set
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 */
631 public function buildOnBehalfOrganization() {
632 if ($this->_membershipContactID) {
633 $entityBlock = array('contact_id' => $this->_membershipContactID);
634 CRM_Core_BAO_Location::getValues($entityBlock, $this->_defaults);
635 }
636
637 if (!$this->_onBehalfRequired) {
638 $this->addElement('checkbox', 'is_for_organization',
639 $this->_values['for_organization'],
640 NULL, array('onclick' => "showOnBehalf( );")
641 );
642 }
643
644 $this->assign('is_for_organization', TRUE);
645 $this->assign('urlPath', 'civicrm/contribute/transact');
646 }
647
648 /**
649 * Build elements to collect information for recurring contributions
650 *
651 *
652 * @param CRM_Core_Form $form
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 *
728 * @return true if no errors, else array of errors
729 * @static
730 */
731 public static function formRule($fields, $files, $self) {
732 $errors = array();
733 $amount = self::computeAmount($fields, $self);
734
735 if ((!empty($fields['selectMembership']) &&
736 $fields['selectMembership'] != 'no_thanks'
737 ) ||
738 (!empty($fields['priceSetId']) &&
739 $self->_useForMember
740 )
741 ) {
742 $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, FALSE, TRUE);
743
744 $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization();
745
746 $unallowedOrgs = array();
747 foreach (array_keys($lifeMember) as $memTypeId) {
748 $unallowedOrgs[] = $membershipOrgDetails[$memTypeId];
749 }
750 }
751
752 //check for atleast one pricefields should be selected
753 if (!empty($fields['priceSetId'])) {
754 $priceField = new CRM_Price_DAO_PriceField();
755 $priceField->price_set_id = $fields['priceSetId'];
756 $priceField->orderBy('weight');
757 $priceField->find();
758
759 $check = array();
760 $membershipIsActive = TRUE;
761 $previousId = $otherAmount = FALSE;
762 while ($priceField->fetch()) {
763
764 if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) {
765 $previousId = $priceField->id;
766 if ($priceField->name == 'membership_amount' && !$priceField->is_active ) {
767 $membershipIsActive = FALSE;
768 }
769 }
770 if ($priceField->name == 'other_amount') {
771 if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) &&
772 array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])) {
773 $otherAmount = $priceField->id;
774 }
775 elseif (!empty($fields["price_{$priceField->id}"])) {
776 $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]);
777 $min = CRM_Utils_Array::value('min_amount', $self->_values);
778 $max = CRM_Utils_Array::value('max_amount', $self->_values);
779 if ($min && $otherAmountVal < $min) {
780 $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1',
781 array(1 => $min)
782 );
783 }
784 if ($max && $otherAmountVal > $max) {
785 $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.',
786 array(1 => $max)
787 );
788 }
789 }
790 }
791 if (!empty($fields["price_{$priceField->id}"]) || ($previousId == $priceField->id && isset($fields["price_{$previousId}"])
792 && empty($fields["price_{$previousId}"]))) {
793 $check[] = $priceField->id;
794 }
795 }
796
797 $currentMemberships = NULL;
798 if ($membershipIsActive) {
799 $is_test = $self->_mode != 'live' ? 1 : 0;
800 $memContactID = $self->_membershipContactID;
801
802 // For anonymous user check using dedupe rule
803 // if user has Cancelled Membership
804 if (!$memContactID) {
805 $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
806 $dedupeParams['check_permission'] = FALSE;
807 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
808 // if we find more than one contact, use the first one
809 $memContactID = CRM_Utils_Array::value(0, $ids);
810 }
811 $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID,
812 $is_test
813 );
814
815 $errorText = 'Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.';
816 foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
817 if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array::value('price_' . $fieldKey, $fields)) {
818 if (!is_array($fields['price_' . $fieldKey])) {
819 if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]])
820 && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)) {
821 $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'])));
822 }
823 }
824 else {
825 foreach ($fields['price_' . $fieldKey] as $key => $ignore) {
826 if (array_key_exists('membership_type_id', $fieldValue['options'][$key])
827 && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)) {
828 $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$key]['membership_type_id'])));
829 }
830 }
831 }
832 }
833 }
834 }
835
836 // CRM-12233
837 if ($membershipIsActive && !$self->_membershipBlock['is_required']
838 && $self->_values['amount_block_is_active']) {
839 $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL;
840 foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
841 // if 'No thank you' membership is selected then set $membershipFieldId
842 if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) {
843 $membershipFieldId = $fieldKey;
844 }
845 elseif ($membershipFieldId) {
846 if ($fieldValue['name'] == 'other_amount') {
847 $otherFieldId = $fieldKey;
848 }
849 elseif ($fieldValue['name'] == 'contribution_amount') {
850 $contributionFieldId = $fieldKey;
851 }
852
853 if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') {
854 $errorKey = $fieldKey;
855 }
856 }
857 }
858 // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error
859 if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) {
860 $errors["price_{$errorKey}"] = ts('Additional Contribution is required.');
861 }
862 }
863 if (empty($check)) {
864 if ($self->_useForMember == 1 && $membershipIsActive) {
865 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
866 }
867 else {
868 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
869 }
870 }
871 if($otherAmount && !empty($check)) {
872 $errors["price_{$otherAmount}"] = ts('Amount is required field.');
873 }
874
875 if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) {
876 $priceFieldIDS = array();
877 $priceFieldMemTypes = array();
878
879 foreach ($self->_priceSet['fields'] as $priceId => $value) {
880 if (!empty($fields['price_' . $priceId]) || ($self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required']))) {
881 if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) {
882 foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
883 if ($isSet) {
884 $priceFieldIDS[] = $priceFldVal;
885 }
886 }
887 }
888 elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) {
889 // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
890 // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
891 $priceFieldIDS[] = $fields['price_' . $priceId];
892 }
893
894 if (!empty($value['options'])) {
895 foreach ($value['options'] as $val) {
896 if (!empty($val['membership_type_id']) && (
897 ($fields['price_' . $priceId] == $val['id']) ||
898 (isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))
899 )
900 ) {
901 $priceFieldMemTypes[] = $val['membership_type_id'];
902 }
903 }
904 }
905 }
906 }
907
908 if (!empty($lifeMember)) {
909 foreach ($priceFieldIDS as $priceFieldId) {
910 if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) &&
911 in_array($membershipOrgDetails[$id], $unallowedOrgs)
912 ) {
913 $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
914 break;
915 }
916 }
917 }
918
919 if (!empty($priceFieldIDS)) {
920 $ids = implode(',', $priceFieldIDS);
921
922 $priceFieldIDS['id'] = $fields['priceSetId'];
923 $self->set('memberPriceFieldIDS', $priceFieldIDS);
924 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
925 foreach ($count as $id => $occurance) {
926 if ($occurance > 1) {
927 $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.');
928 }
929 }
930 }
931
932 if (empty($priceFieldMemTypes)) {
933 $errors['_qf_default'] = ts('Please select at least one membership option.');
934 }
935 }
936
937 CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'],
938 $fields, $lineItem
939 );
940
941 if ($fields['amount'] < 0) {
942 $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
943 }
944 $amount = $fields['amount'];
945 }
946
947 if (isset($fields['selectProduct']) &&
948 $fields['selectProduct'] != 'no_thanks') {
949 $productDAO = new CRM_Contribute_DAO_Product();
950 $productDAO->id = $fields['selectProduct'];
951 $productDAO->find(TRUE);
952 $min_amount = $productDAO->min_contribution;
953
954 if ($amount < $min_amount) {
955 $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount)));
956 CRM_Core_Session::setStatus($errors['selectProduct']);
957 }
958 }
959
960 if (!empty($fields['is_recur'])) {
961 if ($fields['frequency_interval'] <= 0) {
962 $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
963 }
964 if ($fields['frequency_unit'] == '0') {
965 $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).');
966 }
967 }
968
969 if (!empty($fields['is_recur']) &&
970 CRM_Utils_Array::value('payment_processor', $fields) == 0) {
971 $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
972 }
973
974 if (!empty($fields['is_for_organization']) &&
975 !property_exists($self, 'organizationName')
976 ) {
977
978 if (empty($fields['onbehalf']['organization_name'])) {
979 if (!empty($fields['org_option']) && !$fields['onbehalfof_id']) {
980 $errors['organization_id'] = ts('Please select an organization or enter a new one.');
981 }
982 elseif (empty($fields['org_option'])) {
983 $errors['onbehalf']['organization_name'] = ts('Please enter the organization name.');
984 }
985 }
986
987 foreach ($fields['onbehalf'] as $key => $value) {
988 if (strstr($key, 'email')) {
989 $emailLocType = explode('-', $key);
990 }
991 }
992 if (empty($fields['onbehalf']["email-{$emailLocType[1]}"])) {
993 $errors['onbehalf']["email-{$emailLocType[1]}"] = ts('Organization email is required.');
994 }
995 }
996
997 // validate PCP fields - if not anonymous, we need a nick name value
998 if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) &&
999 (CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0) &&
1000 CRM_Utils_Array::value('pcp_roll_nickname', $fields) == ''
1001 ) {
1002 $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
1003 }
1004
1005 // return if this is express mode
1006 $config = CRM_Core_Config::singleton();
1007 if ($self->_paymentProcessor &&
1008 $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON
1009 ) {
1010 if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) ||
1011 CRM_Utils_Array::value($self->_expressButtonName, $fields)
1012 ) {
1013 return $errors;
1014 }
1015 }
1016
1017 //validate the pledge fields.
1018 if (!empty($self->_values['pledge_block_id'])) {
1019 //validation for pledge payment.
1020 if (!empty($self->_values['pledge_id'])) {
1021 if (empty($fields['pledge_amount'])) {
1022 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
1023 }
1024 }
1025 elseif (!empty($fields['is_pledge'])) {
1026 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) {
1027 $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.');
1028 }
1029 else {
1030 if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) {
1031 $errors['pledge_installments'] = ts('Pledge Installments is required field.');
1032 }
1033 elseif (CRM_Utils_array::value('pledge_installments', $fields) == 1) {
1034 $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.');
1035 }
1036 elseif (CRM_Utils_array::value('pledge_installments', $fields) == 0) {
1037 $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
1038 }
1039 }
1040
1041 //validation for Pledge Frequency Interval.
1042 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) {
1043 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
1044 }
1045 else {
1046 if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) {
1047 $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
1048 }
1049 elseif (CRM_Utils_array::value('pledge_frequency_interval', $fields) == 0) {
1050 $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
1051 }
1052 }
1053 }
1054 }
1055
1056 // also return if paylater mode
1057 if (CRM_Utils_Array::value('payment_processor', $fields) == 0 && $self->_isBillingAddressRequiredForPayLater == 0) {
1058 return empty($errors) ? TRUE : $errors;
1059 }
1060
1061 // if the user has chosen a free membership or the amount is less than zero
1062 // i.e. we skip calling the payment processor and hence dont need credit card
1063 // info
1064 if ((float) $amount <= 0.0) {
1065 return $errors;
1066 }
1067
1068 if (!empty($self->_paymentFields)) {
1069 CRM_Core_Form::validateMandatoryFields($self->_paymentFields, $fields, $errors);
1070 }
1071 CRM_Core_Payment_Form::validateCreditCard($fields, $errors);
1072
1073 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1074 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
1075 $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
1076 if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) {
1077 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1078 array(1 => ucwords(str_replace('_', " ", $greeting)))
1079 );
1080 }
1081 }
1082 }
1083
1084 return empty($errors) ? TRUE : $errors;
1085 }
1086
1087 /**
1088 * @param array $params
1089 * @param CRM_Core_Form $form
1090 *
1091 * @return int|mixed|null|string
1092 */
1093 public static function computeAmount(&$params, &$form) {
1094 $amount = NULL;
1095
1096 // first clean up the other amount field if present
1097 if (isset($params['amount_other'])) {
1098 $params['amount_other'] = CRM_Utils_Rule::cleanMoney($params['amount_other']);
1099 }
1100
1101 if (CRM_Utils_Array::value('amount', $params) == 'amount_other_radio' || !empty($params['amount_other'])) {
1102 $amount = $params['amount_other'];
1103 }
1104 elseif (!empty($params['pledge_amount'])) {
1105 $amount = 0;
1106 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
1107 $amount += CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount');
1108 }
1109 }
1110 else {
1111 if (!empty($form->_values['amount'])) {
1112 $amountID = CRM_Utils_Array::value('amount', $params);
1113
1114 if ($amountID) {
1115 $params['amount_level'] = CRM_Utils_Array::value('label', $form->_values[$amountID]);
1116 $amount = CRM_Utils_Array::value('value', $form->_values[$amountID]);
1117 }
1118 }
1119 }
1120 return $amount;
1121 }
1122
1123 /**
1124 * Process the form submission
1125 *
1126 *
1127 * @return void
1128 */
1129 public function postProcess() {
1130 $config = CRM_Core_Config::singleton();
1131 // we first reset the confirm page so it accepts new values
1132 $this->controller->resetPage('Confirm');
1133
1134 // get the submitted form values.
1135 $params = $this->controller->exportValues($this->_name);
1136
1137 //carry campaign from profile.
1138 if (array_key_exists('contribution_campaign_id', $params)) {
1139 $params['campaign_id'] = $params['contribution_campaign_id'];
1140 }
1141
1142 if (!empty($params['onbehalfof_id'])) {
1143 $params['organization_id'] = $params['onbehalfof_id'];
1144 }
1145
1146 $params['currencyID'] = $config->defaultCurrency;
1147
1148 if (!empty($params['priceSetId'])) {
1149 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
1150 if ($is_quick_config) {
1151 $priceField = new CRM_Price_DAO_PriceField();
1152 $priceField->price_set_id = $params['priceSetId'];
1153 $priceField->orderBy('weight');
1154 $priceField->find();
1155
1156 $priceOptions = array();
1157 while ($priceField->fetch()) {
1158 CRM_Price_BAO_PriceFieldValue::getValues($priceField->id, $priceOptions);
1159 if ($selectedPriceOptionID = CRM_Utils_Array::value("price_{$priceField->id}", $params)) {
1160 switch ($priceField->name) {
1161 case 'membership_amount':
1162 $this->_params['selectMembership'] = $params['selectMembership'] = CRM_Utils_Array::value('membership_type_id', $priceOptions[$selectedPriceOptionID]);
1163 $this->set('selectMembership', $params['selectMembership']);
1164 if (CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) == 0) {
1165 $this->_values['amount'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
1166 }
1167 break;
1168
1169 case 'contribution_amount':
1170 $params['amount'] = $selectedPriceOptionID;
1171 $this->_values['amount'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
1172 $this->_values[$selectedPriceOptionID]['value'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
1173 $this->_values[$selectedPriceOptionID]['label'] = CRM_Utils_Array::value('label', $priceOptions[$selectedPriceOptionID]);
1174 $this->_values[$selectedPriceOptionID]['amount_id'] = CRM_Utils_Array::value('id', $priceOptions[$selectedPriceOptionID]);
1175 $this->_values[$selectedPriceOptionID]['weight'] = CRM_Utils_Array::value('weight', $priceOptions[$selectedPriceOptionID]);
1176 break;
1177
1178 case 'other_amount':
1179 $params['amount_other'] = $selectedPriceOptionID;
1180 break;
1181 }
1182 }
1183 }
1184 }
1185 }
1186
1187 if (($this->_values['is_pay_later'] &&
1188 empty($this->_paymentProcessor) &&
1189 !array_key_exists('hidden_processor', $params)) ||
1190 (!empty($params['payment_processor']) && $params['payment_processor'] == 0)) {
1191 $params['is_pay_later'] = 1;
1192 }
1193 else {
1194 $params['is_pay_later'] = 0;
1195 }
1196
1197 $this->set('is_pay_later', $params['is_pay_later']);
1198 // assign pay later stuff
1199 $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
1200 $this->assign('is_pay_later', $params['is_pay_later']);
1201 if ($params['is_pay_later']) {
1202 $this->assign('pay_later_text', $this->_values['pay_later_text']);
1203 $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
1204 }
1205
1206 // from here on down, $params['amount'] holds a monetary value (or null) rather than an option ID
1207 $params['amount'] = self::computeAmount($params, $this);
1208 $params['separate_amount'] = $params['amount'];
1209 $memFee = NULL;
1210 if (!empty($params['selectMembership'])) {
1211 if (!empty($this->_membershipTypeValues)) {
1212 $membershipTypeValues = $this->_membershipTypeValues[$params['selectMembership']];
1213 }
1214 else {
1215 $membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this,
1216 $params['selectMembership']
1217 );
1218 }
1219 $memFee = $membershipTypeValues['minimum_fee'];
1220 if (!$params['amount'] && !$this->_separateMembershipPayment) {
1221 $params['amount'] = $memFee ? $memFee : 0;
1222 }
1223 }
1224 //If the membership & contribution is used in contribution page & not separate payment
1225 $fieldId = $memPresent = $membershipLabel = $fieldOption = $is_quick_config = NULL;
1226 $proceFieldAmount = 0;
1227 if (property_exists($this, '_separateMembershipPayment') && $this->_separateMembershipPayment == 0) {
1228 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
1229 if ($is_quick_config) {
1230 foreach ($this->_priceSet['fields'] as $fieldKey => $fieldVal) {
1231 if ($fieldVal['name'] == 'membership_amount' && !empty($params['price_' . $fieldKey ])) {
1232 $fieldId = $fieldVal['id'];
1233 $fieldOption = $params['price_' . $fieldId];
1234 $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
1235 $memPresent = TRUE;
1236 }
1237 else {
1238 if (!empty($params['price_' . $fieldKey]) && $memPresent && ($fieldVal['name'] == 'other_amount' || $fieldVal['name'] == 'contribution_amount')) {
1239 $fieldId = $fieldVal['id'];
1240 if ($fieldVal['name'] == 'other_amount') {
1241 $proceFieldAmount += $this->_submitValues['price_' . $fieldId];
1242 }
1243 elseif ($fieldVal['name'] == 'contribution_amount' && $this->_submitValues['price_' . $fieldId] > 0) {
1244 $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
1245 }
1246 unset($params['price_' . $fieldId]);
1247 break;
1248 }
1249 }
1250 }
1251 }
1252 }
1253
1254 if (!isset($params['amount_other'])) {
1255 $this->set('amount_level', CRM_Utils_Array::value('amount_level', $params));
1256 }
1257
1258 if ($priceSetId = CRM_Utils_Array::value('priceSetId', $params)) {
1259 $lineItem = array();
1260 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config' );
1261 if ( $is_quick_config ) {
1262 foreach ( $this->_values['fee'] as $key => & $val ) {
1263 if ( $val['name'] == 'other_amount' && $val['html_type'] == 'Text' && array_key_exists( 'price_'.$key, $params ) ) {
1264 $params['price_'.$key] = CRM_Utils_Rule::cleanMoney($params['price_'.$key]); //Clean out any currency symbols
1265 if ( $params['price_'.$key] != 0 ) {
1266 foreach ( $val['options'] as $optionKey => & $options ) {
1267 $options['amount'] = CRM_Utils_Array::value( 'price_'.$key, $params );
1268 break;
1269 }
1270 }
1271 $params['price_'.$key] = 1;
1272 break;
1273 }
1274 }
1275 }
1276 $component = '';
1277 if ($this->_membershipBlock) {
1278 $component = 'membership';
1279 }
1280
1281 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[$priceSetId], $component);
1282 if ($params['tax_amount']) {
1283 $this->set('tax_amount', $params['tax_amount']);
1284 }
1285
1286 if ($proceFieldAmount) {
1287 $lineItem[$params['priceSetId']][$fieldOption]['unit_price'] = $proceFieldAmount;
1288 $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount;
1289 if (isset($lineItem[$params['priceSetId']][$fieldOption]['tax_amount'])) {
1290 $proceFieldAmount += $lineItem[$params['priceSetId']][$fieldOption]['tax_amount'];
1291 }
1292 if (!$this->_membershipBlock['is_separate_payment']) {
1293 $params['amount'] = $proceFieldAmount; //require when separate membership not used
1294 }
1295 }
1296 $this->set('lineItem', $lineItem);
1297 }
1298
1299 if ($this->_membershipBlock['is_separate_payment'] && !empty($params['separate_amount'])) {
1300 $this->set('amount', $params['separate_amount']);
1301 } else {
1302 $this->set('amount', $params['amount']);
1303 }
1304
1305 // generate and set an invoiceID for this transaction
1306 $invoiceID = md5(uniqid(rand(), TRUE));
1307 $this->set('invoiceID', $invoiceID);
1308
1309 // required only if is_monetary and valid positive amount
1310 if ($this->_values['is_monetary'] &&
1311 is_array($this->_paymentProcessor) &&
1312 ((float ) $params['amount'] > 0.0 || $memFee > 0.0)
1313 ) {
1314
1315 // default mode is direct
1316 $this->set('contributeMode', 'direct');
1317
1318 if ($this->_paymentProcessor &&
1319 $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON
1320 ) {
1321 //get the button name
1322 $buttonName = $this->controller->getButtonName();
1323 if (in_array($buttonName,
1324 array($this->_expressButtonName, $this->_expressButtonName . '_x', $this->_expressButtonName . '_y')
1325 ) && empty($params['is_pay_later'])) {
1326 $this->set('contributeMode', 'express');
1327
1328 $donateURL = CRM_Utils_System::url('civicrm/contribute', '_qf_Contribute_display=1');
1329 $params['cancelURL'] = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=1&qfKey={$params['qfKey']}", TRUE, NULL, FALSE);
1330 $params['returnURL'] = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Confirm_display=1&rfp=1&qfKey={$params['qfKey']}", TRUE, NULL, FALSE);
1331 $params['invoiceID'] = $invoiceID;
1332 $params['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
1333
1334 //default action is Sale
1335 $params['payment_action'] = 'Sale';
1336
1337 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
1338 $token = $payment->setExpressCheckout($params);
1339 if (is_a($token, 'CRM_Core_Error')) {
1340 CRM_Core_Error::displaySessionError($token);
1341 CRM_Utils_System::redirect($params['cancelURL']);
1342 }
1343
1344 $this->set('token', $token);
1345
1346 $paymentURL = $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token";
1347 CRM_Utils_System::redirect($paymentURL);
1348 }
1349 }
1350 elseif ($this->_paymentProcessor &&
1351 $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY
1352 ) {
1353 $this->set('contributeMode', 'notify');
1354 }
1355 }
1356
1357 // should we skip the confirm page?
1358 if (empty($this->_values['is_confirm_enabled'])) {
1359 // call the post process hook for the main page before we switch to confirm
1360 $this->postProcessHook();
1361
1362 // build the confirm page
1363 $confirmForm = &$this->controller->_pages['Confirm'];
1364 $confirmForm->preProcess();
1365 $confirmForm->buildQuickForm();
1366
1367 // the confirmation page is valid
1368 $data = &$this->controller->container();
1369 $data['valid']['Confirm'] = 1;
1370
1371 // confirm the contribution
1372 // mainProcess calls the hook also
1373 $confirmForm->mainProcess();
1374 $qfKey = $this->controller->_key;
1375
1376 // redirect to thank you page
1377 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey=$qfKey", TRUE, NULL, FALSE));
1378 }
1379
1380 }
1381
1382 /**
1383 * Handle Payment Processor switching
1384 * For contribution and event registration forms
1385 * @param CRM_Contribute_Form_Contribution_Main|CRM_Event_Form_Registration_Register $form
1386 * @param bool $noFees
1387 */
1388 public static function preProcessPaymentOptions(&$form, $noFees = FALSE) {
1389 $form->_snippet = CRM_Utils_Array::value('snippet', $_GET);
1390
1391 $form->_paymentProcessors = $noFees ? array() : $form->get('paymentProcessors');
1392 $form->_paymentProcessorID = NULL;
1393 if ($form->_paymentProcessors) {
1394 // Fetch type during ajax request
1395 if (isset($_GET['type']) && $form->_snippet) {
1396 $form->_paymentProcessorID = CRM_Utils_Request::retrieve('type', 'Integer', CRM_Core_DAO::$_nullObject, FALSE, 0);
1397 }
1398 // Remember type during form post
1399 elseif (!empty($form->_submitValues)) {
1400 $form->_paymentProcessorID = CRM_Utils_Array::value('payment_processor', $form->_submitValues);
1401 $form->_paymentProcessor = CRM_Utils_Array::value($form->_paymentProcessorID, $form->_paymentProcessors);
1402 $form->set('type', $form->_paymentProcessorID);
1403 $form->set('mode', $form->_mode);
1404 $form->set('paymentProcessor', $form->_paymentProcessor);
1405 }
1406 // Set default payment processor
1407 else {
1408 foreach ($form->_paymentProcessors as $values) {
1409 if (!empty($values['is_default']) || count($form->_paymentProcessors) == 1) {
1410 $form->_paymentProcessorID = $values['id'];
1411 break;
1412 }
1413 }
1414 }
1415 if ($form->_paymentProcessorID) {
1416 CRM_Core_Payment_ProcessorForm::preProcess($form);
1417 }
1418 else {
1419 $form->_paymentProcessor = array();
1420 }
1421
1422 //get payPal express id and make it available to template
1423 foreach ($form->_paymentProcessors as $ppId => $values) {
1424 $payPalExpressId = ($values['payment_processor_type'] == 'PayPal_Express') ? $values['id'] : 0;
1425 $form->assign('payPalExpressId', $payPalExpressId);
1426 if ($payPalExpressId) {
1427 break;
1428 }
1429 }
1430 if (!$form->_snippet) {
1431 // Add JS to show icons for the accepted credit cards
1432 $creditCardTypes = CRM_Core_Payment_Form::getCreditCardCSSNames();
1433 CRM_Core_Resources::singleton()
1434 ->addScriptFile('civicrm', 'templates/CRM/Core/BillingBlock.js', 10)
1435 // workaround for CRM-13634
1436 // ->addSetting(array('config' => array('creditCardTypes' => $creditCardTypes)));
1437 ->addScript('CRM.config.creditCardTypes = ' . json_encode($creditCardTypes) . ';');
1438 }
1439 }
1440 $form->assign('paymentProcessorID', $form->_paymentProcessorID);
1441 }
1442 }