3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class generates form components for processing a contribution.
21 class CRM_Contribute_Form_ContributionBase
extends CRM_Core_Form
{
22 use CRM_Financial_Form_FrontEndPaymentFormTrait
;
25 * The id of the contribution page that we are processing.
32 * The mode that we are in
40 * The contact id related to a membership
44 public $_membershipContactID;
47 * The values for the contribution db object
54 * The paymentProcessor attributes for this page
58 public $_paymentProcessor;
60 public $_paymentObject = NULL;
63 * The membership block for this page
67 public $_membershipBlock = NULL;
70 * Does this form support a separate membership payment
73 protected $_separateMembershipPayment;
76 * The params submitted by the form and computed by the app
83 * The fields involved in this contribution page
90 * The billing location id for this contribution page.
97 * Cache the amount to make things easier
125 * The contact id of the person for whom membership is being added or renewed based on the cid in the url,
126 * checksum, or session
134 * The Membership ID for membership renewal
138 public $_membershipId;
141 * Price Set ID, if the new price set method is used
148 * Array of fields for the price set
159 * In general we are trying to deprecate this parameter but some templates and processors still
160 * require it to denote whether the processor redirects offsite (notify) or not.
162 * The intent is that this knowledge should not be required and all contributions should
163 * be created in a pending state and updated based on the payment result without needing to be
164 * aware of the processor workings.
170 public $_contributeMode;
173 * Contribution page supports memberships
176 public $_useForMember;
182 public $_isBillingAddressRequiredForPayLater;
185 * Flag if email field exists in embedded profile
189 public $_emailExists = FALSE;
192 * Is this a backoffice form.
194 * Processors may display different options to backoffice users.
198 public $isBackOffice = FALSE;
201 * Payment instrument if for the transaction.
203 * This will generally be drawn from the payment processor and is ignored for
208 public $paymentInstrumentID;
211 * Is the price set quick config.
214 public function isQuickConfig() {
215 return self
::$_quickConfig ??
FALSE;
219 * Set variables up before form is built.
221 * @throws \CRM_Contribute_Exception_InactiveContributionPageException
224 public function preProcess() {
226 // current contribution page id
227 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
228 $this->_ccid
= CRM_Utils_Request
::retrieve('ccid', 'Positive', $this);
230 // seems like the session is corrupted and/or we lost the id trail
231 // lets just bump this to a regular session error and redirect user to main page
232 $this->controller
->invalidKeyRedirect();
234 $this->_emailExists
= $this->get('emailExists');
236 // this was used prior to the cleverer this_>getContactID - unsure now
237 $this->_userID
= CRM_Core_Session
::getLoggedInContactID();
239 $this->_contactID
= $this->_membershipContactID
= $this->getContactID();
241 if ($this->_contactID
) {
242 $this->_mid
= CRM_Utils_Request
::retrieve('mid', 'Positive', $this);
244 $membership = new CRM_Member_DAO_Membership();
245 $membership->id
= $this->_mid
;
247 if ($membership->find(TRUE)) {
248 $this->_defaultMemTypeId
= $membership->membership_type_id
;
249 if ($membership->contact_id
!= $this->_contactID
) {
250 $validMembership = FALSE;
251 $organizations = CRM_Contact_BAO_Relationship
::getPermissionedContacts($this->_userID
, NULL, NULL, 'Organization');
252 if (!empty($organizations) && array_key_exists($membership->contact_id
, $organizations)) {
253 $this->_membershipContactID
= $membership->contact_id
;
254 $this->assign('membershipContactID', $this->_membershipContactID
);
255 $this->assign('membershipContactName', $organizations[$this->_membershipContactID
]['name']);
256 $validMembership = TRUE;
259 $membershipType = new CRM_Member_BAO_MembershipType();
260 $membershipType->id
= $membership->membership_type_id
;
261 if ($membershipType->find(TRUE)) {
262 // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values.
263 // Convert to comma separated list.
264 $inheritedRelTypes = implode(CRM_Utils_Array
::explodePadded($membershipType->relationship_type_id
), ',');
265 $permContacts = CRM_Contact_BAO_Relationship
::getPermissionedContacts($this->_userID
, $membershipType->relationship_type_id
);
266 if (array_key_exists($membership->contact_id
, $permContacts)) {
267 $this->_membershipContactID
= $membership->contact_id
;
268 $validMembership = TRUE;
272 if (!$validMembership) {
273 CRM_Core_Session
::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert');
278 CRM_Core_Session
::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert');
284 // we do not want to display recently viewed items, so turn off
285 $this->assign('displayRecent', FALSE);
288 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
289 $this->assign('action', $this->_action
);
292 $this->_mode
= ($this->_action
== 1024) ?
'test' : 'live';
294 $this->_values
= $this->get('values');
295 $this->_fields
= $this->get('fields');
296 $this->_bltID
= $this->get('bltID');
297 $this->_paymentProcessor
= $this->get('paymentProcessor');
299 $this->_priceSetId
= $this->get('priceSetId');
300 $this->_priceSet
= $this->get('priceSet');
302 if (!$this->_values
) {
303 // get all the values from the dao object
307 CRM_Contribute_BAO_ContributionPage
::setValues($this->_id
, $this->_values
);
308 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
309 && !CRM_Core_Permission
::check('add contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']))
311 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
313 if (empty($this->_values
['is_active'])) {
314 throw new CRM_Contribute_Exception_InactiveContributionPageException(ts('The page you requested is currently unavailable.'), $this->_id
);
317 $endDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('end_date', $this->_values
));
318 $now = date('YmdHis');
319 if ($endDate && $endDate < $now) {
320 throw new CRM_Contribute_Exception_PastContributionPageException(ts('The page you requested has past its end date on %1', [1 => CRM_Utils_Date
::customFormat($endDate)]), $this->_id
);
323 $startDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('start_date', $this->_values
));
324 if ($startDate && $startDate > $now) {
325 throw new CRM_Contribute_Exception_FutureContributionPageException(ts('The page you requested will be active from %1', [1 => CRM_Utils_Date
::customFormat($startDate)]), $this->_id
);
328 $this->assignBillingType();
330 // check for is_monetary status
331 $isMonetary = $this->_values
['is_monetary'] ??
NULL;
332 $isPayLater = $this->_values
['is_pay_later'] ??
NULL;
333 if (!empty($this->_ccid
)) {
334 $this->_values
['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
340 $this->_values
['is_pay_later'] = FALSE;
344 $this->setPayLaterLabel($this->_values
['pay_later_text']);
348 $this->_paymentProcessorIDs
= array_filter(explode(
349 CRM_Core_DAO
::VALUE_SEPARATOR
,
350 CRM_Utils_Array
::value('payment_processor', $this->_values
)
353 $this->assignPaymentProcessor($isPayLater);
358 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $this->_id
);
359 CRM_Price_BAO_PriceSet
::initSet($this, 'civicrm_contribution_page', FALSE, $priceSetId);
361 // this avoids getting E_NOTICE errors in php
363 'amount_block_is_active',
364 'is_allow_other_amount',
367 foreach ($setNullFields as $f) {
368 if (!isset($this->_values
[$f])) {
369 $this->_values
[$f] = NULL;
373 //check if Membership Block is enabled, if Membership Fields are included in profile
374 //get membership section for this contribution page
375 $this->_membershipBlock
= CRM_Member_BAO_Membership
::getMembershipBlock($this->_id
);
376 $this->set('membershipBlock', $this->_membershipBlock
);
378 if (!empty($this->_values
['custom_pre_id'])) {
379 $preProfileType = CRM_Core_BAO_UFField
::getProfileType($this->_values
['custom_pre_id']);
382 if (!empty($this->_values
['custom_post_id'])) {
383 $postProfileType = CRM_Core_BAO_UFField
::getProfileType($this->_values
['custom_post_id']);
386 if (((isset($postProfileType) && $postProfileType === 'Membership') ||
387 (isset($preProfileType) && $preProfileType === 'Membership')
389 !$this->_membershipBlock
['is_active']
391 CRM_Core_Error
::statusBounce(ts('This page includes a Profile with Membership fields - but the Membership Block is NOT enabled. Please notify the site administrator.'));
394 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($this->_id
);
397 $this->_values
['pledge_block_id'] = $pledgeBlock['id'] ??
NULL;
398 $this->_values
['max_reminders'] = $pledgeBlock['max_reminders'] ??
NULL;
399 $this->_values
['initial_reminder_day'] = $pledgeBlock['initial_reminder_day'] ??
NULL;
400 $this->_values
['additional_reminder_day'] = $pledgeBlock['additional_reminder_day'] ??
NULL;
402 //set pledge id in values
403 $pledgeId = CRM_Utils_Request
::retrieve('pledgeId', 'Positive', $this);
405 //authenticate pledge user for pledge payment.
407 $this->_values
['pledge_id'] = $pledgeId;
409 //lets override w/ pledge campaign.
410 $this->_values
['campaign_id'] = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
414 self
::authenticatePledgeUser();
417 $this->set('values', $this->_values
);
418 $this->set('fields', $this->_fields
);
422 $pcpId = CRM_Utils_Request
::retrieve('pcpId', 'Positive', $this);
424 $pcp = CRM_PCP_BAO_PCP
::handlePcp($pcpId, 'contribute', $this->_values
);
425 $this->_pcpId
= $pcp['pcpId'];
426 $this->_pcpBlock
= $pcp['pcpBlock'];
427 $this->_pcpInfo
= $pcp['pcpInfo'];
430 // Link (button) for users to create their own Personal Campaign page
431 if ($linkText = CRM_PCP_BAO_PCP
::getPcpBlockStatus($this->_id
, 'contribute')) {
432 $linkTextUrl = CRM_Utils_System
::url('civicrm/contribute/campaign',
433 "action=add&reset=1&pageId={$this->_id}&component=contribute",
436 $this->assign('linkTextUrl', $linkTextUrl);
437 $this->assign('linkText', $linkText);
440 //set pledge block if block id is set
441 if (!empty($this->_values
['pledge_block_id'])) {
442 $this->assign('pledgeBlock', TRUE);
445 // check if one of the (amount , membership) blocks is active or not.
446 $this->_membershipBlock
= $this->get('membershipBlock');
448 if (!$this->_values
['amount_block_is_active'] &&
449 !$this->_membershipBlock
['is_active'] &&
452 CRM_Core_Error
::statusBounce(ts('The requested online contribution page is missing a required Contribution Amount section or Membership section or Price Set. Please check with the site administrator for assistance.'));
455 if ($this->_values
['amount_block_is_active']) {
456 $this->set('amount_block_is_active', $this->_values
['amount_block_is_active']);
459 $this->_contributeMode
= $this->get('contributeMode');
460 $this->assign('contributeMode', $this->_contributeMode
);
462 //assigning is_monetary and is_email_receipt to template
463 $this->assign('is_monetary', $this->_values
['is_monetary']);
464 $this->assign('is_email_receipt', $this->_values
['is_email_receipt']);
465 $this->assign('bltID', $this->_bltID
);
467 //assign cancelSubscription URL to templates
468 $this->assign('cancelSubscriptionUrl',
469 CRM_Utils_Array
::value('cancelSubscriptionUrl', $this->_values
)
472 $title = !empty($this->_values
['frontend_title']) ?
$this->_values
['frontend_title'] : $this->_values
['title'];
474 $this->setTitle(($this->_pcpId ?
$this->_pcpInfo
['title'] : $title));
475 $this->_defaults
= [];
477 $this->_amount
= $this->get('amount');
478 // Assigning this to the template means it will be passed through to the payment form.
479 // This can, for example, by used by payment processors using client side encryption
480 $this->assign('currency', $this->getCurrency());
482 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($this->_values
);
484 //lets allow user to override campaign.
485 $campID = CRM_Utils_Request
::retrieve('campID', 'Positive', $this);
486 if ($campID && CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
487 $this->_values
['campaign_id'] = $campID;
490 //do check for cancel recurring and clean db, CRM-7696
491 if (CRM_Utils_Request
::retrieve('cancel', 'Boolean')) {
492 self
::cancelRecurring();
495 // check if billing block is required for pay later
496 if (!empty($this->_values
['is_pay_later'])) {
497 $this->_isBillingAddressRequiredForPayLater
= $this->_values
['is_billing_required'] ??
NULL;
498 $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater
);
503 * Set the default values.
505 public function setDefaultValues() {
506 return $this->_defaults
;
510 * Assign the minimal set of variables to the template.
512 public function assignToTemplate() {
513 $this->set('name', $this->assignBillingName($this->_params
));
515 $this->assign('paymentProcessor', $this->_paymentProcessor
);
524 $config = CRM_Core_Config
::singleton();
525 if (isset($this->_values
['is_recur']) && !empty($this->_paymentProcessor
['is_recur'])) {
526 $this->assign('is_recur_enabled', 1);
527 $vars = array_merge($vars, [
529 'frequency_interval',
535 if (in_array('CiviPledge', $config->enableComponents
) &&
536 CRM_Utils_Array
::value('is_pledge', $this->_params
) == 1
538 $this->assign('pledge_enabled', 1);
540 $vars = array_merge($vars, [
542 'pledge_frequency_interval',
543 'pledge_frequency_unit',
544 'pledge_installments',
548 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
549 // function to get correct amount level consistently. Remove setting of the amount level in
550 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
551 // to cover all variants.
552 if (isset($this->_params
['amount_other']) ||
isset($this->_params
['selectMembership'])) {
553 $this->_params
['amount_level'] = '';
556 foreach ($vars as $v) {
557 if (isset($this->_params
[$v])) {
558 if ($v == "amount" && $this->_params
[$v] === 0) {
559 $this->_params
[$v] = CRM_Utils_Money
::format($this->_params
[$v], NULL, NULL, TRUE);
561 $this->assign($v, $this->_params
[$v]);
565 $this->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
570 if (!empty($this->_params
['onbehalf_profile_id']) && !empty($this->_params
['onbehalf'])) {
571 $this->assign('onBehalfName', $this->_params
['organization_name']);
572 $locTypeId = array_keys($this->_params
['onbehalf_location']['email']);
573 $this->assign('onBehalfEmail', $this->_params
['onbehalf_location']['email'][$locTypeId[0]]['email']);
575 $this->assignPaymentFields();
576 $this->assignEmailField();
578 // also assign the receipt_text
579 if (isset($this->_values
['receipt_text'])) {
580 $this->assign('receipt_text', $this->_values
['receipt_text']);
585 * Assign email variable in the template.
587 public function assignEmailField() {
588 //If email exist in a profile, the default billing email field is not loaded on the page.
589 //Hence, assign the existing location type email by iterating through the params.
590 if ($this->_emailExists
&& empty($this->_params
["email-{$this->_bltID}"])) {
591 foreach ($this->_params
as $key => $val) {
592 if (substr($key, 0, 6) === 'email-') {
593 $this->assign('email', $this->_params
[$key]);
599 $this->assign('email', CRM_Utils_Array
::value("email-{$this->_bltID}", $this->_params
));
604 * Add the custom fields.
607 * @param string $name
608 * @param bool $viewOnly
609 * @param null $profileContactType
610 * @param array $fieldTypes
612 public function buildCustom($id, $name, $viewOnly = FALSE, $profileContactType = NULL, $fieldTypes = NULL) {
614 $contactID = $this->getContactID();
616 // we don't allow conflicting fields to be
617 // configured via profile - CRM 2100
624 'non_deductible_amount' => 1,
627 'contribution_status_id' => 1,
628 // @todo replace payment_instrument with payment instrument id.
629 // both are available now but the id field is the most consistent.
630 'payment_instrument' => 1,
631 'payment_instrument_id' => 1,
632 'contribution_check_number' => 1,
633 'financial_type' => 1,
636 $fields = CRM_Core_BAO_UFGroup
::getFields($id, FALSE, CRM_Core_Action
::ADD
, NULL, NULL, FALSE,
637 NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, NULL
641 // determine if email exists in profile so we know if we need to manually insert CRM-2888, CRM-15067
642 foreach ($fields as $key => $field) {
643 if (substr($key, 0, 6) == 'email-' &&
644 !in_array($profileContactType, ['honor', 'onbehalf'])
646 $this->_emailExists
= TRUE;
647 $this->set('emailExists', TRUE);
651 if (array_intersect_key($fields, $fieldsToIgnore)) {
652 $fields = array_diff_key($fields, $fieldsToIgnore);
653 CRM_Core_Session
::setStatus(ts('Some of the profile fields cannot be configured for this page.'), ts('Warning'), 'alert');
656 //remove common fields only if profile is not configured for onbehalf/honor
657 if (!in_array($profileContactType, ['honor', 'onbehalf'])) {
658 $fields = array_diff_key($fields, $this->_fields
);
661 CRM_Core_BAO_Address
::checkContactSharedAddressFields($fields, $contactID);
663 // fetch file preview when not submitted yet, like in online contribution Confirm and ThankYou page
664 $viewOnlyFileValues = empty($profileContactType) ?
[] : [$profileContactType => []];
665 foreach ($fields as $key => $field) {
667 isset($field['data_type']) &&
668 $field['data_type'] == 'File' ||
($viewOnly && $field['name'] == 'image_URL')
670 //retrieve file value from submitted values on basis of $profileContactType
671 $fileValue = $this->_params
[$key] ??
NULL;
672 if (!empty($profileContactType) && !empty($this->_params
[$profileContactType])) {
673 $fileValue = $this->_params
[$profileContactType][$key] ??
NULL;
677 $path = $fileValue['name'] ??
NULL;
678 $fileType = $fileValue['type'] ??
NULL;
679 $fileValue = CRM_Utils_File
::getFileURL($path, $fileType);
682 // format custom file value fetched from submitted value
683 if ($profileContactType) {
684 $viewOnlyFileValues[$profileContactType][$key] = $fileValue;
687 $viewOnlyFileValues[$key] = $fileValue;
690 // On viewOnly use-case (as in online contribution Confirm page) we no longer need to set
691 // required property because being required file is already uploaded while registration
692 $field['is_required'] = FALSE;
694 if ($profileContactType) {
695 //Since we are showing honoree name separately so we are removing it from honoree profile just for display
696 if ($profileContactType == 'honor') {
697 $honoreeNamefields = [
705 if (in_array($field['name'], $honoreeNamefields)) {
706 unset($fields[$field['name']]);
710 if (!empty($fieldTypes) && in_array($field['field_type'], $fieldTypes)) {
711 CRM_Core_BAO_UFGroup
::buildProfile(
714 CRM_Profile_Form
::MODE_CREATE
,
719 $this->_fields
[$profileContactType][$key] = $field;
722 unset($fields[$key]);
726 CRM_Core_BAO_UFGroup
::buildProfile(
729 CRM_Profile_Form
::MODE_CREATE
,
733 $this->_fields
[$key] = $field;
735 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
736 if ($field['add_captcha'] && !$this->_userID
) {
741 $this->assign($name, $fields);
743 if ($profileContactType && count($viewOnlyFileValues[$profileContactType])) {
744 $this->assign('viewOnlyPrefixFileValues', $viewOnlyFileValues);
746 elseif (count($viewOnlyFileValues)) {
747 $this->assign('viewOnlyFileValues', $viewOnlyFileValues);
750 if ($addCaptcha && !$viewOnly) {
751 $this->enableCaptchaOnForm();
758 * Enable ReCAPTCHA on Contribution form
760 protected function enableCaptchaOnForm() {
761 CRM_Utils_ReCAPTCHA
::enableCaptchaOnForm($this);
765 * Assign payment field information to the template.
767 * @throws \CRM_Core_Exception
768 * @throws \CiviCRM_API3_Exception
770 public function assignPaymentFields() {
773 if ($this->_amount
> 0.0) {
776 elseif (!empty($this->_params
['selectMembership'])) {
777 $memFee = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params
['selectMembership'], 'minimum_fee');
783 // The concept of contributeMode is deprecated.
784 // The payment processor object can provide info about the fields it shows.
785 if ($isMonetary && is_a($this->_paymentProcessor
['object'], 'CRM_Core_Payment')) {
786 /** @var \CRM_Core_Payment $paymentProcessorObject */
787 $paymentProcessorObject = $this->_paymentProcessor
['object'];
789 $paymentFields = $paymentProcessorObject->getPaymentFormFields();
790 foreach ($paymentFields as $index => $paymentField) {
791 if (!isset($this->_params
[$paymentField])) {
792 unset($paymentFields[$index]);
795 if ($paymentField === 'credit_card_exp_date') {
796 $date = CRM_Utils_Date
::format(CRM_Utils_Array
::value('credit_card_exp_date', $this->_params
));
797 $date = CRM_Utils_Date
::mysqlToIso($date);
798 $this->assign('credit_card_exp_date', $date);
800 elseif ($paymentField === 'credit_card_number') {
801 $this->assign('credit_card_number',
802 CRM_Utils_System
::mungeCreditCard(CRM_Utils_Array
::value('credit_card_number', $this->_params
))
805 elseif ($paymentField === 'credit_card_type') {
806 $this->assign('credit_card_type', CRM_Core_PseudoConstant
::getLabel(
807 'CRM_Core_BAO_FinancialTrxn',
809 CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $this->_params
['credit_card_type'])
813 $this->assign($paymentField, $this->_params
[$paymentField]);
816 $this->assign('paymentFieldsetLabel', CRM_Core_Payment_Form
::getPaymentLabel($paymentProcessorObject));
817 $this->assign('paymentFields', $paymentFields);
823 * Display ReCAPTCHA warning on Contribution form
825 protected function displayCaptchaWarning() {
826 if (CRM_Core_Permission
::check("administer CiviCRM")) {
827 if (!CRM_Utils_ReCAPTCHA
::hasSettingsAvailable()) {
828 $this->assign('displayCaptchaWarning', TRUE);
834 * Check if ReCAPTCHA has to be added on Contribution form forcefully.
836 protected function hasToAddForcefully() {
837 return CRM_Utils_ReCAPTCHA
::hasToAddForcefully();
841 * Add onbehalf/honoree profile fields and native module fields.
844 * @param CRM_Core_Form $form
846 * @throws \API_Exception
847 * @throws \CRM_Core_Exception
848 * @throws \CiviCRM_API3_Exception
850 public function buildComponentForm($id, $form): void
{
855 $contactID = $this->getContactID();
857 foreach (['soft_credit', 'on_behalf'] as $module) {
858 if ($module === 'soft_credit') {
859 if (empty($form->_values
['honoree_profile_id'])) {
863 if (!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values
['honoree_profile_id'], 'is_active')) {
864 CRM_Core_Error
::statusBounce(ts('This contribution page has been configured for contribution on behalf of honoree and the selected honoree profile is either disabled or not found.'));
867 $profileContactType = CRM_Core_BAO_UFGroup
::getContactType($form->_values
['honoree_profile_id']);
868 $requiredProfileFields = [
869 'Individual' => ['first_name', 'last_name'],
870 'Organization' => ['organization_name', 'email'],
871 'Household' => ['household_name', 'email'],
873 $validProfile = CRM_Core_BAO_UFGroup
::checkValidProfile($form->_values
['honoree_profile_id'], $requiredProfileFields[$profileContactType]);
874 if (!$validProfile) {
875 CRM_Core_Error
::statusBounce(ts('This contribution page has been configured for contribution on behalf of honoree and the required fields of the selected honoree profile are disabled or doesn\'t exist.'));
878 foreach (['honor_block_title', 'honor_block_text'] as $name) {
879 $form->assign($name, $form->_values
[$name]);
882 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
884 // radio button for Honor Type
885 foreach ($form->_values
['soft_credit_types'] as $value) {
886 $honorTypes[$value] = $softCreditTypes[$value];
888 $form->addRadio('soft_credit_type_id', NULL, $honorTypes, ['allowClear' => TRUE]);
890 $honoreeProfileFields = CRM_Core_BAO_UFGroup
::getFields(
891 $this->_values
['honoree_profile_id'], FALSE,
895 NULL, CRM_Core_Permission
::CREATE
897 $form->assign('honoreeProfileFields', $honoreeProfileFields);
899 // add the form elements
900 foreach ($honoreeProfileFields as $name => $field) {
901 // If soft credit type is not chosen then make omit requiredness from honoree profile fields
902 if (count($form->_submitValues
) &&
903 empty($form->_submitValues
['soft_credit_type_id']) &&
904 !empty($field['is_required'])
906 $field['is_required'] = FALSE;
908 CRM_Core_BAO_UFGroup
::buildProfile($form, $field, CRM_Profile_Form
::MODE_CREATE
, NULL, FALSE, FALSE, NULL, 'honor');
912 if (empty($form->_values
['onbehalf_profile_id'])) {
916 if (!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values
['onbehalf_profile_id'], 'is_active')) {
917 CRM_Core_Error
::statusBounce(ts('This contribution page has been configured for contribution on behalf of an organization and the selected onbehalf profile is either disabled or not found.'));
920 $member = CRM_Member_BAO_Membership
::getMembershipBlock($form->_id
);
921 if (empty($member['is_active'])) {
922 $msg = ts('Mixed profile not allowed for on behalf of registration/sign up.');
923 $onBehalfProfile = CRM_Core_BAO_UFGroup
::profileGroups($form->_values
['onbehalf_profile_id']);
931 if (in_array($contactType, $onBehalfProfile) &&
932 (in_array('Membership', $onBehalfProfile) ||
933 in_array('Contribution', $onBehalfProfile)
936 CRM_Core_Error
::statusBounce($msg);
942 // retrieve all permissioned organizations of contact $contactID
943 $organizations = CRM_Contact_BAO_Relationship
::getPermissionedContacts($contactID, NULL, NULL, 'Organization');
945 if (count($organizations)) {
946 // Related org url - pass checksum if needed
948 'ufId' => $form->_values
['onbehalf_profile_id'],
951 if (!empty($_GET['cs'])) {
953 'ufId' => $form->_values
['onbehalf_profile_id'],
954 'uid' => $this->_contactID
,
959 $locDataURL = CRM_Utils_System
::url('civicrm/ajax/permlocation', $args, FALSE, NULL, FALSE);
960 $form->assign('locDataURL', $locDataURL);
962 if (count($organizations) > 0) {
963 $form->add('select', 'onbehalfof_id', '', CRM_Utils_Array
::collect('name', $organizations));
966 0 => ts('Select an existing organization'),
967 1 => ts('Enter a new organization'),
969 $form->addRadio('org_option', ts('options'), $orgOptions);
970 $form->setDefaults(['org_option' => 0]);
974 $form->assign('fieldSetTitle', CRM_Core_BAO_UFGroup
::getFrontEndTitle($form->_values
['onbehalf_profile_id']));
976 if (!empty($form->_values
['is_for_organization'])) {
977 if ($form->_values
['is_for_organization'] == 2) {
978 $form->assign('onBehalfRequired', TRUE);
981 $form->addElement('checkbox', 'is_for_organization',
982 $form->_values
['for_organization'],
988 $profileFields = CRM_Core_BAO_UFGroup
::getFields(
989 $form->_values
['onbehalf_profile_id'],
990 FALSE, CRM_Core_Action
::VIEW
, NULL,
991 NULL, FALSE, NULL, FALSE, NULL,
992 CRM_Core_Permission
::CREATE
, NULL
995 $form->assign('onBehalfOfFields', $profileFields);
996 if (!empty($form->_submitValues
['onbehalf'])) {
997 if (!empty($form->_submitValues
['onbehalfof_id'])) {
998 $form->assign('submittedOnBehalf', $form->_submitValues
['onbehalfof_id']);
1000 $form->assign('submittedOnBehalfInfo', json_encode(str_replace('"', '\"', $form->_submitValues
['onbehalf']), JSON_HEX_APOS
));
1003 $fieldTypes = ['Contact', 'Organization'];
1004 if (!empty($form->_membershipBlock
)) {
1005 $fieldTypes = array_merge($fieldTypes, ['Membership']);
1007 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
1008 $fieldTypes = array_merge($fieldTypes, $contactSubType);
1010 foreach ($profileFields as $name => $field) {
1011 if (in_array($field['field_type'], $fieldTypes)) {
1012 [$prefixName, $index] = CRM_Utils_System
::explode('-', $name, 2);
1013 if (in_array($prefixName, ['organization_name', 'email']) && empty($field['is_required'])) {
1014 $field['is_required'] = 1;
1016 if (count($form->_submitValues
) &&
1017 empty($form->_submitValues
['is_for_organization']) &&
1018 $form->_values
['is_for_organization'] == 1 &&
1019 !empty($field['is_required'])
1021 $field['is_required'] = FALSE;
1023 CRM_Core_BAO_UFGroup
::buildProfile($form, $field, NULL, NULL, FALSE, 'onbehalf', NULL, 'onbehalf');
1032 * Check template file exists.
1034 * @param string $suffix
1036 * @return null|string
1038 public function checkTemplateFileExists($suffix = NULL) {
1040 $templateFile = "CRM/Contribute/Form/Contribution/{$this->_id}/{$this->_name}.{$suffix}tpl";
1041 $template = CRM_Core_Form
::getTemplate();
1042 if ($template->template_exists($templateFile)) {
1043 return $templateFile;
1050 * Use the form name to create the tpl file name.
1054 public function getTemplateFileName() {
1055 $fileName = $this->checkTemplateFileExists();
1056 return $fileName ?
: parent
::getTemplateFileName();
1060 * Add the extra.tpl in.
1062 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1063 * i.e. we do not override - why isn't this done at the CRM_Core_Form level?
1067 public function overrideExtraTemplateFileName() {
1068 $fileName = $this->checkTemplateFileExists('extra.');
1069 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();
1073 * Authenticate pledge user during online payment.
1075 * @throws \CRM_Core_Exception
1077 public function authenticatePledgeUser() {
1078 //get the userChecksum and contact id
1079 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
1080 $contactID = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
1082 //get pledge status and contact id
1084 $pledgeParams = ['id' => $this->_values
['pledge_id']];
1085 $returnProperties = ['contact_id', 'status_id'];
1086 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_DAO_Pledge', $pledgeParams, $pledgeValues, $returnProperties);
1089 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1091 array_search('Pending', $allStatus),
1092 array_search('In Progress', $allStatus),
1093 array_search('Overdue', $allStatus),
1097 if ($this->_userID
&&
1098 $this->_userID
== $pledgeValues['contact_id']
1100 //check for authenticated user.
1103 elseif ($userChecksum && $pledgeValues['contact_id']) {
1104 //check for anonymous user.
1105 $validUser = CRM_Contact_BAO_Contact_Utils
::validChecksum($pledgeValues['contact_id'], $userChecksum);
1107 //make sure cid is same as pledge contact id
1108 if ($validUser && ($pledgeValues['contact_id'] != $contactID)) {
1114 CRM_Core_Error
::statusBounce(ts("Oops. It looks like you have an incorrect or incomplete link (URL). Please make sure you've copied the entire link, and try again. Contact the site administrator if this error persists."));
1117 //check for valid pledge status.
1118 if (!in_array($pledgeValues['status_id'], $validStatus)) {
1119 CRM_Core_Error
::statusBounce(ts('Oops. You cannot make a payment for this pledge - pledge status is %1.', [1 => CRM_Utils_Array
::value($pledgeValues['status_id'], $allStatus)]));
1124 * Cancel recurring contributions.
1126 * In case user cancel recurring contribution,
1127 * When we get the control back from payment gate way
1128 * lets delete the recurring and related contribution.
1130 * @throws \CRM_Core_Exception
1132 public function cancelRecurring() {
1133 $isCancel = CRM_Utils_Request
::retrieve('cancel', 'Boolean');
1135 $isRecur = CRM_Utils_Request
::retrieve('isRecur', 'Boolean');
1136 $recurId = CRM_Utils_Request
::retrieve('recurId', 'Positive');
1137 //clean db for recurring contribution.
1138 if ($isRecur && $recurId) {
1139 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($recurId);
1141 $contribId = CRM_Utils_Request
::retrieve('contribId', 'Positive');
1143 CRM_Contribute_BAO_Contribution
::deleteContribution($contribId);
1149 * Build Membership Block in Contribution Pages.
1152 * Contact checked for having a current membership for a particular membership.
1153 * @param bool $isContributionMainPage
1154 * Is this the main page? If so add form input fields.
1155 * (or better yet don't have this functionality in a function shared with forms that don't share it).
1156 * @param int|array $selectedMembershipTypeID
1157 * Selected membership id.
1158 * @param bool $thankPage
1160 * @param null $isTest
1163 * Is this a separate membership payment
1165 * @throws \CiviCRM_API3_Exception
1166 * @throws \CRM_Core_Exception
1168 protected function buildMembershipBlock(
1170 $isContributionMainPage = FALSE,
1171 $selectedMembershipTypeID = NULL,
1176 $separateMembershipPayment = FALSE;
1177 if ($this->_membershipBlock
) {
1178 $this->_currentMemberships
= [];
1180 $membershipTypeIds = $membershipTypes = $radio = $radioOptAttrs = [];
1181 $membershipPriceset = (!empty($this->_priceSetId
) && $this->_useForMember
);
1183 $allowAutoRenewMembership = $autoRenewOption = FALSE;
1184 $autoRenewMembershipTypeOptions = [];
1186 $separateMembershipPayment = $this->_membershipBlock
['is_separate_payment'] ??
NULL;
1188 if ($membershipPriceset) {
1189 foreach ($this->_priceSet
['fields'] as $pField) {
1190 if (empty($pField['options'])) {
1193 foreach ($pField['options'] as $opId => $opValues) {
1194 if (empty($opValues['membership_type_id'])) {
1197 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
1201 elseif (!empty($this->_membershipBlock
['membership_types'])) {
1202 $membershipTypeIds = explode(',', $this->_membershipBlock
['membership_types']);
1205 if (!empty($membershipTypeIds)) {
1206 //set status message if wrong membershipType is included in membershipBlock
1207 if (isset($this->_mid
) && !$membershipPriceset) {
1208 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1210 'membership_type_id'
1212 if (!in_array($membershipTypeID, $membershipTypeIds)) {
1213 CRM_Core_Session
::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Invalid Membership'), 'error');
1217 $membershipTypeValues = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIds);
1218 $this->_membershipTypeValues
= $membershipTypeValues;
1221 // Check if we support auto-renew on this contribution page
1222 // FIXME: If any of the payment processors do NOT support recurring you cannot setup an
1223 // auto-renew payment even if that processor is not selected.
1224 $allowAutoRenewOpt = TRUE;
1225 if (is_array($this->_paymentProcessors
)) {
1226 foreach ($this->_paymentProcessors
as $id => $val) {
1227 if ($id && !$val['is_recur']) {
1228 $allowAutoRenewOpt = FALSE;
1232 foreach ($membershipTypeIds as $value) {
1233 $memType = $membershipTypeValues[$value];
1234 if ($selectedMembershipTypeID != NULL) {
1235 if ($memType['id'] == $selectedMembershipTypeID) {
1236 $this->assign('minimum_fee', $memType['minimum_fee'] ??
NULL);
1237 $this->assign('membership_name', $memType['name']);
1238 if (!$thankPage && $cid) {
1239 $membership = new CRM_Member_DAO_Membership();
1240 $membership->contact_id
= $cid;
1241 $membership->membership_type_id
= $memType['id'];
1242 if ($membership->find(TRUE)) {
1243 $this->assign('renewal_mode', TRUE);
1244 $memType['current_membership'] = $membership->end_date
;
1245 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
1248 $membershipTypes[] = $memType;
1251 elseif ($memType['is_active']) {
1253 if ($allowAutoRenewOpt) {
1254 $javascriptMethod = ['onclick' => "return showHideAutoRenew( this.value );"];
1255 $isAvailableAutoRenew = $this->_membershipBlock
['auto_renew'][$value] ??
1;
1256 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $memType['auto_renew'] * $isAvailableAutoRenew;
1257 $allowAutoRenewMembership = TRUE;
1260 $javascriptMethod = NULL;
1261 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = 0;
1264 //add membership type.
1265 $radio[$memType['id']] = NULL;
1266 $radioOptAttrs[$memType['id']] = $javascriptMethod;
1268 $membership = new CRM_Member_DAO_Membership();
1269 $membership->contact_id
= $cid;
1270 $membership->membership_type_id
= $memType['id'];
1272 //show current membership, skip pending and cancelled membership records,
1273 //because we take first membership record id for renewal
1274 $membership->whereAdd('status_id != 5 AND status_id !=6');
1276 if (!is_null($isTest)) {
1277 $membership->is_test
= $isTest;
1281 $membership->orderBy('end_date DESC');
1283 if ($membership->find(TRUE)) {
1284 if (!$membership->end_date
) {
1285 unset($radio[$memType['id']]);
1286 unset($radioOptAttrs[$memType['id']]);
1287 $this->assign('islifetime', TRUE);
1290 $this->assign('renewal_mode', TRUE);
1291 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
1292 $memType['current_membership'] = $membership->end_date
;
1294 $endDate = $memType['current_membership'];
1295 $this->_defaultMemTypeId
= $memType['id'];
1297 if ($memType['current_membership'] < $endDate) {
1298 $endDate = $memType['current_membership'];
1299 $this->_defaultMemTypeId
= $memType['id'];
1303 $membershipTypes[] = $memType;
1308 $this->assign('membershipBlock', $this->_membershipBlock
);
1309 $this->assign('showRadio', $isContributionMainPage);
1310 $this->assign('membershipTypes', $membershipTypes);
1311 $this->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
1312 $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
1313 //give preference to user submitted auto_renew value.
1314 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$this->isSubmitted());
1315 $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
1317 // Assign autorenew option (0:hide,1:optional,2:required) so we can use it in confirmation etc.
1318 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
);
1319 //$selectedMembershipTypeID is retrieved as an array for membership priceset if multiple
1320 //options for different organisation is selected on the contribution page.
1321 if (is_numeric($selectedMembershipTypeID) && isset($membershipTypeValues[$selectedMembershipTypeID]['auto_renew'])) {
1322 $this->assign('autoRenewOption', $membershipTypeValues[$selectedMembershipTypeID]['auto_renew']);
1325 $this->assign('autoRenewOption', $autoRenewOption);
1328 if ($isContributionMainPage) {
1329 if (!$membershipPriceset) {
1330 if (!$this->_membershipBlock
['is_required']) {
1331 $this->assign('showRadioNoThanks', TRUE);
1332 $radio['no_thanks'] = NULL;
1333 $this->addRadio('selectMembership', NULL, $radio, [], NULL, FALSE, $radioOptAttrs);
1335 elseif ($this->_membershipBlock
['is_required'] && count($radio) == 1) {
1336 $temp = array_keys($radio);
1337 $this->add('hidden', 'selectMembership', $temp[0], ['id' => 'selectMembership']);
1338 $this->assign('singleMembership', TRUE);
1339 $this->assign('showRadio', FALSE);
1342 foreach ($radioOptAttrs as $opt => $attrs) {
1343 $attrs['class'] = ' required';
1345 $this->addRadio('selectMembership', NULL, $radio, [], NULL, FALSE, $radioOptAttrs);
1348 $this->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
1351 if ((!$this->_values
['is_pay_later'] ||
is_array($this->_paymentProcessors
)) && ($allowAutoRenewMembership ||
$autoRenewOption)) {
1352 if ($autoRenewOption == 2) {
1353 $this->addElement('hidden', 'auto_renew', ts('Please renew my membership automatically.'));
1356 $this->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
1363 return $separateMembershipPayment;
1367 * Determine if recurring parameters need to be added to the form parameters.
1370 * - frequency_interval
1373 * For membership this is based on the membership type.
1375 * This needs to be done before processing the pre-approval redirect where relevant on the main page or before any payment processing.
1377 * Arguably the form should start to build $this->_params in the pre-process main page & use that array consistently throughout.
1379 protected function setRecurringMembershipParams() {
1380 $selectedMembershipTypeID = $this->_params
['selectMembership'] ??
NULL;
1381 if ($selectedMembershipTypeID) {
1382 // @todo the price_x fields will ALWAYS allow us to determine the membership - so we should ignore
1383 // 'selectMembership' and calculate from the price_x fields so we have one method that always works
1384 // this is lazy & only catches when selectMembership is set, but the worst of all worlds would be to fix
1385 // this with an else (calculate for price set).
1386 $membershipTypes = CRM_Price_BAO_PriceSet
::getMembershipTypesFromPriceSet($this->_priceSetId
);
1387 if (in_array($selectedMembershipTypeID, $membershipTypes['autorenew_required'])
1388 ||
(in_array($selectedMembershipTypeID, $membershipTypes['autorenew_optional']) &&
1389 !empty($this->_params
['is_recur']))
1391 $this->_params
['auto_renew'] = TRUE;
1394 if ((!empty($this->_params
['selectMembership']) ||
!empty($this->_params
['priceSetId']))
1395 && !empty($this->_paymentProcessor
['is_recur']) &&
1396 !empty($this->_params
['auto_renew'])
1397 && empty($this->_params
['is_recur']) && empty($this->_params
['frequency_interval'])
1400 $this->_params
['is_recur'] = $this->_values
['is_recur'] = 1;
1401 // check if price set is not quick config
1402 if (!empty($this->_params
['priceSetId']) && !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config')) {
1403 list($this->_params
['frequency_interval'], $this->_params
['frequency_unit']) = CRM_Price_BAO_PriceSet
::getRecurDetails($this->_params
['priceSetId']);
1406 // FIXME: set interval and unit based on selected membership type
1407 $this->_params
['frequency_interval'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1408 $this->_params
['selectMembership'], 'duration_interval'
1410 $this->_params
['frequency_unit'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1411 $this->_params
['selectMembership'], 'duration_unit'
1418 * Get the payment processor object for the submission, returning the manual one for offline payments.
1420 * @return CRM_Core_Payment
1422 protected function getPaymentProcessorObject() {
1423 if (!empty($this->_paymentProcessor
)) {
1424 return $this->_paymentProcessor
['object'];
1426 return new CRM_Core_Payment_Manual();
1430 * Get the amount for the main contribution.
1432 * The goal is to expand this function so that all the argy-bargy of figuring out the amount
1433 * winds up here as the main spaghetti shrinks.
1435 * If there is a separate membership contribution this is the 'other one'. Otherwise there
1442 * @throws \CiviCRM_API3_Exception
1444 protected function getMainContributionAmount($params) {
1445 if (!empty($params['selectMembership'])) {
1446 if (empty($params['amount']) && !$this->_separateMembershipPayment
) {
1447 return CRM_Member_BAO_MembershipType
::getMembershipType($params['selectMembership'])['minimum_fee'] ??
0;
1450 return $params['amount'] ??
0;
1454 * Wrapper for processAmount that also sets autorenew.
1457 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
1458 * And, it would make sense to introduce caching into that function and call it from here rather than
1459 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
1460 * @param array $params
1461 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
1463 * Line item array to be altered.
1464 * @param int $priceSetID
1466 public function processAmountAndGetAutoRenew($fields, &$params, &$lineItems, $priceSetID = NULL) {
1467 CRM_Price_BAO_PriceSet
::processAmount($fields, $params, $lineItems, $priceSetID);
1469 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
1470 foreach ($lineItems as $lineItem) {
1471 if (!empty($lineItem['auto_renew']) &&
1472 is_numeric($lineItem['auto_renew'])
1474 $autoRenew[$lineItem['auto_renew']] +
= $lineItem['line_total'];
1477 if (count($autoRenew) > 1) {
1478 $params['autoRenew'] = $autoRenew;