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