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