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