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
157 * Contribution mode e.g express for payment express, notify for off-site + notification back to CiviCRM
160 public $_contributeMode;
163 * Contribution page supports memberships
166 public $_useForMember;
172 public $_isBillingAddressRequiredForPayLater;
175 * Flag if email field exists in embedded profile
179 public $_emailExists = FALSE;
182 * Is this a backoffice form
183 * (this will affect whether paypal express code is displayed)
186 public $isBackOffice = FALSE;
189 * Payment instrument if for the transaction.
191 * This will generally be drawn from the payment processor and is ignored for
196 public $paymentInstrumentID;
199 * Is the price set quick config.
202 public function isQuickConfig() {
203 return isset(self
::$_quickConfig) ? self
::$_quickConfig : FALSE;
207 * Set variables up before form is built.
209 * @throws \CRM_Contribute_Exception_InactiveContributionPageException
212 public function preProcess() {
214 // current contribution page id
215 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
216 $this->_ccid
= CRM_Utils_Request
::retrieve('ccid', 'Positive', $this);
218 // seems like the session is corrupted and/or we lost the id trail
219 // lets just bump this to a regular session error and redirect user to main page
220 $this->controller
->invalidKeyRedirect();
222 $this->_emailExists
= $this->get('emailExists');
224 // this was used prior to the cleverer this_>getContactID - unsure now
225 $this->_userID
= CRM_Core_Session
::singleton()->getLoggedInContactID();
227 $this->_contactID
= $this->_membershipContactID
= $this->getContactID();
229 if ($this->_contactID
) {
230 $this->_mid
= CRM_Utils_Request
::retrieve('mid', 'Positive', $this);
232 $membership = new CRM_Member_DAO_Membership();
233 $membership->id
= $this->_mid
;
235 if ($membership->find(TRUE)) {
236 $this->_defaultMemTypeId
= $membership->membership_type_id
;
237 if ($membership->contact_id
!= $this->_contactID
) {
238 $validMembership = FALSE;
239 $organizations = CRM_Contact_BAO_Relationship
::getPermissionedContacts($this->_userID
, NULL, NULL, 'Organization');
240 if (!empty($organizations) && array_key_exists($membership->contact_id
, $organizations)) {
241 $this->_membershipContactID
= $membership->contact_id
;
242 $this->assign('membershipContactID', $this->_membershipContactID
);
243 $this->assign('membershipContactName', $organizations[$this->_membershipContactID
]['name']);
244 $validMembership = TRUE;
247 $membershipType = new CRM_Member_BAO_MembershipType();
248 $membershipType->id
= $membership->membership_type_id
;
249 if ($membershipType->find(TRUE)) {
250 // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values.
251 // Convert to comma separated list.
252 $inheritedRelTypes = implode(CRM_Utils_Array
::explodePadded($membershipType->relationship_type_id
), ',');
253 $permContacts = CRM_Contact_BAO_Relationship
::getPermissionedContacts($this->_userID
, $membershipType->relationship_type_id
);
254 if (array_key_exists($membership->contact_id
, $permContacts)) {
255 $this->_membershipContactID
= $membership->contact_id
;
256 $validMembership = TRUE;
260 if (!$validMembership) {
261 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');
266 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');
272 // we do not want to display recently viewed items, so turn off
273 $this->assign('displayRecent', FALSE);
276 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
277 $this->assign('action', $this->_action
);
280 $this->_mode
= ($this->_action
== 1024) ?
'test' : 'live';
282 $this->_values
= $this->get('values');
283 $this->_fields
= $this->get('fields');
284 $this->_bltID
= $this->get('bltID');
285 $this->_paymentProcessor
= $this->get('paymentProcessor');
287 $this->_priceSetId
= $this->get('priceSetId');
288 $this->_priceSet
= $this->get('priceSet');
290 if (!$this->_values
) {
291 // get all the values from the dao object
295 CRM_Contribute_BAO_ContributionPage
::setValues($this->_id
, $this->_values
);
296 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
297 && !CRM_Core_Permission
::check('add contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']))
299 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
301 if (empty($this->_values
['is_active'])) {
302 throw new CRM_Contribute_Exception_InactiveContributionPageException(ts('The page you requested is currently unavailable.'), $this->_id
);
305 $endDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('end_date', $this->_values
));
306 $now = date('YmdHis');
307 if ($endDate && $endDate < $now) {
308 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
);
311 $startDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('start_date', $this->_values
));
312 if ($startDate && $startDate > $now) {
313 throw new CRM_Contribute_Exception_FutureContributionPageException(ts('The page you requested will be active from %1', [1 => CRM_Utils_Date
::customFormat($startDate)]), $this->_id
);
316 $this->assignBillingType();
318 // check for is_monetary status
319 $isMonetary = CRM_Utils_Array
::value('is_monetary', $this->_values
);
320 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $this->_values
);
321 if (!empty($this->_ccid
)) {
322 $this->_values
['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
328 $this->_values
['is_pay_later'] = FALSE;
332 $this->setPayLaterLabel($this->_values
['pay_later_text']);
336 $this->_paymentProcessorIDs
= array_filter(explode(
337 CRM_Core_DAO
::VALUE_SEPARATOR
,
338 CRM_Utils_Array
::value('payment_processor', $this->_values
)
341 $this->assignPaymentProcessor($isPayLater);
346 $priceSetId = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $this->_id
);
347 CRM_Price_BAO_PriceSet
::initSet($this, 'civicrm_contribution_page', FALSE, $priceSetId);
349 // this avoids getting E_NOTICE errors in php
351 'amount_block_is_active',
352 'is_allow_other_amount',
355 foreach ($setNullFields as $f) {
356 if (!isset($this->_values
[$f])) {
357 $this->_values
[$f] = NULL;
361 //check if Membership Block is enabled, if Membership Fields are included in profile
362 //get membership section for this contribution page
363 $this->_membershipBlock
= CRM_Member_BAO_Membership
::getMembershipBlock($this->_id
);
364 $this->set('membershipBlock', $this->_membershipBlock
);
366 if (!empty($this->_values
['custom_pre_id'])) {
367 $preProfileType = CRM_Core_BAO_UFField
::getProfileType($this->_values
['custom_pre_id']);
370 if (!empty($this->_values
['custom_post_id'])) {
371 $postProfileType = CRM_Core_BAO_UFField
::getProfileType($this->_values
['custom_post_id']);
374 if (((isset($postProfileType) && $postProfileType == 'Membership') ||
375 (isset($preProfileType) && $preProfileType == 'Membership')
377 !$this->_membershipBlock
['is_active']
379 CRM_Core_Error
::fatal(ts('This page includes a Profile with Membership fields - but the Membership Block is NOT enabled. Please notify the site administrator.'));
382 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($this->_id
);
385 $this->_values
['pledge_block_id'] = CRM_Utils_Array
::value('id', $pledgeBlock);
386 $this->_values
['max_reminders'] = CRM_Utils_Array
::value('max_reminders', $pledgeBlock);
387 $this->_values
['initial_reminder_day'] = CRM_Utils_Array
::value('initial_reminder_day', $pledgeBlock);
388 $this->_values
['additional_reminder_day'] = CRM_Utils_Array
::value('additional_reminder_day', $pledgeBlock);
390 //set pledge id in values
391 $pledgeId = CRM_Utils_Request
::retrieve('pledgeId', 'Positive', $this);
393 //authenticate pledge user for pledge payment.
395 $this->_values
['pledge_id'] = $pledgeId;
397 //lets override w/ pledge campaign.
398 $this->_values
['campaign_id'] = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
402 self
::authenticatePledgeUser();
405 $this->set('values', $this->_values
);
406 $this->set('fields', $this->_fields
);
410 $pcpId = CRM_Utils_Request
::retrieve('pcpId', 'Positive', $this);
412 $pcp = CRM_PCP_BAO_PCP
::handlePcp($pcpId, 'contribute', $this->_values
);
413 $this->_pcpId
= $pcp['pcpId'];
414 $this->_pcpBlock
= $pcp['pcpBlock'];
415 $this->_pcpInfo
= $pcp['pcpInfo'];
418 // Link (button) for users to create their own Personal Campaign page
419 if ($linkText = CRM_PCP_BAO_PCP
::getPcpBlockStatus($this->_id
, 'contribute')) {
420 $linkTextUrl = CRM_Utils_System
::url('civicrm/contribute/campaign',
421 "action=add&reset=1&pageId={$this->_id}&component=contribute",
424 $this->assign('linkTextUrl', $linkTextUrl);
425 $this->assign('linkText', $linkText);
428 //set pledge block if block id is set
429 if (!empty($this->_values
['pledge_block_id'])) {
430 $this->assign('pledgeBlock', TRUE);
433 // check if one of the (amount , membership) blocks is active or not.
434 $this->_membershipBlock
= $this->get('membershipBlock');
436 if (!$this->_values
['amount_block_is_active'] &&
437 !$this->_membershipBlock
['is_active'] &&
440 CRM_Core_Error
::fatal(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.'));
443 if ($this->_values
['amount_block_is_active']) {
444 $this->set('amount_block_is_active', $this->_values
['amount_block_is_active']);
447 $this->_contributeMode
= $this->get('contributeMode');
448 $this->assign('contributeMode', $this->_contributeMode
);
450 //assigning is_monetary and is_email_receipt to template
451 $this->assign('is_monetary', $this->_values
['is_monetary']);
452 $this->assign('is_email_receipt', $this->_values
['is_email_receipt']);
453 $this->assign('bltID', $this->_bltID
);
455 //assign cancelSubscription URL to templates
456 $this->assign('cancelSubscriptionUrl',
457 CRM_Utils_Array
::value('cancelSubscriptionUrl', $this->_values
)
460 $title = !empty($this->_values
['frontend_title']) ?
$this->_values
['frontend_title'] : $this->_values
['title'];
462 $this->setTitle(($this->_pcpId ?
$this->_pcpInfo
['title'] : $title));
463 $this->_defaults
= [];
465 $this->_amount
= $this->get('amount');
466 // Assigning this to the template means it will be passed through to the payment form.
467 // This can, for example, by used by payment processors using client side encryption
468 $this->assign('currency', $this->getCurrency());
470 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($this->_values
);
472 //lets allow user to override campaign.
473 $campID = CRM_Utils_Request
::retrieve('campID', 'Positive', $this);
474 if ($campID && CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
475 $this->_values
['campaign_id'] = $campID;
478 //do check for cancel recurring and clean db, CRM-7696
479 if (CRM_Utils_Request
::retrieve('cancel', 'Boolean')) {
480 self
::cancelRecurring();
483 // check if billing block is required for pay later
484 if (CRM_Utils_Array
::value('is_pay_later', $this->_values
)) {
485 $this->_isBillingAddressRequiredForPayLater
= CRM_Utils_Array
::value('is_billing_required', $this->_values
);
486 $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater
);
491 * Set the default values.
493 public function setDefaultValues() {
494 return $this->_defaults
;
498 * Assign the minimal set of variables to the template.
500 public function assignToTemplate() {
501 $this->set('name', $this->assignBillingName($this->_params
));
503 $this->assign('paymentProcessor', $this->_paymentProcessor
);
512 $config = CRM_Core_Config
::singleton();
513 if (isset($this->_values
['is_recur']) && !empty($this->_paymentProcessor
['is_recur'])) {
514 $this->assign('is_recur_enabled', 1);
515 $vars = array_merge($vars, [
517 'frequency_interval',
523 if (in_array('CiviPledge', $config->enableComponents
) &&
524 CRM_Utils_Array
::value('is_pledge', $this->_params
) == 1
526 $this->assign('pledge_enabled', 1);
528 $vars = array_merge($vars, [
530 'pledge_frequency_interval',
531 'pledge_frequency_unit',
532 'pledge_installments',
536 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
537 // function to get correct amount level consistently. Remove setting of the amount level in
538 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
539 // to cover all variants.
540 if (isset($this->_params
['amount_other']) ||
isset($this->_params
['selectMembership'])) {
541 $this->_params
['amount_level'] = '';
544 foreach ($vars as $v) {
545 if (isset($this->_params
[$v])) {
546 if ($v == "amount" && $this->_params
[$v] === 0) {
547 $this->_params
[$v] = CRM_Utils_Money
::format($this->_params
[$v], NULL, NULL, TRUE);
549 $this->assign($v, $this->_params
[$v]);
553 $this->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
558 if (!empty($this->_params
['onbehalf_profile_id']) && !empty($this->_params
['onbehalf'])) {
559 $this->assign('onBehalfName', $this->_params
['organization_name']);
560 $locTypeId = array_keys($this->_params
['onbehalf_location']['email']);
561 $this->assign('onBehalfEmail', $this->_params
['onbehalf_location']['email'][$locTypeId[0]]['email']);
563 $this->assignPaymentFields();
565 $this->assign('email',
566 $this->controller
->exportValue('Main', "email-{$this->_bltID}")
569 // also assign the receipt_text
570 if (isset($this->_values
['receipt_text'])) {
571 $this->assign('receipt_text', $this->_values
['receipt_text']);
576 * Add the custom fields.
579 * @param string $name
580 * @param bool $viewOnly
581 * @param null $profileContactType
582 * @param array $fieldTypes
584 public function buildCustom($id, $name, $viewOnly = FALSE, $profileContactType = NULL, $fieldTypes = NULL) {
586 $contactID = $this->getContactID();
588 // we don't allow conflicting fields to be
589 // configured via profile - CRM 2100
596 'non_deductible_amount' => 1,
599 'contribution_status_id' => 1,
600 // @todo replace payment_instrument with payment instrument id.
601 // both are available now but the id field is the most consistent.
602 'payment_instrument' => 1,
603 'payment_instrument_id' => 1,
604 'contribution_check_number' => 1,
605 'financial_type' => 1,
608 $fields = CRM_Core_BAO_UFGroup
::getFields($id, FALSE, CRM_Core_Action
::ADD
, NULL, NULL, FALSE,
609 NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, NULL
613 // determine if email exists in profile so we know if we need to manually insert CRM-2888, CRM-15067
614 foreach ($fields as $key => $field) {
615 if (substr($key, 0, 6) == 'email-' &&
616 !in_array($profileContactType, ['honor', 'onbehalf'])
618 $this->_emailExists
= TRUE;
619 $this->set('emailExists', TRUE);
623 if (array_intersect_key($fields, $fieldsToIgnore)) {
624 $fields = array_diff_key($fields, $fieldsToIgnore);
625 CRM_Core_Session
::setStatus(ts('Some of the profile fields cannot be configured for this page.'), ts('Warning'), 'alert');
628 //remove common fields only if profile is not configured for onbehalf/honor
629 if (!in_array($profileContactType, ['honor', 'onbehalf'])) {
630 $fields = array_diff_key($fields, $this->_fields
);
633 CRM_Core_BAO_Address
::checkContactSharedAddressFields($fields, $contactID);
635 // fetch file preview when not submitted yet, like in online contribution Confirm and ThankYou page
636 $viewOnlyFileValues = empty($profileContactType) ?
[] : [$profileContactType => []];
637 foreach ($fields as $key => $field) {
639 isset($field['data_type']) &&
640 $field['data_type'] == 'File' ||
($viewOnly && $field['name'] == 'image_URL')
642 //retrieve file value from submitted values on basis of $profileContactType
643 $fileValue = CRM_Utils_Array
::value($key, $this->_params
);
644 if (!empty($profileContactType) && !empty($this->_params
[$profileContactType])) {
645 $fileValue = CRM_Utils_Array
::value($key, $this->_params
[$profileContactType]);
649 $path = CRM_Utils_Array
::value('name', $fileValue);
650 $fileType = CRM_Utils_Array
::value('type', $fileValue);
651 $fileValue = CRM_Utils_File
::getFileURL($path, $fileType);
654 // format custom file value fetched from submitted value
655 if ($profileContactType) {
656 $viewOnlyFileValues[$profileContactType][$key] = $fileValue;
659 $viewOnlyFileValues[$key] = $fileValue;
662 // On viewOnly use-case (as in online contribution Confirm page) we no longer need to set
663 // required property because being required file is already uploaded while registration
664 $field['is_required'] = FALSE;
666 if ($profileContactType) {
667 //Since we are showing honoree name separately so we are removing it from honoree profile just for display
668 if ($profileContactType == 'honor') {
669 $honoreeNamefields = [
677 if (in_array($field['name'], $honoreeNamefields)) {
678 unset($fields[$field['name']]);
682 if (!empty($fieldTypes) && in_array($field['field_type'], $fieldTypes)) {
683 CRM_Core_BAO_UFGroup
::buildProfile(
686 CRM_Profile_Form
::MODE_CREATE
,
691 $this->_fields
[$profileContactType][$key] = $field;
694 unset($fields[$key]);
698 CRM_Core_BAO_UFGroup
::buildProfile(
701 CRM_Profile_Form
::MODE_CREATE
,
705 $this->_fields
[$key] = $field;
707 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
708 if ($field['add_captcha'] && !$this->_userID
) {
713 $this->assign($name, $fields);
715 if ($profileContactType && count($viewOnlyFileValues[$profileContactType])) {
716 $this->assign('viewOnlyPrefixFileValues', $viewOnlyFileValues);
718 elseif (count($viewOnlyFileValues)) {
719 $this->assign('viewOnlyFileValues', $viewOnlyFileValues);
722 if ($addCaptcha && !$viewOnly) {
723 $this->enableCaptchaOnForm();
730 * Enable ReCAPTCHA on Contribution form
732 protected function enableCaptchaOnForm() {
733 CRM_Utils_ReCAPTCHA
::enableCaptchaOnForm($this);
736 public function assignPaymentFields() {
739 if ($this->_amount
> 0.0) {
742 elseif (!empty($this->_params
['selectMembership'])) {
743 $memFee = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params
['selectMembership'], 'minimum_fee');
749 // The concept of contributeMode is deprecated.
750 // The payment processor object can provide info about the fields it shows.
751 if ($isMonetary && is_a($this->_paymentProcessor
['object'], 'CRM_Core_Payment')) {
752 /** @var $paymentProcessorObject \CRM_Core_Payment */
753 $paymentProcessorObject = $this->_paymentProcessor
['object'];
755 $paymentFields = $paymentProcessorObject->getPaymentFormFields();
756 foreach ($paymentFields as $index => $paymentField) {
757 if (!isset($this->_params
[$paymentField])) {
758 unset($paymentFields[$index]);
761 if ($paymentField === 'credit_card_exp_date') {
762 $date = CRM_Utils_Date
::format(CRM_Utils_Array
::value('credit_card_exp_date', $this->_params
));
763 $date = CRM_Utils_Date
::mysqlToIso($date);
764 $this->assign('credit_card_exp_date', $date);
766 elseif ($paymentField === 'credit_card_number') {
767 $this->assign('credit_card_number',
768 CRM_Utils_System
::mungeCreditCard(CRM_Utils_Array
::value('credit_card_number', $this->_params
))
771 elseif ($paymentField === 'credit_card_type') {
772 $this->assign('credit_card_type', CRM_Core_PseudoConstant
::getLabel(
773 'CRM_Core_BAO_FinancialTrxn',
775 CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $this->_params
['credit_card_type'])
779 $this->assign($paymentField, $this->_params
[$paymentField]);
782 $this->assign('paymentFieldsetLabel', CRM_Core_Payment_Form
::getPaymentLabel($paymentProcessorObject));
783 $this->assign('paymentFields', $paymentFields);
789 * Display ReCAPTCHA warning on Contribution form
791 protected function displayCaptchaWarning() {
792 if (CRM_Core_Permission
::check("administer CiviCRM")) {
793 if (!CRM_Utils_ReCAPTCHA
::hasSettingsAvailable()) {
794 $this->assign('displayCaptchaWarning', TRUE);
800 * Check if ReCAPTCHA has to be added on Contribution form forcefully.
802 protected function hasToAddForcefully() {
803 return CRM_Utils_ReCAPTCHA
::hasToAddForcefully();
807 * Add onbehalf/honoree profile fields and native module fields.
810 * @param CRM_Core_Form $form
812 public function buildComponentForm($id, $form) {
817 $contactID = $this->getContactID();
819 foreach (['soft_credit', 'on_behalf'] as $module) {
820 if ($module == 'soft_credit') {
821 if (empty($form->_values
['honoree_profile_id'])) {
825 if (!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values
['honoree_profile_id'], 'is_active')) {
826 CRM_Core_Error
::fatal(ts('This contribution page has been configured for contribution on behalf of honoree and the selected honoree profile is either disabled or not found.'));
829 $profileContactType = CRM_Core_BAO_UFGroup
::getContactType($form->_values
['honoree_profile_id']);
830 $requiredProfileFields = [
831 'Individual' => ['first_name', 'last_name'],
832 'Organization' => ['organization_name', 'email'],
833 'Household' => ['household_name', 'email'],
835 $validProfile = CRM_Core_BAO_UFGroup
::checkValidProfile($form->_values
['honoree_profile_id'], $requiredProfileFields[$profileContactType]);
836 if (!$validProfile) {
837 CRM_Core_Error
::fatal(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.'));
840 foreach (['honor_block_title', 'honor_block_text'] as $name) {
841 $form->assign($name, $form->_values
[$name]);
844 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
846 // radio button for Honor Type
847 foreach ($form->_values
['soft_credit_types'] as $value) {
848 $honorTypes[$value] = $form->createElement('radio', NULL, NULL, $softCreditTypes[$value], $value);
850 $form->addGroup($honorTypes, 'soft_credit_type_id', NULL)->setAttribute('allowClear', TRUE);
852 $honoreeProfileFields = CRM_Core_BAO_UFGroup
::getFields(
853 $this->_values
['honoree_profile_id'], FALSE,
857 NULL, CRM_Core_Permission
::CREATE
859 $form->assign('honoreeProfileFields', $honoreeProfileFields);
861 // add the form elements
862 foreach ($honoreeProfileFields as $name => $field) {
863 // If soft credit type is not chosen then make omit requiredness from honoree profile fields
864 if (count($form->_submitValues
) &&
865 empty($form->_submitValues
['soft_credit_type_id']) &&
866 !empty($field['is_required'])
868 $field['is_required'] = FALSE;
870 CRM_Core_BAO_UFGroup
::buildProfile($form, $field, CRM_Profile_Form
::MODE_CREATE
, NULL, FALSE, FALSE, NULL, 'honor');
874 if (empty($form->_values
['onbehalf_profile_id'])) {
878 if (!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values
['onbehalf_profile_id'], 'is_active')) {
879 CRM_Core_Error
::fatal(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.'));
882 $member = CRM_Member_BAO_Membership
::getMembershipBlock($form->_id
);
883 if (empty($member['is_active'])) {
884 $msg = ts('Mixed profile not allowed for on behalf of registration/sign up.');
885 $onBehalfProfile = CRM_Core_BAO_UFGroup
::profileGroups($form->_values
['onbehalf_profile_id']);
893 if (in_array($contactType, $onBehalfProfile) &&
894 (in_array('Membership', $onBehalfProfile) ||
895 in_array('Contribution', $onBehalfProfile)
898 CRM_Core_Error
::fatal($msg);
904 // retrieve all permissioned organizations of contact $contactID
905 $organizations = CRM_Contact_BAO_Relationship
::getPermissionedContacts($contactID, NULL, NULL, 'Organization');
907 if (count($organizations)) {
908 // Related org url - pass checksum if needed
910 'ufId' => $form->_values
['onbehalf_profile_id'],
913 if (!empty($_GET['cs'])) {
915 'ufId' => $form->_values
['onbehalf_profile_id'],
916 'uid' => $this->_contactID
,
921 $locDataURL = CRM_Utils_System
::url('civicrm/ajax/permlocation', $args, FALSE, NULL, FALSE);
922 $form->assign('locDataURL', $locDataURL);
924 if (count($organizations) > 0) {
925 $form->add('select', 'onbehalfof_id', '', CRM_Utils_Array
::collect('name', $organizations));
928 0 => ts('Select an existing organization'),
929 1 => ts('Enter a new organization'),
931 $form->addRadio('org_option', ts('options'), $orgOptions);
932 $form->setDefaults(['org_option' => 0]);
936 $form->assign('fieldSetTitle', CRM_Core_BAO_UFGroup
::getTitle($form->_values
['onbehalf_profile_id']));
938 if (CRM_Utils_Array
::value('is_for_organization', $form->_values
)) {
939 if ($form->_values
['is_for_organization'] == 2) {
940 $form->assign('onBehalfRequired', TRUE);
943 $form->addElement('checkbox', 'is_for_organization',
944 $form->_values
['for_organization'],
950 $profileFields = CRM_Core_BAO_UFGroup
::getFields(
951 $form->_values
['onbehalf_profile_id'],
952 FALSE, CRM_Core_Action
::VIEW
, NULL,
953 NULL, FALSE, NULL, FALSE, NULL,
954 CRM_Core_Permission
::CREATE
, NULL
957 $form->assign('onBehalfOfFields', $profileFields);
958 if (!empty($form->_submitValues
['onbehalf'])) {
959 if (!empty($form->_submitValues
['onbehalfof_id'])) {
960 $form->assign('submittedOnBehalf', $form->_submitValues
['onbehalfof_id']);
962 $form->assign('submittedOnBehalfInfo', json_encode(str_replace('"', '\"', $form->_submitValues
['onbehalf']), JSON_HEX_APOS
));
965 $fieldTypes = ['Contact', 'Organization'];
966 if (!empty($form->_membershipBlock
)) {
967 $fieldTypes = array_merge($fieldTypes, ['Membership']);
969 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
970 $fieldTypes = array_merge($fieldTypes, $contactSubType);
972 foreach ($profileFields as $name => $field) {
973 if (in_array($field['field_type'], $fieldTypes)) {
974 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
975 if (in_array($prefixName, ['organization_name', 'email']) && empty($field['is_required'])) {
976 $field['is_required'] = 1;
978 if (count($form->_submitValues
) &&
979 empty($form->_submitValues
['is_for_organization']) &&
980 $form->_values
['is_for_organization'] == 1 &&
981 !empty($field['is_required'])
983 $field['is_required'] = FALSE;
985 CRM_Core_BAO_UFGroup
::buildProfile($form, $field, NULL, NULL, FALSE, 'onbehalf', NULL, 'onbehalf');
994 * Check template file exists.
996 * @param string $suffix
998 * @return null|string
1000 public function checkTemplateFileExists($suffix = NULL) {
1002 $templateFile = "CRM/Contribute/Form/Contribution/{$this->_id}/{$this->_name}.{$suffix}tpl";
1003 $template = CRM_Core_Form
::getTemplate();
1004 if ($template->template_exists($templateFile)) {
1005 return $templateFile;
1012 * Use the form name to create the tpl file name.
1016 public function getTemplateFileName() {
1017 $fileName = $this->checkTemplateFileExists();
1018 return $fileName ?
$fileName : parent
::getTemplateFileName();
1022 * Add the extra.tpl in.
1024 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1025 * i.e. we do not override - why isn't this done at the CRM_Core_Form level?
1029 public function overrideExtraTemplateFileName() {
1030 $fileName = $this->checkTemplateFileExists('extra.');
1031 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();
1035 * Authenticate pledge user during online payment.
1037 public function authenticatePledgeUser() {
1038 //get the userChecksum and contact id
1039 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
1040 $contactID = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
1042 //get pledge status and contact id
1044 $pledgeParams = ['id' => $this->_values
['pledge_id']];
1045 $returnProperties = ['contact_id', 'status_id'];
1046 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_DAO_Pledge', $pledgeParams, $pledgeValues, $returnProperties);
1049 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1051 array_search('Pending', $allStatus),
1052 array_search('In Progress', $allStatus),
1053 array_search('Overdue', $allStatus),
1057 if ($this->_userID
&&
1058 $this->_userID
== $pledgeValues['contact_id']
1060 //check for authenticated user.
1063 elseif ($userChecksum && $pledgeValues['contact_id']) {
1064 //check for anonymous user.
1065 $validUser = CRM_Contact_BAO_Contact_Utils
::validChecksum($pledgeValues['contact_id'], $userChecksum);
1067 //make sure cid is same as pledge contact id
1068 if ($validUser && ($pledgeValues['contact_id'] != $contactID)) {
1074 CRM_Core_Error
::fatal(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."));
1077 //check for valid pledge status.
1078 if (!in_array($pledgeValues['status_id'], $validStatus)) {
1079 CRM_Core_Error
::fatal(ts('Oops. You cannot make a payment for this pledge - pledge status is %1.', [1 => CRM_Utils_Array
::value($pledgeValues['status_id'], $allStatus)]));
1084 * Cancel recurring contributions.
1086 * In case user cancel recurring contribution,
1087 * When we get the control back from payment gate way
1088 * lets delete the recurring and related contribution.
1090 public function cancelRecurring() {
1091 $isCancel = CRM_Utils_Request
::retrieve('cancel', 'Boolean');
1093 $isRecur = CRM_Utils_Request
::retrieve('isRecur', 'Boolean');
1094 $recurId = CRM_Utils_Request
::retrieve('recurId', 'Positive');
1095 //clean db for recurring contribution.
1096 if ($isRecur && $recurId) {
1097 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($recurId);
1099 $contribId = CRM_Utils_Request
::retrieve('contribId', 'Positive');
1101 CRM_Contribute_BAO_Contribution
::deleteContribution($contribId);
1107 * Build Membership Block in Contribution Pages.
1110 * Contact checked for having a current membership for a particular membership.
1111 * @param bool $isContributionMainPage
1112 * Is this the main page? If so add form input fields.
1113 * (or better yet don't have this functionality in a function shared with forms that don't share it).
1114 * @param int|array $selectedMembershipTypeID
1115 * Selected membership id.
1116 * @param bool $thankPage
1118 * @param null $isTest
1121 * Is this a separate membership payment
1123 protected function buildMembershipBlock(
1125 $isContributionMainPage = FALSE,
1126 $selectedMembershipTypeID = NULL,
1131 $separateMembershipPayment = FALSE;
1132 if ($this->_membershipBlock
) {
1133 $this->_currentMemberships
= [];
1135 $membershipTypeIds = $membershipTypes = $radio = [];
1136 $membershipPriceset = (!empty($this->_priceSetId
) && $this->_useForMember
) ?
TRUE : FALSE;
1138 $allowAutoRenewMembership = $autoRenewOption = FALSE;
1139 $autoRenewMembershipTypeOptions = [];
1141 $separateMembershipPayment = CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
);
1143 if ($membershipPriceset) {
1144 foreach ($this->_priceSet
['fields'] as $pField) {
1145 if (empty($pField['options'])) {
1148 foreach ($pField['options'] as $opId => $opValues) {
1149 if (empty($opValues['membership_type_id'])) {
1152 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
1156 elseif (!empty($this->_membershipBlock
['membership_types'])) {
1157 $membershipTypeIds = explode(',', $this->_membershipBlock
['membership_types']);
1160 if (!empty($membershipTypeIds)) {
1161 //set status message if wrong membershipType is included in membershipBlock
1162 if (isset($this->_mid
) && !$membershipPriceset) {
1163 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1165 'membership_type_id'
1167 if (!in_array($membershipTypeID, $membershipTypeIds)) {
1168 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');
1172 $membershipTypeValues = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIds);
1173 $this->_membershipTypeValues
= $membershipTypeValues;
1176 // Check if we support auto-renew on this contribution page
1177 // FIXME: If any of the payment processors do NOT support recurring you cannot setup an
1178 // auto-renew payment even if that processor is not selected.
1179 $allowAutoRenewOpt = TRUE;
1180 if (is_array($this->_paymentProcessors
)) {
1181 foreach ($this->_paymentProcessors
as $id => $val) {
1182 if ($id && !$val['is_recur']) {
1183 $allowAutoRenewOpt = FALSE;
1187 foreach ($membershipTypeIds as $value) {
1188 $memType = $membershipTypeValues[$value];
1189 if ($selectedMembershipTypeID != NULL) {
1190 if ($memType['id'] == $selectedMembershipTypeID) {
1191 $this->assign('minimum_fee',
1192 CRM_Utils_Array
::value('minimum_fee', $memType)
1194 $this->assign('membership_name', $memType['name']);
1195 if (!$thankPage && $cid) {
1196 $membership = new CRM_Member_DAO_Membership();
1197 $membership->contact_id
= $cid;
1198 $membership->membership_type_id
= $memType['id'];
1199 if ($membership->find(TRUE)) {
1200 $this->assign('renewal_mode', TRUE);
1201 $memType['current_membership'] = $membership->end_date
;
1202 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
1205 $membershipTypes[] = $memType;
1208 elseif ($memType['is_active']) {
1210 if ($allowAutoRenewOpt) {
1211 $javascriptMethod = ['onclick' => "return showHideAutoRenew( this.value );"];
1212 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $memType['auto_renew'] * CRM_Utils_Array
::value($value, CRM_Utils_Array
::value('auto_renew', $this->_membershipBlock
));
1213 $allowAutoRenewMembership = TRUE;
1216 $javascriptMethod = NULL;
1217 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = 0;
1220 //add membership type.
1221 $radio[$memType['id']] = $this->createElement('radio', NULL, NULL, NULL,
1222 $memType['id'], $javascriptMethod
1225 $membership = new CRM_Member_DAO_Membership();
1226 $membership->contact_id
= $cid;
1227 $membership->membership_type_id
= $memType['id'];
1229 //show current membership, skip pending and cancelled membership records,
1230 //because we take first membership record id for renewal
1231 $membership->whereAdd('status_id != 5 AND status_id !=6');
1233 if (!is_null($isTest)) {
1234 $membership->is_test
= $isTest;
1238 $membership->orderBy('end_date DESC');
1240 if ($membership->find(TRUE)) {
1241 if (!$membership->end_date
) {
1242 unset($radio[$memType['id']]);
1243 $this->assign('islifetime', TRUE);
1246 $this->assign('renewal_mode', TRUE);
1247 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
1248 $memType['current_membership'] = $membership->end_date
;
1250 $endDate = $memType['current_membership'];
1251 $this->_defaultMemTypeId
= $memType['id'];
1253 if ($memType['current_membership'] < $endDate) {
1254 $endDate = $memType['current_membership'];
1255 $this->_defaultMemTypeId
= $memType['id'];
1259 $membershipTypes[] = $memType;
1264 $this->assign('membershipBlock', $this->_membershipBlock
);
1265 $this->assign('showRadio', $isContributionMainPage);
1266 $this->assign('membershipTypes', $membershipTypes);
1267 $this->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
1268 $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
1269 //give preference to user submitted auto_renew value.
1270 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$this->isSubmitted()) ?
TRUE : FALSE;
1271 $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
1273 // Assign autorenew option (0:hide,1:optional,2:required) so we can use it in confirmation etc.
1274 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
);
1275 //$selectedMembershipTypeID is retrieved as an array for membership priceset if multiple
1276 //options for different organisation is selected on the contribution page.
1277 if (is_numeric($selectedMembershipTypeID) && isset($membershipTypeValues[$selectedMembershipTypeID]['auto_renew'])) {
1278 $this->assign('autoRenewOption', $membershipTypeValues[$selectedMembershipTypeID]['auto_renew']);
1281 $this->assign('autoRenewOption', $autoRenewOption);
1284 if ($isContributionMainPage) {
1285 if (!$membershipPriceset) {
1286 if (!$this->_membershipBlock
['is_required']) {
1287 $this->assign('showRadioNoThanks', TRUE);
1288 $radio[''] = $this->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
1289 $this->addGroup($radio, 'selectMembership', NULL);
1291 elseif ($this->_membershipBlock
['is_required'] && count($radio) == 1) {
1292 $temp = array_keys($radio);
1293 $this->add('hidden', 'selectMembership', $temp[0], ['id' => 'selectMembership']);
1294 $this->assign('singleMembership', TRUE);
1295 $this->assign('showRadio', FALSE);
1298 $this->addGroup($radio, 'selectMembership', NULL);
1301 $this->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
1304 if ((!$this->_values
['is_pay_later'] ||
is_array($this->_paymentProcessors
)) && ($allowAutoRenewMembership ||
$autoRenewOption)) {
1305 if ($autoRenewOption == 2) {
1306 $this->addElement('hidden', 'auto_renew', ts('Please renew my membership automatically.'));
1309 $this->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
1316 return $separateMembershipPayment;
1320 * Determine if recurring parameters need to be added to the form parameters.
1323 * - frequency_interval
1326 * For membership this is based on the membership type.
1328 * This needs to be done before processing the pre-approval redirect where relevant on the main page or before any payment processing.
1330 * Arguably the form should start to build $this->_params in the pre-process main page & use that array consistently throughout.
1332 protected function setRecurringMembershipParams() {
1333 $selectedMembershipTypeID = CRM_Utils_Array
::value('selectMembership', $this->_params
);
1334 if ($selectedMembershipTypeID) {
1335 // @todo the price_x fields will ALWAYS allow us to determine the membership - so we should ignore
1336 // 'selectMembership' and calculate from the price_x fields so we have one method that always works
1337 // this is lazy & only catches when selectMembership is set, but the worst of all worlds would be to fix
1338 // this with an else (calculate for price set).
1339 $membershipTypes = CRM_Price_BAO_PriceSet
::getMembershipTypesFromPriceSet($this->_priceSetId
);
1340 if (in_array($selectedMembershipTypeID, $membershipTypes['autorenew_required'])
1341 ||
(in_array($selectedMembershipTypeID, $membershipTypes['autorenew_optional']) &&
1342 !empty($this->_params
['is_recur']))
1344 $this->_params
['auto_renew'] = TRUE;
1347 if ((!empty($this->_params
['selectMembership']) ||
!empty($this->_params
['priceSetId']))
1348 && !empty($this->_paymentProcessor
['is_recur']) &&
1349 CRM_Utils_Array
::value('auto_renew', $this->_params
)
1350 && empty($this->_params
['is_recur']) && empty($this->_params
['frequency_interval'])
1353 $this->_params
['is_recur'] = $this->_values
['is_recur'] = 1;
1354 // check if price set is not quick config
1355 if (!empty($this->_params
['priceSetId']) && !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config')) {
1356 list($this->_params
['frequency_interval'], $this->_params
['frequency_unit']) = CRM_Price_BAO_PriceSet
::getRecurDetails($this->_params
['priceSetId']);
1359 // FIXME: set interval and unit based on selected membership type
1360 $this->_params
['frequency_interval'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1361 $this->_params
['selectMembership'], 'duration_interval'
1363 $this->_params
['frequency_unit'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1364 $this->_params
['selectMembership'], 'duration_unit'
1371 * Get the payment processor object for the submission, returning the manual one for offline payments.
1373 * @return CRM_Core_Payment
1375 protected function getPaymentProcessorObject() {
1376 if (!empty($this->_paymentProcessor
)) {
1377 return $this->_paymentProcessor
['object'];
1379 return new CRM_Core_Payment_Manual();
1383 * Get the amount for the main contribution.
1385 * The goal is to expand this function so that all the argy-bargy of figuring out the amount
1386 * winds up here as the main spaghetti shrinks.
1388 * If there is a separate membership contribution this is the 'other one'. Otherwise there
1395 * @throws \CiviCRM_API3_Exception
1397 protected function getMainContributionAmount($params) {
1398 if (!empty($params['selectMembership'])) {
1399 if (empty($params['amount']) && !$this->_separateMembershipPayment
) {
1400 return CRM_Member_BAO_MembershipType
::getMembershipType($params['selectMembership'])['minimum_fee'] ??
0;
1403 return $params['amount'] ??
0;