/** * Get line item purchase information. * * This function takes the input parameters and interprets out of it what has been purchased. * * @param $fields * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE); * And, it would make sense to introduce caching into that function and call it from here rather than * require the $fields array which is passed from pillar to post around the form in order to pass it in here. * @param array $params * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8) * @param $lineItem * Line item array to be altered. * @param string $component * This parameter appears to only be relevant to determining whether memberships should be auto-renewed. * (and is effectively a boolean for 'is_membership' which could be calculated from the line items.) */ public static function processAmount($fields, &$params, &$lineItem, $component = '') { // using price set $totalPrice = $totalTax = 0; $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array(); if ($component) { $autoRenew = array(); $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0; } foreach ($fields as $id => $field) { if (empty($params["price_{$id}"]) || empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL) { // skip if nothing was submitted for this field continue; } switch ($field['html_type']) { case 'Text': $firstOption = reset($field['options']); $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]); CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem); if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) { $lineItem = self::setLineItem($field, $lineItem, key($field['options'])); $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty']; } if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') { $taxRates = CRM_Core_PseudoConstant::getTaxRates(); if (array_key_exists($params['financial_type_id'], $taxRates)) { $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']]; $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']); $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2); $lineItem = self::setLineItem($field, $lineItem, key($field['options'])); $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty']; } } $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]); break; case 'Radio': //special case if user select -none- if ($params["price_{$id}"] <= 0) { continue; } $params["price_{$id}"] = array($params["price_{$id}"] => 1); $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]); $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]); $params['amount_priceset_level_radio'] = array(); $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel; if (isset($radioLevel)) { $radioLevel = array_merge($radioLevel, array_keys($params['amount_priceset_level_radio'])); } else { $radioLevel = array_keys($params['amount_priceset_level_radio']); } CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem); if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) { $lineItem = self::setLineItem($field, $lineItem, $optionValueId); $totalTax += $field['options'][$optionValueId]['tax_amount']; if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') { $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']); } } $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]); if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) { $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total']; } break; case 'Select': $params["price_{$id}"] = array($params["price_{$id}"] => 1); $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]); $optionLabel = $field['options'][$optionValueId]['label']; $params['amount_priceset_level_select'] = array(); $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel; if (isset($selectLevel)) { $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select'])); } else { $selectLevel = array_keys($params['amount_priceset_level_select']); } CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem); if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) { $lineItem = self::setLineItem($field, $lineItem, $optionValueId); $totalTax += $field['options'][$optionValueId]['tax_amount']; } $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]); if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) { $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total']; } break; case 'CheckBox': $params['amount_priceset_level_checkbox'] = $optionIds = array(); foreach ($params["price_{$id}"] as $optionId => $option) { $optionIds[] = $optionId; $optionLabel = $field['options'][$optionId]['label']; $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel; if (isset($checkboxLevel)) { $checkboxLevel = array_unique(array_merge($checkboxLevel, array_keys($params['amount_priceset_level_checkbox']))); } else { $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']); } } CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem); foreach ($optionIds as $optionId) { if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) { $lineItem = self::setLineItem($field, $lineItem, $optionId); $totalTax += $field['options'][$optionId]['tax_amount']; } $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]); if ($component && isset($lineItem[$optionId]['auto_renew']) && is_numeric($lineItem[$optionId]['auto_renew'])) { $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total']; } } break; } } $amount_level = array(); $totalParticipant = 0; if (is_array($lineItem)) { foreach ($lineItem as $values) { $totalParticipant += $values['participant_count']; $amount_level[] = $values['label'] . ' - ' . (double) $values['qty']; } } $displayParticipantCount = ''; if ($totalParticipant > 0) { $displayParticipantCount = ' Participant Count -' . $totalParticipant; } $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR; $params['amount'] = CRM_Utils_Money::format($totalPrice, NULL, NULL, TRUE); $params['tax_amount'] = $totalTax; if ($component) { foreach ($autoRenew as $dontCare => $eachAmount) { if (!$eachAmount) { unset($autoRenew[$dontCare]); } } if (count($autoRenew) > 1) { $params['autoRenew'] = $autoRenew; } } }
/** * process the form after the input has been submitted and validated * * @access public * @return None */ public function postProcess() { //get the submitted form values. $submittedValues = $this->controller->exportValues($this->_name); // get the chart type. $chartType = CRM_Utils_Array::value('chart_type', $submittedValues, 'bvg'); //take contribution information monthly require_once 'CRM/Contribute/BAO/Contribution/Utils.php'; $selectedYear = CRM_Utils_Array::value('select_year', $submittedValues, date('Y')); $chartInfoMonthly = CRM_Contribute_BAO_Contribution_Utils::contributionChartMonthly($selectedYear); $chartData = $abbrMonthNames = array(); if (is_array($chartInfoMonthly)) { for ($i = 1; $i <= 12; $i++) { $abbrMonthNames[$i] = strftime('%b', mktime(0, 0, 0, $i, 10, 1970)); } foreach ($abbrMonthNames as $monthKey => $monthName) { $val = CRM_Utils_Array::value($monthKey, $chartInfoMonthly['By Month'], 0); // don't include zero value month. if (!$val && $chartType != 'bvg') { continue; } //build the params for chart. $chartData['by_month']['values'][$monthName] = $val; } $chartData['by_month']['legend'] = 'By Month' . ' - ' . $selectedYear; // handle onclick event. $chartData['by_month']['on_click_fun_name'] = 'byMonthOnClick'; $chartData['by_month']['yname'] = ts('Contribution'); } //take contribution information by yearly $chartInfoYearly = CRM_Contribute_BAO_Contribution_Utils::contributionChartYearly(); //get the years. $this->_years = $chartInfoYearly['By Year']; $hasContributions = false; if (is_array($chartInfoYearly)) { $hasContributions = true; $chartData['by_year']['legend'] = 'By Year'; $chartData['by_year']['values'] = $chartInfoYearly['By Year']; // handle onclick event. $chartData['by_year']['on_click_fun_name'] = 'byYearOnClick'; $chartData['by_year']['yname'] = ts('Contribution'); } $this->assign('hasContributions', $hasContributions); // process the data. require_once 'CRM/Utils/OpenFlashChart.php'; $chartCnt = 1; $monthlyChart = $yearlyChart = false; foreach ($chartData as $chartKey => &$values) { $chartValues = CRM_Utils_Array::value('values', $values); if (!is_array($chartValues) || empty($chartValues)) { continue; } if ($chartKey == 'by_year') { $yearlyChart = true; } if ($chartKey == 'by_month') { $monthlyChart = true; } $values['divName'] = "open_flash_chart_{$chartKey}"; $funName = $chartType == 'bvg' ? 'barChart' : 'pieChart'; // build the chart objects. eval("\$values['object'] = CRM_Utils_OpenFlashChart::" . $funName . '( $values );'); //build the urls. $urlCnt = 0; foreach ($chartValues as $index => $val) { $urlParams = null; if ($chartKey == 'by_month') { $monthPosition = array_search($index, $abbrMonthNames); $startDate = CRM_Utils_Date::format(array('Y' => $selectedYear, 'M' => $monthPosition)); $endDate = date('Ymd', mktime(0, 0, 0, $monthPosition + 1, 0, $selectedYear)); $urlParams = "reset=1&force=1&status=1&start={$startDate}&end={$endDate}&test=0"; } else { if ($chartKey == 'by_year') { $startDate = CRM_Utils_Date::format(array('Y' => $index)); $endDate = date('Ymd', mktime(0, 0, 0, 13, 0, $index)); $urlParams = "reset=1&force=1&status=1&start={$startDate}&end={$endDate}&test=0"; } } if ($urlParams) { $values['on_click_urls']["url_" . $urlCnt++] = CRM_Utils_System::url('civicrm/contribute/search', $urlParams, true, false, false); } } // calculate chart size. $xSize = 400; $ySize = 300; if ($chartType == 'bvg') { $ySize = 250; $xSize = 60 * count($chartValues); //hack to show tooltip. if ($xSize < 150) { $xSize = 150; } } $values['size'] = array('xSize' => $xSize, 'ySize' => $ySize); } // finally assign this chart data to template. $this->assign('hasYearlyChart', $yearlyChart); $this->assign('hasByMonthChart', $monthlyChart); $this->assign('hasOpenFlashChart', empty($chartData) ? false : true); $this->assign('openFlashChartData', json_encode($chartData)); }
/** * @param array $apiParams * @param $mapper * @param string $type * @param bool $category * * @return array */ public static function formatAPIParams($apiParams, $mapper, $type = 'paypal', $category = TRUE) { $type = strtolower($type); if (!in_array($type, array('paypal', 'google', 'csv'))) { // return the params as is return $apiParams; } $params = $transaction = array(); if ($type == 'paypal') { foreach ($apiParams as $detail => $val) { if (isset($mapper['contact'][$detail])) { $params[$mapper['contact'][$detail]] = $val; } elseif (isset($mapper['location'][$detail])) { $params['address'][1][$mapper['location'][$detail]] = $val; } elseif (isset($mapper['transaction'][$detail])) { switch ($detail) { case 'l_period2': // Sadly, PayPal seems to send two distinct data elements in a single field, // so we break them out here. This is somewhat ugly and tragic. $freqUnits = array('D' => 'day', 'W' => 'week', 'M' => 'month', 'Y' => 'year'); list($frequency_interval, $frequency_unit) = explode(' ', $val); $transaction['frequency_interval'] = $frequency_interval; $transaction['frequency_unit'] = $freqUnits[$frequency_unit]; break; case 'subscriptiondate': case 'timestamp': // PayPal dates are in ISO-8601 format. We need a format that // MySQL likes $unix_timestamp = strtotime($val); $transaction[$mapper['transaction'][$detail]] = date('YmdHis', $unix_timestamp); break; case 'note': case 'custom': case 'l_number0': if ($val) { $val = "[PayPal_field:{$detail}] {$val}"; $transaction[$mapper['transaction'][$detail]] = !empty($transaction[$mapper['transaction'][$detail]]) ? $transaction[$mapper['transaction'][$detail]] . " <br/> " . $val : $val; } break; default: $transaction[$mapper['transaction'][$detail]] = $val; } } } if (!empty($transaction) && $category) { $params['transaction'] = $transaction; } else { $params += $transaction; } CRM_Contribute_BAO_Contribution_Utils::_fillCommonParams($params, $type); return $params; } if ($type == 'csv') { $header = $apiParams['header']; unset($apiParams['header']); foreach ($apiParams as $key => $val) { if (isset($mapper['contact'][$header[$key]])) { $params[$mapper['contact'][$header[$key]]] = $val; } elseif (isset($mapper['location'][$header[$key]])) { $params['address'][1][$mapper['location'][$header[$key]]] = $val; } elseif (isset($mapper['transaction'][$header[$key]])) { $transaction[$mapper['transaction'][$header[$key]]] = $val; } else { $params[$header[$key]] = $val; } } if (!empty($transaction) && $category) { $params['transaction'] = $transaction; } else { $params += $transaction; } CRM_Contribute_BAO_Contribution_Utils::_fillCommonParams($params, $type); return $params; } if ($type == 'google') { // return if response smell invalid if (!array_key_exists('risk-information-notification', $apiParams[1][$apiParams[0]]['notifications'])) { return FALSE; } $riskInfo =& $apiParams[1][$apiParams[0]]['notifications']['risk-information-notification']; if (array_key_exists('new-order-notification', $apiParams[1][$apiParams[0]]['notifications'])) { $newOrder =& $apiParams[1][$apiParams[0]]['notifications']['new-order-notification']; } if ($riskInfo['google-order-number']['VALUE'] == $apiParams[2]['google-order-number']['VALUE']) { foreach ($riskInfo['risk-information']['billing-address'] as $field => $info) { if (!empty($mapper['location'][$field])) { $params['address'][1][$mapper['location'][$field]] = $info['VALUE']; } elseif (!empty($mapper['contact'][$field])) { if ($newOrder && !empty($newOrder['buyer-billing-address']['structured-name'])) { foreach ($newOrder['buyer-billing-address']['structured-name'] as $namePart => $nameValue) { $params[$mapper['contact'][$namePart]] = $nameValue['VALUE']; } } else { $params[$mapper['contact'][$field]] = $info['VALUE']; } } elseif (!empty($mapper['transaction'][$field])) { $transaction[$mapper['transaction'][$field]] = $info['VALUE']; } } // Response is an huge array. Lets pickup only those which we ineterested in // using a local mapper, rather than traversing the entire array. $localMapper = array('google-order-number' => $riskInfo['google-order-number']['VALUE'], 'total-charge-amount' => $apiParams[2]['total-charge-amount']['VALUE'], 'currency' => $apiParams[2]['total-charge-amount']['currency'], 'item-name' => $newOrder['shopping-cart']['items']['item']['item-name']['VALUE'], 'timestamp' => $apiParams[2]['timestamp']['VALUE']); if (array_key_exists('latest-charge-fee', $apiParams[2])) { $localMapper['latest-charge-fee'] = $apiParams[2]['latest-charge-fee']['total']['VALUE']; $localMapper['net-amount'] = $localMapper['total-charge-amount'] - $localMapper['latest-charge-fee']; } // This is a subscription (recurring) donation. if (array_key_exists('subscription', $newOrder['shopping-cart']['items']['item'])) { $subscription = $newOrder['shopping-cart']['items']['item']['subscription']; $localMapper['amount'] = $newOrder['order-total']['VALUE']; $localMapper['times'] = $subscription['payments']['subscription-payment']['times']; // Convert Google's period to one compatible with the CiviCRM db field. $freqUnits = array('DAILY' => 'day', 'WEEKLY' => 'week', 'MONHTLY' => 'month', 'YEARLY' => 'year'); $localMapper['period'] = $freqUnits[$subscription['period']]; // Unlike PayPal, Google has no concept of freq. interval, it is always 1. $localMapper['frequency_interval'] = '1'; // Google Checkout dates are in ISO-8601 format. We need a format that // MySQL likes $unix_timestamp = strtotime($localMapper['timestamp']); $mysql_date = date('YmdHis', $unix_timestamp); $localMapper['modified_date'] = $mysql_date; $localMapper['start_date'] = $mysql_date; // This is PayPal's nomenclature, but just use it for Google as well since // we act on the value of trxn_type in processAPIContribution(). $localMapper['trxn_type'] = 'subscrpayment'; } foreach ($localMapper as $localKey => $localVal) { if (!empty($mapper['transaction'][$localKey])) { $transaction[$mapper['transaction'][$localKey]] = $localVal; } } if (empty($params) && empty($transaction)) { continue; } if (!empty($transaction) && $category) { $params['transaction'] = $transaction; } else { $params += $transaction; } CRM_Contribute_BAO_Contribution_Utils::_fillCommonParams($params, $type); } return $params; } }
/** * Retrieve a list of options for the specified field. * * @param int $fieldId * Price field ID. * @param bool $inactiveNeeded * Include inactive options. * @param bool $reset * Ignore stored values\. * * @return array * array of options */ public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) { static $options = array(); if ($reset || empty($options[$fieldId])) { $values = array(); CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded); $options[$fieldId] = $values; $taxRates = CRM_Core_PseudoConstant::getTaxRates(); // ToDo - Code for Hook Invoke foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) { if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates)) { $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']]; $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']); $options[$fieldId][$priceFieldId]['tax_amount'] = round($taxAmount['tax_amount'], 2); } } } return $options[$fieldId]; }
/** * Check tax amount. * * @param array $params * @param bool $isLineItem * * @return mixed */ public static function checkTaxAmount($params, $isLineItem = FALSE) { $taxRates = CRM_Core_PseudoConstant::getTaxRates(); // Update contribution. if (!empty($params['id'])) { $id = $params['id']; $values = $ids = array(); $contrbutionParams = array('id' => $id); $prevContributionValue = CRM_Contribute_BAO_Contribution::getValues($contrbutionParams, $values, $ids); // To assign pervious finantial type on update of contribution if (!isset($params['financial_type_id'])) { $params['financial_type_id'] = $prevContributionValue->financial_type_id; } elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) { // Assisn tax Amount on update of contrbution if (!empty($prevContributionValue->tax_amount)) { $params['tax_amount'] = 'null'; CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id'])); foreach ($params['line_item'] as $setID => $priceField) { foreach ($priceField as $priceFieldID => $priceFieldValue) { $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount']; } } } } } // New Contrbution and update of contribution with tax rate financial type if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && empty($params['skipLineItem']) && !$isLineItem) { $taxRateParams = $taxRates[$params['financial_type_id']]; $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['total_amount'], $taxRateParams); $params['tax_amount'] = round($taxAmount['tax_amount'], 2); // Get Line Item on update of contribution if (isset($params['id'])) { CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id'])); } else { CRM_Price_BAO_LineItem::getLineItemArray($params); } foreach ($params['line_item'] as $setID => $priceField) { foreach ($priceField as $priceFieldID => $priceFieldValue) { $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount']; } } $params['total_amount'] = $params['total_amount'] + $params['tax_amount']; } elseif (isset($params['api.line_item.create'])) { // Update total amount of contribution using lineItem $taxAmountArray = array(); foreach ($params['api.line_item.create'] as $key => $value) { if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) { $taxRate = $taxRates[$value['financial_type_id']]; $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate); $taxAmountArray[] = round($taxAmount['tax_amount'], 2); } } $params['tax_amount'] = array_sum($taxAmountArray); $params['total_amount'] = $params['total_amount'] + $params['tax_amount']; } else { // update line item of contrbution if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) { $taxRate = $taxRates[$params['financial_type_id']]; $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate); $params['tax_amount'] = round($taxAmount['tax_amount'], 2); } } return $params; }
/** * Process the Memberships. * * @param array $membershipParams * Array of membership fields. * @param int $contactID * Contact id. * @param CRM_Contribute_Form_Contribution_Confirm $form * Confirmation form object. * * @param array $premiumParams * @param null $customFieldsFormatted * @param null $includeFieldTypes * * @param array $membershipDetails * * @param array $membershipTypeIDs * * @param bool $isPaidMembership * @param array $membershipID * * @param $isProcessSeparateMembershipTransaction * * @param int $defaultContributionTypeID * @param array $membershipLineItems * Line items specific to membership payment that is separate to contribution. * @param $isPayLater * * @throws \CRM_Core_Exception */ public static function postProcessMembership($membershipParams, $contactID, &$form, $premiumParams, $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID, $isProcessSeparateMembershipTransaction, $defaultContributionTypeID, $membershipLineItems, $isPayLater) { $result = $membershipContribution = NULL; $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE); $errors = $createdMemberships = array(); //@todo move this into the calling function & pass in the correct financialTypeID if (isset($paymentParams['financial_type'])) { $financialTypeID = $paymentParams['financial_type']; } else { $financialTypeID = $defaultContributionTypeID; } if (CRM_Utils_Array::value('membership_source', $form->_params)) { $membershipParams['contribution_source'] = $form->_params['membership_source']; } if ($isPaidMembership) { $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $premiumParams, $contactID, $financialTypeID, 'membership', array(), $isTest, $isPayLater); if (is_a($result[1], 'CRM_Core_Error')) { $errors[1] = CRM_Core_Error::getMessages($result[1]); } elseif (!empty($result[1])) { // Save the contribution ID so that I can be used in email receipts // For example, if you need to generate a tax receipt for the donation only. $form->_values['contribution_other_id'] = $result[1]->id; //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one $membershipContribution = $result[1]; } } if ($isProcessSeparateMembershipTransaction) { try { $lineItems = $form->_lineItem = $membershipLineItems; if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) { unset($membershipParams['is_recur']); } $membershipContribution = self::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array::value('financial_type_id', $membershipDetails)); } catch (CRM_Core_Exception $e) { $errors[2] = $e->getMessage(); $membershipContribution = NULL; } } $membership = NULL; if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) { $membershipContributionID = $membershipContribution->id; } //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) { $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id']; } //@todo it should no longer be possible for it to get to this point & membership to not be an array if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) { $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array()); foreach ($membershipTypeIDs as $memType) { $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1); $createdMemberships[$memType] = self::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form); } if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) { foreach ($form->_lineItem[$form->_priceSetId] as &$priceFieldOp) { if (!empty($priceFieldOp['membership_type_id']) && isset($createdMemberships[$priceFieldOp['membership_type_id']])) { $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']]; $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%B %E%f, %Y') : '-'; $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%B %E%f, %Y') : '-'; } else { $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A'; } } $form->_values['lineItem'] = $form->_lineItem; $form->assign('lineItem', $form->_lineItem); } } if (!empty($errors)) { $message = self::compileErrorMessage($errors); throw new CRM_Core_Exception($message); } $form->_params['createdMembershipIDs'] = array(); // CRM-7851 - Moved after processing Payment Errors //@todo - the reasoning for this being here seems a little outdated foreach ($createdMemberships as $createdMembership) { CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_membership', $createdMembership->id, 'Membership'); $form->_params['createdMembershipIDs'][] = $createdMembership->id; } if (count($createdMemberships) == 1) { //presumably this is only relevant for exactly 1 membership $form->_params['membershipID'] = $createdMembership->id; } //CRM-15232: Check if membership is created and on the basis of it use //membership reciept template to send payment reciept if (count($createdMemberships)) { $form->_values['isMembership'] = TRUE; } if ($form->_contributeMode == 'notify') { if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) { // call postProcess hook before leaving $form->postProcessHook(); // this does not return $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form); $payment->doTransferCheckout($form->_params, 'contribute'); } } if (isset($membershipContributionID)) { $form->_values['contribution_id'] = $membershipContributionID; } // Refer to CRM-16737. Payment processors 'should' return payment_status_id // to denote the outcome of the transaction. // // In 4.7 trxn_id will no longer denote the outcome & all processor transactions must return an array // containing payment_status_id. // In 4.6 support (such as there was) for other ways of denoting payment outcome is retained but the use // of payment_status_id is strongly encouraged. if (!empty($form->_params['is_recur']) && $form->_contributeMode == 'direct') { if (!empty($membershipContribution->trxn_id) && !isset($membershipContribution->payment_status_id) || !empty($membershipContribution->payment_status_id) && $membershipContribution->payment_status_id == 1) { try { civicrm_api3('contribution', 'completetransaction', array('id' => $membershipContribution->id, 'trxn_id' => $membershipContribution->trxn_id)); } catch (CiviCRM_API3_Exception $e) { // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296 // so let's be gentle here CRM_Core_Error::debug_log_message('contribution ' . $membershipContribution->id . ' not completed with trxn_id ' . $membershipContribution->trxn_id . ' and message ' . $e->getMessage()); } } // Do not send an email if Recurring transaction is done via Direct Mode // Email will we sent when the IPN is received. return; } //finally send an email receipt CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $isTest, FALSE, $includeFieldTypes); }
/** * Process the Memberships * * @param array $membershipParams array of membership fields * @param int $contactID contact id * @param object $form form object * * @return void * @access public */ public function postProcessMembership($membershipParams, $contactID, &$form, &$premiumParams) { $tempParams = $membershipParams; $paymentDone = false; $result = null; $isTest = CRM_Utils_Array::value('is_test', $membershipParams, false); $form->assign('membership_assign', true); $form->set('membershipTypeID', $membershipParams['selectMembership']); require_once 'CRM/Member/BAO/MembershipType.php'; require_once 'CRM/Member/BAO/Membership.php'; $membershipTypeID = $membershipParams['selectMembership']; $membershipDetails = self::buildMembershipTypeValues($form, $membershipTypeID); $form->assign('membership_name', $membershipDetails['name']); $minimumFee = CRM_Utils_Array::value('minimum_fee', $membershipDetails); $contributionTypeId = null; if ($form->_values['amount_block_is_active']) { $contributionTypeId = $form->_values['contribution_type_id']; } else { $paymentDone = true; $params['amount'] = $minimumFee; $contributionTypeId = $membershipDetails['contribution_type_id']; } //amount must be greater than zero for //adding contribution record to contribution table. //this condition is arises when separate membership payment is //enable and contribution amount is not selected. fix for CRM-3010 require_once 'CRM/Contribute/BAO/Contribution/Utils.php'; if ($form->_amount > 0.0) { $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $premiumParams, $contactID, $contributionTypeId, 'membership'); } else { // create the CMS contact here since we normally do this under processConfirm CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams, $membershipParams['cms_contactID'], 'email-' . $form->_bltID); } $errors = array(); if (is_a($result[1], 'CRM_Core_Error')) { $errors[1] = CRM_Core_Error::getMessages($result[1]); } else { $contribution[1] = $result[1]; } $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($form->_id); if ($memBlockDetails['is_separate_payment'] && !$paymentDone) { require_once 'CRM/Contribute/DAO/ContributionType.php'; $contributionType = new CRM_Contribute_DAO_ContributionType(); $contributionType->id = $membershipDetails['contribution_type_id']; if (!$contributionType->find(true)) { CRM_Core_Error::fatal("Could not find a system table"); } $tempParams['amount'] = $minimumFee; $invoiceID = md5(uniqid(rand(), true)); $tempParams['invoiceID'] = $invoiceID; //we don't allow recurring membership.CRM-3781. if (CRM_Utils_Array::value('is_recur', $tempParams)) { $tempParams['is_recur'] = 0; } $result = null; if ($form->_values['is_monetary'] && !$form->_params['is_pay_later']) { require_once 'CRM/Core/Payment.php'; $payment =& CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form); if ($form->_contributeMode == 'express') { $result =& $payment->doExpressCheckout($tempParams); } else { $result =& $payment->doDirectPayment($tempParams); } } if (is_a($result, 'CRM_Core_Error')) { $errors[2] = CRM_Core_Error::getMessages($result); } else { //assign receive date when separate membership payment //and contribution amount not selected. if ($form->_amount == 0) { $now = date('YmdHis'); $form->_params['receive_date'] = $now; $receiveDate = CRM_Utils_Date::mysqlToIso($now); $form->set('params', $form->_params); $form->assign('receive_date', $receiveDate); } $form->set('membership_trx_id', $result['trxn_id']); $form->set('membership_amount', $minimumFee); $form->assign('membership_trx_id', $result['trxn_id']); $form->assign('membership_amount', $minimumFee); // we dont need to create the user twice, so lets disable cms_create_account // irrespective of the value, CRM-2888 $tempParams['cms_create_account'] = 0; $pending = $form->_params['is_pay_later'] ? true : false; //set this variable as we are not creating pledge for //separate membership payment contribution. //so for differentiating membership contributon from //main contribution. $form->_params['separate_membership_payment'] = 1; $contribution[2] = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $tempParams, $result, $contactID, $contributionType, false, $pending); } } $index = $memBlockDetails['is_separate_payment'] ? 2 : 1; if (!CRM_Utils_Array::value($index, $errors)) { $membership = self::renewMembership($contactID, $membershipTypeID, $isTest, $form, null, CRM_Utils_Array::value('cms_contactID', $membershipParams)); if (isset($contribution[$index])) { //insert payment record require_once 'CRM/Member/DAO/MembershipPayment.php'; $dao = new CRM_Member_DAO_MembershipPayment(); $dao->membership_id = $membership->id; $dao->contribution_id = $contribution[$index]->id; //Fixed for avoiding duplicate entry error when user goes //back and forward during payment mode is notify if (!$dao->find(true)) { CRM_Utils_Hook::pre('create', 'MembershipPayment', null, $dao); $dao->save(); CRM_Utils_Hook::post('create', 'MembershipPayment', $dao->id, $dao); } } } require_once 'CRM/Core/BAO/CustomValueTable.php'; CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_membership', $membership->id, 'Membership'); if (!empty($errors)) { foreach ($errors as $error) { if (is_string($error)) { $message[] = $error; } } $message = ts("Payment Processor Error message") . ": " . implode('<br/>', $message); $session = CRM_Core_Session::singleton(); $session->setStatus($message); CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$form->_params['qfKey']}")); } $form->_params['membershipID'] = $membership->id; if ($form->_contributeMode == 'notify') { if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) { // this does not return require_once 'CRM/Core/Payment.php'; $payment =& CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form); $payment->doTransferCheckout($form->_params, 'contribute'); } } $form->_values['membership_id'] = $membership->id; if (isset($contribution[$index]->id)) { $form->_values['contribution_id'] = $contribution[$index]->id; } // Do not send an email if Recurring transaction is done via Direct Mode // Email will we sent when the IPN is received. if ($form->_params['is_recur'] && $form->_contributeMode == 'direct') { return true; } //finally send an email receipt require_once "CRM/Contribute/BAO/ContributionPage.php"; CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $isTest); }
static function csv() { $csvFile = '/home/deepak/Desktop/crm-4247.csv'; $delimiter = ";"; $row = 1; $handle = fopen($csvFile, "r"); if (!$handle) { CRM_Core_Error::fatal("Can't locate csv file."); } require_once "CRM/Contribute/BAO/Contribution/Utils.php"; while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) { if ($row !== 1) { $data['header'] = $header; $params = CRM_Contribute_BAO_Contribution_Utils::formatAPIParams($data, self::$_csvParamsMapper, 'csv'); if (CRM_Contribute_BAO_Contribution_Utils::processAPIContribution($params)) { CRM_Core_Error::debug_log_message("Processed - line {$row} of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", true); } else { CRM_Core_Error::debug_log_message("Skipped - line {$row} of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", true); } // clean up memory from dao's CRM_Core_DAO::freeResult(); } else { // we assuming - first row is always the header line $header = $data; CRM_Core_Error::debug_log_message("Considering first row ( line {$row} ) as HEADER ..<p>", true); if (empty($header)) { CRM_Core_Error::fatal("Header is empty."); } } $row++; } fclose($handle); }
/** * Function to process the form * * @access public * @return None */ public function postProcess() { $params = $this->controller->exportValues($this->getName()); if (!$this->_contactID && isset($params['cms_create_account'])) { foreach ($params as $key => $value) { if (substr($key, 0, 5) == 'email' && !empty($value)) { list($fieldName, $locTypeId) = CRM_Utils_System::explode('-', $key, 2); $isPrimary = 0; if ($locTypeId == 'Primary') { require_once "CRM/Core/BAO/LocationType.php"; $locTypeId =& CRM_Core_BAO_LocationType::getDefault(); $isPrimary = 1; } $params['email'] = array(); $params['email'][1]['email'] = $value; $params['email'][1]['location_type_id'] = $locTypeId; $params['email'][1]['is_primary'] = $isPrimary; } } } require_once 'CRM/Dedupe/Finder.php'; $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual'); $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', 'Strict'); if ($ids) { $this->_contactID = $ids['0']; } $contactID =& CRM_Contact_BAO_Contact::createProfileContact($params, $this->_fields, $this->_contactID); $this->set('contactID', $contactID); if (!empty($params['email'])) { $params['email'] = $params['email'][1]['email']; } require_once "CRM/Contribute/BAO/Contribution/Utils.php"; CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email'); }
/** * Get line item purchase information. * * This function takes the input parameters and interprets out of it what has been purchased. * * @param $fields * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE); * And, it would make sense to introduce caching into that function and call it from here rather than * require the $fields array which is passed from pillar to post around the form in order to pass it in here. * @param array $params * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8) * @param $lineItem * Line item array to be altered. * @param string $component * This parameter appears to only be relevant to determining whether memberships should be auto-renewed. * (and is effectively a boolean for 'is_membership' which could be calculated from the line items.) */ public static function processAmount($fields, &$params, &$lineItem, $component = '') { // using price set $totalPrice = $totalTax = 0; $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array(); if ($component) { $autoRenew = array(); $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0; } foreach ($fields as $id => $field) { if (empty($params["price_{$id}"]) || empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL) { // skip if nothing was submitted for this field continue; } switch ($field['html_type']) { case 'Text': $firstOption = reset($field['options']); $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]); CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem); if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) { $lineItem = self::setLineItem($field, $lineItem, key($field['options'])); $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty']; } if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') { $taxRates = CRM_Core_PseudoConstant::getTaxRates(); if (array_key_exists($params['financial_type_id'], $taxRates)) { $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']]; $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']); $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2); $lineItem = self::setLineItem($field, $lineItem, key($field['options'])); $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty']; } } $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]); break; case 'Radio': //special case if user select -none- if ($params["price_{$id}"] <= 0) { continue; } $params["price_{$id}"] = array($params["price_{$id}"] => 1); $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]); $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]); $params['amount_priceset_level_radio'] = array(); $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel; if (isset($radioLevel)) { $radioLevel = array_merge($radioLevel, array_keys($params['amount_priceset_level_radio'])); } else { $radioLevel = array_keys($params['amount_priceset_level_radio']); } CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem); if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) { $lineItem = self::setLineItem($field, $lineItem, $optionValueId); $totalTax += $field['options'][$optionValueId]['tax_amount']; if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') { $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']); } } $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]); if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) { $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total']; } break; case 'Select': $params["price_{$id}"] = array($params["price_{$id}"] => 1); $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]); $optionLabel = $field['options'][$optionValueId]['label']; $params['amount_priceset_level_select'] = array(); $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel; if (isset($selectLevel)) { $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select'])); } else { $selectLevel = array_keys($params['amount_priceset_level_select']); } CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem); if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) { $lineItem = self::setLineItem($field, $lineItem, $optionValueId); $totalTax += $field['options'][$optionValueId]['tax_amount']; } $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]); if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) { $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total']; } break; case 'CheckBox': $params['amount_priceset_level_checkbox'] = $optionIds = array(); foreach ($params["price_{$id}"] as $optionId => $option) { $optionIds[] = $optionId; $optionLabel = $field['options'][$optionId]['label']; $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel; if (isset($checkboxLevel)) { $checkboxLevel = array_unique(array_merge($checkboxLevel, array_keys($params['amount_priceset_level_checkbox']))); } else { $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']); } } CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem); foreach ($optionIds as $optionId) { if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) { $lineItem = self::setLineItem($field, $lineItem, $optionId); $totalTax += $field['options'][$optionId]['tax_amount']; } $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]); if ($component && isset($lineItem[$optionId]['auto_renew']) && is_numeric($lineItem[$optionId]['auto_renew'])) { $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total']; } } break; } } $amount_level = array(); $totalParticipant = 0; if (is_array($lineItem)) { foreach ($lineItem as $values) { $totalParticipant += $values['participant_count']; // This is a bit nasty. The logic of 'quick config' was because price set configuration was // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution // page. // // However, because the quick config concept existed all sorts of logic was hung off it // and function behaviour sometimes depends on whether 'price set' is set - although actually it // is always set at the functional level. In this case we are dealing with the default 'quick config' // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label. // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a // place holder. // // But, in the interests of being careful when capacity is low - avoiding the known default value // will get us by. // Crucially a test has been added so a better solution can be implemented later with some comfort. // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it. if ($values['label'] != ts('Contribution Amount')) { $amount_level[] = $values['label'] . ' - ' . (double) $values['qty']; } } } $displayParticipantCount = ''; if ($totalParticipant > 0) { $displayParticipantCount = ' Participant Count -' . $totalParticipant; } // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it. if (!empty($amount_level)) { $params['amount_level'] = CRM_Utils_Array::implodePadded($amount_level); if (!empty($displayParticipantCount)) { $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR; } } $params['amount'] = CRM_Utils_Money::format($totalPrice, NULL, NULL, TRUE); $params['tax_amount'] = $totalTax; if ($component) { foreach ($autoRenew as $dontCare => $eachAmount) { if (!$eachAmount) { unset($autoRenew[$dontCare]); } } if (count($autoRenew) > 1) { $params['autoRenew'] = $autoRenew; } } }
/** * Get the tax amount (misnamed function). * * @param array $params * @param bool $isLineItem * * @return array */ public static function checkTaxAmount($params, $isLineItem = FALSE) { $taxRates = CRM_Core_PseudoConstant::getTaxRates(); // Update contribution. if (!empty($params['id'])) { // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update // there are no tax implications - early return. if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) { return $params; } if (empty($params['prevContribution'])) { $params['prevContribution'] = self::getOriginalContribution($params['id']); } foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) { if (!isset($params[$field])) { if ($field == 'total_amount' && $params['prevContribution']->tax_amount) { // Tax amount gets added back on later.... $params['total_amount'] = $params['prevContribution']->total_amount - $params['prevContribution']->tax_amount; } else { $params[$field] = $params['prevContribution']->{$field}; if ($params[$field] != $params['prevContribution']->{$field}) { } } } } self::calculateMissingAmountParams($params, $params['id']); if (!array_key_exists($params['financial_type_id'], $taxRates)) { // Assign tax Amount on update of contribution if (!empty($params['prevContribution']->tax_amount)) { $params['tax_amount'] = 'null'; CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id'])); foreach ($params['line_item'] as $setID => $priceField) { foreach ($priceField as $priceFieldID => $priceFieldValue) { $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount']; } } } } } // New Contribution and update of contribution with tax rate financial type if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && empty($params['skipLineItem']) && !$isLineItem) { $taxRateParams = $taxRates[$params['financial_type_id']]; $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount(CRM_Utils_Array::value('total_amount', $params), $taxRateParams); $params['tax_amount'] = round($taxAmount['tax_amount'], 2); // Get Line Item on update of contribution if (isset($params['id'])) { CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id'])); } else { CRM_Price_BAO_LineItem::getLineItemArray($params); } foreach ($params['line_item'] as $setID => $priceField) { foreach ($priceField as $priceFieldID => $priceFieldValue) { $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount']; } } $params['total_amount'] = CRM_Utils_Array::value('total_amount', $params) + $params['tax_amount']; } elseif (isset($params['api.line_item.create'])) { // Update total amount of contribution using lineItem $taxAmountArray = array(); foreach ($params['api.line_item.create'] as $key => $value) { if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) { $taxRate = $taxRates[$value['financial_type_id']]; $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate); $taxAmountArray[] = round($taxAmount['tax_amount'], 2); } } $params['tax_amount'] = array_sum($taxAmountArray); $params['total_amount'] = $params['total_amount'] + $params['tax_amount']; } else { // update line item of contrbution if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) { $taxRate = $taxRates[$params['financial_type_id']]; $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate); $params['tax_amount'] = round($taxAmount['tax_amount'], 2); } } return $params; }
/** * 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; }
/** * @param $rows */ function alterDisplay(&$rows) { require_once 'CRM/Contribute/BAO/Contribution/Utils.php'; require_once 'CRM/Utils/Money.php'; require_once 'CRM/Utils/Date.php'; $config =& CRM_Core_Config::singleton(); // custom code to alter rows $checkList = array(); $entryFound = FALSE; $display_flag = $prev_cid = $cid = 0; $contributionTypes = CRM_Contribute_PseudoConstant::contributionType(); foreach ($rows as $rowNum => $row) { if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') { // don't repeat contact details if its same as the previous row if (array_key_exists('civicrm_contact_id', $row)) { if ($cid = $row['civicrm_contact_id']) { if ($rowNum == 0) { $prev_cid = $cid; } else { if ($prev_cid == $cid) { $display_flag = 1; $prev_cid = $cid; } else { $display_flag = 0; $prev_cid = $cid; } } if ($display_flag) { foreach ($row as $colName => $colVal) { if (in_array($colName, $this->_noRepeats)) { unset($rows[$rowNum][$colName]); } } } $entryFound = TRUE; } } } if (array_key_exists('first_contribution', $row) || array_key_exists('last_contribution', $row)) { $details = CRM_Contribute_BAO_Contribution_Utils::getFirstLastDetails($row['civicrm_contact_id']); if ($details['first']) { $rows[$rowNum]['first_contribution'] = CRM_Utils_Money::format($details['first']['total_amount']) . ' - ' . CRM_Utils_Date::customFormat($details['first']['receive_date'], $config->dateformatFull); } if ($details['last']) { $rows[$rowNum]['last_contribution'] = CRM_Utils_Money::format($details['last']['total_amount']) . ' - ' . CRM_Utils_Date::customFormat($details['last']['receive_date'], $config->dateformatFull); } } // handle state province if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE); $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail', "reset=1&force=1&" . "state_province_id_op=in&state_province_id_value={$value}", $this->_absoluteUrl, $this->_id); $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url; $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("List all contribution(s) for this State."); } $entryFound = TRUE; } // handle country if (array_key_exists('civicrm_address_country_id', $row)) { if ($value = $row['civicrm_address_country_id']) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE); $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail', "reset=1&force=1&" . "country_id_op=in&country_id_value={$value}", $this->_absoluteUrl, $this->_id); $rows[$rowNum]['civicrm_address_country_id_link'] = $url; $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("List all contribution(s) for this Country."); } $entryFound = TRUE; } // convert display name to links if (array_key_exists('civicrm_contact_display_name', $row) && !empty($rows[$rowNum]['civicrm_contact_display_name']) && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $row['civicrm_contact_id'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_display_name_link'] = $url; $rows[$rowNum]['civicrm_contact_display_name_hover'] = ts("View Contact Summary for this Contact."); } // convert soft credit id to link if (array_key_exists('soft_credit_display_name', $row) && !empty($rows[$rowNum]['soft_credit_display_name']) && array_key_exists('id', $row)) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $row['id'], $this->_absoluteUrl); $rows[$rowNum]['soft_credit_display_name_creditor_link'] = $url; $rows[$rowNum]['soft_credit_display_name_creditor_hover'] = ts("View Contact Summary for this Soft Credit."); } // convert hon/mem contact to link if (array_key_exists('civicrm_contact_hon_mem_display_name', $row) && !empty($rows[$rowNum]['civicrm_contribution_honor_contact_id']) && array_key_exists('civicrm_contribution_honor_contact_id', $row)) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $row['civicrm_contribution_honor_contact_id'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_hon_mem_display_name_link'] = $url; $rows[$rowNum]['civicrm_contact_hon_mem_display_name_hover'] = ts("View Contact Summary for this Honor/Memory Contribution."); } // honor of/memory of type if ($value = CRM_Utils_Array::value('civicrm_contribution_honor_type_id', $row) && !empty($rows[$rowNum]['civicrm_contribution_honor_type_id'])) { // rather than do a join, just change the output here, since there these values are pretty static if ($rows[$rowNum]['civicrm_contribution_honor_type_id'] == 1) { $rows[$rowNum]['civicrm_contribution_honor_type_id'] = "In Honor Of"; } elseif ($rows[$rowNum]['civicrm_contribution_honor_type_id'] == 2) { $rows[$rowNum]['civicrm_contribution_honor_type_id'] = "In Memory Of"; } else { $rows[$rowNum]['civicrm_contribution_honor_type_id'] = "n/a"; } } if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_type_id', $row)) { $rows[$rowNum]['civicrm_contribution_contribution_type_id'] = $contributionTypes[$value]; $entryFound = TRUE; } if (($value = CRM_Utils_Array::value('civicrm_contribution_total_amount', $row)) && CRM_Core_Permission::check('access CiviContribute')) { $url = CRM_Utils_System::url("civicrm/contact/view/contribution", "reset=1&id=" . $row['civicrm_contribution_contribution_id'] . "&cid=" . $row['civicrm_contact_id'] . "&action=view&context=contribution&selectedChild=contribute", $this->_absoluteUrl); $rows[$rowNum]['civicrm_contribution_total_amount_link'] = $url; $rows[$rowNum]['civicrm_contribution_total_amount_hover'] = ts("View Details of this Contribution."); $entryFound = TRUE; } // skip looking further in rows, if first row itself doesn't // have the column we need if (!$entryFound) { break; } $lastKey = $rowNum; } }
/** * Post form submission handling. * * This is also called from the test suite. * * @param int $contactID * * @return array */ protected function processFormSubmission($contactID) { $isPayLater = $this->_params['is_pay_later']; if (isset($this->_params['payment_processor_id']) && $this->_params['payment_processor_id'] == 0) { $this->_params['is_pay_later'] = $isPayLater = TRUE; } // add a description field at the very beginning $this->_params['description'] = ts('Online Contribution') . ': ' . ($this->_pcpInfo['title'] ? $this->_pcpInfo['title'] : $this->_values['title']); $this->_params['accountingCode'] = CRM_Utils_Array::value('accountingCode', $this->_values); // fix currency ID $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency; //carry payment processor id. if (CRM_Utils_Array::value('id', $this->_paymentProcessor)) { $this->_params['payment_processor_id'] = $this->_paymentProcessor['id']; } if (!empty($params['image_URL'])) { CRM_Contact_BAO_Contact::processImageParams($params); } $premiumParams = $membershipParams = $params = $this->_params; $fields = array('email-Primary' => 1); // get the add to groups $addToGroups = array(); // now set the values for the billing location. foreach ($this->_fields as $name => $value) { $fields[$name] = 1; // get the add to groups for uf fields if (!empty($value['add_to_group_id'])) { $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id']; } } if (!array_key_exists('first_name', $fields)) { $nameFields = array('first_name', 'middle_name', 'last_name'); foreach ($nameFields as $name) { $fields[$name] = 1; if (array_key_exists("billing_{$name}", $params)) { $params[$name] = $params["billing_{$name}"]; $params['preserveDBName'] = TRUE; } } } // billing email address $fields["email-{$this->_bltID}"] = 1; //unset the billing parameters if it is pay later mode //to avoid creation of billing location if ($isPayLater && !$this->_isBillingAddressRequiredForPayLater) { $billingFields = array('billing_first_name', 'billing_middle_name', 'billing_last_name', "billing_street_address-{$this->_bltID}", "billing_city-{$this->_bltID}", "billing_state_province-{$this->_bltID}", "billing_state_province_id-{$this->_bltID}", "billing_postal_code-{$this->_bltID}", "billing_country-{$this->_bltID}", "billing_country_id-{$this->_bltID}"); foreach ($billingFields as $value) { unset($params[$value]); unset($fields[$value]); } } // if onbehalf-of-organization contribution, take out // organization params in a separate variable, to make sure // normal behavior is continued. And use that variable to // process on-behalf-of functionality. if (!empty($this->_params['hidden_onbehalf_profile'])) { $behalfOrganization = array(); $orgFields = array('organization_name', 'organization_id', 'org_option'); foreach ($orgFields as $fld) { if (array_key_exists($fld, $params)) { $behalfOrganization[$fld] = $params[$fld]; unset($params[$fld]); } } if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) { foreach ($params['onbehalf'] as $fld => $values) { if (strstr($fld, 'custom_')) { $behalfOrganization[$fld] = $values; } elseif (!strstr($fld, '-')) { if (in_array($fld, array('contribution_campaign_id', 'member_campaign_id'))) { $fld = 'campaign_id'; } else { $behalfOrganization[$fld] = $values; } $this->_params[$fld] = $values; } } } if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) { foreach ($params['onbehalf_location'] as $block => $vals) { //fix for custom data (of type checkbox, multi-select) if (substr($block, 0, 7) == 'custom_') { continue; } // fix the index of block elements if (is_array($vals)) { foreach ($vals as $key => $val) { //dont adjust the index of address block as //it's index is WRT to location type $newKey = $block == 'address' ? $key : ++$key; $behalfOrganization[$block][$newKey] = $val; } } } unset($params['onbehalf_location']); } if (!empty($params['onbehalf[image_URL]'])) { $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]']; } } // check for profile double opt-in and get groups to be subscribed $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID); // since we are directly adding contact to group lets unset it from mailing if (!empty($addToGroups)) { foreach ($addToGroups as $groupId) { if (isset($subscribeGroupIds[$groupId])) { unset($subscribeGroupIds[$groupId]); } } } foreach ($addToGroups as $k) { if (array_key_exists($k, $subscribeGroupIds)) { unset($addToGroups[$k]); } } if (empty($contactID)) { $dupeParams = $params; if (!empty($dupeParams['onbehalf'])) { unset($dupeParams['onbehalf']); } if (!empty($dupeParams['honor'])) { unset($dupeParams['honor']); } $dedupeParams = CRM_Dedupe_Finder::formatParams($dupeParams, 'Individual'); $dedupeParams['check_permission'] = FALSE; $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual'); // if we find more than one contact, use the first one $contactID = CRM_Utils_Array::value(0, $ids); // Fetch default greeting id's if creating a contact if (!$contactID) { foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { if (!isset($params[$greeting])) { $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting); } } } $contactType = NULL; } else { $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type'); } $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $contactID, $addToGroups, NULL, $contactType, TRUE); // Make the contact ID associated with the contribution available at the Class level. // Also make available to the session. //@todo consider handling this in $this->getContactID(); $this->set('contactID', $contactID); $this->_contactID = $contactID; //get email primary first if exist $subscriptionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params)); if (!$subscriptionEmail['email']) { $subscriptionEmail['email'] = CRM_Utils_Array::value("email-{$this->_bltID}", $params); } // subscribing contact to groups if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) { CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID); } // If onbehalf-of-organization contribution / signup, add organization // and it's location. if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) { $ufFields = array(); foreach ($this->_fields['onbehalf'] as $name => $value) { $ufFields[$name] = 1; } self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values, $this->_params, $ufFields); } elseif (!empty($this->_membershipContactID) && $contactID != $this->_membershipContactID) { // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household, // store current user id as related contact for later use for mailing / activity.. $this->_values['related_contact'] = $contactID; $this->_params['related_contact'] = $contactID; // swap contact like we do for on-behalf-org case, so parent/primary membership is affected $contactID = $this->_membershipContactID; } // lets store the contactID in the session // for things like tell a friend $session = CRM_Core_Session::singleton(); if (!$session->get('userID')) { $session->set('transaction.userID', $contactID); } else { $session->set('transaction.userID', NULL); } $this->_useForMember = $this->get('useForMember'); // store the fact that this is a membership and membership type is selected $processMembership = FALSE; if (!empty($membershipParams['selectMembership']) && $membershipParams['selectMembership'] != 'no_thanks' || $this->_useForMember) { $processMembership = TRUE; if (!$this->_useForMember) { $this->assign('membership_assign', TRUE); $this->set('membershipTypeID', $this->_params['selectMembership']); } if ($this->_action & CRM_Core_Action::PREVIEW) { $membershipParams['is_test'] = 1; } if ($this->_params['is_pay_later']) { $membershipParams['is_pay_later'] = 1; } } if ($processMembership) { CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE); // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups if (isset($this->_params['related_contact'])) { $membershipParams['cms_contactID'] = $this->_params['related_contact']; } else { $membershipParams['cms_contactID'] = $contactID; } //inherit campaign from contribution page. if (!array_key_exists('campaign_id', $membershipParams)) { $membershipParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values); } if (!empty($membershipParams['onbehalf']) && is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) { $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id']; } $customFieldsFormatted = $fieldTypes = array(); if (!empty($membershipParams['onbehalf']) && is_array($membershipParams['onbehalf'])) { foreach ($membershipParams['onbehalf'] as $key => $value) { if (strstr($key, 'custom_')) { $customFieldId = explode('_', $key); CRM_Core_BAO_CustomField::formatCustomField($customFieldId[1], $customFieldsFormatted, $value, 'Membership', NULL, $contactID); } } $fieldTypes = array('Contact', 'Organization', 'Membership'); } $priceFieldIds = $this->get('memberPriceFieldIDS'); if (!empty($priceFieldIds)) { $contributionTypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id'); unset($priceFieldIds['id']); $membershipTypeIds = array(); $membershipTypeTerms = array(); foreach ($priceFieldIds as $priceFieldId) { if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) { $membershipTypeIds[] = $id; //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition' $term = 1; if ($term = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) { $membershipTypeTerms[$id] = $term > 1 ? $term : 1; } else { $membershipTypeTerms[$id] = 1; } } } $membershipParams['selectMembership'] = $membershipTypeIds; $membershipParams['financial_type_id'] = $contributionTypeID; $membershipParams['types_terms'] = $membershipTypeTerms; } if (!empty($membershipParams['selectMembership'])) { // CRM-12233 $membershipLineItems = array(); if ($this->_separateMembershipPayment && $this->_values['amount_block_is_active']) { foreach ($this->_values['fee'] as $key => $feeValues) { if ($feeValues['name'] == 'membership_amount') { $fieldId = $this->_params['price_' . $key]; $membershipLineItems[$this->_priceSetId][$fieldId] = $this->_lineItem[$this->_priceSetId][$fieldId]; unset($this->_lineItem[$this->_priceSetId][$fieldId]); break; } } } $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater); if (!$this->_amount > 0.0 || !$membershipParams['amount']) { // we need to explicitly create a CMS user in case of free memberships // since it is done under processConfirm for paid memberships CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams, $membershipParams['cms_contactID'], 'email-' . $this->_bltID); } } } else { // at this point we've created a contact and stored its address etc // all the payment processors expect the name and address to be in the // so we copy stuff over to first_name etc. $paymentParams = $this->_params; $contributionTypeId = $this->_values['financial_type_id']; $fieldTypes = array(); if (!empty($paymentParams['onbehalf']) && is_array($paymentParams['onbehalf'])) { foreach ($paymentParams['onbehalf'] as $key => $value) { if (strstr($key, 'custom_')) { $this->_params[$key] = $value; } } $fieldTypes = array('Contact', 'Organization', 'Contribution'); } $financialTypeID = $this->wrangleFinancialTypeID($contributionTypeId); $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($this, $paymentParams, $premiumParams, $contactID, $financialTypeID, 'contribution', $fieldTypes, $this->_mode == 'test' ? 1 : 0, $isPayLater); if (CRM_Utils_Array::value('contribution_status_id', $result) == 1) { civicrm_api3('contribution', 'completetransaction', array('id' => $result['contribution']->id, 'trxn_id' => CRM_Utils_Array::value('trxn_id', $result))); } return $result; } }
/** * @param array $apiParams * @param $mapper * @param string $type * @param bool $category * * @return array */ public static function formatAPIParams($apiParams, $mapper, $type = 'paypal', $category = TRUE) { $type = strtolower($type); if (!in_array($type, array('paypal', 'csv'))) { // return the params as is return $apiParams; } $params = $transaction = array(); if ($type == 'paypal') { foreach ($apiParams as $detail => $val) { if (isset($mapper['contact'][$detail])) { $params[$mapper['contact'][$detail]] = $val; } elseif (isset($mapper['location'][$detail])) { $params['address'][1][$mapper['location'][$detail]] = $val; } elseif (isset($mapper['transaction'][$detail])) { switch ($detail) { case 'l_period2': // Sadly, PayPal seems to send two distinct data elements in a single field, // so we break them out here. This is somewhat ugly and tragic. $freqUnits = array('D' => 'day', 'W' => 'week', 'M' => 'month', 'Y' => 'year'); list($frequency_interval, $frequency_unit) = explode(' ', $val); $transaction['frequency_interval'] = $frequency_interval; $transaction['frequency_unit'] = $freqUnits[$frequency_unit]; break; case 'subscriptiondate': case 'timestamp': // PayPal dates are in ISO-8601 format. We need a format that // MySQL likes $unix_timestamp = strtotime($val); $transaction[$mapper['transaction'][$detail]] = date('YmdHis', $unix_timestamp); break; case 'note': case 'custom': case 'l_number0': if ($val) { $val = "[PayPal_field:{$detail}] {$val}"; $transaction[$mapper['transaction'][$detail]] = !empty($transaction[$mapper['transaction'][$detail]]) ? $transaction[$mapper['transaction'][$detail]] . " <br/> " . $val : $val; } break; default: $transaction[$mapper['transaction'][$detail]] = $val; } } } if (!empty($transaction) && $category) { $params['transaction'] = $transaction; } else { $params += $transaction; } CRM_Contribute_BAO_Contribution_Utils::_fillCommonParams($params, $type); return $params; } if ($type == 'csv') { $header = $apiParams['header']; unset($apiParams['header']); foreach ($apiParams as $key => $val) { if (isset($mapper['contact'][$header[$key]])) { $params[$mapper['contact'][$header[$key]]] = $val; } elseif (isset($mapper['location'][$header[$key]])) { $params['address'][1][$mapper['location'][$header[$key]]] = $val; } elseif (isset($mapper['transaction'][$header[$key]])) { $transaction[$mapper['transaction'][$header[$key]]] = $val; } else { $params[$header[$key]] = $val; } } if (!empty($transaction) && $category) { $params['transaction'] = $transaction; } else { $params += $transaction; } CRM_Contribute_BAO_Contribution_Utils::_fillCommonParams($params, $type); return $params; } }
/** * Implementation of hook_civicrm_buildAmount() * * If the event id of the form being loaded has a discount code, calculate the * the discount and update the price and label. Apply the initial autodiscount * based on a users membership. * * Check all priceset items and only apply the discount to the discounted items. * * @param string $pageType * @param CRM_Core_Form $form * @param $amounts */ function cividiscount_civicrm_buildAmount($pagetype, &$form, &$amounts) { if ((!$form->getVar('_action') || $form->getVar('_action') & CRM_Core_Action::PREVIEW || $form->getVar('_action') & CRM_Core_Action::ADD || $form->getVar('_action') & CRM_Core_Action::UPDATE) && !empty($amounts) && is_array($amounts) && ($pagetype == 'event' || $pagetype == 'membership')) { if (!$pagetype == 'membership' && in_array(get_class($form), array('CRM_Contribute_Form_Contribution', 'CRM_Contribute_Form_Contribution_Main'))) { return; } $contact_id = _cividiscount_get_form_contact_id($form); $autodiscount = FALSE; $eid = $form->getVar('_eventId'); $psid = $form->get('priceSetId'); $ps = $form->get('priceSet'); $v = $form->getVar('_values'); $code = trim(CRM_Utils_Request::retrieve('discountcode', 'String', $form, false, null, 'REQUEST')); if (!array_key_exists('discountcode', $form->_submitValues) && ($pid = $form->getVar('_participantId')) && $form->getVar('_action') & CRM_Core_Action::UPDATE) { $code = _cividiscount_get_item_by_track('civicrm_participant', $pid, $contact_id, TRUE); } if (!empty($v['currency'])) { $currency = $v['currency']; } elseif (!empty($v['event']['currency'])) { $currency = $v['event']['currency']; } else { $currency = CRM_Core_Config::singleton()->defaultCurrency; } // If additional participants are not allowed to receive a discount we need // to interrupt the form processing on build and POST. // This is a potential landmine if the form processing ever changes in Civi. if (!_cividiscount_allow_multiple()) { // POST from participant form to confirm page if ($form->getVar('_lastParticipant') == 1) { return; } // On build participant form $keys = array_keys($_GET); foreach ($keys as $key) { if (substr($key, 0, 16) == "_qf_Participant_") { // We can somewhat safely assume we're in the additional participant // registration form. // @todo what is the effect of this? if ($_GET[$key] == 'true') { return; } } } } $form->set('_discountInfo', NULL); $discountCalculator = new CRM_CiviDiscount_DiscountCalculator($pagetype, $eid, $contact_id, $code, FALSE); $discounts = $discountCalculator->getDiscounts(); if (!empty($code) && empty($discounts)) { $form->set('discountCodeErrorMsg', ts('The discount code you entered is invalid.')); } // here we check if discount is configured for events or for membership types. // There are two scenarios: // 1. Discount is configure for the event or membership type, in that case we should apply discount only // if default fee / membership type is configured. ( i.e price set with quick config true ) // 2. Discount is configure at price field level, in this case discount should be applied only for // that particular price set field. $keys = array_keys($discounts); $key = array_shift($keys); // in this case discount is specified for event id or membership type id, so we need to get info of // associated price set fields. For events discount we already have the list, but for memberships we // need to filter at membership type level //retrieve price set field associated with this priceset $priceSetInfo = CRM_CiviDiscount_Utils::getPriceSetsInfo($psid); $originalAmounts = $amounts; //$discount = array_shift($discounts); foreach ($discounts as $done_care => $discount) { if (!empty($discountCalculator->autoDiscounts) && array_key_exists($done_care, $discountCalculator->autoDiscounts)) { $autodiscount = TRUE; } else { $autodiscount = FALSE; } $priceFields = isset($discount['pricesets']) ? $discount['pricesets'] : array(); if (empty($priceFields) && (!empty($code) || $autodiscount)) { // apply discount to all the price fields if no price set set if ($pagetype == 'event') { $applyToAllLineItems = TRUE; if (!empty($key)) { $discounts[$key]['pricesets'] = array_keys($priceSetInfo); } } else { // filter only valid membership types that have discount foreach ($priceSetInfo as $pfID => $priceFieldValues) { if (!empty($priceFieldValues['membership_type_id']) && in_array($priceFieldValues['membership_type_id'], CRM_Utils_Array::value('memberships', $discount, array()))) { $priceFields[$pfID] = $pfID; } } } } // we should check for MultParticipant AND set Error Messages only if // this $discount is autodiscount or used discount if ($autodiscount || !empty($code) && $code == $discount['code']) { $apcount = _cividiscount_checkEventDiscountMultipleParticipants($pagetype, $form, $discount); } else { // silently set FALSE $apcount = FALSE; } if (empty($apcount)) { //this was set to return but that doesn't make sense as there might be another discount continue; } $discountApplied = FALSE; if (!empty($autodiscount) || !empty($code)) { foreach ($amounts as $fee_id => &$fee) { if (!is_array($fee['options'])) { continue; } foreach ($fee['options'] as $option_id => &$option) { if (!empty($applyToAllLineItems) || CRM_Utils_Array::value($option['id'], $priceFields)) { $originalLabel = $originalAmounts[$fee_id]['options'][$option_id]['label']; $originalAmount = CRM_Utils_Rule::cleanMoney($originalAmounts[$fee_id]['options'][$option_id]['amount']); list($amount, $label) = _cividiscount_calc_discount($originalAmount, $originalLabel, $discount, $autodiscount, $currency); $discountAmount = $originalAmounts[$fee_id]['options'][$option_id]['amount'] - $amount; if ($discountAmount > CRM_Utils_Array::value('discount_applied', $option)) { $option['amount'] = $amount; $option['label'] = $label; $option['discount_applied'] = $discountAmount; /* * Priyanka Karan @ Veda NFP Consulting Ltd * Re-calculate VAT/Sales TAX on discounted amount. */ $recalculateTaxAmount = array(); if (array_key_exists('tax_amount', $originalAmounts[$fee_id]['options'][$option_id]) && array_key_exists('tax_rate', $originalAmounts[$fee_id]['options'][$option_id])) { $recalculateTaxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($amount, $originalAmounts[$fee_id]['options'][$option_id]['tax_rate']); if (!empty($recalculateTaxAmount)) { $option['tax_amount'] = round($recalculateTaxAmount['tax_amount'], 2); } } } $discountApplied = TRUE; } } } } } // Display discount message if one is available if ($pagetype == 'event') { foreach ($discounts as $code => $discount) { if (isset($discount['events']) && array_key_exists($eid, $discount['events']) && $discount['discount_msg_enabled'] && (!isset($discountApplied) || !$discountApplied) && !empty($discount['autodiscount'])) { CRM_Core_Session::setStatus(html_entity_decode($discount['discount_msg']), '', 'no-popup'); } } } // this seems to incorrectly set to only the last discount but it seems not to matter in the way it is used if (isset($discountApplied) && $discountApplied) { if (!empty($ps['fields'])) { $ps['fields'] = $amounts; $form->setVar('_priceSet', $ps); } $form->set('_discountInfo', array('discount' => $discount, 'autodiscount' => $autodiscount, 'contact_id' => $contact_id)); } } }
/** * Browse all price set fields. * * @return void */ public function browse() { $resourceManager = CRM_Core_Resources::singleton(); if (!empty($_GET['new']) && $resourceManager->ajaxPopupsEnabled) { $resourceManager->addScriptFile('civicrm', 'js/crm.addNew.js', 999, 'html-header'); } $priceField = array(); $priceFieldBAO = new CRM_Price_BAO_PriceField(); // fkey is sid $priceFieldBAO->price_set_id = $this->_sid; $priceFieldBAO->orderBy('weight, label'); $priceFieldBAO->find(); // display taxTerm for priceFields $invoiceSettings = Civi::settings()->get('contribution_invoice_settings'); $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); $getTaxDetails = FALSE; $taxRate = CRM_Core_PseudoConstant::getTaxRates(); CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes); while ($priceFieldBAO->fetch()) { $priceField[$priceFieldBAO->id] = array(); CRM_Core_DAO::storeValues($priceFieldBAO, $priceField[$priceFieldBAO->id]); // get price if it's a text field if ($priceFieldBAO->html_type == 'Text') { $optionValues = array(); $params = array('price_field_id' => $priceFieldBAO->id); CRM_Price_BAO_PriceFieldValue::retrieve($params, $optionValues); $financialTypeId = $optionValues['financial_type_id']; if (!array_key_exists($financialTypeId, $financialTypes)) { unset($priceField[$priceFieldBAO->id]); continue; } $priceField[$priceFieldBAO->id]['price'] = CRM_Utils_Array::value('amount', $optionValues); if ($invoicing && isset($taxRate[$financialTypeId])) { $priceField[$priceFieldBAO->id]['tax_rate'] = $taxRate[$financialTypeId]; $getTaxDetails = TRUE; } if (isset($priceField[$priceFieldBAO->id]['tax_rate'])) { $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceField[$priceFieldBAO->id]['price'], $priceField[$priceFieldBAO->id]['tax_rate']); $priceField[$priceFieldBAO->id]['tax_amount'] = $taxAmount['tax_amount']; } } $action = array_sum(array_keys(self::actionLinks())); if ($this->_isSetReserved) { $action -= CRM_Core_Action::UPDATE + CRM_Core_Action::DELETE + CRM_Core_Action::ENABLE + CRM_Core_Action::DISABLE; } else { if ($priceFieldBAO->is_active) { $action -= CRM_Core_Action::ENABLE; } else { $action -= CRM_Core_Action::DISABLE; } } if ($priceFieldBAO->active_on == '0000-00-00 00:00:00') { $priceField[$priceFieldBAO->id]['active_on'] = ''; } if ($priceFieldBAO->expire_on == '0000-00-00 00:00:00') { $priceField[$priceFieldBAO->id]['expire_on'] = ''; } // need to translate html types from the db $htmlTypes = CRM_Price_BAO_PriceField::htmlTypes(); $priceField[$priceFieldBAO->id]['html_type_display'] = $htmlTypes[$priceField[$priceFieldBAO->id]['html_type']]; $priceField[$priceFieldBAO->id]['order'] = $priceField[$priceFieldBAO->id]['weight']; $priceField[$priceFieldBAO->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('fid' => $priceFieldBAO->id, 'sid' => $this->_sid), ts('more'), FALSE, 'priceField.row.actions', 'PriceField', $priceFieldBAO->id); $this->assign('taxTerm', $taxTerm); $this->assign('getTaxDetails', $getTaxDetails); } $returnURL = CRM_Utils_System::url('civicrm/admin/price/field', "reset=1&action=browse&sid={$this->_sid}"); $filter = "price_set_id = {$this->_sid}"; CRM_Utils_Weight::addOrder($priceField, 'CRM_Price_DAO_PriceField', 'id', $returnURL, $filter); $this->assign('priceField', $priceField); }
/** * 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(); $honorCId = $recurringContributionID = null; if ($online) { if ($form->get('honor_block_is_active')) { $honorCId = $form->createHonorContact(); } $recurringContributionID = $form->processRecurringContribution($params, $contactID); } else { 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; } // check contribution Type // first create the contribution record $contribParams = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'contribution_page_id' => $online ? $form->_id : null, '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; 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) { $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id); 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'] = $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'); 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/Contribute/BAO/FinancialTrxn.php'; $trxn =& CRM_Contribute_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; }
/** * Browse all price fields. * * @return void */ public function browse() { $customOption = array(); CRM_Price_BAO_PriceFieldValue::getValues($this->_fid, $customOption); // CRM-15378 - check if these price options are in an Event price set $isEvent = FALSE; $extendComponentId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'extends', 'id'); $allComponents = explode(CRM_Core_DAO::VALUE_SEPARATOR, $extendComponentId); $eventComponentId = CRM_Core_Component::getComponentID('CiviEvent'); if (in_array($eventComponentId, $allComponents)) { $isEvent = TRUE; } $config = CRM_Core_Config::singleton(); $financialType = CRM_Contribute_PseudoConstant::financialType(); $taxRate = CRM_Core_PseudoConstant::getTaxRates(); // display taxTerm for priceFields $invoiceSettings = Civi::settings()->get('contribution_invoice_settings'); $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); $getTaxDetails = FALSE; foreach ($customOption as $id => $values) { $action = array_sum(array_keys($this->actionLinks())); // Adding the required fields in the array if (isset($taxRate[$values['financial_type_id']])) { $customOption[$id]['tax_rate'] = $taxRate[$values['financial_type_id']]; if ($invoicing && isset($customOption[$id]['tax_rate'])) { $getTaxDetails = TRUE; } $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($customOption[$id]['amount'], $customOption[$id]['tax_rate']); $customOption[$id]['tax_amount'] = $taxAmount['tax_amount']; } if (!empty($values['financial_type_id'])) { $customOption[$id]['financial_type_id'] = $financialType[$values['financial_type_id']]; } // update enable/disable links depending on price_field properties. if ($this->_isSetReserved) { $action -= CRM_Core_Action::UPDATE + CRM_Core_Action::DELETE + CRM_Core_Action::DISABLE + CRM_Core_Action::ENABLE; } else { if ($values['is_active']) { $action -= CRM_Core_Action::ENABLE; } else { $action -= CRM_Core_Action::DISABLE; } } if (!empty($customOption[$id]['is_default'])) { $customOption[$id]['is_default'] = '<img src="' . $config->resourceBase . 'i/check.gif" />'; } else { $customOption[$id]['is_default'] = ''; } $customOption[$id]['order'] = $customOption[$id]['weight']; $customOption[$id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('oid' => $id, 'fid' => $this->_fid, 'sid' => $this->_sid), ts('more'), FALSE, 'priceFieldValue.row.actions', 'PriceFieldValue', $id); } // Add order changing widget to selector $returnURL = CRM_Utils_System::url('civicrm/admin/price/field/option', "action=browse&reset=1&fid={$this->_fid}&sid={$this->_sid}"); $filter = "price_field_id = {$this->_fid}"; CRM_Utils_Weight::addOrder($customOption, 'CRM_Price_DAO_PriceFieldValue', 'id', $returnURL, $filter); $this->assign('taxTerm', $taxTerm); $this->assign('getTaxDetails', $getTaxDetails); $this->assign('customOption', $customOption); $this->assign('sid', $this->_sid); $this->assign('isEvent', $isEvent); }
/** * Function to process the form * * @access public * * @return None */ public function postProcess() { $params = $this->controller->exportValues($this->getName()); if (!$this->_donorID) { foreach ($params as $key => $value) { if (substr($key, 0, 5) == 'email' && !empty($value)) { $params['email'] = $value; } } } $donorID =& CRM_Contact_BAO_Contact::createProfileContact($params, $this->_fields, $this->_donorID, $addToGroups); $this->set('donorID', $donorID); require_once "CRM/Contribute/BAO/Contribution/Utils.php"; CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $donorID, 'email'); }
/** * 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; }
/** * Process the Memberships * * @param array $membershipParams array of membership fields * @param int $contactID contact id * @param object $form form object * * @return void * @access public */ public static function postProcessMembership($membershipParams, $contactID, &$form, &$premiumParams, $customFieldsFormatted = NULL, $includeFieldTypes = NULL) { $tempParams = $membershipParams; $paymentDone = FALSE; $result = NULL; $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE); $form->assign('membership_assign', TRUE); $form->set('membershipTypeID', $membershipParams['selectMembership']); $singleMembershipTypeID = $membershipTypeID = $membershipParams['selectMembership']; if (is_array($membershipTypeID) && count($membershipTypeID) == 1) { $singleMembershipTypeID = $membershipTypeID[0]; } $membershipDetails = self::buildMembershipTypeValues($form, $singleMembershipTypeID); $form->assign('membership_name', CRM_Utils_Array::value('name', $membershipDetails)); $minimumFee = CRM_Utils_Array::value('minimum_fee', $membershipDetails); $contributionTypeId = NULL; if ($form->_values['amount_block_is_active']) { $contributionTypeId = $form->_values['financial_type_id']; } else { $paymentDone = TRUE; $params['amount'] = $minimumFee; $contributionTypeId = CRM_Utils_Array::value('financial_type_id', $membershipDetails); if (!$contributionTypeId) { $contributionTypeId = CRM_Utils_Array::value('financial_type_id', $membershipParams); } } //amount must be greater than zero for //adding contribution record to contribution table. //this condition arises when separate membership payment is //enabled and contribution amount is not selected. fix for CRM-3010 if ($form->_amount > 0.0 && $membershipParams['amount']) { $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $premiumParams, $contactID, $contributionTypeId, 'membership'); } else { // we need to explicitly create a CMS user in case of free memberships // since the below has already been done under processConfirm for paid memberships CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams, $membershipParams['cms_contactID'], 'email-' . $form->_bltID); } $errors = array(); if (is_a($result[1], 'CRM_Core_Error')) { $errors[1] = CRM_Core_Error::getMessages($result[1]); } elseif (CRM_Utils_Array::value(1, $result)) { // Save the contribution ID so that I can be used in email receipts // For example, if you need to generate a tax receipt for the donation only. $form->_values['contribution_other_id'] = $result[1]->id; $contribution[1] = $result[1]; } $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($form->_id); if (CRM_Utils_Array::value('is_separate_payment', $memBlockDetails) && !$paymentDone) { $form->_lineItem = $form->_memLineItem; $contributionType = new CRM_Financial_DAO_FinancialType(); $contributionType->id = CRM_Utils_Array::value('financial_type_id', $membershipDetails); if (!$contributionType->find(TRUE)) { CRM_Core_Error::fatal(ts("Could not find a system table")); } $tempParams['amount'] = $minimumFee; $invoiceID = md5(uniqid(rand(), TRUE)); $tempParams['invoiceID'] = $invoiceID; //we don't allow recurring membership.CRM-3781. if (CRM_Utils_Array::value('is_recur', $tempParams)) { $tempParams['is_recur'] = 0; } $result = NULL; if ($form->_values['is_monetary'] && !$form->_params['is_pay_later'] && $minimumFee > 0.0) { $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form); if ($form->_contributeMode == 'express') { $result =& $payment->doExpressCheckout($tempParams); } else { $result =& $payment->doDirectPayment($tempParams); } } if (is_a($result, 'CRM_Core_Error')) { $errors[2] = CRM_Core_Error::getMessages($result); } else { //assign receive date when separate membership payment //and contribution amount not selected. if ($form->_amount == 0) { $now = date('YmdHis'); $form->_params['receive_date'] = $now; $receiveDate = CRM_Utils_Date::mysqlToIso($now); $form->set('params', $form->_params); $form->assign('receive_date', $receiveDate); } $form->set('membership_trx_id', $result['trxn_id']); $form->set('membership_amount', $minimumFee); $form->assign('membership_trx_id', $result['trxn_id']); $form->assign('membership_amount', $minimumFee); // we dont need to create the user twice, so lets disable cms_create_account // irrespective of the value, CRM-2888 $tempParams['cms_create_account'] = 0; $pending = $form->_params['is_pay_later'] ? CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0) > 0.0 ? TRUE : FALSE : FALSE; //set this variable as we are not creating pledge for //separate membership payment contribution. //so for differentiating membership contributon from //main contribution. $form->_params['separate_membership_payment'] = 1; $contribution[2] = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $tempParams, $result, $contactID, $contributionType, TRUE, $pending); } } $index = CRM_Utils_Array::value('is_separate_payment', $memBlockDetails) ? 2 : 1; if (!CRM_Utils_Array::value($index, $errors)) { if (isset($membershipParams['onbehalf']) && CRM_Utils_Array::value('member_campaign_id', $membershipParams['onbehalf'])) { $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id']; } if (is_array($membershipTypeID)) { $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array()); $createdMemberships = array(); foreach ($membershipTypeID as $memType) { $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1); $membership = self::renewMembership($contactID, $memType, $isTest, $form, NULL, CRM_Utils_Array::value('cms_contactID', $membershipParams), $customFieldsFormatted, CRM_Utils_Array::value($memType, $typesTerms, 1)); $createdMemberships[$memType] = $membership; if (isset($contribution[$index])) { //insert payment record $dao = new CRM_Member_DAO_MembershipPayment(); $dao->membership_id = $membership->id; $dao->contribution_id = $contribution[$index]->id; //Fixed for avoiding duplicate entry error when user goes //back and forward during payment mode is notify if (!$dao->find(TRUE)) { CRM_Utils_Hook::pre('create', 'MembershipPayment', NULL, $dao); $dao->save(); CRM_Utils_Hook::post('create', 'MembershipPayment', $dao->id, $dao); } } } if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) { foreach ($form->_lineItem[$form->_priceSetId] as &$priceFieldOp) { if (CRM_Utils_Array::value('membership_type_id', $priceFieldOp) && isset($createdMemberships[$priceFieldOp['membership_type_id']])) { $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']]; $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%d%f %b, %Y') : '-'; $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%d%f %b, %Y') : '-'; } else { $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A'; } } $form->_values['lineItem'] = $form->_lineItem; $form->assign('lineItem', $form->_lineItem); } } else { $membership = self::renewMembership($contactID, $membershipTypeID, $isTest, $form, NULL, CRM_Utils_Array::value('cms_contactID', $membershipParams), $customFieldsFormatted, CRM_Utils_Array::value('types_terms', $membershipParams, 1), CRM_Utils_Array::value('contribution_status_id', $result) == 2 ? TRUE : FALSE); if (isset($contribution[$index])) { //insert payment record $dao = new CRM_Member_DAO_MembershipPayment(); $dao->membership_id = $membership->id; $dao->contribution_id = $contribution[$index]->id; //Fixed for avoiding duplicate entry error when user goes //back and forward during payment mode is notify if (!$dao->find(TRUE)) { CRM_Utils_Hook::pre('create', 'MembershipPayment', NULL, $dao); $dao->save(); CRM_Utils_Hook::post('create', 'MembershipPayment', $dao->id, $dao); } } } } if (!empty($errors)) { foreach ($errors as $error) { if (is_string($error)) { $message[] = $error; } } $message = ts('Payment Processor Error message') . ': ' . implode('<br/>', $message); throw new CRM_Core_Exception($message); } // CRM-7851 CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_membership', $membership->id, 'Membership'); $form->_params['membershipID'] = $membership->id; if ($form->_contributeMode == 'notify') { if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) { // call postprocess hook before leaving $form->postProcessHook(); // this does not return $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form); $payment->doTransferCheckout($form->_params, 'contribute'); } } $form->_values['membership_id'] = $membership->id; if (isset($contribution[$index]->id)) { $form->_values['contribution_id'] = $contribution[$index]->id; } // Do not send an email if Recurring transaction is done via Direct Mode // Email will we sent when the IPN is received. if (CRM_Utils_Array::value('is_recur', $form->_params) && $form->_contributeMode == 'direct') { return TRUE; } //finally send an email receipt CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $isTest, FALSE, $includeFieldTypes); }
/** * Membership processing section. * * This is in a separate function as part of a move towards refactoring. * * @param int $contactID * @param array $membershipParams * @param array $premiumParams * @param bool $isPayLater */ protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater) { // This could be set by a hook. if (!empty($this->_params['installments'])) { $membershipParams['installments'] = $this->_params['installments']; } // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups if (isset($this->_params['related_contact'])) { $membershipParams['cms_contactID'] = $this->_params['related_contact']; } else { $membershipParams['cms_contactID'] = $contactID; } if (!empty($membershipParams['onbehalf']) && is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) { $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id']; } $customFieldsFormatted = $fieldTypes = array(); if (!empty($membershipParams['onbehalf']) && is_array($membershipParams['onbehalf'])) { foreach ($membershipParams['onbehalf'] as $key => $value) { if (strstr($key, 'custom_')) { $customFieldId = explode('_', $key); CRM_Core_BAO_CustomField::formatCustomField($customFieldId[1], $customFieldsFormatted, $value, 'Membership', NULL, $contactID); } } $fieldTypes = array('Contact', 'Organization', 'Membership'); } $priceFieldIds = $this->get('memberPriceFieldIDS'); if (!empty($priceFieldIds)) { $contributionTypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id'); unset($priceFieldIds['id']); $membershipTypeIds = array(); $membershipTypeTerms = array(); foreach ($priceFieldIds as $priceFieldId) { if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) { $membershipTypeIds[] = $id; //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition' $term = 1; if ($term = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) { $membershipTypeTerms[$id] = $term > 1 ? $term : 1; } else { $membershipTypeTerms[$id] = 1; } } } $membershipParams['selectMembership'] = $membershipTypeIds; $membershipParams['financial_type_id'] = $contributionTypeID; $membershipParams['types_terms'] = $membershipTypeTerms; } if (!empty($membershipParams['selectMembership'])) { // CRM-12233 $membershipLineItems = array(); if ($this->_separateMembershipPayment && $this->_values['amount_block_is_active']) { foreach ($this->_values['fee'] as $key => $feeValues) { if ($feeValues['name'] == 'membership_amount') { $fieldId = $this->_params['price_' . $key]; $membershipLineItems[$this->_priceSetId][$fieldId] = $this->_lineItem[$this->_priceSetId][$fieldId]; unset($this->_lineItem[$this->_priceSetId][$fieldId]); break; } } } try { $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems, $isPayLater); } catch (CRM_Core_Exception $e) { CRM_Core_Session::singleton()->setStatus($e->getMessage()); CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}")); } if (!$this->_amount > 0.0 || !$membershipParams['amount']) { // we need to explicitly create a CMS user in case of free memberships // since it is done under processConfirm for paid memberships CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams, $membershipParams['cms_contactID'], 'email-' . $this->_bltID); } } }
/** * Function to process the form * * @access public * * @return None */ public function postProcess() { $params = $this->controller->exportValues($this->getName()); if (!$this->_contactID && isset($params['cms_create_account'])) { foreach ($params as $key => $value) { if (substr($key, 0, 5) == 'email' && !empty($value)) { list($fieldName, $locTypeId) = CRM_Utils_System::explode('-', $key, 2); $isPrimary = 0; if ($locTypeId == 'Primary') { $locTypeDefault = CRM_Core_BAO_LocationType::getDefault(); $locTypeId = NULL; if ($locTypeDefault) { $locTypeId = $locTypeDefault->id; } $isPrimary = 1; } $params['email'] = array(); $params['email'][1]['email'] = $value; $params['email'][1]['location_type_id'] = $locTypeId; $params['email'][1]['is_primary'] = $isPrimary; } } } $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual'); $dedupeParams['check_permission'] = FALSE; $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', 'Unsupervised'); if ($ids) { $this->_contactID = $ids['0']; } $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $this->_fields, $this->_contactID); $this->set('contactID', $contactID); if (!empty($params['email'])) { $params['email'] = $params['email'][1]['email']; } CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email'); }
/** * Process the form after the input has been submitted and validated. */ public function postProcess() { $config = CRM_Core_Config::singleton(); $chartType = 'bvg'; if ($this->_chartType) { $chartType = $this->_chartType; } $selectedYear = date('Y'); if ($this->_year) { $selectedYear = $this->_year; } //take contribution information monthly $chartInfoMonthly = CRM_Contribute_BAO_Contribution_Utils::contributionChartMonthly($selectedYear); $chartData = $abbrMonthNames = array(); if (is_array($chartInfoMonthly)) { for ($i = 1; $i <= 12; $i++) { $abbrMonthNames[$i] = strftime('%b', mktime(0, 0, 0, $i, 10, 1970)); } foreach ($abbrMonthNames as $monthKey => $monthName) { $val = CRM_Utils_Array::value($monthKey, $chartInfoMonthly['By Month'], 0); // don't include zero value month. if (!$val && $chartType != 'bvg') { continue; } //build the params for chart. $chartData['by_month']['values'][$monthName] = $val; } $chartData['by_month']['legend'] = 'By Month' . ' - ' . $selectedYear; // handle onclick event. $chartData['by_month']['on_click_fun_name'] = 'byMonthOnClick'; $chartData['by_month']['yname'] = ts('Contribution'); } //take contribution information by yearly $chartInfoYearly = CRM_Contribute_BAO_Contribution_Utils::contributionChartYearly(); //get the years. $this->_years = $chartInfoYearly['By Year']; $hasContributions = FALSE; if (is_array($chartInfoYearly)) { $hasContributions = TRUE; $chartData['by_year']['legend'] = 'By Year'; $chartData['by_year']['values'] = $chartInfoYearly['By Year']; // handle onclick event. $chartData['by_year']['on_click_fun_name'] = 'byYearOnClick'; $chartData['by_year']['yname'] = ts('Total Amount'); } $this->assign('hasContributions', $hasContributions); // process the data. $chartCnt = 1; $monthlyChart = $yearlyChart = FALSE; foreach ($chartData as $chartKey => &$values) { $chartValues = CRM_Utils_Array::value('values', $values); if (!is_array($chartValues) || empty($chartValues)) { continue; } if ($chartKey == 'by_year') { $yearlyChart = TRUE; if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] !== 1 || $config->fiscalYearStart['d'] !== 1)) { $values['xLabelAngle'] = 45; } else { $values['xLabelAngle'] = 0; } } if ($chartKey == 'by_month') { $monthlyChart = TRUE; } $values['divName'] = "open_flash_chart_{$chartKey}"; $funName = $chartType == 'bvg' ? 'barChart' : 'pieChart'; // build the chart objects. $values['object'] = CRM_Utils_OpenFlashChart::$funName($values); //build the urls. $urlCnt = 0; foreach ($chartValues as $index => $val) { $urlParams = NULL; if ($chartKey == 'by_month') { $monthPosition = array_search($index, $abbrMonthNames); $startDate = CRM_Utils_Date::format(array('Y' => $selectedYear, 'M' => $monthPosition)); $endDate = date('Ymd', mktime(0, 0, 0, $monthPosition + 1, 0, $selectedYear)); $urlParams = "reset=1&force=1&status=1&start={$startDate}&end={$endDate}&test=0"; } elseif ($chartKey == 'by_year') { if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) { $startDate = date('Ymd', mktime(0, 0, 0, $config->fiscalYearStart['M'], $config->fiscalYearStart['d'], substr($index, 0, 4))); $endDate = date('Ymd', mktime(0, 0, 0, $config->fiscalYearStart['M'], $config->fiscalYearStart['d'], substr($index, 0, 4) + 1)); } else { $startDate = CRM_Utils_Date::format(array('Y' => substr($index, 0, 4))); $endDate = date('Ymd', mktime(0, 0, 0, 13, 0, substr($index, 0, 4))); } $urlParams = "reset=1&force=1&status=1&start={$startDate}&end={$endDate}&test=0"; } if ($urlParams) { $values['on_click_urls']["url_" . $urlCnt++] = CRM_Utils_System::url('civicrm/contribute/search', $urlParams, TRUE, FALSE, FALSE); } } // calculate chart size. $xSize = 400; $ySize = 300; if ($chartType == 'bvg') { $ySize = 250; $xSize = 60 * count($chartValues); // reduce x size by 100 for by_month if ($chartKey == 'by_month') { $xSize -= 100; } //hack to show tooltip. if ($xSize < 150) { $xSize = 150; } } $values['size'] = array('xSize' => $xSize, 'ySize' => $ySize); } // finally assign this chart data to template. $this->assign('hasYearlyChart', $yearlyChart); $this->assign('hasByMonthChart', $monthlyChart); $this->assign('hasOpenFlashChart', empty($chartData) ? FALSE : TRUE); $this->assign('openFlashChartData', json_encode($chartData)); }
/** * process the form after the input has been submitted and validated * * @access public * @return None */ public function postProcess() { //get the submitted form values. $submittedValues = $this->controller->exportValues($this->_name); //take contribution information monthly require_once 'CRM/Contribute/BAO/Contribution/Utils.php'; $selectedYear = CRM_Utils_Array::value('select_year', $submittedValues, date('Y')); $chartInfoMonthly = CRM_Contribute_BAO_Contribution_Utils::contributionChartMonthly($selectedYear); $pChartParams = array(); $monthlyData = false; $abbrMonthNames = array(); if (is_array($chartInfoMonthly)) { $monthlyData = true; for ($i = 1; $i <= 12; $i++) { $abbrMonthNames[$i] = strftime('%b', mktime(0, 0, 0, $i, 10, 1970)); } foreach ($abbrMonthNames as $monthKey => $monthName) { if (!CRM_Utils_Array::value($monthKey, $chartInfoMonthly['By Month'])) { //set zero value to month which is not in db $chartInfoMonthly['By Month'][$monthKey] = 0; } } //sort the array. ksort($chartInfoMonthly['By Month']); //build the params for pChart. $pChartParams['by_month']['values'] = array_combine($abbrMonthNames, $chartInfoMonthly['By Month']); $pChartParams['by_month']['legend'] = 'By Month' . ' - ' . $selectedYear; } $this->assign('monthlyData', $monthlyData); //take contribution information by yearly $chartInfoYearly = CRM_Contribute_BAO_Contribution_Utils::contributionChartYearly(); //get the years. $this->_years = $chartInfoYearly['By Year']; $hasContributions = false; if (is_array($chartInfoYearly)) { $hasContributions = true; $pChartParams['by_year']['legend'] = 'By Year'; $pChartParams['by_year']['values'] = $chartInfoYearly['By Year']; } $this->assign('hasContributions', $hasContributions); //handle pchart functionality. if (!empty($pChartParams)) { $filesValues = array(); require_once 'CRM/Utils/PChart.php'; if ('p3' == CRM_Utils_Array::value('chart_type', $submittedValues, 'bvg')) { //assign shape for map $this->assign('shape', 'poly'); $this->assign('chartType', 'pie'); $chartParams = array(); if ($monthlyData) { $chartParams = array($pChartParams['by_month'], $pChartParams['by_year']); } else { $chartParams = array($pChartParams['by_year']); } //build the pie graph $filesValues = CRM_Utils_PChart::pieGraph($chartParams); } else { //assign shape for map $this->assign('shape', 'rect'); $this->assign('chartType', 'bar'); $chartParams = array(); if ($monthlyData) { $chartParams = array($pChartParams['by_month'], $pChartParams['by_year']); } else { $chartParams = array($pChartParams['by_year']); } //build the bar graph. $filesValues = CRM_Utils_PChart::barGraph($chartParams); } $formatMonthly = true; foreach ($filesValues as $chartIndex => $values) { if ($monthlyData && $formatMonthly) { $this->assign('monthCoords', $values['coords']); $this->assign('monthFilePath', $values['file_name']); //build the month urls for map. $monthUrls = array(); foreach ($values['coords'] as $month => $value) { $monthPosition = array_search($month, $abbrMonthNames); $startDate = CRM_Utils_Date::format(array('Y' => $selectedYear, 'M' => $monthPosition)); $endDate = date('Ymd', mktime(0, 0, 0, $monthPosition + 1, 0, $selectedYear)); $monthUrls[$month] = CRM_Utils_System::url('civicrm/contribute/search', "reset=1&force=1&status=1&start={$startDate}&end={$endDate}&test=0"); } $this->assign('monthUrls', $monthUrls); $formatMonthly = false; } else { $this->assign('yearCoords', $values['coords']); $this->assign('yearFilePath', $values['file_name']); //build year urls for map $yearUrls = array(); foreach ($values['coords'] as $year => $value) { $startDate = CRM_Utils_Date::format(array('Y' => $year)); if ($year) { $endDate = date('Ymd', mktime(0, 0, 0, 13, 0, $year)); } $yearUrls[$year] = CRM_Utils_System::url('civicrm/contribute/search', "reset=1&force=1&status=1&start={$startDate}&end={$endDate}&test=0"); } $this->assign('yearUrls', $yearUrls); } } } }