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