Skip to content
Snippets Groups Projects
Confirm.php 99.3 KiB
Newer Older
  • Learn to ignore specific revisions
  • Kevin Cristiano's avatar
    Kevin Cristiano committed
    <?php
    /*
     +--------------------------------------------------------------------+
     | CiviCRM version 4.7                                                |
     +--------------------------------------------------------------------+
    
     | Copyright CiviCRM LLC (c) 2004-2017                                |
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
     +--------------------------------------------------------------------+
     | This file is a part of CiviCRM.                                    |
     |                                                                    |
     | CiviCRM is free software; you can copy, modify, and distribute it  |
     | under the terms of the GNU Affero General Public License           |
     | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
     |                                                                    |
     | CiviCRM is distributed in the hope that it will be useful, but     |
     | WITHOUT ANY WARRANTY; without even the implied warranty of         |
     | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
     | See the GNU Affero General Public License for more details.        |
     |                                                                    |
     | You should have received a copy of the GNU Affero General Public   |
     | License and the CiviCRM Licensing Exception along                  |
     | with this program; if not, contact CiviCRM LLC                     |
     | at info[AT]civicrm[DOT]org. If you have questions about the        |
     | GNU Affero General Public License or the licensing of CiviCRM,     |
     | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
     +--------------------------------------------------------------------+
     */
    
    /**
     *
     * @package CRM
    
     * @copyright CiviCRM LLC (c) 2004-2017
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
     */
    
    /**
     * form to process actions on the group aspect of Custom Data
     */
    class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_ContributionBase {
    
      /**
       * The id of the contact associated with this contribution.
       *
       * @var int
       */
      public $_contactID;
    
    
      /**
       * The id of the contribution object that is created when the form is submitted.
       *
       * @var int
       */
      public $_contributionID;
    
    
      /**
       * @param $form
       * @param $params
       * @param $contributionParams
       * @param $pledgeID
       * @param $contribution
       * @param $isEmailReceipt
       * @return mixed
       */
      public static function handlePledge(&$form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt) {
        if ($pledgeID) {
          //when user doing pledge payments.
          //update the schedule when payment(s) are made
          $amount = $params['amount'];
          $pledgePaymentParams = array();
          foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
            $scheduledAmount = CRM_Core_DAO::getFieldValue(
              'CRM_Pledge_DAO_PledgePayment',
              $paymentId,
              'scheduled_amount',
              'id'
            );
    
            $pledgePayment = ($amount >= $scheduledAmount) ? $scheduledAmount : $amount;
            if ($pledgePayment > 0) {
              $pledgePaymentParams[] = array(
                'id' => $paymentId,
                'contribution_id' => $contribution->id,
                'status_id' => $contribution->contribution_status_id,
                'actual_amount' => $pledgePayment,
              );
              $amount -= $pledgePayment;
            }
          }
          if ($amount > 0 && count($pledgePaymentParams)) {
            $pledgePaymentParams[count($pledgePaymentParams) - 1]['actual_amount'] += $amount;
          }
          foreach ($pledgePaymentParams as $p) {
            CRM_Pledge_BAO_PledgePayment::add($p);
          }
    
          //update pledge status according to the new payment statuses
          CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID);
          return $form;
        }
        else {
          //when user creating pledge record.
          $pledgeParams = array();
          $pledgeParams['contact_id'] = $contribution->contact_id;
          $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
          $pledgeParams['contribution_id'] = $contribution->id;
          $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
          $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
          $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
          $pledgeParams['installments'] = $params['pledge_installments'];
          $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
          if ($pledgeParams['frequency_unit'] == 'month') {
            $pledgeParams['frequency_day'] = intval(date("d"));
          }
          else {
            $pledgeParams['frequency_day'] = 1;
          }
          $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
          if (CRM_Utils_Array::value('start_date', $params)) {
            $pledgeParams['frequency_day'] = intval(date("d", strtotime(CRM_Utils_Array::value('start_date', $params))));
            $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date('Ymd', strtotime(CRM_Utils_Array::value('start_date', $params)));
          }
          $pledgeParams['status_id'] = $contribution->contribution_status_id;
          $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
          $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
          $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
          $pledgeParams['is_test'] = $contribution->is_test;
          $pledgeParams['acknowledge_date'] = date('Ymd');
          $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
    
          //inherit campaign from contirb page.
          $pledgeParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $contributionParams);
    
          $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
    
          $form->_params['pledge_id'] = $pledge->id;
    
          //send acknowledgment email. only when pledge is created
          if ($pledge->id && $isEmailReceipt) {
            //build params to send acknowledgment.
            $pledgeParams['id'] = $pledge->id;
            $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
            $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
    
            //scheduled amount will be same as installment_amount.
            $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
    
            //get total pledge amount.
            $pledgeParams['total_pledge_amount'] = $pledge->amount;
    
            CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
            return $form;
          }
          return $form;
        }
      }
    
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
      /**
       * Set the parameters to be passed to contribution create function.
       *
       * @param array $params
       * @param int $financialTypeID
       * @param float $nonDeductibleAmount
       * @param bool $pending
       * @param array $paymentProcessorOutcome
       * @param string $receiptDate
       * @param int $recurringContributionID
       *
       * @return array
       */
      public static function getContributionParams(
        $params, $financialTypeID, $nonDeductibleAmount, $pending,
        $paymentProcessorOutcome, $receiptDate, $recurringContributionID) {
        $contributionParams = array(
          'financial_type_id' => $financialTypeID,
          'receive_date' => (CRM_Utils_Array::value('receive_date', $params)) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'),
          'non_deductible_amount' => $nonDeductibleAmount,
          'total_amount' => $params['amount'],
          'tax_amount' => CRM_Utils_Array::value('tax_amount', $params),
          'amount_level' => CRM_Utils_Array::value('amount_level', $params),
          'invoice_id' => $params['invoiceID'],
          'currency' => $params['currencyID'],
          'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
          //configure cancel reason, cancel date and thankyou date
          //from 'contribution' type profile if included
          'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0),
          'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : NULL,
          'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : NULL,
          //setting to make available to hook - although seems wrong to set on form for BAO hook availability
          'skipLineItem' => CRM_Utils_Array::value('skipLineItem', $params, 0),
        );
    
        if ($paymentProcessorOutcome) {
          $contributionParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $paymentProcessorOutcome);
        }
        if (!$pending && $paymentProcessorOutcome) {
          $contributionParams += array(
            'fee_amount' => CRM_Utils_Array::value('fee_amount', $paymentProcessorOutcome),
            'net_amount' => CRM_Utils_Array::value('net_amount', $paymentProcessorOutcome, $params['amount']),
            'trxn_id' => $paymentProcessorOutcome['trxn_id'],
            'receipt_date' => $receiptDate,
            // also add financial_trxn details as part of fix for CRM-4724
            'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $paymentProcessorOutcome),
          );
        }
    
        // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
        $contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contributionParams['non_deductible_amount'], ' '));
        $contributionParams['total_amount'] = trim(CRM_Utils_Money::format($contributionParams['total_amount'], ' '));
    
        if ($recurringContributionID) {
          $contributionParams['contribution_recur_id'] = $recurringContributionID;
        }
    
        $contributionParams['contribution_status_id'] = $pending ? 2 : 1;
        if (isset($contributionParams['invoice_id'])) {
          $contributionParams['id'] = CRM_Core_DAO::getFieldValue(
            'CRM_Contribute_DAO_Contribution',
            $contributionParams['invoice_id'],
            'id',
            'invoice_id'
          );
        }
    
        return $contributionParams;
      }
    
      /**
       * Get non-deductible amount.
       *
       * This is a bit too much about wierd form interpretation to be this deep.
       *
       * CRM-11885
       *  if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
       * it.
       *
       * @param array $params
       * @param CRM_Financial_BAO_FinancialType $financialType
       * @param bool $online
    
       * @param CRM_Contribute_Form_Contribution_Confirm $form
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
       *
       * @return array
       */
    
      protected static function getNonDeductibleAmount($params, $financialType, $online, $form) {
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
        if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
          return $params['non_deductible_amount'];
        }
    
        $priceSetId = CRM_Utils_Array::value('priceSetId', $params);
        // return non-deductible amount if it is set at the price field option level
        if ($priceSetId && !empty($form->_lineItem)) {
          $nonDeductibleAmount = CRM_Price_BAO_PriceSet::getNonDeductibleAmountFromPriceSet($priceSetId, $form->_lineItem);
        }
    
        if (!empty($nonDeductibleAmount)) {
          return $nonDeductibleAmount;
        }
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
        else {
          if ($financialType->is_deductible) {
            if ($online && isset($params['selectProduct'])) {
              $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
            }
            if (!$online && isset($params['product_name'][0])) {
              $selectProduct = $params['product_name'][0];
            }
            // if there is a product - compare the value to the contribution amount
            if (isset($selectProduct) &&
              $selectProduct != 'no_thanks'
            ) {
              $productDAO = new CRM_Contribute_DAO_Product();
              $productDAO->id = $selectProduct;
              $productDAO->find(TRUE);
              // product value exceeds contribution amount
              if ($params['amount'] < $productDAO->price) {
                $nonDeductibleAmount = $params['amount'];
                return $nonDeductibleAmount;
              }
              // product value does NOT exceed contribution amount
              else {
                return $productDAO->price;
              }
            }
            // contribution is deductible - but there is no product
            else {
              return '0.00';
            }
          }
          // contribution is NOT deductible
          else {
            return $params['amount'];
          }
        }
      }
    
      /**
       * Set variables up before form is built.
       */
      public function preProcess() {
        $config = CRM_Core_Config::singleton();
        parent::preProcess();
    
        // lineItem isn't set until Register postProcess
        $this->_lineItem = $this->get('lineItem');
    
        $this->_ccid = $this->get('ccid');
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
        $this->_paymentProcessor = $this->get('paymentProcessor');
        $this->_params = $this->controller->exportValues('Main');
        $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
        $this->_params['amount'] = $this->get('amount');
        if (isset($this->_params['amount'])) {
          $this->setFormAmountFields($this->_params['priceSetId']);
        }
    
        $this->_params['tax_amount'] = $this->get('tax_amount');
        $this->_useForMember = $this->get('useForMember');
    
        if (isset($this->_params['credit_card_exp_date'])) {
          $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
          $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
        }
    
        $this->_params['currencyID'] = $config->defaultCurrency;
    
        if (!empty($this->_membershipBlock)) {
          $this->_params['selectMembership'] = $this->get('selectMembership');
        }
        if (!empty($this->_paymentProcessor) &&  $this->_paymentProcessor['object']->supports('preApproval')) {
          $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
          $this->_params = array_merge($this->_params, $preApprovalParams);
    
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
          // We may have fetched some billing details from the getPreApprovalDetails function so we
          // want to ensure we set this after that function has been called.
          CRM_Core_Payment_Form::mapParams($this->_bltID, $preApprovalParams, $this->_params, FALSE);
        }
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
    
        $this->_params['is_pay_later'] = $this->get('is_pay_later');
        $this->assign('is_pay_later', $this->_params['is_pay_later']);
        if ($this->_params['is_pay_later']) {
    
          $this->assign('pay_later_receipt', CRM_Utils_Array::value('pay_later_receipt', $this->_values));
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
        }
        // if onbehalf-of-organization
        if (!empty($this->_values['onbehalf_profile_id']) && !empty($this->_params['onbehalf']['organization_name'])) {
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
          $this->_params['organization_id'] = CRM_Utils_Array::value('onbehalfof_id', $this->_params);
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
          $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name'];
          $addressBlocks = array(
            'street_address',
            'city',
            'state_province',
            'postal_code',
            'country',
            'supplemental_address_1',
            'supplemental_address_2',
            'supplemental_address_3',
            'postal_code_suffix',
            'geo_code_1',
            'geo_code_2',
            'address_name',
          );
    
          $blocks = array('email', 'phone', 'im', 'url', 'openid');
          foreach ($this->_params['onbehalf'] as $loc => $value) {
            $field = $typeId = NULL;
            if (strstr($loc, '-')) {
              list($field, $locType) = explode('-', $loc);
            }
    
            if (in_array($field, $addressBlocks)) {
              if ($locType == 'Primary') {
                $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
                $locType = $defaultLocationType->id;
              }
    
              if ($field == 'country') {
                $value = CRM_Core_PseudoConstant::countryIsoCode($value);
              }
              elseif ($field == 'state_province') {
                $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
              }
    
              $isPrimary = 1;
              if (isset($this->_params['onbehalf_location']['address'])
                && count($this->_params['onbehalf_location']['address']) > 0
              ) {
                $isPrimary = 0;
              }
    
              $this->_params['onbehalf_location']['address'][$locType][$field] = $value;
              if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) {
                $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
              }
              $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
            }
            elseif (in_array($field, $blocks)) {
              if (!$typeId || is_numeric($typeId)) {
                $blockName = $fieldName = $field;
                $locationType = 'location_type_id';
                if ($locType == 'Primary') {
                  $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
                  $locationValue = $defaultLocationType->id;
                }
                else {
                  $locationValue = $locType;
                }
                $locTypeId = '';
                $phoneExtField = array();
    
                if ($field == 'url') {
                  $blockName = 'website';
                  $locationType = 'website_type_id';
                  list($field, $locationValue) = explode('-', $loc);
                }
                elseif ($field == 'im') {
                  $fieldName = 'name';
                  $locTypeId = 'provider_id';
                  $typeId = $this->_params['onbehalf']["{$loc}-provider_id"];
                }
                elseif ($field == 'phone') {
                  list($field, $locType, $typeId) = explode('-', $loc);
                  $locTypeId = 'phone_type_id';
    
                  //check if extension field exists
                  $extField = str_replace('phone', 'phone_ext', $loc);
                  if (isset($this->_params['onbehalf'][$extField])) {
                    $phoneExtField = array('phone_ext' => $this->_params['onbehalf'][$extField]);
                  }
                }
    
                $isPrimary = 1;
                if (isset ($this->_params['onbehalf_location'][$blockName])
                  && count($this->_params['onbehalf_location'][$blockName]) > 0
                ) {
                  $isPrimary = 0;
                }
                if ($locationValue) {
                  $blockValues = array(
                    $fieldName => $value,
                    $locationType => $locationValue,
                    'is_primary' => $isPrimary,
                  );
    
                  if ($locTypeId) {
                    $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
                  }
                  if (!empty($phoneExtField)) {
                    $blockValues = array_merge($blockValues, $phoneExtField);
                  }
    
                  $this->_params['onbehalf_location'][$blockName][] = $blockValues;
                }
              }
            }
            elseif (strstr($loc, 'custom')) {
              if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) {
                $value = $this->_params['onbehalf']["{$loc}_id"];
              }
              $this->_params['onbehalf_location']["{$loc}"] = $value;
            }
            else {
              if ($loc == 'contact_sub_type') {
                $this->_params['onbehalf_location'][$loc] = $value;
              }
              else {
                $this->_params['onbehalf_location'][$field] = $value;
              }
            }
          }
        }
        elseif (!empty($this->_values['is_for_organization'])) {
          // no on behalf of an organization, CRM-5519
          // so reset loc blocks from main params.
          foreach (array(
                     'phone',
                     'email',
                     'address',
                   ) as $blk) {
            if (isset($this->_params[$blk])) {
              unset($this->_params[$blk]);
            }
          }
        }
        $this->setRecurringMembershipParams();
    
        if ($this->_pcpId) {
          $params = $this->processPcp($this, $this->_params);
          $this->_params = $params;
        }
        $this->_params['invoiceID'] = $this->get('invoiceID');
    
        //carry campaign from profile.
        if (array_key_exists('contribution_campaign_id', $this->_params)) {
          $this->_params['campaign_id'] = $this->_params['contribution_campaign_id'];
        }
    
        // assign contribution page id to the template so we can add css class for it
        $this->assign('contributionPageID', $this->_id);
    
        $this->assign('is_for_organization', CRM_Utils_Array::value('is_for_organization', $this->_params));
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
    
        $this->set('params', $this->_params);
      }
    
      /**
       * Build the form object.
       */
      public function buildQuickForm() {
        $this->assignToTemplate();
    
        $params = $this->_params;
        // make sure we have values for it
    
        if (!empty($this->_values['honoree_profile_id']) && !empty($params['soft_credit_type_id']) && empty($this->_ccid)) {
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
          $honorName = NULL;
          $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
    
          $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
          CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($this, $params['honor']);
    
          $fieldTypes = array('Contact');
          $fieldTypes[] = CRM_Core_BAO_UFGroup::getContactType($this->_values['honoree_profile_id']);
          $this->buildCustom($this->_values['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
        }
        $this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values));
        $amount_block_is_active = $this->get('amount_block_is_active');
        $this->assign('amount_block_is_active', $amount_block_is_active);
    
        $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
        $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
        if ($invoicing) {
          $getTaxDetails = FALSE;
          $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
          foreach ($this->_lineItem as $key => $value) {
            foreach ($value as $v) {
              if (isset($v['tax_rate'])) {
                if ($v['tax_rate'] != '') {
                  $getTaxDetails = TRUE;
                }
              }
            }
          }
          $this->assign('getTaxDetails', $getTaxDetails);
          $this->assign('taxTerm', $taxTerm);
          $this->assign('totalTaxAmount', $params['tax_amount']);
        }
        if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
          $option = CRM_Utils_Array::value('options_' . $params['selectProduct'], $params);
          $productID = $params['selectProduct'];
          CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE,
            $productID, $option
          );
          $this->set('productID', $productID);
          $this->set('option', $option);
        }
        $config = CRM_Core_Config::singleton();
    
        if (in_array('CiviMember', $config->enableComponents) && empty($this->_ccid)) {
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
          if (isset($params['selectMembership']) &&
            $params['selectMembership'] != 'no_thanks'
          ) {
            $this->buildMembershipBlock(
              $this->_membershipContactID,
              FALSE,
              $params['selectMembership'],
              FALSE
            );
            if (!empty($params['auto_renew'])) {
              $this->assign('auto_renew', TRUE);
            }
          }
          else {
            $this->assign('membershipBlock', FALSE);
          }
        }
    
        if (empty($this->_ccid)) {
          $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE);
          $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE);
        }
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
    
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
        if (!empty($this->_values['onbehalf_profile_id']) &&
          !empty($params['onbehalf']) &&
          ($this->_values['is_for_organization'] == 2 ||
            !empty($params['is_for_organization'])
    
          ) && empty($this->_ccid)
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
        ) {
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
          $fieldTypes = array('Contact', 'Organization');
          $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
          $fieldTypes = array_merge($fieldTypes, $contactSubType);
          if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
            $fieldTypes = array_merge($fieldTypes, array('Membership'));
          }
          else {
            $fieldTypes = array_merge($fieldTypes, array('Contribution'));
          }
    
          $this->buildCustom($this->_values['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
        }
    
        $this->_separateMembershipPayment = $this->get('separateMembershipPayment');
        $this->assign('is_separate_payment', $this->_separateMembershipPayment);
        if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
          $this->assign('lineItem', $this->_lineItem);
        }
        else {
          $this->assign('is_quick_config', 1);
          $this->_params['is_quick_config'] = 1;
        }
        $this->assign('priceSetID', $this->_priceSetId);
    
        // The concept of contributeMode is deprecated.
        // the is_monetary concept probably should be too as it can be calculated from
        // the existence of 'amount' & seems fragile.
    
        if ($this->_contributeMode == 'notify' ||
          $this->_amount < 0.0 || $this->_params['is_pay_later'] ||
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
          ($this->_separateMembershipPayment && $this->_amount <= 0.0)
        ) {
          $contribButton = ts('Continue');
          $this->assign('button', ts('Continue'));
        }
    
        elseif (!empty($this->_ccid)) {
          $contribButton = ts('Make Payment');
          $this->assign('button', ts('Make Payment'));
        }
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
        else {
          $contribButton = ts('Make Contribution');
          $this->assign('button', ts('Make Contribution'));
        }
        $this->addButtons(array(
            array(
              'type' => 'next',
              'name' => $contribButton,
              'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
              'isDefault' => TRUE,
              'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
            ),
            array(
              'type' => 'back',
              'name' => ts('Go Back'),
            ),
          )
        );
    
        $defaults = array();
        $fields = array_fill_keys(array_keys($this->_fields), 1);
        $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
    
        $contact = $this->_params;
        foreach ($fields as $name => $dontCare) {
          // Recursively set defaults for nested fields
          if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' || $name == 'honor')) {
            foreach ($contact[$name] as $fieldName => $fieldValue) {
              if (is_array($fieldValue) && !in_array($this->_fields[$name][$fieldName]['html_type'], array(
                  'Multi-Select',
                  'AdvMulti-Select',
                ))
              ) {
                foreach ($fieldValue as $key => $value) {
                  $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
                }
              }
              else {
                $defaults["{$name}[{$fieldName}]"] = $fieldValue;
              }
            }
          }
          elseif (isset($contact[$name])) {
            $defaults[$name] = $contact[$name];
            if (substr($name, 0, 7) == 'custom_') {
              $timeField = "{$name}_time";
              if (isset($contact[$timeField])) {
                $defaults[$timeField] = $contact[$timeField];
              }
              if (isset($contact["{$name}_id"])) {
                $defaults["{$name}_id"] = $contact["{$name}_id"];
              }
            }
            elseif (in_array($name, array(
                'addressee',
                'email_greeting',
                'postal_greeting',
              )) && !empty($contact[$name . '_custom'])
            ) {
              $defaults[$name . '_custom'] = $contact[$name . '_custom'];
            }
          }
        }
    
        $this->assign('useForMember', $this->get('useForMember'));
    
        $this->setDefaults($defaults);
    
        $this->freeze();
      }
    
      /**
       * Overwrite action.
       *
       * Since we are only showing elements in frozen mode no help display needed.
       *
       * @return int
       */
      public function getAction() {
        if ($this->_action & CRM_Core_Action::PREVIEW) {
          return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
        }
        else {
          return CRM_Core_Action::VIEW;
        }
      }
    
      /**
       * Set default values for the form.
       *
       * Note that in edit/view mode
       * the default values are retrieved from the database
       */
      public function setDefaultValues() {
      }
    
      /**
       * Process the form.
       */
      public function postProcess() {
        $contactID = $this->getContactID();
        $result = $this->processFormSubmission($contactID);
        if (is_array($result) && !empty($result['is_payment_failure'])) {
          // We will probably have the function that gets this error throw an exception on the next round of refactoring.
          CRM_Core_Session::singleton()->setStatus(ts("Payment Processor Error message :") .
              $result['error']->getMessage());
          CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact',
            "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
          ));
        }
        // Presumably this is for hooks to access? Not quite clear & perhaps not required.
        $this->set('params', $this->_params);
      }
    
      /**
       * Wrangle financial type ID.
       *
       * This wrangling of the financialType ID was happening in a shared function rather than in the form it relates to & hence has been moved to that form
       * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
       *
       * Comments from previous refactor indicate doubt as to what was going on.
       *
       * @param int $contributionTypeId
       *
       * @return null|string
       */
      public function wrangleFinancialTypeID($contributionTypeId) {
        if (isset($paymentParams['financial_type'])) {
          $contributionTypeId = $paymentParams['financial_type'];
        }
        elseif (!empty($this->_values['pledge_id'])) {
          $contributionTypeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
            $this->_values['pledge_id'],
            'financial_type_id'
          );
        }
        return $contributionTypeId;
      }
    
      /**
       * Process the form.
       *
       * @param array $premiumParams
       * @param CRM_Contribute_BAO_Contribution $contribution
       */
      protected function postProcessPremium($premiumParams, $contribution) {
        $hour = $minute = $second = 0;
        // assigning Premium information to receipt tpl
        $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
        if ($selectProduct &&
          $selectProduct != 'no_thanks'
        ) {
          $startDate = $endDate = "";
          $this->assign('selectPremium', TRUE);
          $productDAO = new CRM_Contribute_DAO_Product();
          $productDAO->id = $selectProduct;
          $productDAO->find(TRUE);
          $this->assign('product_name', $productDAO->name);
          $this->assign('price', $productDAO->price);
          $this->assign('sku', $productDAO->sku);
          $this->assign('option', CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams));
    
          $periodType = $productDAO->period_type;
    
          if ($periodType) {
            $fixed_period_start_day = $productDAO->fixed_period_start_day;
            $duration_unit = $productDAO->duration_unit;
            $duration_interval = $productDAO->duration_interval;
            if ($periodType == 'rolling') {
              $startDate = date('Y-m-d');
            }
            elseif ($periodType == 'fixed') {
              if ($fixed_period_start_day) {
                $date = explode('-', date('Y-m-d'));
                $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
                $day = substr($fixed_period_start_day, -2) . "<br/>";
                $year = $date[0];
                $startDate = $year . '-' . $month . '-' . $day;
              }
              else {
                $startDate = date('Y-m-d');
              }
            }
    
            $date = explode('-', $startDate);
            $year = $date[0];
            $month = $date[1];
            $day = $date[2];
    
            switch ($duration_unit) {
              case 'year':
                $year = $year + $duration_interval;
                break;
    
              case 'month':
                $month = $month + $duration_interval;
                break;
    
              case 'day':
                $day = $day + $duration_interval;
                break;
    
              case 'week':
                $day = $day + ($duration_interval * 7);
            }
            $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
            $this->assign('start_date', $startDate);
            $this->assign('end_date', $endDate);
          }
    
          $dao = new CRM_Contribute_DAO_Premium();
          $dao->entity_table = 'civicrm_contribution_page';
          $dao->entity_id = $this->_id;
          $dao->find(TRUE);
          $this->assign('contact_phone', $dao->premiums_contact_phone);
          $this->assign('contact_email', $dao->premiums_contact_email);
    
          //create Premium record
          $params = array(
            'product_id' => $premiumParams['selectProduct'],
            'contribution_id' => $contribution->id,
            'product_option' => CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams),
            'quantity' => 1,
            'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
            'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
          );
          if (!empty($premiumParams['selectProduct'])) {
            $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
            $daoPremiumsProduct->product_id = $premiumParams['selectProduct'];
            $daoPremiumsProduct->premiums_id = $dao->id;
            $daoPremiumsProduct->find(TRUE);
            $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id;
          }
          //Fixed For CRM-3901
          $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
          $daoContrProd->contribution_id = $contribution->id;
          if ($daoContrProd->find(TRUE)) {
            $params['id'] = $daoContrProd->id;
          }
    
          CRM_Contribute_BAO_Contribution::addPremium($params);
          if ($productDAO->cost && !empty($params['financial_type_id'])) {
            $trxnParams = array(
              'cost' => $productDAO->cost,
              'currency' => $productDAO->currency,
              'financial_type_id' => $params['financial_type_id'],
              'contributionId' => $contribution->id,
            );
            CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
          }
        }
        elseif ($selectProduct == 'no_thanks') {
          //Fixed For CRM-3901
          $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
          $daoContrProd->contribution_id = $contribution->id;
          if ($daoContrProd->find(TRUE)) {
            $daoContrProd->delete();
          }
        }
      }
    
      /**
       * Process the contribution.
       *
       * @param CRM_Core_Form $form
       * @param array $params
       * @param array $result
       * @param array $contributionParams
       *   Parameters to be passed to contribution create action.
       *   This differs from params in that we are currently adding params to it and 1) ensuring they are being
       *   passed consistently & 2) documenting them here.
       *   - contact_id
       *   - line_item
       *   - is_test
       *   - campaign_id
       *   - contribution_page_id
       *   - source
       *   - payment_type_id
       *   - thankyou_date (not all forms will set this)
       *
       * @param CRM_Financial_DAO_FinancialType $financialType
       * @param bool $online
       *   Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
       *
       * @param int $billingLocationID
       *   ID of billing location type.
       * @param bool $isRecur
       *   Is this recurring?
       *
       * @return \CRM_Contribute_DAO_Contribution
       * @throws \Exception
       */
      public static function processFormContribution(
        &$form,
        $params,
        $result,
        $contributionParams,
        $financialType,
        $online,
        $billingLocationID,
        $isRecur
      ) {
        $transaction = new CRM_Core_Transaction();
        $contactID = $contributionParams['contact_id'];
    
        $isEmailReceipt = !empty($form->_values['is_email_receipt']);
        $isSeparateMembershipPayment = empty($params['separate_membership_payment']) ? FALSE : TRUE;
        $pledgeID = !empty($params['pledge_id']) ? $params['pledge_id'] : CRM_Utils_Array::value('pledge_id', $form->_values);
        if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) &&
          (!empty($params['is_pledge']) || $pledgeID)) {
          $isPledge = TRUE;
        }
        else {
          $isPledge = FALSE;
        }
    
        // add these values for the recurringContrib function ,CRM-10188
        $params['financial_type_id'] = $financialType->id;
    
        $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID);
    
        //@todo - this is being set from the form to resolve CRM-10188 - an
        // eNotice caused by it not being set @ the front end
        // however, we then get it being over-written with null for backend contributions
        // a better fix would be to set the values in the respective forms rather than require
        // a function being shared by two forms to deal with their respective values
        // moving it to the BAO & not taking the $form as a param would make sense here.
        if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
          $params['is_email_receipt'] = $isEmailReceipt;
        }
        $params['is_recur'] = $isRecur;
    
        $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'];
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
        $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType);
    
        $nonDeductibleAmount = self::getNonDeductibleAmount($params, $financialType, $online, $form);
    
    Kevin Cristiano's avatar
    Kevin Cristiano committed
    
        $now = date('YmdHis');
        $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
        if ($isEmailReceipt) {
          $receiptDate = $now;
        }
    
        if (isset($params['amount'])) {
          $contributionParams = array_merge(self::getContributionParams(
            $params, $financialType->id, $nonDeductibleAmount, TRUE,
            $result, $receiptDate,
            $recurringContributionID), $contributionParams
          );
          $contribution = CRM_Contribute_BAO_Contribution::add($contributionParams);
    
          $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
          $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
          if ($invoicing) {
            $dataArray = array();
            // @todo - interrogate the line items passed in on the params array.
            // No reason to assume line items will be set on the form.
            foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
              foreach ($lineItemValue as $key => $value) {
                if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
                  if (isset($dataArray[$value['tax_rate']])) {
                    $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                  }
                  else {
                    $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                  }
                }
              }
            }
            $smarty = CRM_Core_Smarty::singleton();
            $smarty->assign('dataArray', $dataArray);
            $smarty->assign('totalTaxAmount', $params['tax_amount']);
          }
          if (is_a($contribution, 'CRM_Core_Error')) {
            $message = CRM_Core_Error::getMessages($contribution);
            CRM_Core_Error::fatal($message);
          }
    
          // lets store it in the form variable so postProcess hook can get to this and use it
          $form->_contributionID = $contribution->id;
        }
    
        // process soft credit / pcp params first
        CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
    
        //CRM-13981, processing honor contact into soft-credit contribution
        CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);