3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class generates form components for processing a contribution.
37 class CRM_Contribute_Form_ContributionBase
extends CRM_Core_Form
{
40 * The id of the contribution page that we are processing.
47 * The mode that we are in
55 * The contact id related to a membership
59 public $_membershipContactID;
62 * The values for the contribution db object
69 * The paymentProcessor attributes for this page
73 public $_paymentProcessor;
75 public $_paymentObject = NULL;
78 * The membership block for this page
82 public $_membershipBlock = NULL;
85 * Does this form support a separate membership payment
88 protected $_separateMembershipPayment;
91 * The params submitted by the form and computed by the app
95 public $_params = array();
98 * The fields involved in this contribution page
102 public $_fields = array();
105 * The billing location id for this contribution page.
112 * Cache the amount to make things easier
140 * The contact id of the person for whom membership is being added or renewed based on the cid in the url,
141 * checksum, or session
149 * The Membership ID for membership renewal
153 public $_membershipId;
156 * Price Set ID, if the new price set method is used
163 * Array of fields for the price set
172 * Contribution mode e.g express for payment express, notify for off-site + notification back to CiviCRM
175 public $_contributeMode;
178 * Contribution page supports memberships
181 public $_useForMember;
188 public $_isBillingAddressRequiredForPayLater;
191 * Flag if email field exists in embedded profile
195 public $_emailExists = FALSE;
198 * Is this a backoffice form
199 * (this will affect whether paypal express code is displayed)
202 public $isBackOffice = FALSE;
205 * Payment instrument if for the transaction.
207 * This will generally be drawn from the payment processor and is ignored for
212 public $paymentInstrumentID;
215 * Is the price set quick config.
218 public function isQuickConfig() {
219 return isset(self
::$_quickConfig) ? self
::$_quickConfig : FALSE;
223 * Set variables up before form is built.
225 * @throws \CRM_Contribute_Exception_InactiveContributionPageException
228 public function preProcess() {
230 // current contribution page id
231 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
232 $this->_ccid
= CRM_Utils_Request
::retrieve('ccid', 'Positive', $this);
234 // seems like the session is corrupted and/or we lost the id trail
235 // lets just bump this to a regular session error and redirect user to main page
236 $this->controller
->invalidKeyRedirect();
238 $this->_emailExists
= $this->get('emailExists');
240 // this was used prior to the cleverer this_>getContactID - unsure now
241 $this->_userID
= CRM_Core_Session
::singleton()->getLoggedInContactID();
243 $this->_contactID
= $this->_membershipContactID
= $this->getContactID();
245 if ($this->_contactID
) {
246 $this->_mid
= CRM_Utils_Request
::retrieve('mid', 'Positive', $this);
248 $membership = new CRM_Member_DAO_Membership();
249 $membership->id
= $this->_mid
;
251 if ($membership->find(TRUE)) {
252 $this->_defaultMemTypeId
= $membership->membership_type_id
;
253 if ($membership->contact_id
!= $this->_contactID
) {
254 $validMembership = FALSE;
255 $organizations = CRM_Contact_BAO_Relationship
::getPermissionedContacts($this->_userID
, NULL, NULL, 'Organization');
256 if (!empty($organizations) && array_key_exists($membership->contact_id
, $organizations)) {
257 $this->_membershipContactID
= $membership->contact_id
;
258 $this->assign('membershipContactID', $this->_membershipContactID
);
259 $this->assign('membershipContactName', $organizations[$this->_membershipContactID
]['name']);
260 $validMembership = TRUE;
263 $membershipType = new CRM_Member_BAO_MembershipType();
264 $membershipType->id
= $membership->membership_type_id
;
265 if ($membershipType->find(TRUE)) {
266 // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values.
267 // Convert to comma separated list.
268 $inheritedRelTypes = implode(CRM_Utils_Array
::explodePadded($membershipType->relationship_type_id
), ',');
269 $permContacts = CRM_Contact_BAO_Relationship
::getPermissionedContacts($this->_userID
, $membershipType->relationship_type_id
);
270 if (array_key_exists($membership->contact_id
, $permContacts)) {
271 $this->_membershipContactID
= $membership->contact_id
;
272 $validMembership = TRUE;
276 if (!$validMembership) {
277 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');
282 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');
288 // we do not want to display recently viewed items, so turn off
289 $this->assign('displayRecent', FALSE);
290 // Contribution page values are cleared from session, so can't use normal Printer Friendly view.
291 // Use Browser Print instead.
292 $this->assign('browserPrint', TRUE);
295 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
296 $this->assign('action', $this->_action
);
299 $this->_mode
= ($this->_action
== 1024) ?
'test' : 'live';
301 $this->_values
= $this->get('values');
302 $this->_fields
= $this->get('fields');
303 $this->_bltID
= $this->get('bltID');
304 $this->_paymentProcessor
= $this->get('paymentProcessor');
306 $this->_priceSetId
= $this->get('priceSetId');
307 $this->_priceSet
= $this->get('priceSet');
309 if (!$this->_values
) {
310 // get all the values from the dao object
311 $this->_values
= array();
312 $this->_fields
= array();
314 CRM_Contribute_BAO_ContributionPage
::setValues($this->_id
, $this->_values
);
315 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
316 && !CRM_Core_Permission
::check('add contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']))
318 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
320 if (empty($this->_values
['is_active'])) {
321 throw new CRM_Contribute_Exception_InactiveContributionPageException(ts('The page you requested is currently unavailable.'), $this->_id
);
324 $endDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('end_date', $this->_values
));
325 $now = date('YmdHis');
326 if ($endDate && $endDate < $now) {
327 throw new CRM_Contribute_Exception_PastContributionPageException(ts('The page you requested has past its end date on ' . CRM_Utils_Date
::customFormat($endDate)), $this->_id
);
330 $startDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('start_date', $this->_values
));
331 if ($startDate && $startDate > $now) {
332 throw new CRM_Contribute_Exception_FutureContributionPageException(ts('The page you requested will be active from ' . CRM_Utils_Date
::customFormat($startDate)), $this->_id
);
335 $this->assignBillingType();
337 // check for is_monetary status
338 $isMonetary = CRM_Utils_Array
::value('is_monetary', $this->_values
);
339 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $this->_values
);
340 if (!empty($this->_ccid
)) {
341 $this->_values
['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
347 $this->_values
['is_pay_later'] = FALSE;
352 $this->_paymentProcessorIDs
= array_filter(explode(
353 CRM_Core_DAO
::VALUE_SEPARATOR
,
354 CRM_Utils_Array
::value('payment_processor', $this->_values
)
357 $this->assignPaymentProcessor($isPayLater);
362 CRM_Price_BAO_PriceSet
::initSet($this, $this->_id
, 'civicrm_contribution_page');
364 // this avoids getting E_NOTICE errors in php
365 $setNullFields = array(
366 'amount_block_is_active',
367 'is_allow_other_amount',
370 foreach ($setNullFields as $f) {
371 if (!isset($this->_values
[$f])) {
372 $this->_values
[$f] = NULL;
376 //check if Membership Block is enabled, if Membership Fields are included in profile
377 //get membership section for this contribution page
378 $this->_membershipBlock
= CRM_Member_BAO_Membership
::getMembershipBlock($this->_id
);
379 $this->set('membershipBlock', $this->_membershipBlock
);
381 if (!empty($this->_values
['custom_pre_id'])) {
382 $preProfileType = CRM_Core_BAO_UFField
::getProfileType($this->_values
['custom_pre_id']);
385 if (!empty($this->_values
['custom_post_id'])) {
386 $postProfileType = CRM_Core_BAO_UFField
::getProfileType($this->_values
['custom_post_id']);
389 if (((isset($postProfileType) && $postProfileType == 'Membership') ||
390 (isset($preProfileType) && $preProfileType == 'Membership')
392 !$this->_membershipBlock
['is_active']
394 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.'));
397 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($this->_id
);
400 $this->_values
['pledge_block_id'] = CRM_Utils_Array
::value('id', $pledgeBlock);
401 $this->_values
['max_reminders'] = CRM_Utils_Array
::value('max_reminders', $pledgeBlock);
402 $this->_values
['initial_reminder_day'] = CRM_Utils_Array
::value('initial_reminder_day', $pledgeBlock);
403 $this->_values
['additional_reminder_day'] = CRM_Utils_Array
::value('additional_reminder_day', $pledgeBlock);
405 //set pledge id in values
406 $pledgeId = CRM_Utils_Request
::retrieve('pledgeId', 'Positive', $this);
408 //authenticate pledge user for pledge payment.
410 $this->_values
['pledge_id'] = $pledgeId;
412 //lets override w/ pledge campaign.
413 $this->_values
['campaign_id'] = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
417 self
::authenticatePledgeUser();
420 $this->set('values', $this->_values
);
421 $this->set('fields', $this->_fields
);
425 $pcpId = CRM_Utils_Request
::retrieve('pcpId', 'Positive', $this);
427 $pcp = CRM_PCP_BAO_PCP
::handlePcp($pcpId, 'contribute', $this->_values
);
428 $this->_pcpId
= $pcp['pcpId'];
429 $this->_pcpBlock
= $pcp['pcpBlock'];
430 $this->_pcpInfo
= $pcp['pcpInfo'];
433 // Link (button) for users to create their own Personal Campaign page
434 if ($linkText = CRM_PCP_BAO_PCP
::getPcpBlockStatus($this->_id
, 'contribute')) {
435 $linkTextUrl = CRM_Utils_System
::url('civicrm/contribute/campaign',
436 "action=add&reset=1&pageId={$this->_id}&component=contribute",
439 $this->assign('linkTextUrl', $linkTextUrl);
440 $this->assign('linkText', $linkText);
443 //set pledge block if block id is set
444 if (!empty($this->_values
['pledge_block_id'])) {
445 $this->assign('pledgeBlock', TRUE);
448 // check if one of the (amount , membership) blocks is active or not.
449 $this->_membershipBlock
= $this->get('membershipBlock');
451 if (!$this->_values
['amount_block_is_active'] &&
452 !$this->_membershipBlock
['is_active'] &&
455 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.'));
458 if ($this->_values
['amount_block_is_active']) {
459 $this->set('amount_block_is_active', $this->_values
['amount_block_is_active']);
462 $this->_contributeMode
= $this->get('contributeMode');
463 $this->assign('contributeMode', $this->_contributeMode
);
465 //assigning is_monetary and is_email_receipt to template
466 $this->assign('is_monetary', $this->_values
['is_monetary']);
467 $this->assign('is_email_receipt', $this->_values
['is_email_receipt']);
468 $this->assign('bltID', $this->_bltID
);
470 //assign cancelSubscription URL to templates
471 $this->assign('cancelSubscriptionUrl',
472 CRM_Utils_Array
::value('cancelSubscriptionUrl', $this->_values
)
475 // assigning title to template in case someone wants to use it, also setting CMS page title
477 $this->assign('title', $this->_pcpInfo
['title']);
478 CRM_Utils_System
::setTitle($this->_pcpInfo
['title']);
481 $this->assign('title', $this->_values
['title']);
482 CRM_Utils_System
::setTitle($this->_values
['title']);
484 $this->_defaults
= array();
486 $this->_amount
= $this->get('amount');
487 // Assigning this to the template means it will be passed through to the payment form.
488 // This can, for example, by used by payment processors using client side encryption
489 $this->assign('currency', $this->getCurrency());
492 // these lines exist to support a non-default currenty on the form but are probably
493 // obsolete & meddling wth the defaultCurrency is not the right approach....
494 $config = CRM_Core_Config
::singleton();
495 $config->defaultCurrency
= CRM_Utils_Array
::value('currency',
497 $config->defaultCurrency
500 //lets allow user to override campaign.
501 $campID = CRM_Utils_Request
::retrieve('campID', 'Positive', $this);
502 if ($campID && CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
503 $this->_values
['campaign_id'] = $campID;
506 //do check for cancel recurring and clean db, CRM-7696
507 if (CRM_Utils_Request
::retrieve('cancel', 'Boolean')) {
508 self
::cancelRecurring();
511 // check if billing block is required for pay later
512 if (CRM_Utils_Array
::value('is_pay_later', $this->_values
)) {
513 $this->_isBillingAddressRequiredForPayLater
= CRM_Utils_Array
::value('is_billing_required', $this->_values
);
514 $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater
);
519 * Set the default values.
521 public function setDefaultValues() {
522 return $this->_defaults
;
526 * Assign the minimal set of variables to the template.
528 public function assignToTemplate() {
529 $this->set('name', $this->assignBillingName($this->_params
));
531 $this->assign('paymentProcessor', $this->_paymentProcessor
);
540 $config = CRM_Core_Config
::singleton();
541 if (isset($this->_values
['is_recur']) && !empty($this->_paymentProcessor
['is_recur'])) {
542 $this->assign('is_recur_enabled', 1);
543 $vars = array_merge($vars, array(
545 'frequency_interval',
551 if (in_array('CiviPledge', $config->enableComponents
) &&
552 CRM_Utils_Array
::value('is_pledge', $this->_params
) == 1
554 $this->assign('pledge_enabled', 1);
556 $vars = array_merge($vars, array(
558 'pledge_frequency_interval',
559 'pledge_frequency_unit',
560 'pledge_installments',
564 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
565 // function to get correct amount level consistently. Remove setting of the amount level in
566 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
567 // to cover all variants.
568 if (isset($this->_params
['amount_other']) ||
isset($this->_params
['selectMembership'])) {
569 $this->_params
['amount_level'] = '';
572 foreach ($vars as $v) {
573 if (isset($this->_params
[$v])) {
574 if ($v == "amount" && $this->_params
[$v] === 0) {
575 $this->_params
[$v] = CRM_Utils_Money
::format($this->_params
[$v], NULL, NULL, TRUE);
577 $this->assign($v, $this->_params
[$v]);
581 $this->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
586 if (!empty($this->_params
['onbehalf_profile_id']) && !empty($this->_params
['onbehalf'])) {
587 $this->assign('onBehalfName', $this->_params
['organization_name']);
588 $locTypeId = array_keys($this->_params
['onbehalf_location']['email']);
589 $this->assign('onBehalfEmail', $this->_params
['onbehalf_location']['email'][$locTypeId[0]]['email']);
594 if ($this->_amount
> 0.0) {
597 elseif (!empty($this->_params
['selectMembership'])) {
598 $memFee = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params
['selectMembership'], 'minimum_fee');
604 // The concept of contributeMode is deprecated.
605 // The payment processor object can provide info about the fields it shows.
606 if ($isMonetary && is_a($this->_paymentProcessor
['object'], 'CRM_Core_Payment')) {
607 /** @var $paymentProcessorObject \CRM_Core_Payment */
608 $paymentProcessorObject = $this->_paymentProcessor
['object'];
610 $paymentFields = $paymentProcessorObject->getPaymentFormFields();
611 foreach ($paymentFields as $index => $paymentField) {
612 if (!isset($this->_params
[$paymentField])) {
613 unset($paymentFields[$index]);
616 if ($paymentField === 'credit_card_exp_date') {
617 $date = CRM_Utils_Date
::format(CRM_Utils_Array
::value('credit_card_exp_date', $this->_params
));
618 $date = CRM_Utils_Date
::mysqlToIso($date);
619 $this->assign('credit_card_exp_date', $date);
621 elseif ($paymentField === 'credit_card_number') {
622 $this->assign('credit_card_number',
623 CRM_Utils_System
::mungeCreditCard(CRM_Utils_Array
::value('credit_card_number', $this->_params
))
626 elseif ($paymentField === 'credit_card_type') {
627 $this->assign('credit_card_type', CRM_Core_PseudoConstant
::getLabel(
628 'CRM_Core_BAO_FinancialTrxn',
630 CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $this->_params
['credit_card_type'])
634 $this->assign($paymentField, $this->_params
[$paymentField]);
637 $this->assign('paymentFieldsetLabel', CRM_Core_Payment_Form
::getPaymentLabel($paymentProcessorObject));
638 $this->assign('paymentFields', $paymentFields);
642 $this->assign('email',
643 $this->controller
->exportValue('Main', "email-{$this->_bltID}")
646 // also assign the receipt_text
647 if (isset($this->_values
['receipt_text'])) {
648 $this->assign('receipt_text', $this->_values
['receipt_text']);
653 * Add the custom fields.
656 * @param string $name
657 * @param bool $viewOnly
658 * @param null $profileContactType
659 * @param array $fieldTypes
661 public function buildCustom($id, $name, $viewOnly = FALSE, $profileContactType = NULL, $fieldTypes = NULL) {
663 $contactID = $this->getContactID();
665 // we don't allow conflicting fields to be
666 // configured via profile - CRM 2100
667 $fieldsToIgnore = array(
673 'non_deductible_amount' => 1,
676 'contribution_status_id' => 1,
677 // @todo replace payment_instrument with payment instrument id.
678 // both are available now but the id field is the most consistent.
679 'payment_instrument' => 1,
680 'payment_instrument_id' => 1,
681 'contribution_check_number' => 1,
682 'financial_type' => 1,
685 $fields = CRM_Core_BAO_UFGroup
::getFields($id, FALSE, CRM_Core_Action
::ADD
, NULL, NULL, FALSE,
686 NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, NULL
690 // determine if email exists in profile so we know if we need to manually insert CRM-2888, CRM-15067
691 foreach ($fields as $key => $field) {
692 if (substr($key, 0, 6) == 'email-' &&
693 !in_array($profileContactType, array('honor', 'onbehalf'))
695 $this->_emailExists
= TRUE;
696 $this->set('emailExists', TRUE);
700 if (array_intersect_key($fields, $fieldsToIgnore)) {
701 $fields = array_diff_key($fields, $fieldsToIgnore);
702 CRM_Core_Session
::setStatus(ts('Some of the profile fields cannot be configured for this page.'), ts('Warning'), 'alert');
705 //remove common fields only if profile is not configured for onbehalf/honor
706 if (!in_array($profileContactType, array('honor', 'onbehalf'))) {
707 $fields = array_diff_key($fields, $this->_fields
);
710 CRM_Core_BAO_Address
::checkContactSharedAddressFields($fields, $contactID);
712 // fetch file preview when not submitted yet, like in online contribution Confirm and ThankYou page
713 $viewOnlyFileValues = empty($profileContactType) ?
array() : array($profileContactType => array());
714 foreach ($fields as $key => $field) {
716 isset($field['data_type']) &&
717 $field['data_type'] == 'File' ||
($viewOnly && $field['name'] == 'image_URL')
719 //retrieve file value from submitted values on basis of $profileContactType
720 $fileValue = CRM_Utils_Array
::value($key, $this->_params
);
721 if (!empty($profileContactType) && !empty($this->_params
[$profileContactType])) {
722 $fileValue = CRM_Utils_Array
::value($key, $this->_params
[$profileContactType]);
726 $path = CRM_Utils_Array
::value('name', $fileValue);
727 $fileType = CRM_Utils_Array
::value('type', $fileValue);
728 $fileValue = CRM_Utils_File
::getFileURL($path, $fileType);
731 // format custom file value fetched from submitted value
732 if ($profileContactType) {
733 $viewOnlyFileValues[$profileContactType][$key] = $fileValue;
736 $viewOnlyFileValues[$key] = $fileValue;
739 // On viewOnly use-case (as in online contribution Confirm page) we no longer need to set
740 // required property because being required file is already uploaded while registration
741 $field['is_required'] = FALSE;
743 if ($profileContactType) {
744 //Since we are showing honoree name separately so we are removing it from honoree profile just for display
745 if ($profileContactType == 'honor') {
746 $honoreeNamefields = array(
754 if (in_array($field['name'], $honoreeNamefields)) {
755 unset($fields[$field['name']]);
759 if (!empty($fieldTypes) && in_array($field['field_type'], $fieldTypes)) {
760 CRM_Core_BAO_UFGroup
::buildProfile(
763 CRM_Profile_Form
::MODE_CREATE
,
768 $this->_fields
[$profileContactType][$key] = $field;
771 unset($fields[$key]);
775 CRM_Core_BAO_UFGroup
::buildProfile(
778 CRM_Profile_Form
::MODE_CREATE
,
782 $this->_fields
[$key] = $field;
784 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
785 if ($field['add_captcha'] && !$this->_userID
) {
790 $this->assign($name, $fields);
792 if ($profileContactType && count($viewOnlyFileValues[$profileContactType])) {
793 $this->assign('viewOnlyPrefixFileValues', $viewOnlyFileValues);
795 elseif (count($viewOnlyFileValues)) {
796 $this->assign('viewOnlyFileValues', $viewOnlyFileValues);
799 if ($addCaptcha && !$viewOnly) {
800 $this->enableCaptchaOnForm();
807 * Enable ReCAPTCHA on Contribution form
809 protected function enableCaptchaOnForm() {
810 $captcha = CRM_Utils_ReCAPTCHA
::singleton();
811 if ($captcha->hasSettingsAvailable()) {
812 $captcha->add($this);
813 $this->assign('isCaptcha', TRUE);
818 * Display ReCAPTCHA warning on Contribution form
820 protected function displayCaptchaWarning() {
821 if (CRM_Core_Permission
::check("administer CiviCRM")) {
822 $captcha = CRM_Utils_ReCAPTCHA
::singleton();
823 if (!$captcha->hasSettingsAvailable()) {
824 $this->assign('displayCaptchaWarning', TRUE);
830 * Check if ReCAPTCHA has to be added on Contribution form forcefully.
832 protected function hasToAddForcefully() {
833 $captcha = CRM_Utils_ReCAPTCHA
::singleton();
834 return $captcha->hasToAddForcefully();
838 * Add onbehalf/honoree profile fields and native module fields.
841 * @param CRM_Core_Form $form
843 public function buildComponentForm($id, $form) {
848 $contactID = $this->getContactID();
850 foreach (array('soft_credit', 'on_behalf') as $module) {
851 if ($module == 'soft_credit') {
852 if (empty($form->_values
['honoree_profile_id'])) {
856 if (!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values
['honoree_profile_id'], 'is_active')) {
857 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.'));
860 $profileContactType = CRM_Core_BAO_UFGroup
::getContactType($form->_values
['honoree_profile_id']);
861 $requiredProfileFields = array(
862 'Individual' => array('first_name', 'last_name'),
863 'Organization' => array('organization_name', 'email'),
864 'Household' => array('household_name', 'email'),
866 $validProfile = CRM_Core_BAO_UFGroup
::checkValidProfile($form->_values
['honoree_profile_id'], $requiredProfileFields[$profileContactType]);
867 if (!$validProfile) {
868 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.'));
871 foreach (array('honor_block_title', 'honor_block_text') as $name) {
872 $form->assign($name, $form->_values
[$name]);
875 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
877 // radio button for Honor Type
878 foreach ($form->_values
['soft_credit_types'] as $value) {
879 $honorTypes[$value] = $form->createElement('radio', NULL, NULL, $softCreditTypes[$value], $value);
881 $form->addGroup($honorTypes, 'soft_credit_type_id', NULL)->setAttribute('allowClear', TRUE);
883 $honoreeProfileFields = CRM_Core_BAO_UFGroup
::getFields(
884 $this->_values
['honoree_profile_id'], FALSE,
888 NULL, CRM_Core_Permission
::CREATE
890 $form->assign('honoreeProfileFields', $honoreeProfileFields);
892 // add the form elements
893 foreach ($honoreeProfileFields as $name => $field) {
894 // If soft credit type is not chosen then make omit requiredness from honoree profile fields
895 if (count($form->_submitValues
) &&
896 empty($form->_submitValues
['soft_credit_type_id']) &&
897 !empty($field['is_required'])
899 $field['is_required'] = FALSE;
901 CRM_Core_BAO_UFGroup
::buildProfile($form, $field, CRM_Profile_Form
::MODE_CREATE
, NULL, FALSE, FALSE, NULL, 'honor');
905 if (empty($form->_values
['onbehalf_profile_id'])) {
909 if (!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values
['onbehalf_profile_id'], 'is_active')) {
910 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.'));
913 $member = CRM_Member_BAO_Membership
::getMembershipBlock($form->_id
);
914 if (empty($member['is_active'])) {
915 $msg = ts('Mixed profile not allowed for on behalf of registration/sign up.');
916 $onBehalfProfile = CRM_Core_BAO_UFGroup
::profileGroups($form->_values
['onbehalf_profile_id']);
924 if (in_array($contactType, $onBehalfProfile) &&
925 (in_array('Membership', $onBehalfProfile) ||
926 in_array('Contribution', $onBehalfProfile)
929 CRM_Core_Error
::fatal($msg);
935 // retrieve all permissioned organizations of contact $contactID
936 $organizations = CRM_Contact_BAO_Relationship
::getPermissionedContacts($contactID, NULL, NULL, 'Organization');
938 if (count($organizations)) {
939 // Related org url - pass checksum if needed
941 'ufId' => $form->_values
['onbehalf_profile_id'],
944 if (!empty($_GET['cs'])) {
946 'ufId' => $form->_values
['onbehalf_profile_id'],
947 'uid' => $this->_contactID
,
952 $locDataURL = CRM_Utils_System
::url('civicrm/ajax/permlocation', $args, FALSE, NULL, FALSE);
953 $form->assign('locDataURL', $locDataURL);
955 if (count($organizations) > 0) {
956 $form->add('select', 'onbehalfof_id', '', CRM_Utils_Array
::collect('name', $organizations));
959 0 => ts('Select an existing organization'),
960 1 => ts('Enter a new organization'),
962 $form->addRadio('org_option', ts('options'), $orgOptions);
963 $form->setDefaults(array('org_option' => 0));
967 $form->assign('fieldSetTitle', ts(CRM_Core_BAO_UFGroup
::getTitle($form->_values
['onbehalf_profile_id'])));
969 if (CRM_Utils_Array
::value('is_for_organization', $form->_values
)) {
970 if ($form->_values
['is_for_organization'] == 2) {
971 $form->assign('onBehalfRequired', TRUE);
974 $form->addElement('checkbox', 'is_for_organization',
975 $form->_values
['for_organization'],
981 $profileFields = CRM_Core_BAO_UFGroup
::getFields(
982 $form->_values
['onbehalf_profile_id'],
983 FALSE, CRM_Core_Action
::VIEW
, NULL,
984 NULL, FALSE, NULL, FALSE, NULL,
985 CRM_Core_Permission
::CREATE
, NULL
988 $form->assign('onBehalfOfFields', $profileFields);
989 if (!empty($form->_submitValues
['onbehalf'])) {
990 if (!empty($form->_submitValues
['onbehalfof_id'])) {
991 $form->assign('submittedOnBehalf', $form->_submitValues
['onbehalfof_id']);
993 $form->assign('submittedOnBehalfInfo', json_encode(str_replace('"', '\"', $form->_submitValues
['onbehalf']), JSON_HEX_APOS
));
996 $fieldTypes = array('Contact', 'Organization');
997 if (!empty($form->_membershipBlock
)) {
998 $fieldTypes = array_merge($fieldTypes, array('Membership'));
1000 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
1001 $fieldTypes = array_merge($fieldTypes, $contactSubType);
1003 foreach ($profileFields as $name => $field) {
1004 if (in_array($field['field_type'], $fieldTypes)) {
1005 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
1006 if (in_array($prefixName, array('organization_name', 'email')) && empty($field['is_required'])) {
1007 $field['is_required'] = 1;
1009 if (count($form->_submitValues
) &&
1010 empty($form->_submitValues
['is_for_organization']) &&
1011 $form->_values
['is_for_organization'] == 1 &&
1012 !empty($field['is_required'])
1014 $field['is_required'] = FALSE;
1016 CRM_Core_BAO_UFGroup
::buildProfile($form, $field, NULL, NULL, FALSE, 'onbehalf', NULL, 'onbehalf');
1025 * Check template file exists.
1027 * @param string $suffix
1029 * @return null|string
1031 public function checkTemplateFileExists($suffix = NULL) {
1033 $templateFile = "CRM/Contribute/Form/Contribution/{$this->_id}/{$this->_name}.{$suffix}tpl";
1034 $template = CRM_Core_Form
::getTemplate();
1035 if ($template->template_exists($templateFile)) {
1036 return $templateFile;
1043 * Use the form name to create the tpl file name.
1047 public function getTemplateFileName() {
1048 $fileName = $this->checkTemplateFileExists();
1049 return $fileName ?
$fileName : parent
::getTemplateFileName();
1053 * Add the extra.tpl in.
1055 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1056 * i.e. we do not override - why isn't this done at the CRM_Core_Form level?
1060 public function overrideExtraTemplateFileName() {
1061 $fileName = $this->checkTemplateFileExists('extra.');
1062 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();
1066 * Authenticate pledge user during online payment.
1068 public function authenticatePledgeUser() {
1069 //get the userChecksum and contact id
1070 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
1071 $contactID = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
1073 //get pledge status and contact id
1074 $pledgeValues = array();
1075 $pledgeParams = array('id' => $this->_values
['pledge_id']);
1076 $returnProperties = array('contact_id', 'status_id');
1077 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_DAO_Pledge', $pledgeParams, $pledgeValues, $returnProperties);
1080 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1081 $validStatus = array(
1082 array_search('Pending', $allStatus),
1083 array_search('In Progress', $allStatus),
1084 array_search('Overdue', $allStatus),
1088 if ($this->_userID
&&
1089 $this->_userID
== $pledgeValues['contact_id']
1091 //check for authenticated user.
1094 elseif ($userChecksum && $pledgeValues['contact_id']) {
1095 //check for anonymous user.
1096 $validUser = CRM_Contact_BAO_Contact_Utils
::validChecksum($pledgeValues['contact_id'], $userChecksum);
1098 //make sure cid is same as pledge contact id
1099 if ($validUser && ($pledgeValues['contact_id'] != $contactID)) {
1105 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."));
1108 //check for valid pledge status.
1109 if (!in_array($pledgeValues['status_id'], $validStatus)) {
1110 CRM_Core_Error
::fatal(ts('Oops. You cannot make a payment for this pledge - pledge status is %1.', array(1 => CRM_Utils_Array
::value($pledgeValues['status_id'], $allStatus))));
1115 * Cancel recurring contributions.
1117 * In case user cancel recurring contribution,
1118 * When we get the control back from payment gate way
1119 * lets delete the recurring and related contribution.
1121 public function cancelRecurring() {
1122 $isCancel = CRM_Utils_Request
::retrieve('cancel', 'Boolean');
1124 $isRecur = CRM_Utils_Request
::retrieve('isRecur', 'Boolean');
1125 $recurId = CRM_Utils_Request
::retrieve('recurId', 'Positive');
1126 //clean db for recurring contribution.
1127 if ($isRecur && $recurId) {
1128 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($recurId);
1130 $contribId = CRM_Utils_Request
::retrieve('contribId', 'Positive');
1132 CRM_Contribute_BAO_Contribution
::deleteContribution($contribId);
1138 * Build Membership Block in Contribution Pages.
1141 * Contact checked for having a current membership for a particular membership.
1142 * @param bool $isContributionMainPage
1143 * Is this the main page? If so add form input fields.
1144 * (or better yet don't have this functionality in a function shared with forms that don't share it).
1145 * @param int|array $selectedMembershipTypeID
1146 * Selected membership id.
1147 * @param bool $thankPage
1149 * @param null $isTest
1152 * Is this a separate membership payment
1154 protected function buildMembershipBlock(
1156 $isContributionMainPage = FALSE,
1157 $selectedMembershipTypeID = NULL,
1162 $separateMembershipPayment = FALSE;
1163 if ($this->_membershipBlock
) {
1164 $this->_currentMemberships
= array();
1166 $membershipTypeIds = $membershipTypes = $radio = array();
1167 $membershipPriceset = (!empty($this->_priceSetId
) && $this->_useForMember
) ?
TRUE : FALSE;
1169 $allowAutoRenewMembership = $autoRenewOption = FALSE;
1170 $autoRenewMembershipTypeOptions = array();
1172 $separateMembershipPayment = CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
);
1174 if ($membershipPriceset) {
1175 foreach ($this->_priceSet
['fields'] as $pField) {
1176 if (empty($pField['options'])) {
1179 foreach ($pField['options'] as $opId => $opValues) {
1180 if (empty($opValues['membership_type_id'])) {
1183 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
1187 elseif (!empty($this->_membershipBlock
['membership_types'])) {
1188 $membershipTypeIds = explode(',', $this->_membershipBlock
['membership_types']);
1191 if (!empty($membershipTypeIds)) {
1192 //set status message if wrong membershipType is included in membershipBlock
1193 if (isset($this->_mid
) && !$membershipPriceset) {
1194 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1196 'membership_type_id'
1198 if (!in_array($membershipTypeID, $membershipTypeIds)) {
1199 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');
1203 $membershipTypeValues = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIds);
1204 $this->_membershipTypeValues
= $membershipTypeValues;
1206 foreach ($membershipTypeIds as $value) {
1207 $memType = $membershipTypeValues[$value];
1208 if ($selectedMembershipTypeID != NULL) {
1209 if ($memType['id'] == $selectedMembershipTypeID) {
1210 $this->assign('minimum_fee',
1211 CRM_Utils_Array
::value('minimum_fee', $memType)
1213 $this->assign('membership_name', $memType['name']);
1214 if (!$thankPage && $cid) {
1215 $membership = new CRM_Member_DAO_Membership();
1216 $membership->contact_id
= $cid;
1217 $membership->membership_type_id
= $memType['id'];
1218 if ($membership->find(TRUE)) {
1219 $this->assign('renewal_mode', TRUE);
1220 $memType['current_membership'] = $membership->end_date
;
1221 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
1224 $membershipTypes[] = $memType;
1227 elseif ($memType['is_active']) {
1228 $javascriptMethod = NULL;
1229 $allowAutoRenewOpt = (int) $memType['auto_renew'];
1230 if (is_array($this->_paymentProcessors
)) {
1231 foreach ($this->_paymentProcessors
as $id => $val) {
1232 if ($id && !$val['is_recur']) {
1233 $allowAutoRenewOpt = 0;
1239 $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
1240 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $allowAutoRenewOpt * CRM_Utils_Array
::value($value, CRM_Utils_Array
::value('auto_renew', $this->_membershipBlock
));;
1242 if ($allowAutoRenewOpt) {
1243 $allowAutoRenewMembership = TRUE;
1246 //add membership type.
1247 $radio[$memType['id']] = $this->createElement('radio', NULL, NULL, NULL,
1248 $memType['id'], $javascriptMethod
1251 $membership = new CRM_Member_DAO_Membership();
1252 $membership->contact_id
= $cid;
1253 $membership->membership_type_id
= $memType['id'];
1255 //show current membership, skip pending and cancelled membership records,
1256 //because we take first membership record id for renewal
1257 $membership->whereAdd('status_id != 5 AND status_id !=6');
1259 if (!is_null($isTest)) {
1260 $membership->is_test
= $isTest;
1264 $membership->orderBy('end_date DESC');
1266 if ($membership->find(TRUE)) {
1267 if (!$membership->end_date
) {
1268 unset($radio[$memType['id']]);
1269 $this->assign('islifetime', TRUE);
1272 $this->assign('renewal_mode', TRUE);
1273 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
1274 $memType['current_membership'] = $membership->end_date
;
1276 $endDate = $memType['current_membership'];
1277 $this->_defaultMemTypeId
= $memType['id'];
1279 if ($memType['current_membership'] < $endDate) {
1280 $endDate = $memType['current_membership'];
1281 $this->_defaultMemTypeId
= $memType['id'];
1285 $membershipTypes[] = $memType;
1290 $this->assign('membershipBlock', $this->_membershipBlock
);
1291 $this->assign('showRadio', $isContributionMainPage);
1292 $this->assign('membershipTypes', $membershipTypes);
1293 $this->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
1294 $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
1295 //give preference to user submitted auto_renew value.
1296 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$this->isSubmitted()) ?
TRUE : FALSE;
1297 $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
1299 // Assign autorenew option (0:hide,1:optional,2:required) so we can use it in confirmation etc.
1300 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
);
1301 //$selectedMembershipTypeID is retrieved as an array for membership priceset if multiple
1302 //options for different organisation is selected on the contribution page.
1303 if (is_numeric($selectedMembershipTypeID) && isset($membershipTypeValues[$selectedMembershipTypeID]['auto_renew'])) {
1304 $this->assign('autoRenewOption', $membershipTypeValues[$selectedMembershipTypeID]['auto_renew']);
1307 $this->assign('autoRenewOption', $autoRenewOption);
1310 if ($isContributionMainPage) {
1311 if (!$membershipPriceset) {
1312 if (!$this->_membershipBlock
['is_required']) {
1313 $this->assign('showRadioNoThanks', TRUE);
1314 $radio[''] = $this->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
1315 $this->addGroup($radio, 'selectMembership', NULL);
1317 elseif ($this->_membershipBlock
['is_required'] && count($radio) == 1) {
1318 $temp = array_keys($radio);
1319 $this->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
1320 $this->assign('singleMembership', TRUE);
1321 $this->assign('showRadio', FALSE);
1324 $this->addGroup($radio, 'selectMembership', NULL);
1327 $this->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
1330 if ((!$this->_values
['is_pay_later'] ||
is_array($this->_paymentProcessors
)) && ($allowAutoRenewMembership ||
$autoRenewOption)) {
1331 if ($autoRenewOption == 2) {
1332 $this->addElement('hidden', 'auto_renew', ts('Please renew my membership automatically.'));
1335 $this->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
1342 return $separateMembershipPayment;
1346 * Determine if recurring parameters need to be added to the form parameters.
1349 * - frequency_interval
1352 * For membership this is based on the membership type.
1354 * This needs to be done before processing the pre-approval redirect where relevant on the main page or before any payment processing.
1356 * Arguably the form should start to build $this->_params in the pre-process main page & use that array consistently throughout.
1358 protected function setRecurringMembershipParams() {
1359 $selectedMembershipTypeID = CRM_Utils_Array
::value('selectMembership', $this->_params
);
1360 if ($selectedMembershipTypeID) {
1361 // @todo the price_x fields will ALWAYS allow us to determine the membership - so we should ignore
1362 // 'selectMembership' and calculate from the price_x fields so we have one method that always works
1363 // this is lazy & only catches when selectMembership is set, but the worst of all worlds would be to fix
1364 // this with an else (calculate for price set).
1365 $membershipTypes = CRM_Price_BAO_PriceSet
::getMembershipTypesFromPriceSet($this->_priceSetId
);
1366 if (in_array($selectedMembershipTypeID, $membershipTypes['autorenew_required'])
1367 ||
(in_array($selectedMembershipTypeID, $membershipTypes['autorenew_optional']) &&
1368 !empty($this->_params
['is_recur']))
1370 $this->_params
['auto_renew'] = TRUE;
1373 if ((!empty($this->_params
['selectMembership']) ||
!empty($this->_params
['priceSetId']))
1374 && !empty($this->_paymentProcessor
['is_recur']) &&
1375 CRM_Utils_Array
::value('auto_renew', $this->_params
)
1376 && empty($this->_params
['is_recur']) && empty($this->_params
['frequency_interval'])
1379 $this->_params
['is_recur'] = $this->_values
['is_recur'] = 1;
1380 // check if price set is not quick config
1381 if (!empty($this->_params
['priceSetId']) && !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config')) {
1382 list($this->_params
['frequency_interval'], $this->_params
['frequency_unit']) = CRM_Price_BAO_PriceSet
::getRecurDetails($this->_params
['priceSetId']);
1385 // FIXME: set interval and unit based on selected membership type
1386 $this->_params
['frequency_interval'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1387 $this->_params
['selectMembership'], 'duration_interval'
1389 $this->_params
['frequency_unit'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1390 $this->_params
['selectMembership'], 'duration_unit'