/** * Set default values for the form. Note that in edit/view mode * the default values are retrieved from the database * * * @return void */ public function setDefaultValues() { $defaults = array(); if ($this->_pid) { $dao = new CRM_Contribute_DAO_PremiumsProduct(); $dao->id = $this->_pid; $dao->find(TRUE); $defaults['product_id'] = $dao->product_id; $defaults['financial_type_id'] = $dao->financial_type_id; $defaults['weight'] = $dao->weight; } else { $dao = new CRM_Contribute_DAO_Product(); $dao->id = key($this->_products); $dao->find(TRUE); $defaults['financial_type_id'] = $dao->financial_type_id; } if (!isset($defaults['weight']) || !$defaults['weight']) { $pageID = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0); $dao = new CRM_Contribute_DAO_Premium(); $dao->entity_table = 'civicrm_contribution_page'; $dao->entity_id = $pageID; $dao->find(TRUE); $premiumID = $dao->id; $sql = 'SELECT max( weight ) as max_weight FROM civicrm_premiums_product WHERE premiums_id = %1'; $params = array(1 => array($premiumID, 'Integer')); $dao = CRM_Core_DAO::executeQuery($sql, $params); $dao->fetch(); $defaults['weight'] = $dao->max_weight + 1; } return $defaults; }
/** * Takes a bunch of params that are needed to match certain criteria and * retrieves the relevant objects. Typically the valid params are only * contact_id. We'll tweak this function to be more full featured over a period * of time. This is the inverse function of create. It also stores all the retrieved * values in the default array * * @param array $params (reference ) an assoc array of name/value pairs * @param array $defaults (reference ) an assoc array to hold the flattened values * * @return object CRM_Contribute_BAO_ManagePremium object * @access public * @static */ static function retrieve(&$params, &$defaults) { $premium = new CRM_Contribute_DAO_Product(); $premium->copyValues($params); if ($premium->find(TRUE)) { $premium->product_name = $premium->name; CRM_Core_DAO::storeValues($premium, $defaults); return $premium; } return NULL; }
/** * Retrieve premium product and their options. * * @return array * product and option arrays */ public static function getPremiumProductInfo() { if (!self::$productInfo) { $products = $options = array(); $dao = new CRM_Contribute_DAO_Product(); $dao->is_active = 1; $dao->find(); while ($dao->fetch()) { $products[$dao->id] = $dao->name . " ( " . $dao->sku . " )"; $opts = explode(',', $dao->options); foreach ($opts as $k => $v) { $ops[$k] = trim($v); } if ($ops[0] != '') { $options[$dao->id] = $opts; } } self::$productInfo = array($products, $options); } return self::$productInfo; }
/** * * @return void * @access public * @static */ function browse() { // get all custom groups sorted by weight $premiums = array(); require_once 'CRM/Contribute/DAO/Product.php'; $pageID = CRM_Utils_Request::retrieve('id', 'Positive', $this, false, 0); $dao = new CRM_Contribute_DAO_Premium(); $dao->entity_table = 'civicrm_contribution_page'; $dao->entity_id = $pageID; $dao->find(true); $premiumID = $dao->id; $this->assign('products', false); if (!$premiumID) { return; } require_once 'CRM/Contribute/DAO/PremiumsProduct.php'; $dao = new CRM_Contribute_DAO_PremiumsProduct(); $dao->premiums_id = $premiumID; $dao->orderBy('weight'); $dao->find(); while ($dao->fetch()) { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $dao->product_id; $productDAO->is_active = 1; if ($productDAO->find(true)) { $premiums[$productDAO->id] = array(); $premiums[$productDAO->id]['weight'] = $dao->weight; CRM_Core_DAO::storeValues($productDAO, $premiums[$productDAO->id]); $action = array_sum(array_keys($this->links())); $premiums[$dao->product_id]['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $pageID, 'pid' => $dao->id)); } } require_once 'CRM/Contribute/PseudoConstant.php'; if (count(CRM_Contribute_PseudoConstant::products($pageID)) == 0) { $this->assign('products', false); } else { $this->assign('products', true); } // Add order changing widget to selector $returnURL = CRM_Utils_System::url('civicrm/admin/contribute/premium', "reset=1&action=update&id={$pageID}"); $filter = "premiums_id = {$premiumID}"; require_once 'CRM/Utils/Weight.php'; CRM_Utils_Weight::addOrder($premiums, 'CRM_Contribute_DAO_PremiumsProduct', 'id', $returnURL, $filter); $this->assign('rows', $premiums); }
/** * Calculate non deductible amount. * * CRM-11956 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] - * if non_deductible_amount does NOT exist - then calculate it depending on: * $financialType->is_deductible and whether there is a product (premium). * * @param $params * @param $formValues * * @return array */ protected function calculateNonDeductibleAmount($params, $formValues) { if (!empty($params['non_deductible_amount'])) { return $params['non_deductible_amount']; } $financialType = new CRM_Financial_DAO_FinancialType(); $financialType->id = $params['financial_type_id']; $financialType->find(TRUE); if ($financialType->is_deductible) { if (isset($formValues['product_name'][0])) { $selectProduct = $formValues['product_name'][0]; } // if there is a product - compare the value to the contribution amount if (isset($selectProduct)) { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $selectProduct; $productDAO->find(TRUE); // product value exceeds contribution amount if ($params['total_amount'] < $productDAO->price) { return $params['total_amount']; } else { return $productDAO->price; } } else { return '0.00'; } } else { return $params['total_amount']; } return 0; }
/** * 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(); } } }
/** * Browse function. */ public function browse() { // get all custom groups sorted by weight $premiums = array(); $pageID = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0); $dao = new CRM_Contribute_DAO_Premium(); $dao->entity_table = 'civicrm_contribution_page'; $dao->entity_id = $pageID; $dao->find(TRUE); $premiumID = $dao->id; $this->assign('products', FALSE); $this->assign('id', $pageID); if (!$premiumID) { return; } $dao = new CRM_Contribute_DAO_PremiumsProduct(); $dao->premiums_id = $premiumID; $dao->orderBy('weight'); $dao->find(); while ($dao->fetch()) { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $dao->product_id; $productDAO->is_active = 1; if ($productDAO->find(TRUE)) { $premiums[$productDAO->id] = array(); $premiums[$productDAO->id]['weight'] = $dao->weight; CRM_Core_DAO::storeValues($productDAO, $premiums[$productDAO->id]); $action = array_sum(array_keys($this->links())); $premiums[$dao->product_id]['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $pageID, 'pid' => $dao->id), ts('more'), FALSE, 'premium.contributionpage.row', 'Premium', $dao->id); //Financial Type if (!empty($dao->financial_type_id)) { $premiums[$productDAO->id]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $dao->financial_type_id, 'name'); } } } if (count(CRM_Contribute_PseudoConstant::products($pageID)) == 0) { $this->assign('products', FALSE); } else { $this->assign('products', TRUE); } // Add order changing widget to selector $returnURL = CRM_Utils_System::url('civicrm/admin/contribute/premium', "reset=1&action=update&id={$pageID}"); $filter = "premiums_id = {$premiumID}"; CRM_Utils_Weight::addOrder($premiums, 'CRM_Contribute_DAO_PremiumsProduct', 'id', $returnURL, $filter); $this->assign('rows', $premiums); }
/** * Process the contribution * * @param $form * @param $params * @param $result * @param $contactID * @param $contributionType * @param bool $deductibleMode * @param bool $pending * @param bool $online * * @return CRM_Contribute_DAO_Contribution * @access public */ static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = TRUE, $pending = FALSE, $online = TRUE) { $transaction = new CRM_Core_Transaction(); $className = get_class($form); $recurringContributionID = NULL; // add these values for the recurringContrib function ,CRM-10188 $params['financial_type_id'] = $contributionType->id; //@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'])) { $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $form->_values); } $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online); $config = CRM_Core_Config::singleton(); // CRM-11885 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it. if (isset($params['non_deductible_amount']) && !empty($params['non_deductible_amount'])) { $nonDeductibleAmount = $params['non_deductible_amount']; } else { //if ($contributionType->is_deductible && $deductibleMode) { if ($contributionType->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']; } else { $nonDeductibleAmount = $productDAO->price; } } else { $nonDeductibleAmount = '0.00'; } } else { $nonDeductibleAmount = $params['amount']; } } $now = date('YmdHis'); $receiptDate = CRM_Utils_Array::value('receipt_date', $params); if (!empty($form->_values['is_email_receipt'])) { $receiptDate = $now; } //get the contrib page id. $campaignId = $contributionPageId = NULL; if ($online) { $contributionPageId = $form->_id; $campaignId = CRM_Utils_Array::value('campaign_id', $params); if (!array_key_exists('campaign_id', $params)) { $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values); } } else { //also for offline we do support - CRM-7290 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params); $campaignId = CRM_Utils_Array::value('campaign_id', $params); } // first create the contribution record $contribParams = array('contact_id' => $contactID, 'financial_type_id' => $contributionType->id, 'contribution_page_id' => $contributionPageId, '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'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || !empty($params['source']) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), '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, 'campaign_id' => $campaignId); if (!$online && isset($params['thankyou_date'])) { $contribParams['thankyou_date'] = $params['thankyou_date']; } if (!$online || $form->_values['is_monetary']) { if (empty($params['is_pay_later'])) { $contribParams['payment_instrument_id'] = 1; } } if (!$pending && $result) { $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $result), 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result)); } if ($recurringContributionID) { $contribParams['contribution_recur_id'] = $recurringContributionID; } $contribParams['contribution_status_id'] = $pending ? 2 : 1; $contribParams['is_test'] = 0; if ($form->_mode == 'test') { $contribParams['is_test'] = 1; } $ids = array(); if (isset($contribParams['invoice_id'])) { $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id'); if (isset($contribID)) { $ids['contribution'] = $contribID; $contribParams['id'] = $contribID; } } //create an contribution address if ($form->_contributeMode != 'notify' && empty($params['is_pay_later']) && !empty($form->_values['is_monetary'])) { $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID); } // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' ')); $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' ')); // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin. if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) { // if its due to pcp if (!empty($params['pcp_made_through_id'])) { $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id'); } else { $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params); } // Pass these details onto with the contribution to make them // available at hook_post_process, CRM-8908 $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId; } if (isset($params['amount'])) { $contribParams['line_item'] = $form->_lineItem; //add contribution record $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids); 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; } //CRM-13981, processing honor contact into soft-credit contribution CRM_Contact_Form_ProfileContact::postProcess($form); // process soft credit / pcp pages CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution); //handle pledge stuff. if (empty($form->_params['separate_membership_payment']) && !empty($form->_values['pledge_block_id']) && (!empty($form->_params['is_pledge']) || !empty($form->_values['pledge_id']))) { if (!empty($form->_values['pledge_id'])) { //when user doing pledge payments. //update the schedule when payment(s) are made foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) { $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id'); $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount); CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams); } //update pledge status according to the new payment statuses CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']); } 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"); $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'] = $campaignId; $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams); $form->_params['pledge_id'] = $pledge->id; //send acknowledgment email. only when pledge is created if ($pledge->id) { //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); } } } if ($online && $contribution) { CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution'); } elseif ($contribution) { //handle custom data. $params['contribution_id'] = $contribution->id; if (!empty($params['custom']) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) { CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id); } } // Save note if ($contribution && !empty($params['contribution_note'])) { $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['contribution_note'], 'entity_id' => $contribution->id, 'contact_id' => $contribution->contact_id, 'modified_date' => date('Ymd')); CRM_Core_BAO_Note::add($noteParams, array()); } if (isset($params['related_contact'])) { $contactID = $params['related_contact']; } elseif (isset($params['cms_contactID'])) { $contactID = $params['cms_contactID']; } //create contribution activity w/ individual and target //activity w/ organisation contact id when onbelf, CRM-4027 $targetContactID = NULL; if (!empty($params['hidden_onbehalf_profile'])) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $contactID; } // create an activity record if ($contribution) { CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); } $transaction->commit(); // CRM-13074 - create the CMSUser after the transaction is completed as it // is not appropriate to delete a valid contribution if a user create problem occurs CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID); return $contribution; }
/** * Calculate non deductible amount. * * CRM-11956 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] - * if non_deductible_amount does NOT exist - then calculate it depending on: * $financialType->is_deductible and whether there is a product (premium). * * @param $params * @param $formValues * * @return array */ protected function calculateNonDeductibleAmount($params, $formValues) { if (!empty($params['non_deductible_amount'])) { return $params['non_deductible_amount']; } $priceSetId = CRM_Utils_Array::value('price_set_id', $params); // return non-deductible amount if it is set at the price field option level if ($priceSetId && !empty($params['line_item'])) { $nonDeductibleAmount = CRM_Price_BAO_PriceSet::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']); if (!empty($nonDeductibleAmount)) { return $nonDeductibleAmount; } } $financialType = new CRM_Financial_DAO_FinancialType(); $financialType->id = $params['financial_type_id']; $financialType->find(TRUE); if ($financialType->is_deductible) { if (isset($formValues['product_name'][0])) { $selectProduct = $formValues['product_name'][0]; } // if there is a product - compare the value to the contribution amount if (isset($selectProduct)) { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $selectProduct; $productDAO->find(TRUE); // product value exceeds contribution amount if ($params['total_amount'] < $productDAO->price) { return $params['total_amount']; } else { return $productDAO->price; } } else { return '0.00'; } } else { return $params['total_amount']; } return 0; }
function sendMail(&$input, &$ids, &$objects, &$values, $recur = false, $returnMessageText = false) { $contribution =& $objects['contribution']; $membership =& $objects['membership']; $participant =& $objects['participant']; $event =& $objects['event']; if (empty($values)) { $values = array(); $contribID = $ids['contribution']; if ($input['component'] == 'contribute') { require_once 'CRM/Contribute/BAO/ContributionPage.php'; if (isset($contribution->contribution_page_id)) { CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values); } else { // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id) $values['is_email_receipt'] = 1; $values['title'] = 'Contribution'; } // set lineItem for contribution require_once 'CRM/Price/BAO/Set.php'; if ($contribID && ($pId = CRM_Price_BAO_Set::getFor('civicrm_contribution', $contribID))) { require_once 'CRM/Price/BAO/LineItem.php'; $values['lineItem'][0] = CRM_Price_BAO_LineItem::getLineItems($contribID, 'contribution'); $values['priceSetID'] = $pId; } require_once 'CRM/Contribute/BAO/Contribution.php'; $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds($contribID, $contribution->contact_id); // if this is onbehalf of contribution then set related contact if ($relatedContactId = $relatedContact['individual_id']) { $values['related_contact'] = $ids['related_contact'] = $relatedContactId; } } else { // event $eventParams = array('id' => $objects['event']->id); $values['event'] = array(); require_once 'CRM/Event/BAO/Event.php'; CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); //get location details $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event'); require_once 'CRM/Core/BAO/Location.php'; require_once 'CRM/Event/Form/ManageEvent/Location.php'; $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); require_once 'CRM/Core/BAO/UFJoin.php'; $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'weight' => 1); $values['custom_pre_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams); $ufJoinParams['weight'] = 2; $values['custom_post_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams); // set lineItem for event contribution if ($contribID) { require_once 'CRM/Event/BAO/Participant.php'; $participantIds = CRM_Event_BAO_Participant::getParticipantIds($contribID); require_once 'CRM/Price/BAO/LineItem.php'; if (!empty($participantIds)) { foreach ($participantIds as $pIDs) { $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs); if (!CRM_Utils_System::isNull($lineItem)) { $values['lineItem'][] = $lineItem; } } } } } // set receipt from e-mail and name in value if (!$returnMessageText) { require_once 'CRM/Contact/BAO/Contact/Location.php'; $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID); $values['receipt_from_email'] = $userEmail; $values['receipt_from_name'] = $userName; } // set display address of contributor if ($contribution->address_id) { require_once 'CRM/Core/BAO/Address.php'; $addressParams = array('id' => $contribution->address_id); $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, false, 'id'); $addressDetails = array_values($addressDetails); $values['address'] = $addressDetails[0]['display']; } } $template =& CRM_Core_Smarty::singleton(); // CRM_Core_Error::debug('tpl',$template); //assign honor infomation to receiptmessage if ($honarID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'honor_contact_id')) { $honorDefault = array(); $honorIds = array(); $honorIds['contribution'] = $contribution->id; $idParams = array('id' => $honarID, 'contact_id' => $honarID); require_once "CRM/Contact/BAO/Contact.php"; CRM_Contact_BAO_Contact::retrieve($idParams, $honorDefault, $honorIds); require_once "CRM/Core/PseudoConstant.php"; $honorType = CRM_Core_PseudoConstant::honor(); $prefix = CRM_Core_PseudoConstant::individualPrefix(); $template->assign('honor_block_is_active', 1); $template->assign('honor_prefix', $prefix[$honorDefault["prefix_id"]]); $template->assign('honor_first_name', CRM_Utils_Array::value("first_name", $honorDefault)); $template->assign('honor_last_name', CRM_Utils_Array::value("last_name", $honorDefault)); $template->assign('honor_email', CRM_Utils_Array::value("email", $honorDefault["email"][1])); $template->assign('honor_type', $honorType[$contribution->honor_type_id]); } require_once 'CRM/Contribute/DAO/ContributionProduct.php'; $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->contribution_id = $contribution->id; if ($dao->find(true)) { $premiumId = $dao->product_id; $template->assign('option', $dao->product_option); require_once 'CRM/Contribute/DAO/Product.php'; $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $premiumId; $productDAO->find(true); $template->assign('selectPremium', true); $template->assign('product_name', $productDAO->name); $template->assign('price', $productDAO->price); $template->assign('sku', $productDAO->sku); } // add the new contribution values if ($input['component'] == 'contribute') { $template->assign('title', $values['title']); $template->assign('amount', $input['amount']); //PCP Info require_once 'CRM/Contribute/DAO/ContributionSoft.php'; $softDAO = new CRM_Contribute_DAO_ContributionSoft(); $softDAO->contribution_id = $contribution->id; if ($softDAO->find(true)) { $template->assign('pcpBlock', true); $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll); $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname); $template->assign('pcp_personal_note', $softDAO->pcp_personal_note); //assign the pcp page title for email subject require_once 'CRM/Contribute/DAO/PCP.php'; $pcpDAO = new CRM_Contribute_DAO_PCP(); $pcpDAO->id = $softDAO->pcp_id; if ($pcpDAO->find(true)) { $template->assign('title', $pcpDAO->title); } } } else { $template->assign('title', $values['event']['title']); $template->assign('totalAmount', $input['amount']); } if ($contribution->contribution_type_id) { $values['contribution_type_id'] = $contribution->contribution_type_id; } $template->assign('trxn_id', $contribution->trxn_id); $template->assign('receive_date', CRM_Utils_Date::mysqlToIso($contribution->receive_date)); $template->assign('contributeMode', 'notify'); $template->assign('action', $contribution->is_test ? 1024 : 1); $template->assign('receipt_text', CRM_Utils_Array::value('receipt_text', $values)); $template->assign('is_monetary', 1); $template->assign('is_recur', $recur); $template->assign('currency', $contribution->currency); if ($recur) { require_once 'CRM/Core/Payment.php'; $paymentObject =& CRM_Core_Payment::singleton($contribution->is_test ? 'test' : 'live', $objects['paymentProcessor']); if (!empty($membership) && $membership->id) { $url = $paymentObject->cancelSubscriptionURL($membership->id, 'membership'); } else { $url = $paymentObject->cancelSubscriptionURL(); } $template->assign('cancelSubscriptionUrl', $url); if ($objects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) { //direct mode showing billing block, so use directIPN for temporary $template->assign('contributeMode', 'directIPN'); } } require_once 'CRM/Utils/Address.php'; $template->assign('address', CRM_Utils_Address::format($input)); if ($input['component'] == 'event') { require_once 'CRM/Core/OptionGroup.php'; $participant_role = CRM_Core_OptionGroup::values('participant_role'); $values['event']['participant_role'] = $participant_role[$participant->role_id]; $template->assign('event', $values['event']); $template->assign('location', $values['location']); $template->assign('customPre', $values['custom_pre_id']); $template->assign('customPost', $values['custom_post_id']); $isTest = false; if ($participant->is_test) { $isTest = true; } $values['params'] = array(); require_once "CRM/Event/BAO/Event.php"; //to get email of primary participant. $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $participant->contact_id, 'email', 'contact_id'); $primaryAmount[] = array('label' => $participant->fee_level . ' - ' . $primaryEmail, 'amount' => $participant->fee_amount); //build an array of cId/pId of participants $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($participant->id, null, $ids['contact'], $isTest, true); unset($additionalIDs[$participant->id]); //send receipt to additional participant if exists if (count($additionalIDs)) { $template->assign('isPrimary', 0); $template->assign('customProfile', null); //set additionalParticipant true $values['params']['additionalParticipant'] = true; foreach ($additionalIDs as $pId => $cId) { $amount = array(); //to change the status pending to completed $additional = new CRM_Event_DAO_Participant(); $additional->id = $pId; $additional->contact_id = $cId; $additional->find(true); $additional->register_date = $participant->register_date; $additional->status_id = 1; $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id'); //if additional participant dont have email //use display name. if (!$additionalParticipantInfo) { require_once "CRM/Contact/BAO/Contact.php"; $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id); } $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount); $primaryAmount[] = array('label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount); $additional->save(); $additional->free(); $template->assign('amount', $amount); CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText); } } //build an array of custom profile and assigning it to template $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participant->id, $values, null, $isTest); if (count($customProfile)) { $template->assign('customProfile', $customProfile); } // for primary contact $values['params']['additionalParticipant'] = false; $template->assign('isPrimary', 1); $template->assign('amount', $primaryAmount); $template->assign('register_date', CRM_Utils_Date::isoToMysql($participant->register_date)); if ($contribution->payment_instrument_id) { require_once 'CRM/Contribute/PseudoConstant.php'; $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $template->assign('paidBy', $paymentInstrument[$contribution->payment_instrument_id]); } // carry paylater, since we did not created billing, // so need to pull email from primary location, CRM-4395 $values['params']['is_pay_later'] = $participant->is_pay_later; return CRM_Event_BAO_Event::sendMail($ids['contact'], $values, $participant->id, $isTest, $returnMessageText); } else { if ($membership) { $values['membership_id'] = $membership->id; // need to set the membership values here $template->assign('membership_assign', 1); require_once 'CRM/Member/PseudoConstant.php'; $template->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)); $template->assign('mem_start_date', $membership->start_date); $template->assign('mem_end_date', $membership->end_date); // if separate payment there are two contributions recorded and the // admin will need to send a receipt for each of them separately. // we dont link the two in the db (but can potentially infer it if needed) $template->assign('is_separate_payment', 0); } $values['contribution_id'] = $contribution->id; if (CRM_Utils_Array::value('related_contact', $ids)) { $values['related_contact'] = $ids['related_contact']; if (isset($ids['onbehalf_dupe_alert'])) { $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert']; } require_once 'CRM/Core/BAO/Address.php'; $entityBlock = array('contact_id' => $ids['contact'], 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Home', 'id', 'name')); $address = CRM_Core_BAO_Address::getValues($entityBlock); $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']); } $isTest = false; if ($contribution->is_test) { $isTest = true; } // CRM_Core_Error::debug('val',$values); require_once 'CRM/Contribute/BAO/ContributionPage.php'; return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText); } }
/** * Process the contribution * * @return void * @access public */ static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = TRUE, $pending = FALSE, $online = TRUE) { $transaction = new CRM_Core_Transaction(); $className = get_class($form); $honorCId = $recurringContributionID = NULL; if ($online && $form->get('honor_block_is_active')) { $honorCId = $form->createHonorContact(); } // add these values for the recurringContrib function ,CRM-10188 $params['contribution_type_id'] = $contributionType->id; $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $form->_values); $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online); if (!$online && isset($params['honor_contact_id'])) { $honorCId = $params['honor_contact_id']; } $config = CRM_Core_Config::singleton(); if (!$online && isset($params['non_deductible_amount'])) { $nonDeductibleAmount = $params['non_deductible_amount']; } else { $nonDeductibleAmount = $params['amount']; } if ($online && $contributionType->is_deductible && $deductibleMode) { $selectProduct = CRM_Utils_Array::value('selectProduct', $params); if ($selectProduct && $selectProduct != 'no_thanks') { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $selectProduct; $productDAO->find(TRUE); if ($params['amount'] < $productDAO->price) { $nonDeductibleAmount = $params['amount']; } else { $nonDeductibleAmount = $productDAO->price; } } else { $nonDeductibleAmount = '0.00'; } } $now = date('YmdHis'); $receiptDate = CRM_Utils_Array::value('receipt_date', $params); if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) { $receiptDate = $now; } //get the contrib page id. $campaignId = $contributionPageId = NULL; if ($online) { $contributionPageId = $form->_id; $campaignId = CRM_Utils_Array::value('campaign_id', $params); if (!array_key_exists('campaign_id', $params)) { $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values); } } else { //also for offline we do support - CRM-7290 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params); $campaignId = CRM_Utils_Array::value('campaign_id', $params); } // first create the contribution record $contribParams = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'contribution_page_id' => $contributionPageId, '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'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || CRM_Utils_Array::value('source', $params) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), '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, 'campaign_id' => $campaignId); if (!$online && isset($params['thankyou_date'])) { $contribParams['thankyou_date'] = $params['thankyou_date']; } if (!$online || $form->_values['is_monetary']) { if (!CRM_Utils_Array::value('is_pay_later', $params)) { $contribParams['payment_instrument_id'] = 1; } } if (!$pending && $result) { $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $result), 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result)); } if (isset($honorCId)) { $contribParams['honor_contact_id'] = $honorCId; $contribParams['honor_type_id'] = $params['honor_type_id']; } if ($recurringContributionID) { $contribParams['contribution_recur_id'] = $recurringContributionID; } $contribParams['contribution_status_id'] = $pending ? 2 : 1; $contribParams['is_test'] = 0; if ($form->_mode == 'test') { $contribParams['is_test'] = 1; } $ids = array(); if (isset($contribParams['invoice_id'])) { $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id'); if (isset($contribID)) { $ids['contribution'] = $contribID; $contribParams['id'] = $contribID; } } //create an contribution address if ($form->_contributeMode != 'notify' && !CRM_Utils_Array::value('is_pay_later', $params) && CRM_Utils_Array::value('is_monetary', $form->_values)) { $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID); } // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' ')); $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' ')); // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin. if (CRM_Utils_Array::value('pcp_made_through_id', $params) || CRM_Utils_Array::value('soft_credit_to', $params)) { // if its due to pcp if (CRM_Utils_Array::value('pcp_made_through_id', $params)) { $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id'); } else { $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params); } // Pass these details onto with the contribution to make them // available at hook_post_process, CRM-8908 $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId; } if ($params['amount']) { //add contribution record $contribution =& CRM_Contribute_BAO_Contribution::add($contribParams, $ids); } // process soft credit / pcp pages CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution); // process price set, CRM-5095 if ($contribution && $contribution->id && $form->_priceSetId) { if (CRM_Utils_Array::value('is_quick_config', $form->_params)) { $temp = array(); foreach ($form->_lineItem as $key => $val) { foreach ($val as $k => $v) { if (CRM_Utils_Money::format($v['line_total']) == CRM_Utils_Money::format($contribution->total_amount)) { $temp[$key][$k] = $form->_lineItem[$key][$k]; CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $temp); } } } } elseif (!CRM_Utils_Array::value('is_quick_config', $form->_params)) { CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $form->_lineItem); } if (!$form->_separateMembershipPayment && CRM_Utils_Array::value('is_quick_config', $form->_params)) { $form->_lineItem = null; } } //handle pledge stuff. if (!CRM_Utils_Array::value('separate_membership_payment', $form->_params) && CRM_Utils_Array::value('pledge_block_id', $form->_values) && (CRM_Utils_Array::value('is_pledge', $form->_params) || CRM_Utils_Array::value('pledge_id', $form->_values))) { if (CRM_Utils_Array::value('pledge_id', $form->_values)) { //when user doing pledge payments. //update the schedule when payment(s) are made foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) { $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id'); $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount); CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams); } //update pledge status according to the new payment statuses CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']); } 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['contribution_type_id'] = $contribution->contribution_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"); $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'] = $campaignId; $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams); $form->_params['pledge_id'] = $pledge->id; //send acknowledgment email. only when pledge is created if ($pledge->id) { //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); } } } if ($online && $contribution) { CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution'); } elseif ($contribution) { //handle custom data. $params['contribution_id'] = $contribution->id; if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) { CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id); } } if (isset($params['related_contact'])) { $contactID = $params['related_contact']; } elseif (isset($params['cms_contactID'])) { $contactID = $params['cms_contactID']; } CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID); // return if pending if ($pending) { return $contribution; } // next create the transaction record if ($contribution && (!$online || $form->_values['is_monetary']) && $result['trxn_id']) { $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'currency' => $params['currencyID'], 'payment_processor' => $form->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id'], 'trxn_result_code' => isset($result['trxn_result_code']) ? $result['trxn_result_code'] : FALSE); $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams); } //create contribution activity w/ individual and target //activity w/ organisation contact id when onbelf, CRM-4027 $targetContactID = NULL; if (CRM_Utils_Array::value('hidden_onbehalf_profile', $params)) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $contactID; } // create an activity record if ($contribution) { CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); } $transaction->commit(); return $contribution; }
/** * global form rule * * @param array $fields the input form values * @param array $files the uploaded files if any * @param array $options additional user data * * @return true if no errors, else array of errors * @access public * @static */ static function formRule($fields, $files, $self) { $errors = array(); $amount = self::computeAmount($fields, $self); //check for atleast one pricefields should be selected if (CRM_Utils_Array::value('priceSetId', $fields)) { $priceField = new CRM_Price_DAO_Field(); $priceField->price_set_id = $fields['priceSetId']; $priceField->find(); $check = array(); while ($priceField->fetch()) { if (!empty($fields["price_{$priceField->id}"])) { $check[] = $priceField->id; } } if (empty($check)) { if ($self->_useForMember == 1) { $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).'); } else { $errors['_qf_default'] = ts('Select at least one option from Contribution(s).'); } } require_once 'CRM/Price/BAO/Set.php'; if ($self->_useForMember == 1 && !empty($check)) { $priceFieldIDS = array(); $priceFieldMemTypes = array(); foreach ($self->_priceSet['fields'] as $priceId => $value) { if (!empty($fields['price_' . $priceId])) { if (is_array($fields['price_' . $priceId])) { foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) { if ($isSet) { $priceFieldIDS[] = $priceFldVal; } } } else { $priceFieldIDS[] = $fields['price_' . $priceId]; } if (CRM_Utils_Array::value('options', $value)) { foreach ($value['options'] as $val) { if (CRM_Utils_Array::value('membership_type_id', $val)) { $priceFieldMemTypes[] = $val['membership_type_id']; } } } } } $ids = implode(',', $priceFieldIDS); $priceFieldIDS['id'] = $fields['priceSetId']; $self->set('memberPriceFieldIDS', $priceFieldIDS); $count = CRM_Price_BAO_Set::getMembershipCount($ids); foreach ($count as $id => $occurance) { if ($occurance > 1) { $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.'); } } if (empty($priceFieldMemTypes)) { $errors['_qf_default'] = ts('Please select at least one membership option.'); } } CRM_Price_BAO_Set::processAmount($self->_values['fee'], $fields, $lineItem); if ($fields['amount'] < 0) { $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly'); } $amount = $fields['amount']; } if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks' && $self->_values['amount_block_is_active']) { require_once 'CRM/Contribute/DAO/Product.php'; require_once 'CRM/Utils/Money.php'; $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $fields['selectProduct']; $productDAO->find(true); $min_amount = $productDAO->min_contribution; if ($amount < $min_amount) { $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount))); } } if ($self->_values['honor_block_is_active'] && CRM_Utils_Array::value('honor_type_id', $fields)) { // make sure there is a first name and last name if email is not there if (!CRM_Utils_Array::value('honor_email', $fields)) { if (!CRM_Utils_Array::value('honor_first_name', $fields) || !CRM_Utils_Array::value('honor_last_name', $fields)) { $errors['honor_last_name'] = ts('In Honor Of - First Name and Last Name, OR an Email Address is required.'); } } } if (isset($fields['is_recur']) && $fields['is_recur']) { if ($fields['frequency_interval'] <= 0) { $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).'); } if ($fields['frequency_unit'] == '0') { $errors['frequency_unit'] = ts('Please select a period (e.g. months, years ...) for how often you want to make this recurring contribution (EXAMPLE: Every 3 MONTHS).'); } } if (CRM_Utils_Array::value('is_recur', $fields) && $fields['is_pay_later']) { $errors['is_pay_later'] = ' '; $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.'); } if (CRM_Utils_Array::value('is_for_organization', $fields) && !property_exists($self, 'organizationName')) { if (!CRM_Utils_Array::value('organization_name', $fields['onbehalf'])) { if (CRM_Utils_Array::value('org_option', $fields) && !$fields['onbehalfof_id']) { $errors['organization_id'] = ts('Please select an organization or enter a new one.'); } else { if (!CRM_Utils_Array::value('org_option', $fields)) { $errors['onbehalf']['organization_name'] = ts('Please enter the organization name.'); } } } foreach ($fields['onbehalf'] as $key => $value) { if (strstr($key, 'email')) { $emailLocType = explode('-', $key); } } if (!CRM_Utils_Array::value("email-{$emailLocType[1]}", $fields['onbehalf'])) { $errors['onbehalf']["email-{$emailLocType[1]}"] = ts('Organization email is required.'); } } if (CRM_Utils_Array::value('selectMembership', $fields) && $fields['selectMembership'] != 'no_thanks') { require_once 'CRM/Member/BAO/Membership.php'; require_once 'CRM/Member/BAO/MembershipType.php'; if (!empty($self->_membershipTypeValues)) { $memTypeDetails = $self->_membershipTypeValues[$fields['selectMembership']]; } else { $memTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($self, $fields['selectMembership']); } if ($self->_values['amount_block_is_active'] && !CRM_Utils_Array::value('is_separate_payment', $self->_membershipBlock)) { require_once 'CRM/Utils/Money.php'; if ($amount < CRM_Utils_Array::value('minimum_fee', $memTypeDetails)) { $errors['selectMembership'] = ts('The Membership you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($memTypeDetails['minimum_fee']))); } } else { if (CRM_Utils_Array::value('minimum_fee', $memTypeDetails)) { // we dont have an amount, so lets get an amount for cc checks $amount = $memTypeDetails['minimum_fee']; } } } if ($self->_values['is_monetary']) { //validate other amount. $checkOtherAmount = false; if (CRM_Utils_Array::value('amount', $fields) == 'amount_other_radio' || CRM_Utils_Array::value('amount_other', $fields)) { $checkOtherAmount = true; } $otherAmountVal = CRM_Utils_Array::value('amount_other', $fields); if ($checkOtherAmount || $otherAmountVal) { if (!$otherAmountVal) { $errors['amount_other'] = ts('Amount is required field.'); } //validate for min and max. if ($otherAmountVal) { $min = CRM_Utils_Array::value('min_amount', $self->_values); $max = CRM_Utils_Array::value('max_amount', $self->_values); if ($min && $otherAmountVal < $min) { $errors['amount_other'] = ts('Contribution amount must be at least %1', array(1 => $min)); } if ($max && $otherAmountVal > $max) { $errors['amount_other'] = ts('Contribution amount cannot be more than %1.', array(1 => $max)); } } } } // validate PCP fields - if not anonymous, we need a nick name value if ($self->_pcpId && CRM_Utils_Array::value('pcp_display_in_roll', $fields) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') { $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.'); } // return if this is express mode $config = CRM_Core_Config::singleton(); if ($self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) { if (CRM_Utils_Array::value($self->_expressButtonName . '_x', $fields) || CRM_Utils_Array::value($self->_expressButtonName . '_y', $fields) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) { return $errors; } } //validate the pledge fields. if (CRM_Utils_Array::value('pledge_block_id', $self->_values)) { //validation for pledge payment. if (CRM_Utils_Array::value('pledge_id', $self->_values)) { if (empty($fields['pledge_amount'])) { $errors['pledge_amount'] = ts('At least one payment option needs to be checked.'); } } else { if (CRM_Utils_Array::value('is_pledge', $fields)) { if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == false) { $errors['pledge_installments'] = ts('Please enter a valid pledge installment.'); } else { if (CRM_Utils_Array::value('pledge_installments', $fields) == null) { $errors['pledge_installments'] = ts('Pledge Installments is required field.'); } else { if (CRM_Utils_array::value('pledge_installments', $fields) == 1) { $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.'); } else { if (CRM_Utils_array::value('pledge_installments', $fields) == 0) { $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.'); } } } } //validation for Pledge Frequency Interval. if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == false) { $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.'); } else { if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == null) { $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.'); } else { if (CRM_Utils_array::value('pledge_frequency_interval', $fields) == 0) { $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0'); } } } } } } // also return if paylater mode if (CRM_Utils_Array::value('is_pay_later', $fields)) { return empty($errors) ? true : $errors; } // if the user has chosen a free membership or the amount is less than zero // i.e. we skip calling the payment processor and hence dont need credit card // info if ((double) $amount <= 0.0) { return $errors; } foreach ($self->_fields as $name => $fld) { if ($fld['is_required'] && CRM_Utils_System::isNull(CRM_Utils_Array::value($name, $fields))) { $errors[$name] = ts('%1 is a required field.', array(1 => $fld['title'])); } } // make sure that credit card number and cvv are valid require_once 'CRM/Utils/Rule.php'; if (CRM_Utils_Array::value('credit_card_type', $fields)) { if (CRM_Utils_Array::value('credit_card_number', $fields) && !CRM_Utils_Rule::creditCardNumber($fields['credit_card_number'], $fields['credit_card_type'])) { $errors['credit_card_number'] = ts('Please enter a valid Credit Card Number'); } if (CRM_Utils_Array::value('cvv2', $fields) && !CRM_Utils_Rule::cvv($fields['cvv2'], $fields['credit_card_type'])) { $errors['cvv2'] = ts('Please enter a valid Credit Card Verification Number'); } } $elements = array('email_greeting' => 'email_greeting_custom', 'postal_greeting' => 'postal_greeting_custom', 'addressee' => 'addressee_custom'); foreach ($elements as $greeting => $customizedGreeting) { if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) { $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name'); if ($customizedValue == $greetingType && !CRM_Utils_Array::value($customizedGreeting, $fields)) { $errors[$customizedGreeting] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting)))); } } } return empty($errors) ? true : $errors; }
/** * Function to build Premium B im Contribution Pages * * @param int $pageId * @static */ function buildPremiumPreviewBlock($form, $productID, $premiumProductID = null) { require_once 'CRM/Contribute/DAO/Product.php'; if ($premiumProductID) { require_once 'CRM/Contribute/DAO/PremiumsProduct.php'; $dao = new CRM_Contribute_DAO_PremiumsProduct(); $dao->id = $premiumProductID; $dao->find(true); $productID = $dao->product_id; } $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $productID; $productDAO->is_active = 1; if ($productDAO->find(true)) { CRM_Core_DAO::storeValues($productDAO, $products[$productDAO->id]); } $radio[$productDAO->id] = $form->createElement('radio', null, null, null, $productDAO->id, null); $options = $temp = array(); $temp = explode(',', $productDAO->options); foreach ($temp as $value) { $options[$value] = $value; } if ($temp[0] != '') { $form->add('select', 'options_' . $productDAO->id, null, $options); } $form->addGroup($radio, 'selectProduct', null); $form->assign('showRadio', true); $form->assign('showSelectOptions', true); $form->assign('products', $products); $form->assign('preview', true); }
/** * Browse all custom data groups. * * * @return void * @access public * @static */ function browse() { // get all custom groups sorted by weight $premiums = array(); $dao = new CRM_Contribute_DAO_Product(); $dao->orderBy('name'); $dao->find(); while ($dao->fetch()) { $premiums[$dao->id] = array(); CRM_Core_DAO::storeValues($dao, $premiums[$dao->id]); // form all action links $action = array_sum(array_keys($this->links())); if ($dao->is_active) { $action -= CRM_Core_Action::ENABLE; } else { $action -= CRM_Core_Action::DISABLE; } $premiums[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $dao->id)); } $this->assign('rows', $premiums); }
/** * Function to build the form * * @return None * @access public */ public function buildQuickForm() { if ($this->_cdType) { return CRM_Custom_Form_CustomData::buildQuickForm($this); } // build price set form. $buildPriceSet = FALSE; if (empty($this->_lineItems) && ($this->_priceSetId || CRM_Utils_Array::value('price_set_id', $_POST))) { $buildPriceSet = TRUE; $getOnlyPriceSetElements = TRUE; if (!$this->_priceSetId) { $this->_priceSetId = $_POST['price_set_id']; $getOnlyPriceSetElements = FALSE; } $this->set('priceSetId', $this->_priceSetId); CRM_Price_BAO_Set::buildPriceSet($this); // get only price set form elements. if ($getOnlyPriceSetElements) { return; } } // use to build form during form rule. $this->assign('buildPriceSet', $buildPriceSet); $showAdditionalInfo = FALSE; $defaults = $this->_values; $additionalDetailFields = array('note', 'thankyou_date', 'invoice_id', 'non_deductible_amount', 'fee_amount', 'net_amount'); foreach ($additionalDetailFields as $key) { if (!empty($defaults[$key])) { $defaults['hidden_AdditionalDetail'] = 1; break; } } $honorFields = array('honor_type_id', 'honor_prefix_id', 'honor_first_name', 'honor_lastname', 'honor_email'); foreach ($honorFields as $key) { if (!empty($defaults[$key])) { $defaults['hidden_Honoree'] = 1; break; } } //check for honoree pane. if ($this->_ppID && CRM_Utils_Array::value('honor_contact_id', $this->_pledgeValues)) { $defaults['hidden_Honoree'] = 1; } if ($this->_productDAO) { if ($this->_productDAO->product_id) { $defaults['hidden_Premium'] = 1; } } if ($this->_noteID && isset($this->_values['note'])) { $defaults['hidden_AdditionalDetail'] = 1; } $paneNames = array(ts('Additional Details') => 'AdditionalDetail', ts('Honoree Information') => 'Honoree'); //Add Premium pane only if Premium is exists. $dao = new CRM_Contribute_DAO_Product(); $dao->is_active = 1; if ($dao->find(TRUE)) { $paneNames[ts('Premium Information')] = 'Premium'; } $ccPane = NULL; if ($this->_mode) { if (CRM_Utils_Array::value('payment_type', $this->_processors) & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT) { $ccPane = array(ts('Direct Debit Information') => 'DirectDebit'); } else { $ccPane = array(ts('Credit Card Information') => 'CreditCard'); } } if (is_array($ccPane)) { $paneNames = array_merge($ccPane, $paneNames); } $buildRecurBlock = FALSE; foreach ($paneNames as $name => $type) { $urlParams = "snippet=4&formType={$type}"; if ($this->_mode) { $urlParams .= "&mode={$this->_mode}"; } $open = 'false'; if ($type == 'CreditCard' || $type == 'DirectDebit') { $open = 'true'; } $allPanes[$name] = array('url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams), 'open' => $open, 'id' => $type); // see if we need to include this paneName in the current form if ($this->_formType == $type || CRM_Utils_Array::value("hidden_{$type}", $_POST) || CRM_Utils_Array::value("hidden_{$type}", $defaults)) { $showAdditionalInfo = TRUE; $allPanes[$name]['open'] = 'true'; } if ($type == 'CreditCard') { $buildRecurBlock = TRUE; $this->add('hidden', 'hidden_CreditCard', 1); CRM_Core_Payment_Form::buildCreditCard($this, TRUE); } elseif ($type == 'DirectDebit') { $buildRecurBlock = TRUE; $this->add('hidden', 'hidden_DirectDebit', 1); CRM_Core_Payment_Form::buildDirectDebit($this, TRUE); } else { eval('CRM_Contribute_Form_AdditionalInfo::build' . $type . '( $this );'); } } if (empty($this->_recurPaymentProcessors)) { $buildRecurBlock = FALSE; } if ($buildRecurBlock) { CRM_Contribute_Form_Contribution_Main::buildRecur($this); $this->setDefaults(array('is_recur' => 0)); } $this->assign('buildRecurBlock', $buildRecurBlock); $qfKey = $this->controller->_key; $this->assign('qfKey', $qfKey); $this->assign('allPanes', $allPanes); $this->assign('showAdditionalInfo', $showAdditionalInfo); if ($this->_formType) { $this->assign('formType', $this->_formType); return; } $this->applyFilter('__ALL__', 'trim'); if ($this->_action & CRM_Core_Action::DELETE) { $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'spacing' => ' ', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); return; } //need to assign custom data type and subtype to the template $this->assign('customDataType', 'Contribution'); $this->assign('customDataSubType', $this->_contributionType); $this->assign('entityID', $this->_id); if ($this->_context == 'standalone') { CRM_Contact_Form_NewContact::buildQuickForm($this); } $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution'); $element = $this->add('select', 'contribution_type_id', ts('Contribution Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType(), TRUE, array('onChange' => "buildCustomData( 'Contribution', this.value );")); if ($this->_online) { $element->freeze(); } if (!$this->_mode) { $element = $this->add('select', 'payment_instrument_id', ts('Paid By'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")); if ($this->_online) { $element->freeze(); } } $element = $this->add('text', 'trxn_id', ts('Transaction ID'), $attributes['trxn_id']); if ($this->_online) { $element->freeze(); } else { $this->addRule('trxn_id', ts('This Transaction ID already exists in the database. Include the account number for checks.'), 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id')); } //add receipt for offline contribution $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?')); $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails); $status = CRM_Contribute_PseudoConstant::contributionStatus(); // supressing contribution statuses that are NOT relevant to pledges (CRM-5169) if ($this->_ppID) { $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); foreach (array('Cancelled', 'Failed', 'In Progress') as $supress) { unset($status[CRM_Utils_Array::key($supress, $statusName)]); } } $this->add('select', 'contribution_status_id', ts('Contribution Status'), $status, FALSE, array('onClick' => "if (this.value != 3) { status();} else return false", 'onChange' => "return showHideByValue('contribution_status_id','3','cancelInfo','table-row','select',false);")); // add various dates $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime')); if ($this->_online) { $this->assign('hideCalender', TRUE); } $element = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']); if ($this->_online) { $element->freeze(); } $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime')); $this->addDateTime('cancel_date', ts('Cancelled Date'), FALSE, array('formatType' => 'activityDateTime')); $this->add('textarea', 'cancel_reason', ts('Cancellation Reason'), $attributes['cancel_reason']); $recurJs = NULL; if ($buildRecurBlock) { $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;"); } $element = $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, NULL, $recurJs); if ($this->_online) { $element->freeze(); } if (empty($this->_lineItems)) { $buildPriceSet = FALSE; $priceSets = CRM_Price_BAO_Set::getAssoc(FALSE, 'CiviContribute'); if (!empty($priceSets) && !$this->_ppID) { $buildPriceSet = TRUE; } // don't allow price set for contribution if it is related to participant, or if it is a pledge payment // and if we already have line items for that participant. CRM-5095 if ($buildPriceSet && $this->_id) { $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id); $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_id, 'id', 'contribution_id'); if ($pledgePaymentId) { $buildPriceSet = FALSE; } if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) { $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID); if (!CRM_Utils_System::isNull($participantLI)) { $buildPriceSet = FALSE; } } } $hasPriceSets = FALSE; if ($buildPriceSet) { $hasPriceSets = TRUE; $element = $this->add('select', 'price_set_id', ts('Choose price set'), array('' => ts('Choose price set')) + $priceSets, NULL, array('onchange' => "buildAmount( this.value );")); if ($this->_online) { $element->freeze(); } } $this->assign('hasPriceSets', $hasPriceSets); $currencyFreeze = FALSE; if ($this->_online || $this->_ppID) { $attributes['total_amount'] = array_merge($attributes['total_amount'], array('READONLY' => TRUE, 'style' => "background-color:#EBECE4")); $optionTypes = array('1' => ts('Adjust Pledge Payment Schedule?'), '2' => ts('Adjust Total Pledge Amount?')); $element = $this->addRadio('option_type', NULL, $optionTypes, array(), '<br/>'); $currencyFreeze = TRUE; } $element = $this->addMoney('total_amount', ts('Total Amount'), $hasPriceSets ? FALSE : TRUE, $attributes['total_amount'], TRUE, 'currency', NULL, $currencyFreeze); } $element = $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes)); //CRM-7362 --add campaigns. CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values)); // CRM-7368 allow user to set or edit PCP link for contributions $siteHasPCPs = CRM_Contribute_PseudoConstant::pcPage(); if (!CRM_Utils_Array::crmIsEmptyArray($siteHasPCPs)) { $this->assign('siteHasPCPs', 1); $pcpDataUrl = CRM_Utils_System::url('civicrm/ajax/rest', "className=CRM_Contact_Page_AJAX&fnName=getPCPList&json=1&context=contact&reset=1", FALSE, NULL, FALSE); $this->assign('pcpDataUrl', $pcpDataUrl); $this->addElement('text', 'pcp_made_through', ts('Credit to a Personal Campaign Page')); $this->addElement('hidden', 'pcp_made_through_id', '', array('id' => 'pcp_made_through_id')); $this->addElement('checkbox', 'pcp_display_in_roll', ts('Display in Honor Roll?'), NULL); $this->addElement('text', 'pcp_roll_nickname', ts('Name (for Honor Roll)')); $this->addElement('textarea', 'pcp_personal_note', ts('Personal Note (for Honor Roll)')); } $dataUrl = CRM_Utils_System::url('civicrm/ajax/rest', "className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1&context=contact&reset=1&context=softcredit&id={$this->_id}", FALSE, NULL, FALSE); $this->assign('dataUrl', $dataUrl); $this->addElement('text', 'soft_credit_to', ts('Soft Credit To')); // Tell tpl to hide Soft Credit field if contribution is linked directly to a PCP Page if (CRM_Utils_Array::value('pcp_made_through_id', $this->_values)) { $this->assign('pcpLinked', 1); } $this->addElement('hidden', 'soft_contact_id', '', array('id' => 'soft_contact_id')); $js = NULL; if (!$this->_mode) { $js = array('onclick' => "return verify( );"); } $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mailing_backend'); $this->assign('outBound_option', $mailingInfo['outBound_option']); $this->addButtons(array(array('type' => 'upload', 'name' => ts('Save'), 'js' => $js, 'isDefault' => TRUE), array('type' => 'upload', 'name' => ts('Save and New'), 'js' => $js, 'subName' => 'new'), array('type' => 'cancel', 'name' => ts('Cancel')))); $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this); if ($this->_action & CRM_Core_Action::VIEW) { $this->freeze(); } }
/** * Process the form submission. */ public function postProcess() { $sendReceipt = $pId = $contribution = $isRelatedId = FALSE; $softParams = $softIDs = array(); if ($this->_action & CRM_Core_Action::DELETE) { CRM_Contribute_BAO_Contribution::deleteContribution($this->_id); CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute")); return; } // Get the submitted form values. $submittedValues = $this->controller->exportValues($this->_name); if (!empty($submittedValues['price_set_id']) && $this->_action & CRM_Core_Action::UPDATE) { $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution'); $lineID = key($line); $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id'); $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config'); if ($quickConfig) { CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution'); } } // Process price set and get total amount and line items. $lineItem = array(); $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues); if (empty($priceSetId) && !$this->_id) { $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name'); $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId)); $fieldID = key($this->_priceSet['fields']); $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']); $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount']; $submittedValues['price_' . $fieldID] = 1; } if ($priceSetId) { CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]); // Unset tax amount for offline 'is_quick_config' contribution. if ($this->_priceSet['is_quick_config'] && !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())) { unset($submittedValues['tax_amount']); } $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues); } if ($this->_id) { if ($this->_compId) { if ($this->_context == 'participant') { $pId = $this->_compId; } elseif ($this->_context == 'membership') { $isRelatedId = TRUE; } else { $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id'); } } else { $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id); if (array_key_exists('membership', $contributionDetails)) { $isRelatedId = TRUE; } elseif (array_key_exists('participant', $contributionDetails)) { $pId = $contributionDetails['participant']; } } } if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) { // CRM-10117 update the line items for participants. if ($pId) { $entityTable = 'participant'; $entityID = $pId; $isRelatedId = FALSE; $participantParams = array('fee_amount' => $submittedValues['total_amount'], 'id' => $entityID); CRM_Event_BAO_Participant::add($participantParams); if (empty($this->_lineItems)) { $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1); } } else { $entityTable = 'contribution'; $entityID = $this->_id; } $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId); foreach (array_keys($lineItems) as $id) { $lineItems[$id]['id'] = $id; } $itemId = key($lineItems); if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) { $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id'); } if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) { $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues)); // Update line total and total amount with tax on edit. $financialItemsId = CRM_Core_PseudoConstant::getTaxRates(); if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) { $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']]; } else { $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = ""; $submittedValues['tax_amount'] = 'null'; } if ($lineItems[$itemId]['tax_rate']) { $lineItems[$itemId]['tax_amount'] = $lineItems[$itemId]['tax_rate'] / 100 * $lineItems[$itemId]['line_total']; $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount']; $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount']; } } // CRM-10117 update the line items for participants. if (!empty($lineItems[$itemId]['price_field_id'])) { $lineItem[$this->_priceSetId] = $lineItems; } } $isQuickConfig = 0; if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) { $isQuickConfig = 1; } //CRM-11529 for quick config back office transactions //when financial_type_id is passed in form, update the //line items with the financial type selected in form if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)) { foreach ($lineItem[$this->_priceSetId] as &$values) { $values['financial_type_id'] = $submittedValues['financial_type_id']; } } if (!isset($submittedValues['total_amount'])) { $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values); } $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE); if (!empty($submittedValues['pcp_made_through_id'])) { $pcp = array(); $fields = array('pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note'); foreach ($fields as $f) { $pcp[$f] = CRM_Utils_Array::value($f, $submittedValues); } } $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id'])); if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) { //Delete existing soft credit records if soft credit list is empty on update CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id)); } else { //build soft credit params foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) { if ($val && $submittedValues['soft_credit_amount'][$key]) { $softParams[$key]['contact_id'] = $val; $softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($submittedValues['soft_credit_amount'][$key]); $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key]; if (!empty($submittedValues['soft_credit_id'][$key])) { $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key]; } } } } // set the contact, when contact is selected if (!empty($submittedValues['contact_id'])) { $this->_contactID = $submittedValues['contact_id']; } // Credit Card Contribution. if ($this->_mode) { $this->processCreditCard($submittedValues, $lineItem); } else { // Offline Contribution. $submittedValues = $this->unsetCreditCardFields($submittedValues); // get the required field value only. $formValues = $submittedValues; $params = $ids = array(); $params['contact_id'] = $this->_contactID; $params['currency'] = $this->getCurrency($submittedValues); $fields = array('financial_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number'); foreach ($fields as $f) { $params[$f] = CRM_Utils_Array::value($f, $formValues); } if (!empty($pcp)) { $params['pcp'] = $pcp; } if (!empty($softParams)) { $params['soft_credit'] = $softParams; $params['soft_credit_ids'] = $softIDs; } // CRM-5740 if priceset is used, no need to cleanup money. if ($priceSetId) { $params['skipCleanMoney'] = 1; } $dates = array('receive_date', 'receipt_date', 'cancel_date'); foreach ($dates as $d) { $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE); } if (!empty($formValues['is_email_receipt'])) { $params['receipt_date'] = date("Y-m-d"); } if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name') || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')) { if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) { $params['cancel_date'] = date('Y-m-d'); } } else { $params['cancel_date'] = $params['cancel_reason'] = 'null'; } // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) { $params['is_pay_later'] = 1; } elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) { $params['is_pay_later'] = 0; } $ids['contribution'] = $params['id'] = $this->_id; // Add Additional common information to formatted params. CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this); if ($pId) { $params['contribution_mode'] = 'participant'; $params['participant_id'] = $pId; $params['skipLineItem'] = 1; } elseif ($isRelatedId) { $params['contribution_mode'] = 'membership'; } $params['line_item'] = $lineItem; $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor); if (isset($submittedValues['tax_amount'])) { $params['tax_amount'] = $submittedValues['tax_amount']; } //create contribution. if ($isQuickConfig) { $params['is_quick_config'] = 1; } // CRM-11956 // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] - // if non_deductible_amount does NOT exist - then calculate it depending on: // $ContributionType->is_deductible and whether there is a product (premium). if (empty($params['non_deductible_amount'])) { $contributionType = new CRM_Financial_DAO_FinancialType(); $contributionType->id = $params['financial_type_id']; if (!$contributionType->find(TRUE)) { CRM_Core_Error::fatal('Could not find a system table'); } if ($contributionType->is_deductible) { if (isset($formValues['product_name'][0])) { $selectProduct = $formValues['product_name'][0]; } // if there is a product - compare the value to the contribution amount if (isset($selectProduct)) { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $selectProduct; $productDAO->find(TRUE); // product value exceeds contribution amount if ($params['total_amount'] < $productDAO->price) { $params['non_deductible_amount'] = $params['total_amount']; } else { $params['non_deductible_amount'] = $productDAO->price; } } else { $params['non_deductible_amount'] = '0.00'; } } else { $params['non_deductible_amount'] = $params['total_amount']; } } $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids); // process associated membership / participant, CRM-4395 $relatedComponentStatusMsg = NULL; if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) { $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values), $contribution->receive_date); } //process note if ($contribution->id && isset($formValues['note'])) { CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID); } //process premium if ($contribution->id && isset($formValues['product_name'][0])) { CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id, $this->_premiumID, $this->_options); } // assign tax calculation for contribution receipts $taxRate = array(); $getTaxDetails = FALSE; $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); if ($invoicing) { if ($this->_action & CRM_Core_Action::ADD) { $line = $lineItem; } elseif ($this->_action & CRM_Core_Action::UPDATE) { $line = $this->_lineItems; } foreach ($line as $key => $value) { foreach ($value as $v) { if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) { $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v); } else { if (isset($v['tax_rate'])) { $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v); $getTaxDetails = TRUE; } } } } } if ($invoicing) { if ($this->_action & CRM_Core_Action::UPDATE) { if (isset($submittedValues['tax_amount'])) { $totalTaxAmount = $submittedValues['tax_amount']; } else { $totalTaxAmount = $this->_values['tax_amount']; } $this->assign('totalTaxAmount', $totalTaxAmount); $this->assign('dataArray', $taxRate); } else { if (!empty($submittedValues['price_set_id'])) { $this->assign('totalTaxAmount', $submittedValues['tax_amount']); $this->assign('getTaxDetails', $getTaxDetails); $this->assign('dataArray', $taxRate); $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings)); } else { $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues)); } } } //send receipt mail. if ($contribution->id && !empty($formValues['is_email_receipt'])) { $formValues['contact_id'] = $this->_contactID; $formValues['contribution_id'] = $contribution->id; $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id); // to get 'from email id' for send receipt $this->fromEmailId = $formValues['from_email_address']; $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues); } $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id'); //update pledge payment status. if ($this->_ppID && $contribution->id && $this->_action & CRM_Core_Action::ADD || $pledgePaymentId && $this->_action & CRM_Core_Action::UPDATE) { if ($this->_ppID) { //store contribution id in payment record. CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id); } else { $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id'); $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'pledge_id', 'contribution_id'); } $adjustTotalAmount = FALSE; if (CRM_Utils_Array::value('option_type', $formValues) == 2) { $adjustTotalAmount = TRUE; } $updatePledgePaymentStatus = FALSE; //do only if either the status or the amount has changed if ($this->_action & CRM_Core_Action::ADD) { $updatePledgePaymentStatus = TRUE; } elseif ($this->_action & CRM_Core_Action::UPDATE && ($this->_defaults['contribution_status_id'] != $formValues['contribution_status_id'] || $this->_defaults['total_amount'] != $formValues['total_amount'])) { $updatePledgePaymentStatus = TRUE; } if ($updatePledgePaymentStatus) { CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount, $adjustTotalAmount); } } $statusMsg = ts('The contribution record has been saved.'); if (!empty($formValues['is_email_receipt']) && $sendReceipt) { $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.'); } if ($relatedComponentStatusMsg) { $statusMsg .= ' ' . $relatedComponentStatusMsg; } CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success'); //Offline Contribution ends. } $session = CRM_Core_Session::singleton(); $buttonName = $this->controller->getButtonName(); if ($this->_context == 'standalone') { if ($buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add', 'reset=1&action=add&context=standalone')); } else { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute")); } } elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}")); } elseif ($buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}")); } //store contribution ID if not yet set (on create) if (empty($this->_id) && !empty($contribution->id)) { $this->_id = $contribution->id; } }
/** * Set variables up before form is built. * * @return void */ public function preProcess() { $id = $this->get('id'); $values = $ids = array(); $params = array('id' => $id); $context = CRM_Utils_Request::retrieve('context', 'String', $this); $this->assign('context', $context); CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids); CRM_Contribute_BAO_Contribution::resolveDefaults($values); $cancelledStatus = TRUE; $status = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); if (CRM_Utils_Array::value('contribution_status_id', $values) == array_search('Cancelled', $status)) { $cancelledStatus = FALSE; } $this->assign('cancelledStatus', $cancelledStatus); if (!empty($values['contribution_page_id'])) { $contribPages = CRM_Contribute_PseudoConstant::contributionPage(NULL, TRUE); $values['contribution_page_title'] = CRM_Utils_Array::value(CRM_Utils_Array::value('contribution_page_id', $values), $contribPages); } // get recieved into i.e to_financial_account_id from last trxn $financialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($values['contribution_id'], 'DESC'); $values['to_financial_account'] = ''; if (!empty($financialTrxnId['financialTrxnId'])) { $values['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $financialTrxnId['financialTrxnId'], 'to_financial_account_id'); if ($values['to_financial_account_id']) { $values['to_financial_account'] = CRM_Contribute_PseudoConstant::financialAccount($values['to_financial_account_id']); } $values['payment_processor_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $financialTrxnId['financialTrxnId'], 'payment_processor_id'); if ($values['payment_processor_id']) { $values['payment_processor_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor', $values['payment_processor_id'], 'name'); } } if (!empty($values['contribution_recur_id'])) { $sql = "SELECT installments, frequency_interval, frequency_unit FROM civicrm_contribution_recur WHERE id = %1"; $params = array(1 => array($values['contribution_recur_id'], 'Integer')); $dao = CRM_Core_DAO::executeQuery($sql, $params); if ($dao->fetch()) { $values['recur_installments'] = $dao->installments; $values['recur_frequency_unit'] = $dao->frequency_unit; $values['recur_frequency_interval'] = $dao->frequency_interval; } } $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $id, 0, CRM_Utils_Array::value('financial_type_id', $values)); CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree); $premiumId = NULL; if ($id) { $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->contribution_id = $id; if ($dao->find(TRUE)) { $premiumId = $dao->id; $productID = $dao->product_id; } } if ($premiumId) { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $productID; $productDAO->find(TRUE); $this->assign('premium', $productDAO->name); $this->assign('option', $dao->product_option); $this->assign('fulfilled', $dao->fulfilled_date); } // Get Note $noteValue = CRM_Core_BAO_Note::getNote(CRM_Utils_Array::value('id', $values), 'civicrm_contribution'); $values['note'] = array_values($noteValue); // show billing address location details, if exists if (!empty($values['address_id'])) { $addressParams = array('id' => CRM_Utils_Array::value('address_id', $values)); $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id'); $addressDetails = array_values($addressDetails); $values['billing_address'] = $addressDetails[0]['display']; } //assign soft credit record if exists. $SCRecords = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($values['contribution_id'], TRUE); if (!empty($SCRecords['soft_credit'])) { $this->assign('softContributions', $SCRecords['soft_credit']); unset($SCRecords['soft_credit']); } //assign pcp record if exists foreach ($SCRecords as $name => $value) { $this->assign($name, $value); } $lineItems = array(); if ($id) { $lineItem = CRM_Price_BAO_LineItem::getLineItems($id, 'contribution', 1, TRUE, TRUE); if (!empty($lineItem)) { $lineItems[] = $lineItem; } } $this->assign('lineItem', empty($lineItems) ? FALSE : $lineItems); $values['totalAmount'] = $values['total_amount']; //do check for campaigns if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) { $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId); $values['campaign'] = $campaigns[$campaignId]; } // assign values to the template $this->assign($values); $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); $this->assign('invoicing', $invoicing); if ($invoicing && isset($values['tax_amount'])) { $this->assign('totalTaxAmount', $values['tax_amount']); } $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']); $this->assign('displayName', $displayName); // Check if this is default domain contact CRM-10482 if (CRM_Contact_BAO_Contact::checkDomainContact($values['contact_id'])) { $displayName .= ' (' . ts('default organization') . ')'; } // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container CRM_Utils_System::setTitle(ts('View Contribution from') . ' ' . $displayName); // add viewed contribution to recent items list $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); $title = $displayName . ' - (' . CRM_Utils_Money::format($values['total_amount']) . ' ' . ' - ' . $values['financial_type'] . ')'; $recentOther = array(); if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); } if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); } CRM_Utils_Recent::add($title, $url, $values['id'], 'Contribution', $values['contact_id'], NULL, $recentOther); }
/** * Function to send email receipt. * * @form object of Contribution form. * @param array $params (reference ) an assoc array of name/value pairs. * @$ccContribution boolen, is it credit card contribution. * @access public. * @return None. */ function emailReceipt(&$form, &$params, $ccContribution = false) { $this->assign('receiptType', 'contribution'); // Retrieve Contribution Type Name from contribution_type_id $params['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $params['contribution_type_id']); if (CRM_Utils_Array::value('payment_instrument_id', $params)) { require_once 'CRM/Contribute/PseudoConstant.php'; $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $params['paidBy'] = $paymentInstrument[$params['payment_instrument_id']]; } // retrieve individual prefix value for honoree if (CRM_Utils_Array::value('hidden_Honoree', $params)) { $individualPrefix = CRM_Core_PseudoConstant::individualPrefix(); $honor = CRM_Core_PseudoConstant::honor(); $params['honor_prefix'] = CRM_Utils_Array::value($params['honor_prefix_id'], $individualPrefix); $params["honor_type"] = CRM_Utils_Array::value($params["honor_type_id"], $honor); } // retrieve premium product name and assigned fulfilled // date to template if (CRM_Utils_Array::value('hidden_Premium', $params)) { if (CRM_Utils_Array::value($params['product_name'][0], $form->_options)) { $params['product_option'] = $form->_options[$params['product_name'][0]][$params['product_name'][1]]; } //fix for crm-4584 if (!empty($params['product_name'])) { require_once 'CRM/Contribute/DAO/Product.php'; $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $params['product_name'][0]; $productDAO->find(true); $params['product_name'] = $productDAO->name; $params['product_sku'] = $productDAO->sku; } $this->assign('fulfilled_date', CRM_Utils_Date::processDate($params['fulfilled_date'])); } $this->assign('ccContribution', $ccContribution); if ($ccContribution) { //build the name. $name = CRM_Utils_Array::value('billing_first_name', $params); if (CRM_Utils_Array::value('billing_middle_name', $params)) { $name .= " {$params['billing_middle_name']}"; } $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $params); $name = trim($name); $this->assign('billingName', $name); //assign the address formatted up for display $addressParts = array("street_address" => "billing_street_address-{$form->_bltID}", "city" => "billing_city-{$form->_bltID}", "postal_code" => "billing_postal_code-{$form->_bltID}", "state_province" => "state_province-{$form->_bltID}", "country" => "country-{$form->_bltID}"); $addressFields = array(); foreach ($addressParts as $name => $field) { $addressFields[$name] = CRM_Utils_Array::value($field, $params); } require_once 'CRM/Utils/Address.php'; $this->assign('address', CRM_Utils_Address::format($addressFields)); $date = CRM_Utils_Date::format($params['credit_card_exp_date']); $date = CRM_Utils_Date::mysqlToIso($date); $this->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $params)); $this->assign('credit_card_exp_date', $date); $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number'])); } else { //offline contribution //Retrieve the name and email from receipt is to be send $params['receipt_from_name'] = $form->userDisplayName; $params['receipt_from_email'] = $form->userEmail; // assigned various dates to the templates $form->assign('receipt_date', CRM_Utils_Date::processDate($params['receipt_date'])); $form->assign('cancel_date', CRM_Utils_Date::processDate($params['cancel_date'])); if (CRM_Utils_Array::value('thankyou_date', $params)) { $form->assign('thankyou_date', CRM_Utils_Date::processDate($params['thankyou_date'])); } if ($form->_action & CRM_Core_Action::UPDATE) { $form->assign('lineItem', empty($form->_lineItems) ? false : $form->_lineItems); } } //handle custom data if (CRM_Utils_Array::value('hidden_custom', $params)) { $contribParams = array(array('contribution_id', '=', $params['contribution_id'], 0, 0)); if ($form->_mode == 'test') { $contribParams[] = array('contribution_test', '=', 1, 0, 0); } //retrieve custom data require_once "CRM/Core/BAO/UFGroup.php"; $customGroup = array(); foreach ($form->_groupTree as $groupID => $group) { $customFields = $customValues = array(); if ($groupID == 'info') { continue; } foreach ($group['fields'] as $k => $field) { $field['title'] = $field['label']; $customFields["custom_{$k}"] = $field; } //build the array of customgroup contain customfields. CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, false, $contribParams); $customGroup[$group['title']] = $customValues; } //assign all custom group and corresponding fields to template. $form->assign('customGroup', $customGroup); } $form->assign_by_ref('formValues', $params); require_once 'CRM/Contact/BAO/Contact/Location.php'; require_once 'CRM/Utils/Mail.php'; list($contributorDisplayName, $contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']); $this->assign('contactID', $params['contact_id']); $this->assign('contributionID', $params['contribution_id']); $this->assign('currency', $params['currency']); $this->assign('receive_date', CRM_Utils_Date::processDate($params['receive_date'])); $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID); require_once 'CRM/Core/BAO/MessageTemplates.php'; list($sendReceipt, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_offline_receipt', 'contactId' => $params['contact_id'], 'from' => "{$userName} <{$userEmail}>", 'toName' => $contributorDisplayName, 'toEmail' => $contributorEmail, 'isTest' => $form->_mode == 'test')); return $sendReceipt; }
/** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { $id = $this->get('id'); $values = $ids = array(); $params = array('id' => $id); $context = CRM_Utils_Request::retrieve('context', 'String', $this); $this->assign('context', $context); CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids); $softParams = array('contribution_id' => $values['contribution_id']); if ($softContribution = CRM_Contribute_BAO_Contribution::getSoftContribution($softParams, TRUE)) { $values = array_merge($values, $softContribution); } CRM_Contribute_BAO_Contribution::resolveDefaults($values); if (CRM_Utils_Array::value('contribution_page_id', $values)) { $contribPages = CRM_Contribute_PseudoConstant::contributionPage(NULL, TRUE); $values['contribution_page_title'] = CRM_Utils_Array::value(CRM_Utils_Array::value('contribution_page_id', $values), $contribPages); } if (CRM_Utils_Array::value('honor_contact_id', $values)) { $sql = "SELECT display_name FROM civicrm_contact WHERE id = %1"; $params = array(1 => array($values['honor_contact_id'], 'Integer')); $dao = CRM_Core_DAO::executeQuery($sql, $params); if ($dao->fetch()) { $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$values['honor_contact_id']}"); $values['honor_display'] = "<A href = {$url}>" . $dao->display_name . "</A>"; } $honor = CRM_Core_PseudoConstant::honor(); $values['honor_type'] = CRM_Utils_Array::value(CRM_Utils_Array::value('honor_type_id', $values), $honor); } if (CRM_Utils_Array::value('contribution_recur_id', $values)) { $sql = "SELECT installments, frequency_interval, frequency_unit FROM civicrm_contribution_recur WHERE id = %1"; $params = array(1 => array($values['contribution_recur_id'], 'Integer')); $dao = CRM_Core_DAO::executeQuery($sql, $params); if ($dao->fetch()) { $values['recur_installments'] = $dao->installments; $values['recur_frequency_unit'] = $dao->frequency_unit; $values['recur_frequency_interval'] = $dao->frequency_interval; } } $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $id, 0, $values['contribution_type_id']); CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree); $premiumId = NULL; if ($id) { $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->contribution_id = $id; if ($dao->find(TRUE)) { $premiumId = $dao->id; $productID = $dao->product_id; } } if ($premiumId) { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $productID; $productDAO->find(TRUE); $this->assign('premium', $productDAO->name); $this->assign('option', $dao->product_option); $this->assign('fulfilled', $dao->fulfilled_date); } // Get Note $noteValue = CRM_Core_BAO_Note::getNote($values['id'], 'civicrm_contribution'); $values['note'] = array_values($noteValue); // show billing address location details, if exists if (CRM_Utils_Array::value('address_id', $values)) { $addressParams = array('id' => CRM_Utils_Array::value('address_id', $values)); $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id'); $addressDetails = array_values($addressDetails); $values['billing_address'] = $addressDetails[0]['display']; } //get soft credit record if exists. if ($softContribution = CRM_Contribute_BAO_Contribution::getSoftContribution($softParams)) { $softContribution['softCreditToName'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $softContribution['soft_credit_to'], 'display_name'); //hack to avoid dispalyName conflict //for viewing softcredit record. $softContribution['displayName'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['contact_id'], 'display_name'); $values = array_merge($values, $softContribution); } $lineItems = array(); if ($id) { $lineItem = CRM_Price_BAO_LineItem::getLineItems($id, 'contribution', 1); empty($lineItem) ? null : ($lineItems[] = $lineItem); } $this->assign('lineItem', empty($lineItems) ? FALSE : $lineItems); $values['totalAmount'] = $values['total_amount']; //do check for campaigns if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) { $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId); $values['campaign'] = $campaigns[$campaignId]; } // assign values to the template $this->assign($values); // add viewed contribution to recent items list $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['contact_id'], 'display_name'); $this->assign('displayName', $displayName); $title = $displayName . ' - (' . CRM_Utils_Money::format($values['total_amount']) . ' ' . ' - ' . $values['contribution_type'] . ')'; $recentOther = array(); if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); } if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); } CRM_Utils_Recent::add($title, $url, $values['id'], 'Contribution', $values['contact_id'], NULL, $recentOther); }
/** * Get all premiums. * * * @param int $pageID * @return array * array of all Premiums if any */ public static function products($pageID = NULL) { $products = array(); $dao = new CRM_Contribute_DAO_Product(); $dao->is_active = 1; $dao->orderBy('id'); $dao->find(); while ($dao->fetch()) { $products[$dao->id] = $dao->name; } if ($pageID) { $dao = new CRM_Contribute_DAO_Premium(); $dao->entity_table = 'civicrm_contribution_page'; $dao->entity_id = $pageID; $dao->find(TRUE); $premiumID = $dao->id; $productID = array(); $dao = new CRM_Contribute_DAO_PremiumsProduct(); $dao->premiums_id = $premiumID; $dao->find(); while ($dao->fetch()) { $productID[$dao->product_id] = $dao->product_id; } $tempProduct = array(); foreach ($products as $key => $value) { if (!array_key_exists($key, $productID)) { $tempProduct[$key] = $value; } } return $tempProduct; } return $products; }
/** * Browse all custom data groups. * * * @return void */ public function browse() { // get all custom groups sorted by weight $premiums = array(); $dao = new CRM_Contribute_DAO_Product(); $dao->orderBy('name'); $dao->find(); while ($dao->fetch()) { $premiums[$dao->id] = array(); CRM_Core_DAO::storeValues($dao, $premiums[$dao->id]); // form all action links $action = array_sum(array_keys($this->links())); if ($dao->is_active) { $action -= CRM_Core_Action::ENABLE; } else { $action -= CRM_Core_Action::DISABLE; } $premiums[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $dao->id), ts('more'), FALSE, 'premium.manage.row', 'Premium', $dao->id); //Financial Type if (!empty($dao->financial_type_id)) { require_once 'CRM/Core/DAO.php'; $premiums[$dao->id]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $dao->financial_type_id, 'name'); } } $this->assign('rows', $premiums); }
/** * Send email receipt. * * @param CRM_Core_Form $form * instance of Contribution form. * @param array $params * (reference ) an assoc array of name/value pairs. * @param bool $ccContribution * is it credit card contribution. * * @return array */ public static function emailReceipt(&$form, &$params, $ccContribution = FALSE) { $form->assign('receiptType', 'contribution'); // Retrieve Financial Type Name from financial_type_id $params['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $params['financial_type_id']); if (!empty($params['payment_instrument_id'])) { $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $params['paidBy'] = $paymentInstrument[$params['payment_instrument_id']]; if ($params['paidBy'] != 'Check' && isset($params['check_number'])) { unset($params['check_number']); } } // retrieve individual prefix value for honoree if (isset($params['soft_credit'])) { $softCreditTypes = $softCredits = array(); foreach ($params['soft_credit'] as $key => $softCredit) { $softCredits[$key] = array('Name' => $softCredit['contact_name'], 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency'])); $softCreditTypes[$key] = $softCredit['soft_credit_type_label']; } $form->assign('softCreditTypes', $softCreditTypes); $form->assign('softCredits', $softCredits); } // retrieve premium product name and assigned fulfilled // date to template if (!empty($params['hidden_Premium'])) { if (isset($params['product_name']) && is_array($params['product_name']) && !empty($params['product_name'])) { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $params['product_name'][0]; $productOptionID = $params['product_name'][1]; $productDAO->find(TRUE); $params['product_name'] = $productDAO->name; $params['product_sku'] = $productDAO->sku; if (empty($params['product_option']) && !empty($form->_options[$productDAO->id])) { $params['product_option'] = $form->_options[$productDAO->id][$productOptionID]; } } if (!empty($params['fulfilled_date'])) { $form->assign('fulfilled_date', CRM_Utils_Date::processDate($params['fulfilled_date'])); } } $form->assign('ccContribution', $ccContribution); if ($ccContribution) { //build the name. $name = CRM_Utils_Array::value('billing_first_name', $params); if (!empty($params['billing_middle_name'])) { $name .= " {$params['billing_middle_name']}"; } $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $params); $name = trim($name); $form->assign('billingName', $name); //assign the address formatted up for display $addressParts = array("street_address" => "billing_street_address-{$form->_bltID}", "city" => "billing_city-{$form->_bltID}", "postal_code" => "billing_postal_code-{$form->_bltID}", "state_province" => "state_province-{$form->_bltID}", "country" => "country-{$form->_bltID}"); $addressFields = array(); foreach ($addressParts as $name => $field) { $addressFields[$name] = CRM_Utils_Array::value($field, $params); } $form->assign('address', CRM_Utils_Address::format($addressFields)); $date = CRM_Utils_Date::format($params['credit_card_exp_date']); $date = CRM_Utils_Date::mysqlToIso($date); $form->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $params)); $form->assign('credit_card_exp_date', $date); $form->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number'])); } else { //offline contribution // assigned various dates to the templates $form->assign('receipt_date', CRM_Utils_Date::processDate($params['receipt_date'])); if (!empty($params['cancel_date'])) { $form->assign('cancel_date', CRM_Utils_Date::processDate($params['cancel_date'])); } if (!empty($params['thankyou_date'])) { $form->assign('thankyou_date', CRM_Utils_Date::processDate($params['thankyou_date'])); } if ($form->_action & CRM_Core_Action::UPDATE) { $form->assign('lineItem', empty($form->_lineItems) ? FALSE : $form->_lineItems); } } //handle custom data if (!empty($params['hidden_custom'])) { $contribParams = array(array('contribution_id', '=', $params['contribution_id'], 0, 0)); if ($form->_mode == 'test') { $contribParams[] = array('contribution_test', '=', 1, 0, 0); } //retrieve custom data $customGroup = array(); foreach ($form->_groupTree as $groupID => $group) { $customFields = $customValues = array(); if ($groupID == 'info') { continue; } foreach ($group['fields'] as $k => $field) { $field['title'] = $field['label']; $customFields["custom_{$k}"] = $field; } //build the array of customgroup contain customfields. CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $contribParams); $customGroup[$group['title']] = $customValues; } //assign all custom group and corresponding fields to template. $form->assign('customGroup', $customGroup); } $form->assign_by_ref('formValues', $params); list($contributorDisplayName, $contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']); $form->assign('contactID', $params['contact_id']); $form->assign('contributionID', $params['contribution_id']); if (!empty($params['currency'])) { $form->assign('currency', $params['currency']); } if (!empty($params['receive_date'])) { $form->assign('receive_date', CRM_Utils_Date::processDate($params['receive_date'])); } $template = CRM_Core_Smarty::singleton(); $taxAmt = $template->get_template_vars('dataArray'); $eventTaxAmt = $template->get_template_vars('totalTaxAmount'); $prefixValue = Civi::settings()->get('contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue); if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) { $isEmailPdf = TRUE; } else { $isEmailPdf = FALSE; } list($sendReceipt, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_offline_receipt', 'contactId' => $params['contact_id'], 'contributionId' => $params['contribution_id'], 'from' => $params['from_email_address'], 'toName' => $contributorDisplayName, 'toEmail' => $contributorEmail, 'isTest' => $form->_mode == 'test', 'PDFFilename' => ts('receipt') . '.pdf', 'isEmailPdf' => $isEmailPdf)); return $sendReceipt; }
/** * Apply variables for message to smarty template - this function is part of analysing what is in the huge * function & breaking it down into manageable chunks. Eventually it will be refactored into something else * Note we send directly from this function in some cases because it is only partly refactored * Don't call this function directly as the signature will change * * @param $values * @param $input * @param CRM_Core_SMARTY $template * @param bool $recur * @param bool $returnMessageText * * @return mixed */ public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) { $template->assign('first_name', $this->_relatedObjects['contact']->first_name); $template->assign('last_name', $this->_relatedObjects['contact']->last_name); $template->assign('displayName', $this->_relatedObjects['contact']->display_name); if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) { $template->assign('useForMember', TRUE); } //assign honor information to receipt message $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id); if (isset($softRecord['soft_credit'])) { //if id of contribution page is present if (!empty($values['id'])) { $values['honor'] = array('honor_profile_values' => array(), 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'), 'honor_id' => $softRecord['soft_credit'][1]['contact_id']); $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type'); $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']); $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id')); } else { //offline contribution $softCreditTypes = $softCredits = array(); foreach ($softRecord['soft_credit'] as $key => $softCredit) { $softCreditTypes[$key] = $softCredit['soft_credit_type_label']; $softCredits[$key] = array('Name' => $softCredit['contact_name'], 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency'])); } $template->assign('softCreditTypes', $softCreditTypes); $template->assign('softCredits', $softCredits); } } $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->contribution_id = $this->id; if ($dao->find(TRUE)) { $premiumId = $dao->product_id; $template->assign('option', $dao->product_option); $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $premiumId; $productDAO->find(TRUE); $template->assign('selectPremium', TRUE); $template->assign('product_name', $productDAO->name); $template->assign('price', $productDAO->price); $template->assign('sku', $productDAO->sku); } $template->assign('title', CRM_Utils_Array::value('title', $values)); $amount = CRM_Utils_Array::value('total_amount', $input, CRM_Utils_Array::value('amount', $input), NULL); if (empty($amount) && isset($this->total_amount)) { $amount = $this->total_amount; } $template->assign('amount', $amount); // add the new contribution values if (strtolower($this->_component) == 'contribute') { //PCP Info $softDAO = new CRM_Contribute_DAO_ContributionSoft(); $softDAO->contribution_id = $this->id; if ($softDAO->find(TRUE)) { $template->assign('pcpBlock', TRUE); $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll); $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname); $template->assign('pcp_personal_note', $softDAO->pcp_personal_note); //assign the pcp page title for email subject $pcpDAO = new CRM_PCP_DAO_PCP(); $pcpDAO->id = $softDAO->pcp_id; if ($pcpDAO->find(TRUE)) { $template->assign('title', $pcpDAO->title); } } } if ($this->financial_type_id) { $values['financial_type_id'] = $this->financial_type_id; } $template->assign('trxn_id', $this->trxn_id); $template->assign('receive_date', CRM_Utils_Date::mysqlToIso($this->receive_date)); $template->assign('contributeMode', 'notify'); $template->assign('action', $this->is_test ? 1024 : 1); $template->assign('receipt_text', CRM_Utils_Array::value('receipt_text', $values)); $template->assign('is_monetary', 1); $template->assign('is_recur', (bool) $recur); $template->assign('currency', $this->currency); $template->assign('address', CRM_Utils_Address::format($input)); if (!empty($values['customGroup'])) { $template->assign('customGroup', $values['customGroup']); } if ($this->_component == 'event') { $template->assign('title', $values['event']['title']); $participantRoles = CRM_Event_PseudoConstant::participantRole(); $viewRoles = array(); foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) { $viewRoles[] = $participantRoles[$v]; } $values['event']['participant_role'] = implode(', ', $viewRoles); $template->assign('event', $values['event']); $template->assign('participant', $values['participant']); $template->assign('location', $values['location']); $template->assign('customPre', $values['custom_pre_id']); $template->assign('customPost', $values['custom_post_id']); $isTest = FALSE; if ($this->_relatedObjects['participant']->is_test) { $isTest = TRUE; } $values['params'] = array(); //to get email of primary participant. $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id'); $primaryAmount[] = array('label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects['participant']->fee_amount); //build an array of cId/pId of participants $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE); unset($additionalIDs[$this->_relatedObjects['participant']->id]); //send receipt to additional participant if exists if (count($additionalIDs)) { $template->assign('isPrimary', 0); $template->assign('customProfile', NULL); //set additionalParticipant true $values['params']['additionalParticipant'] = TRUE; foreach ($additionalIDs as $pId => $cId) { $amount = array(); //to change the status pending to completed $additional = new CRM_Event_DAO_Participant(); $additional->id = $pId; $additional->contact_id = $cId; $additional->find(TRUE); $additional->register_date = $this->_relatedObjects['participant']->register_date; $additional->status_id = 1; $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id'); //if additional participant dont have email //use display name. if (!$additionalParticipantInfo) { $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id); } $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount); $primaryAmount[] = array('label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount); $additional->save(); $additional->free(); $template->assign('amount', $amount); CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText); } } //build an array of custom profile and assigning it to template $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest); if (count($customProfile)) { $template->assign('customProfile', $customProfile); } // for primary contact $values['params']['additionalParticipant'] = FALSE; $template->assign('isPrimary', 1); $template->assign('amount', $primaryAmount); $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date)); if ($this->payment_instrument_id) { $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]); } // carry paylater, since we did not created billing, // so need to pull email from primary location, CRM-4395 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later; } return $template; }
/** * global form rule * * @param array $fields the input form values * @param array $files the uploaded files if any * @param array $options additional user data * * @return true if no errors, else array of errors * @access public * @static */ static function formRule($fields, $files, $self) { $errors = array(); $amount = self::computeAmount($fields, $self); if (!empty($fields['selectMembership']) && $fields['selectMembership'] != 'no_thanks' || !empty($fields['priceSetId']) && $self->_useForMember) { $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_userID, FALSE, TRUE); $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(); $unallowedOrgs = array(); foreach (array_keys($lifeMember) as $memTypeId) { $unallowedOrgs[] = $membershipOrgDetails[$memTypeId]; } } //check for atleast one pricefields should be selected if (!empty($fields['priceSetId'])) { $priceField = new CRM_Price_DAO_PriceField(); $priceField->price_set_id = $fields['priceSetId']; $priceField->orderBy('weight'); $priceField->find(); $check = array(); $membershipIsActive = TRUE; $previousId = $otherAmount = FALSE; while ($priceField->fetch()) { if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) { $previousId = $priceField->id; if ($priceField->name == 'membership_amount' && !$priceField->is_active) { $membershipIsActive = FALSE; } } if ($priceField->name == 'other_amount') { if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) && array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])) { $otherAmount = $priceField->id; } elseif (!empty($fields["price_{$priceField->id}"])) { $otherAmountVal = $fields["price_{$priceField->id}"]; $min = CRM_Utils_Array::value('min_amount', $self->_values); $max = CRM_Utils_Array::value('max_amount', $self->_values); if ($min && $otherAmountVal < $min) { $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1', array(1 => $min)); } if ($max && $otherAmountVal > $max) { $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.', array(1 => $max)); } } } if (!empty($fields["price_{$priceField->id}"]) || $previousId == $priceField->id && isset($fields["price_{$previousId}"]) && empty($fields["price_{$previousId}"])) { $check[] = $priceField->id; } } // CRM-12233 if ($membershipIsActive && !$self->_membershipBlock['is_required'] && $self->_values['amount_block_is_active']) { $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL; foreach ($self->_values['fee'] as $fieldKey => $fieldValue) { // if 'No thank you' membership is selected then set $membershipFieldId if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) { $membershipFieldId = $fieldKey; } elseif ($membershipFieldId) { if ($fieldValue['name'] == 'other_amount') { $otherFieldId = $fieldKey; } elseif ($fieldValue['name'] == 'contribution_amount') { $contributionFieldId = $fieldKey; } if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') { $errorKey = $fieldKey; } } } // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) { $errors["price_{$errorKey}"] = ts('Additional Contribution is required.'); } } if (empty($check)) { if ($self->_useForMember == 1 && $membershipIsActive) { $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).'); } else { $errors['_qf_default'] = ts('Select at least one option from Contribution(s).'); } } if ($otherAmount && !empty($check)) { $errors["price_{$otherAmount}"] = ts('Amount is required field.'); } if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) { $priceFieldIDS = array(); $priceFieldMemTypes = array(); foreach ($self->_priceSet['fields'] as $priceId => $value) { if (!empty($fields['price_' . $priceId]) || $self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required'])) { if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) { foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) { if ($isSet) { $priceFieldIDS[] = $priceFldVal; } } } elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) { // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577 $priceFieldIDS[] = $fields['price_' . $priceId]; } if (!empty($value['options'])) { foreach ($value['options'] as $val) { if (!empty($val['membership_type_id'])) { $priceFieldMemTypes[] = $val['membership_type_id']; } } } } } if (!empty($lifeMember)) { foreach ($priceFieldIDS as $priceFieldId) { if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) && in_array($membershipOrgDetails[$id], $unallowedOrgs)) { $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.'); break; } } } if (!empty($priceFieldIDS)) { $ids = implode(',', $priceFieldIDS); $priceFieldIDS['id'] = $fields['priceSetId']; $self->set('memberPriceFieldIDS', $priceFieldIDS); $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids); foreach ($count as $id => $occurance) { if ($occurance > 1) { $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.'); } } } if (empty($priceFieldMemTypes)) { $errors['_qf_default'] = ts('Please select at least one membership option.'); } } CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem); if ($fields['amount'] < 0) { $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly'); } $amount = $fields['amount']; } if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks') { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $fields['selectProduct']; $productDAO->find(TRUE); $min_amount = $productDAO->min_contribution; if ($amount < $min_amount) { $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount))); CRM_Core_Session::setStatus($errors['selectProduct']); } } if (!empty($fields['is_recur'])) { if ($fields['frequency_interval'] <= 0) { $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).'); } if ($fields['frequency_unit'] == '0') { $errors['frequency_unit'] = ts('Please select a period (e.g. months, years ...) for how often you want to make this recurring contribution (EXAMPLE: Every 3 MONTHS).'); } } if (!empty($fields['is_recur']) && CRM_Utils_Array::value('payment_processor', $fields) == 0) { $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.'); } if (!empty($fields['is_for_organization']) && !property_exists($self, 'organizationName')) { if (empty($fields['onbehalf']['organization_name'])) { if (!empty($fields['org_option']) && !$fields['onbehalfof_id']) { $errors['organization_id'] = ts('Please select an organization or enter a new one.'); } elseif (empty($fields['org_option'])) { $errors['onbehalf']['organization_name'] = ts('Please enter the organization name.'); } } foreach ($fields['onbehalf'] as $key => $value) { if (strstr($key, 'email')) { $emailLocType = explode('-', $key); } } if (empty($fields['onbehalf']["email-{$emailLocType[1]}"])) { $errors['onbehalf']["email-{$emailLocType[1]}"] = ts('Organization email is required.'); } } // validate PCP fields - if not anonymous, we need a nick name value if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') { $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.'); } // return if this is express mode $config = CRM_Core_Config::singleton(); if ($self->_paymentProcessor && $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) { if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) { return $errors; } } //validate the pledge fields. if (!empty($self->_values['pledge_block_id'])) { //validation for pledge payment. if (!empty($self->_values['pledge_id'])) { if (empty($fields['pledge_amount'])) { $errors['pledge_amount'] = ts('At least one payment option needs to be checked.'); } } elseif (!empty($fields['is_pledge'])) { if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) { $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.'); } else { if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) { $errors['pledge_installments'] = ts('Pledge Installments is required field.'); } elseif (CRM_Utils_array::value('pledge_installments', $fields) == 1) { $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.'); } elseif (CRM_Utils_array::value('pledge_installments', $fields) == 0) { $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.'); } } //validation for Pledge Frequency Interval. if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) { $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.'); } else { if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) { $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.'); } elseif (CRM_Utils_array::value('pledge_frequency_interval', $fields) == 0) { $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0'); } } } } // also return if paylater mode if (CRM_Utils_Array::value('payment_processor', $fields) == 0) { return empty($errors) ? TRUE : $errors; } // if the user has chosen a free membership or the amount is less than zero // i.e. we skip calling the payment processor and hence dont need credit card // info if ((double) $amount <= 0.0) { return $errors; } if (!empty($self->_paymentFields)) { CRM_Core_Form::validateMandatoryFields($self->_paymentFields, $fields, $errors); } CRM_Core_Payment_Form::validateCreditCard($fields, $errors); foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) { $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name'); if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) { $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting)))); } } } return empty($errors) ? TRUE : $errors; }
/** * Global form rule. * * @param array $fields * The input form values. * @param array $files * The uploaded files if any. * @param CRM_Core_Form $self * * @return bool|array * true if no errors, else array of errors */ public static function formRule($fields, $files, $self) { $errors = array(); $amount = self::computeAmount($fields, $self->_values); if (CRM_Utils_Array::value('auto_renew', $fields) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) { $errors['auto_renew'] = ts('You cannot have auto-renewal on if you are paying later.'); } if (!empty($fields['selectMembership']) && $fields['selectMembership'] != 'no_thanks' || !empty($fields['priceSetId']) && $self->_useForMember) { $isTest = $self->_action & CRM_Core_Action::PREVIEW ? TRUE : FALSE; $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, $isTest, TRUE); $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(); $unallowedOrgs = array(); foreach (array_keys($lifeMember) as $memTypeId) { $unallowedOrgs[] = $membershipOrgDetails[$memTypeId]; } } //check for atleast one pricefields should be selected if (!empty($fields['priceSetId']) && empty($self->_ccid)) { $priceField = new CRM_Price_DAO_PriceField(); $priceField->price_set_id = $fields['priceSetId']; $priceField->orderBy('weight'); $priceField->find(); $check = array(); $membershipIsActive = TRUE; $previousId = $otherAmount = FALSE; while ($priceField->fetch()) { if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) { $previousId = $priceField->id; if ($priceField->name == 'membership_amount' && !$priceField->is_active) { $membershipIsActive = FALSE; } } if ($priceField->name == 'other_amount') { if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) && array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])) { $otherAmount = $priceField->id; } elseif (!empty($fields["price_{$priceField->id}"])) { $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]); $min = CRM_Utils_Array::value('min_amount', $self->_values); $max = CRM_Utils_Array::value('max_amount', $self->_values); if ($min && $otherAmountVal < $min) { $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1', array(1 => $min)); } if ($max && $otherAmountVal > $max) { $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.', array(1 => $max)); } } } if (!empty($fields["price_{$priceField->id}"]) || $previousId == $priceField->id && isset($fields["price_{$previousId}"]) && empty($fields["price_{$previousId}"])) { $check[] = $priceField->id; } } $currentMemberships = NULL; if ($membershipIsActive) { $is_test = $self->_mode != 'live' ? 1 : 0; $memContactID = $self->_membershipContactID; // For anonymous user check using dedupe rule // if user has Cancelled Membership if (!$memContactID) { $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual'); $dedupeParams['check_permission'] = FALSE; $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual'); // if we find more than one contact, use the first one $memContactID = CRM_Utils_Array::value(0, $ids); } $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID, $is_test); $errorText = 'Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.'; foreach ($self->_values['fee'] as $fieldKey => $fieldValue) { if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array::value('price_' . $fieldKey, $fields)) { if (!is_array($fields['price_' . $fieldKey]) && isset($fieldValue['options'][$fields['price_' . $fieldKey]])) { if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]]) && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)) { $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id']))); } } else { if (is_array($fields['price_' . $fieldKey])) { foreach (array_keys($fields['price_' . $fieldKey]) as $key) { if (array_key_exists('membership_type_id', $fieldValue['options'][$key]) && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)) { $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$key]['membership_type_id']))); } } } } } } } // CRM-12233 if ($membershipIsActive && !$self->_membershipBlock['is_required'] && $self->_values['amount_block_is_active']) { $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL; foreach ($self->_values['fee'] as $fieldKey => $fieldValue) { // if 'No thank you' membership is selected then set $membershipFieldId if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) { $membershipFieldId = $fieldKey; } elseif ($membershipFieldId) { if ($fieldValue['name'] == 'other_amount') { $otherFieldId = $fieldKey; } elseif ($fieldValue['name'] == 'contribution_amount') { $contributionFieldId = $fieldKey; } if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') { $errorKey = $fieldKey; } } } // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) { $errors["price_{$errorKey}"] = ts('Additional Contribution is required.'); } } if (empty($check) && empty($self->_ccid)) { if ($self->_useForMember == 1 && $membershipIsActive) { $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).'); } else { $errors['_qf_default'] = ts('Select at least one option from Contribution(s).'); } } if ($otherAmount && !empty($check)) { $errors["price_{$otherAmount}"] = ts('Amount is required field.'); } if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) { $priceFieldIDS = array(); $priceFieldMemTypes = array(); foreach ($self->_priceSet['fields'] as $priceId => $value) { if (!empty($fields['price_' . $priceId]) || $self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required'])) { if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) { foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) { if ($isSet) { $priceFieldIDS[] = $priceFldVal; } } } elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) { // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577 $priceFieldIDS[] = $fields['price_' . $priceId]; } if (!empty($value['options'])) { foreach ($value['options'] as $val) { if (!empty($val['membership_type_id']) && ($fields['price_' . $priceId] == $val['id'] || isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))) { $priceFieldMemTypes[] = $val['membership_type_id']; } } } } } if (!empty($lifeMember)) { foreach ($priceFieldIDS as $priceFieldId) { if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) && in_array($membershipOrgDetails[$id], $unallowedOrgs)) { $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.'); break; } } } if (!empty($priceFieldIDS)) { $ids = implode(',', $priceFieldIDS); $priceFieldIDS['id'] = $fields['priceSetId']; $self->set('memberPriceFieldIDS', $priceFieldIDS); $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids); foreach ($count as $id => $occurrence) { if ($occurrence > 1) { $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.'); } } } if (empty($priceFieldMemTypes) && $self->_membershipBlock['is_required'] == 1) { $errors['_qf_default'] = ts('Please select at least one membership option.'); } } CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem); if ($fields['amount'] < 0) { $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly'); } $amount = $fields['amount']; } if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks') { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $fields['selectProduct']; $productDAO->find(TRUE); $min_amount = $productDAO->min_contribution; if ($amount < $min_amount) { $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount))); CRM_Core_Session::setStatus($errors['selectProduct']); } } //CRM-16285 - Function to handle validation errors on form, for recurring contribution field. CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors); if (!empty($fields['is_recur']) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) { $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.'); } // validate PCP fields - if not anonymous, we need a nick name value if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') { $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.'); } // return if this is express mode $config = CRM_Core_Config::singleton(); if ($self->_paymentProcessor && $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) { if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) { return $errors; } } //validate the pledge fields. if (!empty($self->_values['pledge_block_id'])) { //validation for pledge payment. if (!empty($self->_values['pledge_id'])) { if (empty($fields['pledge_amount'])) { $errors['pledge_amount'] = ts('At least one payment option needs to be checked.'); } } elseif (!empty($fields['is_pledge'])) { if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) { $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.'); } else { if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) { $errors['pledge_installments'] = ts('Pledge Installments is required field.'); } elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 1) { $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.'); } elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 0) { $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.'); } } //validation for Pledge Frequency Interval. if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) { $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.'); } else { if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) { $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.'); } elseif (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == 0) { $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0'); } } } } // if the user has chosen a free membership or the amount is less than zero // i.e. we don't need to validate payment related fields or profiles. if ((double) $amount <= 0.0) { return $errors; } if (CRM_Utils_Array::value('payment_processor_id', $fields) == NULL) { $errors['payment_processor_id'] = ts('Payment Method is a required field.'); } else { CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, !$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing'); } foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) { $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name'); if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) { $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting)))); } } } return empty($errors) ? TRUE : $errors; }
/** * Process the contribution * * @return void * @access public */ static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = true, $pending = false, $online = true) { require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); $className = get_class($form); $honorCId = $recurringContributionID = null; if ($online && $form->get('honor_block_is_active')) { $honorCId = $form->createHonorContact(); } $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $online); if (!$online && isset($params['honor_contact_id'])) { $honorCId = $params['honor_contact_id']; } $config = CRM_Core_Config::singleton(); if (!$online && isset($params['non_deductible_amount'])) { $nonDeductibleAmount = $params['non_deductible_amount']; } else { $nonDeductibleAmount = $params['amount']; } if ($online && $contributionType->is_deductible && $deductibleMode) { $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams); if ($selectProduct && $selectProduct != 'no_thanks') { require_once 'CRM/Contribute/DAO/Product.php'; $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $selectProduct; $productDAO->find(true); if ($params['amount'] < $productDAO->price) { $nonDeductibleAmount = $params['amount']; } else { $nonDeductibleAmount = $productDAO->price; } } else { $nonDeductibleAmount = '0.00'; } } $now = date('YmdHis'); $receiptDate = CRM_Utils_Array::value('receipt_date', $params); if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) { $receiptDate = $now; } //get the contrib page id. $contributionPageId = null; if ($online) { $contributionPageId = $form->_id; } else { //also for offline we do support - CRM-7290 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params); } // first create the contribution record $contribParams = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'contribution_page_id' => $contributionPageId, 'receive_date' => $now, 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $params['amount'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || CRM_Utils_Array::value('source', $params) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), '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); if (!$online && isset($params['thankyou_date'])) { $contribParams['thankyou_date'] = $params['thankyou_date']; } if (!$online || $form->_values['is_monetary']) { if (!CRM_Utils_Array::value('is_pay_later', $params)) { $contribParams['payment_instrument_id'] = 1; } } if (!$pending && $result) { $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => $result['trxn_result_code'], 'payment_processor' => $result['payment_processor']); } if (isset($honorCId)) { $contribParams['honor_contact_id'] = $honorCId; $contribParams['honor_type_id'] = $params['honor_type_id']; } if ($recurringContributionID) { $contribParams['contribution_recur_id'] = $recurringContributionID; } $contribParams['contribution_status_id'] = $pending ? 2 : 1; $contribParams['is_test'] = 0; if ($form->_mode == 'test') { $contribParams['is_test'] = 1; } $ids = array(); if (isset($contribParams['invoice_id'])) { $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id'); if (isset($contribID)) { $ids['contribution'] = $contribID; $contribParams['id'] = $contribID; } } foreach (array('pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note') as $val) { if (CRM_Utils_Array::value($val, $params)) { $contribSoftParams[$val] = $params[$val]; } } require_once 'CRM/Contribute/BAO/Contribution.php'; //create an contribution address if ($form->_contributeMode != 'notify' && !CRM_Utils_Array::value('is_pay_later', $params)) { $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID); } // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts require_once 'CRM/Utils/Money.php'; $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' ')); $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' ')); //add contribution record $contribution =& CRM_Contribute_BAO_Contribution::add($contribParams, $ids); // process price set, CRM-5095 if ($contribution->id && $form->_priceSetId) { require_once 'CRM/Contribute/Form/AdditionalInfo.php'; CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $form->_lineItem); } //add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin. if (CRM_Utils_Array::value('pcp_made_through_id', $params) || CRM_Utils_Array::value('soft_credit_to', $params)) { $contribSoftParams['contribution_id'] = $contribution->id; $contribSoftParams['amount'] = $params['amount']; //if its due to pcp if (CRM_Utils_Array::value('pcp_made_through_id', $params)) { $contribSoftParams['pcp_id'] = $params['pcp_made_through_id']; $contribSoftParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_PCP', $params['pcp_made_through_id'], 'contact_id'); } else { $contribSoftParams['contact_id'] = CRM_Utils_Array::value('soft_credit_to', $params); } $softContribution = CRM_Contribute_BAO_Contribution::addSoftContribution($contribSoftParams); } //handle pledge stuff. if (!CRM_Utils_Array::value('separate_membership_payment', $form->_params) && CRM_Utils_Array::value('pledge_block_id', $form->_values) && (CRM_Utils_Array::value('is_pledge', $form->_params) || CRM_Utils_Array::value('pledge_id', $form->_values))) { if (CRM_Utils_Array::value('pledge_id', $form->_values)) { //when user doing pledge payments. //update the schedule when payment(s) are made require_once 'CRM/Pledge/BAO/Payment.php'; foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) { $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Payment', $paymentId, 'scheduled_amount', 'id'); $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount); CRM_Pledge_BAO_Payment::add($pledgePaymentParams); } //update pledge status according to the new payment statuses CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($form->_values['pledge_id']); } 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['contribution_type_id'] = $contribution->contribution_type_id; $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval']; $pledgeParams['installments'] = $params['pledge_installments']; $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit']; $pledgeParams['frequency_day'] = 1; $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd"); $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']; require_once 'CRM/Pledge/BAO/Pledge.php'; $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams); $form->_params['pledge_id'] = $pledge->id; //send acknowledgment email. only when pledge is created if ($pledge->id) { //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; require_once 'CRM/Pledge/BAO/Pledge.php'; CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams); } } } if ($online) { require_once 'CRM/Core/BAO/CustomValueTable.php'; CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution'); } else { //handle custom data. $params['contribution_id'] = $contribution->id; if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) { require_once 'CRM/Core/BAO/CustomValueTable.php'; CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id); } } require_once 'CRM/Contribute/BAO/Contribution/Utils.php'; if (isset($params['related_contact'])) { $contactID = $params['related_contact']; } else { if (isset($params['cms_contactID'])) { $contactID = $params['cms_contactID']; } } CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID); // return if pending if ($pending) { return $contribution; } // next create the transaction record if ((!$online || $form->_values['is_monetary']) && $result['trxn_id']) { $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'currency' => $params['currencyID'], 'payment_processor' => $form->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id'], 'trxn_result_code' => $result['trxn_result_code']); require_once 'CRM/Core/BAO/FinancialTrxn.php'; $trxn =& CRM_Core_BAO_FinancialTrxn::create($trxnParams); } //create contribution activity w/ individual and target //activity w/ organisation contact id when onbelf, CRM-4027 $targetContactID = null; if (CRM_Utils_Array::value('is_for_organization', $params)) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $contactID; } // create an activity record require_once 'CRM/Activity/BAO/Activity.php'; CRM_Activity_BAO_Activity::addActivity($contribution, null, $targetContactID); $transaction->commit(); return $contribution; }