First commit
This commit is contained in:
commit
c6e2478c40
13918 changed files with 2303184 additions and 0 deletions
5793
sites/all/modules/civicrm/CRM/Contribute/BAO/Contribution.php
Normal file
5793
sites/all/modules/civicrm/CRM/Contribute/BAO/Contribution.php
Normal file
File diff suppressed because it is too large
Load diff
|
@ -0,0 +1,625 @@
|
|||
<?php
|
||||
/*
|
||||
+--------------------------------------------------------------------+
|
||||
| CiviCRM version 4.7 |
|
||||
+--------------------------------------------------------------------+
|
||||
| Copyright CiviCRM LLC (c) 2004-2017 |
|
||||
+--------------------------------------------------------------------+
|
||||
| This file is a part of CiviCRM. |
|
||||
| |
|
||||
| CiviCRM is free software; you can copy, modify, and distribute it |
|
||||
| under the terms of the GNU Affero General Public License |
|
||||
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
|
||||
| |
|
||||
| CiviCRM is distributed in the hope that it will be useful, but |
|
||||
| WITHOUT ANY WARRANTY; without even the implied warranty of |
|
||||
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
|
||||
| See the GNU Affero General Public License for more details. |
|
||||
| |
|
||||
| You should have received a copy of the GNU Affero General Public |
|
||||
| License and the CiviCRM Licensing Exception along |
|
||||
| with this program; if not, contact CiviCRM LLC |
|
||||
| at info[AT]civicrm[DOT]org. If you have questions about the |
|
||||
| GNU Affero General Public License or the licensing of CiviCRM, |
|
||||
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
|
||||
+--------------------------------------------------------------------+
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @package CRM
|
||||
* @copyright CiviCRM LLC (c) 2004-2017
|
||||
*/
|
||||
class CRM_Contribute_BAO_Contribution_Utils {
|
||||
|
||||
/**
|
||||
* Process payment after confirmation.
|
||||
*
|
||||
* @param CRM_Core_Form $form
|
||||
* Form object.
|
||||
* @param array $paymentParams
|
||||
* Array with payment related key.
|
||||
* value pairs
|
||||
* @param int $contactID
|
||||
* Contact id.
|
||||
* @param int $financialTypeID
|
||||
* Financial type id.
|
||||
* @param bool $isTest
|
||||
* @param bool $isRecur
|
||||
*
|
||||
* @throws CRM_Core_Exception
|
||||
* @throws Exception
|
||||
* @return array
|
||||
* associated array
|
||||
*
|
||||
*/
|
||||
public static function processConfirm(
|
||||
&$form,
|
||||
&$paymentParams,
|
||||
$contactID,
|
||||
$financialTypeID,
|
||||
$isTest,
|
||||
$isRecur
|
||||
) {
|
||||
CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, TRUE);
|
||||
$isPaymentTransaction = self::isPaymentTransaction($form);
|
||||
|
||||
$financialType = new CRM_Financial_DAO_FinancialType();
|
||||
$financialType->id = $financialTypeID;
|
||||
$financialType->find(TRUE);
|
||||
if ($financialType->is_deductible) {
|
||||
$form->assign('is_deductible', TRUE);
|
||||
$form->set('is_deductible', TRUE);
|
||||
}
|
||||
|
||||
// add some financial type details to the params list
|
||||
// if folks need to use it
|
||||
//CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
|
||||
$paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params['contributionType_name'] = $financialType->name;
|
||||
//CRM-11456
|
||||
$paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount::getAccountingCode($financialTypeID);
|
||||
$paymentParams['contributionPageID'] = $form->_params['contributionPageID'] = $form->_values['id'];
|
||||
$paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
|
||||
|
||||
//fix for CRM-16317
|
||||
if (empty($form->_params['receive_date'])) {
|
||||
$form->_params['receive_date'] = date('YmdHis');
|
||||
}
|
||||
if (!empty($form->_params['start_date'])) {
|
||||
$form->_params['start_date'] = date('YmdHis');
|
||||
}
|
||||
$form->assign('receive_date',
|
||||
CRM_Utils_Date::mysqlToIso($form->_params['receive_date'])
|
||||
);
|
||||
|
||||
if (empty($form->_values['amount'])) {
|
||||
// If the amount is not in _values[], set it
|
||||
$form->_values['amount'] = $form->_params['amount'];
|
||||
}
|
||||
|
||||
if ($isPaymentTransaction) {
|
||||
$contributionParams = array(
|
||||
'id' => CRM_Utils_Array::value('contribution_id', $paymentParams),
|
||||
'contact_id' => $contactID,
|
||||
'is_test' => $isTest,
|
||||
'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams, CRM_Utils_Array::value('campaign_id', $form->_values)),
|
||||
'contribution_page_id' => $form->_id,
|
||||
'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
|
||||
);
|
||||
if (isset($paymentParams['line_item'])) {
|
||||
// @todo make sure this is consisently set at this point.
|
||||
$contributionParams['line_item'] = $paymentParams['line_item'];
|
||||
}
|
||||
if (!empty($form->_paymentProcessor)) {
|
||||
$contributionParams['payment_instrument_id'] = $paymentParams['payment_instrument_id'] = $form->_paymentProcessor['payment_instrument_id'];
|
||||
}
|
||||
|
||||
// @todo this is the wrong place for this - it should be done as close to form submission
|
||||
// as possible
|
||||
$paymentParams['amount'] = CRM_Utils_Rule::cleanMoney($paymentParams['amount']);
|
||||
$contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution(
|
||||
$form,
|
||||
$paymentParams,
|
||||
NULL,
|
||||
$contributionParams,
|
||||
$financialType,
|
||||
TRUE,
|
||||
$form->_bltID,
|
||||
$isRecur
|
||||
);
|
||||
|
||||
$paymentParams['item_name'] = $form->_params['description'];
|
||||
|
||||
$paymentParams['qfKey'] = $form->controller->_key;
|
||||
if ($paymentParams['skipLineItem']) {
|
||||
// We are not processing the line item here because we are processing a membership.
|
||||
// Do not continue with contribution processing in this function.
|
||||
return array('contribution' => $contribution);
|
||||
}
|
||||
|
||||
$paymentParams['contributionID'] = $contribution->id;
|
||||
//CRM-15297 deprecate contributionTypeID
|
||||
$paymentParams['financialTypeID'] = $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
|
||||
$paymentParams['contributionPageID'] = $contribution->contribution_page_id;
|
||||
if (isset($paymentParams['contribution_source'])) {
|
||||
$paymentParams['source'] = $paymentParams['contribution_source'];
|
||||
}
|
||||
|
||||
if (CRM_Utils_Array::value('is_recur', $form->_params) && $contribution->contribution_recur_id) {
|
||||
$paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
|
||||
}
|
||||
if (isset($paymentParams['contribution_source'])) {
|
||||
$form->_params['source'] = $paymentParams['contribution_source'];
|
||||
}
|
||||
|
||||
// get the price set values for receipt.
|
||||
if ($form->_priceSetId && $form->_lineItem) {
|
||||
$form->_values['lineItem'] = $form->_lineItem;
|
||||
$form->_values['priceSetID'] = $form->_priceSetId;
|
||||
}
|
||||
|
||||
$form->_values['contribution_id'] = $contribution->id;
|
||||
$form->_values['contribution_page_id'] = $contribution->contribution_page_id;
|
||||
|
||||
if (!empty($form->_paymentProcessor)) {
|
||||
try {
|
||||
$payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
|
||||
if ($form->_contributeMode == 'notify') {
|
||||
// We want to get rid of this & make it generic - eg. by making payment processing the last thing
|
||||
// and always calling it first.
|
||||
$form->postProcessHook();
|
||||
}
|
||||
$result = $payment->doPayment($paymentParams);
|
||||
$form->_params = array_merge($form->_params, $result);
|
||||
$form->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
|
||||
if (!empty($result['trxn_id'])) {
|
||||
$contribution->trxn_id = $result['trxn_id'];
|
||||
}
|
||||
if (!empty($result['payment_status_id'])) {
|
||||
$contribution->payment_status_id = $result['payment_status_id'];
|
||||
}
|
||||
$result['contribution'] = $contribution;
|
||||
if ($result['payment_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution',
|
||||
'status_id', 'Pending') && $payment->isSendReceiptForPending()) {
|
||||
CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
|
||||
$form->_values,
|
||||
$contribution->is_test
|
||||
);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
|
||||
// Clean up DB as appropriate.
|
||||
if (!empty($paymentParams['contributionID'])) {
|
||||
CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'],
|
||||
$paymentParams['contactID'], $e->getMessage());
|
||||
}
|
||||
if (!empty($paymentParams['contributionRecurID'])) {
|
||||
CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
|
||||
}
|
||||
|
||||
$result['is_payment_failure'] = TRUE;
|
||||
$result['error'] = $e;
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only pay later or unpaid should reach this point, although pay later likely does not & is handled via the
|
||||
// manual processor, so it's unclear what this set is for and whether the following send ever fires.
|
||||
$form->set('params', $form->_params);
|
||||
|
||||
if ($form->_params['amount'] == 0) {
|
||||
// This is kind of a back-up for pay-later $0 transactions.
|
||||
// In other flows they pick up the manual processor & get dealt with above (I
|
||||
// think that might be better...).
|
||||
return array(
|
||||
'payment_status_id' => 1,
|
||||
'contribution' => $contribution,
|
||||
'payment_processor_id' => 0,
|
||||
);
|
||||
}
|
||||
|
||||
CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
|
||||
$form->_values,
|
||||
$contribution->is_test
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is a payment being made.
|
||||
* Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
|
||||
* to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
|
||||
* @param CRM_Core_Form $form
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
static protected function isPaymentTransaction($form) {
|
||||
return ($form->_amount >= 0.0) ? TRUE : FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the contribution details by month of the year.
|
||||
*
|
||||
* @param int $param
|
||||
* Year.
|
||||
*
|
||||
* @return array
|
||||
* associated array
|
||||
*/
|
||||
public static function contributionChartMonthly($param) {
|
||||
if ($param) {
|
||||
$param = array(1 => array($param, 'Integer'));
|
||||
}
|
||||
else {
|
||||
$param = date("Y");
|
||||
$param = array(1 => array($param, 'Integer'));
|
||||
}
|
||||
|
||||
$query = "
|
||||
SELECT sum(contrib.total_amount) AS ctAmt,
|
||||
MONTH( contrib.receive_date) AS contribMonth
|
||||
FROM civicrm_contribution AS contrib
|
||||
INNER JOIN civicrm_contact AS contact ON ( contact.id = contrib.contact_id )
|
||||
WHERE contrib.contact_id = contact.id
|
||||
AND ( contrib.is_test = 0 OR contrib.is_test IS NULL )
|
||||
AND contrib.contribution_status_id = 1
|
||||
AND date_format(contrib.receive_date,'%Y') = %1
|
||||
AND contact.is_deleted = 0
|
||||
GROUP BY contribMonth
|
||||
ORDER BY month(contrib.receive_date)";
|
||||
|
||||
$dao = CRM_Core_DAO::executeQuery($query, $param);
|
||||
|
||||
$params = NULL;
|
||||
while ($dao->fetch()) {
|
||||
if ($dao->contribMonth) {
|
||||
$params['By Month'][$dao->contribMonth] = $dao->ctAmt;
|
||||
}
|
||||
}
|
||||
return $params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the contribution details by year.
|
||||
*
|
||||
* @return array
|
||||
* associated array
|
||||
*/
|
||||
public static function contributionChartYearly() {
|
||||
$config = CRM_Core_Config::singleton();
|
||||
$yearClause = "year(contrib.receive_date) as contribYear";
|
||||
if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) {
|
||||
$yearClause = "CASE
|
||||
WHEN (MONTH(contrib.receive_date)>= " . $config->fiscalYearStart['M'] . "
|
||||
&& DAYOFMONTH(contrib.receive_date)>= " . $config->fiscalYearStart['d'] . " )
|
||||
THEN
|
||||
concat(YEAR(contrib.receive_date), '-',YEAR(contrib.receive_date)+1)
|
||||
ELSE
|
||||
concat(YEAR(contrib.receive_date)-1,'-', YEAR(contrib.receive_date))
|
||||
END AS contribYear";
|
||||
}
|
||||
|
||||
$query = "
|
||||
SELECT sum(contrib.total_amount) AS ctAmt,
|
||||
{$yearClause}
|
||||
FROM civicrm_contribution AS contrib
|
||||
INNER JOIN civicrm_contact contact ON ( contact.id = contrib.contact_id )
|
||||
WHERE ( contrib.is_test = 0 OR contrib.is_test IS NULL )
|
||||
AND contrib.contribution_status_id = 1
|
||||
AND contact.is_deleted = 0
|
||||
GROUP BY contribYear
|
||||
ORDER BY contribYear";
|
||||
$dao = CRM_Core_DAO::executeQuery($query);
|
||||
|
||||
$params = NULL;
|
||||
while ($dao->fetch()) {
|
||||
if (!empty($dao->contribYear)) {
|
||||
$params['By Year'][$dao->contribYear] = $dao->ctAmt;
|
||||
}
|
||||
}
|
||||
return $params;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $params
|
||||
* @param int $contactID
|
||||
* @param $mail
|
||||
*/
|
||||
public static function createCMSUser(&$params, $contactID, $mail) {
|
||||
// lets ensure we only create one CMS user
|
||||
static $created = FALSE;
|
||||
|
||||
if ($created) {
|
||||
return;
|
||||
}
|
||||
$created = TRUE;
|
||||
|
||||
if (!empty($params['cms_create_account'])) {
|
||||
$params['contactID'] = !empty($params['onbehalf_contact_id']) ? $params['onbehalf_contact_id'] : $contactID;
|
||||
if (!CRM_Core_BAO_CMSUser::create($params, $mail)) {
|
||||
CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $params
|
||||
* @param string $type
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function _fillCommonParams(&$params, $type = 'paypal') {
|
||||
if (array_key_exists('transaction', $params)) {
|
||||
$transaction = &$params['transaction'];
|
||||
}
|
||||
else {
|
||||
$transaction = &$params;
|
||||
}
|
||||
|
||||
$params['contact_type'] = 'Individual';
|
||||
|
||||
$billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
|
||||
if (!$billingLocTypeId) {
|
||||
$billingLocTypeId = 1;
|
||||
}
|
||||
if (!CRM_Utils_System::isNull($params['address'])) {
|
||||
$params['address'][1]['is_primary'] = 1;
|
||||
$params['address'][1]['location_type_id'] = $billingLocTypeId;
|
||||
}
|
||||
if (!CRM_Utils_System::isNull($params['email'])) {
|
||||
$params['email'] = array(
|
||||
1 => array(
|
||||
'email' => $params['email'],
|
||||
'location_type_id' => $billingLocTypeId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (isset($transaction['trxn_id'])) {
|
||||
// set error message if transaction has already been processed.
|
||||
$contribution = new CRM_Contribute_DAO_Contribution();
|
||||
$contribution->trxn_id = $transaction['trxn_id'];
|
||||
if ($contribution->find(TRUE)) {
|
||||
$params['error'][] = ts('transaction already processed.');
|
||||
}
|
||||
}
|
||||
else {
|
||||
// generate a new transaction id, if not already exist
|
||||
$transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
|
||||
}
|
||||
|
||||
if (!isset($transaction['financial_type_id'])) {
|
||||
$contributionTypes = array_keys(CRM_Contribute_PseudoConstant::financialType());
|
||||
$transaction['financial_type_id'] = $contributionTypes[0];
|
||||
}
|
||||
|
||||
if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
|
||||
$transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
|
||||
}
|
||||
|
||||
if (!isset($transaction['invoice_id'])) {
|
||||
$transaction['invoice_id'] = $transaction['trxn_id'];
|
||||
}
|
||||
|
||||
$source = ts('ContributionProcessor: %1 API',
|
||||
array(1 => ucfirst($type))
|
||||
);
|
||||
if (isset($transaction['source'])) {
|
||||
$transaction['source'] = $source . ':: ' . $transaction['source'];
|
||||
}
|
||||
else {
|
||||
$transaction['source'] = $source;
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $contactID
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public static function getFirstLastDetails($contactID) {
|
||||
static $_cache;
|
||||
|
||||
if (!$_cache) {
|
||||
$_cache = array();
|
||||
}
|
||||
|
||||
if (!isset($_cache[$contactID])) {
|
||||
$sql = "
|
||||
SELECT total_amount, receive_date
|
||||
FROM civicrm_contribution c
|
||||
WHERE contact_id = %1
|
||||
ORDER BY receive_date ASC
|
||||
LIMIT 1
|
||||
";
|
||||
$params = array(1 => array($contactID, 'Integer'));
|
||||
|
||||
$dao = CRM_Core_DAO::executeQuery($sql, $params);
|
||||
$details = array(
|
||||
'first' => NULL,
|
||||
'last' => NULL,
|
||||
);
|
||||
if ($dao->fetch()) {
|
||||
$details['first'] = array(
|
||||
'total_amount' => $dao->total_amount,
|
||||
'receive_date' => $dao->receive_date,
|
||||
);
|
||||
}
|
||||
|
||||
// flip asc and desc to get the last query
|
||||
$sql = str_replace('ASC', 'DESC', $sql);
|
||||
$dao = CRM_Core_DAO::executeQuery($sql, $params);
|
||||
if ($dao->fetch()) {
|
||||
$details['last'] = array(
|
||||
'total_amount' => $dao->total_amount,
|
||||
'receive_date' => $dao->receive_date,
|
||||
);
|
||||
}
|
||||
|
||||
$_cache[$contactID] = $details;
|
||||
}
|
||||
return $_cache[$contactID];
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the tax amount based on given tax rate.
|
||||
*
|
||||
* @param float $amount
|
||||
* Amount of field.
|
||||
* @param float $taxRate
|
||||
* Tax rate of selected financial account for field.
|
||||
* @param bool $ugWeDoNotKnowIfItNeedsCleaning_Help
|
||||
* This should ALWAYS BE FALSE and then be removed. A 'clean' money string uses a standardised format
|
||||
* such as '1000.99' for one thousand $/Euro/CUR and ninety nine cents/units.
|
||||
* However, we are in the habit of not necessarily doing that so need to grandfather in
|
||||
* the new expectation.
|
||||
*
|
||||
* @return array
|
||||
* array of tax amount
|
||||
*
|
||||
*/
|
||||
public static function calculateTaxAmount($amount, $taxRate, $ugWeDoNotKnowIfItNeedsCleaning_Help = FALSE) {
|
||||
$taxAmount = array();
|
||||
if ($ugWeDoNotKnowIfItNeedsCleaning_Help) {
|
||||
Civi::log()->warning('Deprecated function, make sure money is in usable format before calling this.', array('civi.tag' => 'deprecated'));
|
||||
$amount = CRM_Utils_Rule::cleanMoney($amount);
|
||||
}
|
||||
// There can not be any rounding at this stage - as this is prior to quantity multiplication
|
||||
$taxAmount['tax_amount'] = ($taxRate / 100) * $amount;
|
||||
|
||||
return $taxAmount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format monetary amount: round and return to desired decimal place
|
||||
* CRM-20145
|
||||
*
|
||||
* @param float $amount
|
||||
* Monetary amount
|
||||
* @param int $decimals
|
||||
* How many decimal places to round to and return
|
||||
*
|
||||
* @return float
|
||||
* Amount rounded and returned with the desired decimal places
|
||||
*/
|
||||
public static function formatAmount($amount, $decimals = 2) {
|
||||
return number_format((float) round($amount, (int) $decimals), (int) $decimals, '.', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get contribution statuses by entity e.g. contribution, membership or 'participant'
|
||||
*
|
||||
* @param string $usedFor
|
||||
* @param int $id
|
||||
* Contribution ID
|
||||
*
|
||||
* @return array $statuses
|
||||
* Array of contribution statuses in array('status id' => 'label') format
|
||||
*/
|
||||
public static function getContributionStatuses($usedFor = 'contribution', $id = NULL) {
|
||||
if ($usedFor == 'pledge') {
|
||||
$statusNames = CRM_Pledge_BAO_Pledge::buildOptions('status_id', 'validate');
|
||||
}
|
||||
else {
|
||||
$statusNames = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate');
|
||||
}
|
||||
|
||||
$statusNamesToUnset = array();
|
||||
// on create fetch statuses on basis of component
|
||||
if (!$id) {
|
||||
$statusNamesToUnset = array(
|
||||
'Refunded',
|
||||
'Chargeback',
|
||||
'Pending refund',
|
||||
);
|
||||
|
||||
// Event registration and New Membership backoffice form support partially paid payment,
|
||||
// so exclude this status only for 'New Contribution' form
|
||||
if ($usedFor == 'contribution') {
|
||||
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
|
||||
'In Progress',
|
||||
'Overdue',
|
||||
'Partially paid',
|
||||
));
|
||||
}
|
||||
elseif ($usedFor == 'participant') {
|
||||
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
|
||||
'Cancelled',
|
||||
'Failed',
|
||||
));
|
||||
}
|
||||
elseif ($usedFor == 'membership') {
|
||||
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
|
||||
'In Progress',
|
||||
'Overdue',
|
||||
));
|
||||
}
|
||||
}
|
||||
else {
|
||||
$contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $id, 'contribution_status_id');
|
||||
$name = CRM_Utils_Array::value($contributionStatus, $statusNames);
|
||||
switch ($name) {
|
||||
case 'Completed':
|
||||
// [CRM-17498] Removing unsupported status change options.
|
||||
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
|
||||
'Pending',
|
||||
'Failed',
|
||||
'Partially paid',
|
||||
'Pending refund',
|
||||
));
|
||||
break;
|
||||
|
||||
case 'Cancelled':
|
||||
case 'Chargeback':
|
||||
case 'Refunded':
|
||||
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
|
||||
'Pending',
|
||||
'Failed',
|
||||
));
|
||||
break;
|
||||
|
||||
case 'Pending':
|
||||
case 'In Progress':
|
||||
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
|
||||
'Refunded',
|
||||
'Chargeback',
|
||||
));
|
||||
break;
|
||||
|
||||
case 'Failed':
|
||||
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
|
||||
'Pending',
|
||||
'Refunded',
|
||||
'Chargeback',
|
||||
'Completed',
|
||||
'In Progress',
|
||||
'Cancelled',
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($statusNamesToUnset as $name) {
|
||||
unset($statusNames[CRM_Utils_Array::key($name, $statusNames)]);
|
||||
}
|
||||
|
||||
// based on filtered statuse names fetch the final list of statuses in array('id' => 'label') format
|
||||
if ($usedFor == 'pledge') {
|
||||
$statuses = CRM_Pledge_BAO_Pledge::buildOptions('status_id');
|
||||
}
|
||||
else {
|
||||
$statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
|
||||
}
|
||||
foreach ($statuses as $statusID => $label) {
|
||||
if (!array_key_exists($statusID, $statusNames)) {
|
||||
unset($statuses[$statusID]);
|
||||
}
|
||||
}
|
||||
|
||||
return $statuses;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,987 @@
|
|||
<?php
|
||||
/*
|
||||
+--------------------------------------------------------------------+
|
||||
| CiviCRM version 4.7 |
|
||||
+--------------------------------------------------------------------+
|
||||
| Copyright CiviCRM LLC (c) 2004-2017 |
|
||||
+--------------------------------------------------------------------+
|
||||
| This file is a part of CiviCRM. |
|
||||
| |
|
||||
| CiviCRM is free software; you can copy, modify, and distribute it |
|
||||
| under the terms of the GNU Affero General Public License |
|
||||
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
|
||||
| |
|
||||
| CiviCRM is distributed in the hope that it will be useful, but |
|
||||
| WITHOUT ANY WARRANTY; without even the implied warranty of |
|
||||
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
|
||||
| See the GNU Affero General Public License for more details. |
|
||||
| |
|
||||
| You should have received a copy of the GNU Affero General Public |
|
||||
| License and the CiviCRM Licensing Exception along |
|
||||
| with this program; if not, contact CiviCRM LLC |
|
||||
| at info[AT]civicrm[DOT]org. If you have questions about the |
|
||||
| GNU Affero General Public License or the licensing of CiviCRM, |
|
||||
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
|
||||
+--------------------------------------------------------------------+
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @package CRM
|
||||
* @copyright CiviCRM LLC (c) 2004-2017
|
||||
*/
|
||||
|
||||
/**
|
||||
* This class contains Contribution Page related functions.
|
||||
*/
|
||||
class CRM_Contribute_BAO_ContributionPage extends CRM_Contribute_DAO_ContributionPage {
|
||||
|
||||
/**
|
||||
* Creates a contribution page.
|
||||
*
|
||||
* @param array $params
|
||||
*
|
||||
* @return CRM_Contribute_DAO_ContributionPage
|
||||
*/
|
||||
public static function create($params) {
|
||||
$financialTypeId = NULL;
|
||||
if (!empty($params['id']) && !CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id'], NULL, 1)) {
|
||||
$financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $params['id'], 'financial_type_id');
|
||||
}
|
||||
|
||||
if (isset($params['payment_processor']) && is_array($params['payment_processor'])) {
|
||||
$params['payment_processor'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['payment_processor']);
|
||||
}
|
||||
$hook = empty($params['id']) ? 'create' : 'edit';
|
||||
CRM_Utils_Hook::pre($hook, 'ContributionPage', CRM_Utils_Array::value('id', $params), $params);
|
||||
$dao = new CRM_Contribute_DAO_ContributionPage();
|
||||
$dao->copyValues($params);
|
||||
$dao->save();
|
||||
if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
|
||||
CRM_Price_BAO_PriceFieldValue::updateFinancialType($params['id'], 'civicrm_contribution_page', $params['financial_type_id']);
|
||||
}
|
||||
CRM_Utils_Hook::post($hook, 'ContributionPage', $dao->id, $dao);
|
||||
return $dao;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the is_active flag in the db.
|
||||
*
|
||||
* @deprecated - this bypasses hooks.
|
||||
*
|
||||
* @param int $id
|
||||
* Id of the database record.
|
||||
* @param bool $is_active
|
||||
* Value we want to set the is_active field.
|
||||
*
|
||||
* @return Object
|
||||
* DAO object on success, null otherwise
|
||||
*/
|
||||
public static function setIsActive($id, $is_active) {
|
||||
return CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionPage', $id, 'is_active', $is_active);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load values for a contribution page.
|
||||
*
|
||||
* @param int $id
|
||||
* @param array $values
|
||||
*/
|
||||
public static function setValues($id, &$values) {
|
||||
$modules = array('CiviContribute', 'soft_credit', 'on_behalf');
|
||||
$values['custom_pre_id'] = $values['custom_post_id'] = NULL;
|
||||
|
||||
$params = array('id' => $id);
|
||||
CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage', $params, $values);
|
||||
|
||||
// get the profile ids
|
||||
$ufJoinParams = array(
|
||||
'entity_table' => 'civicrm_contribution_page',
|
||||
'entity_id' => $id,
|
||||
);
|
||||
|
||||
// retrieve profile id as also unserialize module_data corresponding to each $module
|
||||
foreach ($modules as $module) {
|
||||
$ufJoinParams['module'] = $module;
|
||||
$ufJoin = new CRM_Core_DAO_UFJoin();
|
||||
$ufJoin->copyValues($ufJoinParams);
|
||||
if ($module == 'CiviContribute') {
|
||||
$ufJoin->orderBy('weight asc');
|
||||
$ufJoin->find();
|
||||
while ($ufJoin->fetch()) {
|
||||
if ($ufJoin->weight == 1) {
|
||||
$values['custom_pre_id'] = $ufJoin->uf_group_id;
|
||||
}
|
||||
else {
|
||||
$values['custom_post_id'] = $ufJoin->uf_group_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
$ufJoin->find(TRUE);
|
||||
if (!$ufJoin->is_active) {
|
||||
continue;
|
||||
}
|
||||
$params = CRM_Contribute_BAO_ContributionPage::formatModuleData($ufJoin->module_data, TRUE, $module);
|
||||
$values = array_merge($params, $values);
|
||||
if ($module == 'soft_credit') {
|
||||
$values['honoree_profile_id'] = $ufJoin->uf_group_id;
|
||||
$values['honor_block_is_active'] = $ufJoin->is_active;
|
||||
}
|
||||
else {
|
||||
$values['onbehalf_profile_id'] = $ufJoin->uf_group_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the emails.
|
||||
*
|
||||
* @param int $contactID
|
||||
* Contact id.
|
||||
* @param array $values
|
||||
* Associated array of fields.
|
||||
* @param bool $isTest
|
||||
* If in test mode.
|
||||
* @param bool $returnMessageText
|
||||
* Return the message text instead of sending the mail.
|
||||
*
|
||||
* @param array $fieldTypes
|
||||
*/
|
||||
public static function sendMail($contactID, $values, $isTest = FALSE, $returnMessageText = FALSE, $fieldTypes = NULL) {
|
||||
$gIds = array();
|
||||
$params = array('custom_pre_id' => array(), 'custom_post_id' => array());
|
||||
$email = NULL;
|
||||
|
||||
// We are trying to fight the good fight against leaky variables (CRM-17519) so let's get really explicit
|
||||
// about ensuring the variables we want for the template are defined.
|
||||
// @todo add to this until all tpl params are explicit in this function and not waltzing around the codebase.
|
||||
// Next stage is to remove this & ensure there are no e-notices - ie. all are set before they hit this fn.
|
||||
$valuesRequiredForTemplate = array(
|
||||
'customPre',
|
||||
'customPost',
|
||||
'customPre_grouptitle',
|
||||
'customPost_grouptitle',
|
||||
'useForMember',
|
||||
'membership_assign',
|
||||
'amount',
|
||||
'receipt_date',
|
||||
'is_pay_later',
|
||||
);
|
||||
|
||||
foreach ($valuesRequiredForTemplate as $valueRequiredForTemplate) {
|
||||
if (!isset($values[$valueRequiredForTemplate])) {
|
||||
$values[$valueRequiredForTemplate] = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($values['custom_pre_id'])) {
|
||||
$preProfileType = CRM_Core_BAO_UFField::getProfileType($values['custom_pre_id']);
|
||||
if ($preProfileType == 'Membership' && !empty($values['membership_id'])) {
|
||||
$params['custom_pre_id'] = array(
|
||||
array(
|
||||
'member_id',
|
||||
'=',
|
||||
$values['membership_id'],
|
||||
0,
|
||||
0,
|
||||
),
|
||||
);
|
||||
}
|
||||
elseif ($preProfileType == 'Contribution' && !empty($values['contribution_id'])) {
|
||||
$params['custom_pre_id'] = array(
|
||||
array(
|
||||
'contribution_id',
|
||||
'=',
|
||||
$values['contribution_id'],
|
||||
0,
|
||||
0,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
$gIds['custom_pre_id'] = $values['custom_pre_id'];
|
||||
}
|
||||
|
||||
if (isset($values['custom_post_id'])) {
|
||||
$postProfileType = CRM_Core_BAO_UFField::getProfileType($values['custom_post_id']);
|
||||
if ($postProfileType == 'Membership' && !empty($values['membership_id'])) {
|
||||
$params['custom_post_id'] = array(
|
||||
array(
|
||||
'member_id',
|
||||
'=',
|
||||
$values['membership_id'],
|
||||
0,
|
||||
0,
|
||||
),
|
||||
);
|
||||
}
|
||||
elseif ($postProfileType == 'Contribution' && !empty($values['contribution_id'])) {
|
||||
$params['custom_post_id'] = array(
|
||||
array(
|
||||
'contribution_id',
|
||||
'=',
|
||||
$values['contribution_id'],
|
||||
0,
|
||||
0,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
$gIds['custom_post_id'] = $values['custom_post_id'];
|
||||
}
|
||||
|
||||
if (!empty($values['is_for_organization'])) {
|
||||
if (!empty($values['membership_id'])) {
|
||||
$params['onbehalf_profile'] = array(
|
||||
array(
|
||||
'member_id',
|
||||
'=',
|
||||
$values['membership_id'],
|
||||
0,
|
||||
0,
|
||||
),
|
||||
);
|
||||
}
|
||||
elseif (!empty($values['contribution_id'])) {
|
||||
$params['onbehalf_profile'] = array(
|
||||
array(
|
||||
'contribution_id',
|
||||
'=',
|
||||
$values['contribution_id'],
|
||||
0,
|
||||
0,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
//check whether it is a test drive
|
||||
if ($isTest && !empty($params['custom_pre_id'])) {
|
||||
$params['custom_pre_id'][] = array(
|
||||
'contribution_test',
|
||||
'=',
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
if ($isTest && !empty($params['custom_post_id'])) {
|
||||
$params['custom_post_id'][] = array(
|
||||
'contribution_test',
|
||||
'=',
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
if (!$returnMessageText && !empty($gIds)) {
|
||||
//send notification email if field values are set (CRM-1941)
|
||||
foreach ($gIds as $key => $gId) {
|
||||
if ($gId) {
|
||||
$email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
|
||||
if ($email) {
|
||||
$val = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $contactID, CRM_Utils_Array::value($key, $params), TRUE);
|
||||
CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($values['is_email_receipt']) || !empty($values['onbehalf_dupe_alert']) ||
|
||||
$returnMessageText
|
||||
) {
|
||||
$template = CRM_Core_Smarty::singleton();
|
||||
|
||||
// get the billing location type
|
||||
if (!array_key_exists('related_contact', $values)) {
|
||||
$billingLocationTypeId = CRM_Core_BAO_LocationType::getBilling();
|
||||
}
|
||||
else {
|
||||
// presence of related contact implies onbehalf of org case,
|
||||
// where location type is set to default.
|
||||
$locType = CRM_Core_BAO_LocationType::getDefault();
|
||||
$billingLocationTypeId = $locType->id;
|
||||
}
|
||||
|
||||
if (!array_key_exists('related_contact', $values)) {
|
||||
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, FALSE, $billingLocationTypeId);
|
||||
}
|
||||
// get primary location email if no email exist( for billing location).
|
||||
if (!$email) {
|
||||
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
|
||||
}
|
||||
if (empty($displayName)) {
|
||||
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
|
||||
}
|
||||
|
||||
//for display profile need to get individual contact id,
|
||||
//hence get it from related_contact if on behalf of org true CRM-3767
|
||||
//CRM-5001 Contribution/Membership:: On Behalf of Organization,
|
||||
//If profile GROUP contain the Individual type then consider the
|
||||
//profile is of Individual ( including the custom data of membership/contribution )
|
||||
//IF Individual type not present in profile then it is consider as Organization data.
|
||||
$userID = $contactID;
|
||||
if ($preID = CRM_Utils_Array::value('custom_pre_id', $values)) {
|
||||
if (!empty($values['related_contact'])) {
|
||||
$preProfileTypes = CRM_Core_BAO_UFGroup::profileGroups($preID);
|
||||
//@todo - following line should not refer to undefined $postProfileTypes? figure out way to test
|
||||
if (in_array('Individual', $preProfileTypes) || in_array('Contact', $postProfileTypes)) {
|
||||
//Take Individual contact ID
|
||||
$userID = CRM_Utils_Array::value('related_contact', $values);
|
||||
}
|
||||
}
|
||||
list($values['customPre_grouptitle'], $values['customPre']) = self::getProfileNameAndFields($preID, $userID, $params['custom_pre_id']);
|
||||
}
|
||||
$userID = $contactID;
|
||||
if ($postID = CRM_Utils_Array::value('custom_post_id', $values)) {
|
||||
if (!empty($values['related_contact'])) {
|
||||
$postProfileTypes = CRM_Core_BAO_UFGroup::profileGroups($postID);
|
||||
if (in_array('Individual', $postProfileTypes) || in_array('Contact', $postProfileTypes)) {
|
||||
//Take Individual contact ID
|
||||
$userID = CRM_Utils_Array::value('related_contact', $values);
|
||||
}
|
||||
}
|
||||
list($values['customPost_grouptitle'], $values['customPost']) = self::getProfileNameAndFields($postID, $userID, $params['custom_post_id']);
|
||||
}
|
||||
if (isset($values['honor'])) {
|
||||
$honorValues = $values['honor'];
|
||||
$template->_values = array('honoree_profile_id' => $values['honoree_profile_id']);
|
||||
CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields(
|
||||
$template,
|
||||
$honorValues['honor_profile_values'],
|
||||
$honorValues['honor_id']
|
||||
);
|
||||
}
|
||||
|
||||
$title = isset($values['title']) ? $values['title'] : CRM_Contribute_PseudoConstant::contributionPage($values['contribution_page_id']);
|
||||
|
||||
// Set email variables explicitly to avoid leaky smarty variables.
|
||||
// All of these will be assigned to the template, replacing any that might be assigned elsewhere.
|
||||
$tplParams = array(
|
||||
'email' => $email,
|
||||
'receiptFromEmail' => CRM_Utils_Array::value('receipt_from_email', $values),
|
||||
'contactID' => $contactID,
|
||||
'displayName' => $displayName,
|
||||
'contributionID' => CRM_Utils_Array::value('contribution_id', $values),
|
||||
'contributionOtherID' => CRM_Utils_Array::value('contribution_other_id', $values),
|
||||
// CRM-5095
|
||||
'lineItem' => CRM_Utils_Array::value('lineItem', $values),
|
||||
// CRM-5095
|
||||
'priceSetID' => CRM_Utils_Array::value('priceSetID', $values),
|
||||
'title' => $title,
|
||||
'isShare' => CRM_Utils_Array::value('is_share', $values),
|
||||
'thankyou_title' => CRM_Utils_Array::value('thankyou_title', $values),
|
||||
'customPre' => $values['customPre'],
|
||||
'customPre_grouptitle' => $values['customPre_grouptitle'],
|
||||
'customPost' => $values['customPost'],
|
||||
'customPost_grouptitle' => $values['customPost_grouptitle'],
|
||||
'useForMember' => $values['useForMember'],
|
||||
'membership_assign' => $values['membership_assign'],
|
||||
'amount' => $values['amount'],
|
||||
'is_pay_later' => $values['is_pay_later'],
|
||||
'receipt_date' => !$values['receipt_date'] ? NULL : date('YmdHis', strtotime($values['receipt_date'])),
|
||||
'pay_later_receipt' => CRM_Utils_Array::value('pay_later_receipt', $values),
|
||||
'honor_block_is_active' => CRM_Utils_Array::value('honor_block_is_active', $values),
|
||||
'contributionStatus' => CRM_Utils_Array::value('contribution_status', $values),
|
||||
);
|
||||
|
||||
if ($contributionTypeId = CRM_Utils_Array::value('financial_type_id', $values)) {
|
||||
$tplParams['financialTypeId'] = $contributionTypeId;
|
||||
$tplParams['financialTypeName'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
|
||||
$contributionTypeId);
|
||||
// Legacy support
|
||||
$tplParams['contributionTypeName'] = $tplParams['financialTypeName'];
|
||||
$tplParams['contributionTypeId'] = $contributionTypeId;
|
||||
}
|
||||
|
||||
if ($contributionPageId = CRM_Utils_Array::value('id', $values)) {
|
||||
$tplParams['contributionPageId'] = $contributionPageId;
|
||||
}
|
||||
|
||||
// address required during receipt processing (pdf and email receipt)
|
||||
if ($displayAddress = CRM_Utils_Array::value('address', $values)) {
|
||||
$tplParams['address'] = $displayAddress;
|
||||
}
|
||||
|
||||
// CRM-6976
|
||||
$originalCCReceipt = CRM_Utils_Array::value('cc_receipt', $values);
|
||||
|
||||
// cc to related contacts of contributor OR the one who
|
||||
// signs up. Is used for cases like - on behalf of
|
||||
// contribution / signup ..etc
|
||||
if (array_key_exists('related_contact', $values)) {
|
||||
list($ccDisplayName, $ccEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($values['related_contact']);
|
||||
$ccMailId = "{$ccDisplayName} <{$ccEmail}>";
|
||||
|
||||
//@todo - this is the only place in this function where $values is altered - but I can't find any evidence it is used
|
||||
$values['cc_receipt'] = !empty($values['cc_receipt']) ? ($values['cc_receipt'] . ',' . $ccMailId) : $ccMailId;
|
||||
|
||||
// reset primary-email in the template
|
||||
$tplParams['email'] = $ccEmail;
|
||||
|
||||
$tplParams['onBehalfName'] = $displayName;
|
||||
$tplParams['onBehalfEmail'] = $email;
|
||||
|
||||
if (!empty($values['onbehalf_profile_id'])) {
|
||||
self::buildCustomDisplay($values['onbehalf_profile_id'], 'onBehalfProfile', $contactID, $template, $params['onbehalf_profile'], $fieldTypes);
|
||||
}
|
||||
}
|
||||
|
||||
// use either the contribution or membership receipt, based on whether it’s a membership-related contrib or not
|
||||
$sendTemplateParams = array(
|
||||
'groupName' => !empty($values['isMembership']) ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
|
||||
'valueName' => !empty($values['isMembership']) ? 'membership_online_receipt' : 'contribution_online_receipt',
|
||||
'contactId' => $contactID,
|
||||
'tplParams' => $tplParams,
|
||||
'isTest' => $isTest,
|
||||
'PDFFilename' => 'receipt.pdf',
|
||||
);
|
||||
|
||||
if ($returnMessageText) {
|
||||
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
|
||||
return array(
|
||||
'subject' => $subject,
|
||||
'body' => $message,
|
||||
'to' => $displayName,
|
||||
'html' => $html,
|
||||
);
|
||||
}
|
||||
|
||||
if (empty($values['receipt_from_name']) && empty($values['receipt_from_name'])) {
|
||||
list($values['receipt_from_name'], $values['receipt_from_email']) = CRM_Core_BAO_Domain::getNameAndEmail();
|
||||
}
|
||||
|
||||
if ($values['is_email_receipt']) {
|
||||
$sendTemplateParams['from'] = CRM_Utils_Array::value('receipt_from_name', $values) . ' <' . $values['receipt_from_email'] . '>';
|
||||
$sendTemplateParams['toName'] = $displayName;
|
||||
$sendTemplateParams['toEmail'] = $email;
|
||||
$sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
|
||||
$sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
|
||||
//send email with pdf invoice
|
||||
$template = CRM_Core_Smarty::singleton();
|
||||
$taxAmt = $template->get_template_vars('dataArray');
|
||||
$prefixValue = Civi::settings()->get('contribution_invoice_settings');
|
||||
$invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
|
||||
if (isset($invoicing) && isset($prefixValue['is_email_pdf'])) {
|
||||
$sendTemplateParams['isEmailPdf'] = TRUE;
|
||||
$sendTemplateParams['contributionId'] = $values['contribution_id'];
|
||||
}
|
||||
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
|
||||
}
|
||||
|
||||
// send duplicate alert, if dupe match found during on-behalf-of processing.
|
||||
if (!empty($values['onbehalf_dupe_alert'])) {
|
||||
$sendTemplateParams['groupName'] = 'msg_tpl_workflow_contribution';
|
||||
$sendTemplateParams['valueName'] = 'contribution_dupalert';
|
||||
$sendTemplateParams['from'] = ts('Automatically Generated') . " <{$values['receipt_from_email']}>";
|
||||
$sendTemplateParams['toName'] = CRM_Utils_Array::value('receipt_from_name', $values);
|
||||
$sendTemplateParams['toEmail'] = CRM_Utils_Array::value('receipt_from_email', $values);
|
||||
$sendTemplateParams['tplParams']['onBehalfID'] = $contactID;
|
||||
$sendTemplateParams['tplParams']['receiptMessage'] = $message;
|
||||
|
||||
// fix cc and reset back to original, CRM-6976
|
||||
$sendTemplateParams['cc'] = $originalCCReceipt;
|
||||
|
||||
CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the profile title and fields.
|
||||
*
|
||||
* @param int $gid
|
||||
* @param int $cid
|
||||
* @param array $params
|
||||
* @param array $fieldTypes
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected static function getProfileNameAndFields($gid, $cid, &$params, $fieldTypes = array()) {
|
||||
$groupTitle = NULL;
|
||||
$values = array();
|
||||
if ($gid) {
|
||||
if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $cid)) {
|
||||
$fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL);
|
||||
foreach ($fields as $k => $v) {
|
||||
if (!$groupTitle) {
|
||||
$groupTitle = $v["groupTitle"];
|
||||
}
|
||||
// suppress all file fields from display and formatting fields
|
||||
if (
|
||||
CRM_Utils_Array::value('data_type', $v, '') == 'File' ||
|
||||
CRM_Utils_Array::value('name', $v, '') == 'image_URL' ||
|
||||
CRM_Utils_Array::value('field_type', $v) == 'Formatting'
|
||||
) {
|
||||
unset($fields[$k]);
|
||||
}
|
||||
|
||||
if (!empty($fieldTypes) && (!in_array($v['field_type'], $fieldTypes))) {
|
||||
unset($fields[$k]);
|
||||
}
|
||||
}
|
||||
|
||||
CRM_Core_BAO_UFGroup::getValues($cid, $fields, $values, FALSE, $params);
|
||||
}
|
||||
}
|
||||
return array($groupTitle, $values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the emails for Recurring Contribution Notification.
|
||||
*
|
||||
* @param string $type
|
||||
* TxnType.
|
||||
* @param int $contactID
|
||||
* Contact id for contributor.
|
||||
* @param int $pageID
|
||||
* Contribution page id.
|
||||
* @param object $recur
|
||||
* Object of recurring contribution table.
|
||||
* @param bool|object $autoRenewMembership is it a auto renew membership.
|
||||
*/
|
||||
public static function recurringNotify($type, $contactID, $pageID, $recur, $autoRenewMembership = FALSE) {
|
||||
$value = array();
|
||||
$isEmailReceipt = FALSE;
|
||||
if ($pageID) {
|
||||
CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $pageID, $value, array(
|
||||
'title',
|
||||
'is_email_receipt',
|
||||
'receipt_from_name',
|
||||
'receipt_from_email',
|
||||
'cc_receipt',
|
||||
'bcc_receipt',
|
||||
));
|
||||
$isEmailReceipt = CRM_Utils_Array::value('is_email_receipt', $value[$pageID]);
|
||||
}
|
||||
elseif ($recur->id) {
|
||||
// This means we are coming from back-office - ie. no page ID, but recurring.
|
||||
// Ideally this information would be passed into the function clearly rather than guessing by convention.
|
||||
$isEmailReceipt = TRUE;
|
||||
}
|
||||
|
||||
if ($isEmailReceipt) {
|
||||
if ($pageID) {
|
||||
$receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$pageID]) . '" <' . $value[$pageID]['receipt_from_email'] . '>';
|
||||
|
||||
$receiptFromName = $value[$pageID]['receipt_from_name'];
|
||||
$receiptFromEmail = $value[$pageID]['receipt_from_email'];
|
||||
}
|
||||
else {
|
||||
$domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
|
||||
$receiptFrom = "$domainValues[0] <$domainValues[1]>";
|
||||
$receiptFromName = $domainValues[0];
|
||||
$receiptFromEmail = $domainValues[1];
|
||||
}
|
||||
|
||||
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, FALSE);
|
||||
$templatesParams = array(
|
||||
'groupName' => 'msg_tpl_workflow_contribution',
|
||||
'valueName' => 'contribution_recurring_notify',
|
||||
'contactId' => $contactID,
|
||||
'tplParams' => array(
|
||||
'recur_frequency_interval' => $recur->frequency_interval,
|
||||
'recur_frequency_unit' => $recur->frequency_unit,
|
||||
'recur_installments' => $recur->installments,
|
||||
'recur_start_date' => $recur->start_date,
|
||||
'recur_end_date' => $recur->end_date,
|
||||
'recur_amount' => $recur->amount,
|
||||
'recur_txnType' => $type,
|
||||
'displayName' => $displayName,
|
||||
'receipt_from_name' => $receiptFromName,
|
||||
'receipt_from_email' => $receiptFromEmail,
|
||||
'auto_renew_membership' => $autoRenewMembership,
|
||||
),
|
||||
'from' => $receiptFrom,
|
||||
'toName' => $displayName,
|
||||
'toEmail' => $email,
|
||||
);
|
||||
//CRM-13811
|
||||
if ($pageID) {
|
||||
$templatesParams['cc'] = CRM_Utils_Array::value('cc_receipt', $value[$pageID]);
|
||||
$templatesParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $value[$pageID]);
|
||||
}
|
||||
if ($recur->id) {
|
||||
// in some cases its just recurringNotify() thats called for the first time and these urls don't get set.
|
||||
// like in PaypalPro, & therefore we set it here additionally.
|
||||
$template = CRM_Core_Smarty::singleton();
|
||||
$paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($recur->id, 'recur', 'obj');
|
||||
$url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'cancel');
|
||||
$template->assign('cancelSubscriptionUrl', $url);
|
||||
|
||||
$url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'billing');
|
||||
$template->assign('updateSubscriptionBillingUrl', $url);
|
||||
|
||||
$url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'update');
|
||||
$template->assign('updateSubscriptionUrl', $url);
|
||||
}
|
||||
|
||||
list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($templatesParams);
|
||||
|
||||
if ($sent) {
|
||||
CRM_Core_Error::debug_log_message('Success: mail sent for recurring notification.');
|
||||
}
|
||||
else {
|
||||
CRM_Core_Error::debug_log_message('Failure: mail not sent for recurring notification.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the custom fields for contribution page (ie profile).
|
||||
*
|
||||
* @deprecated assigning values to smarty like this is risky because
|
||||
* - it is hard to debug since $name is used in the assign
|
||||
* - it is potentially 'leaky' - it's better to do this on the form
|
||||
* or close to where it is used / required. See CRM-17519 for leakage e.g.
|
||||
*
|
||||
* @param int $gid
|
||||
* Uf group id.
|
||||
* @param string $name
|
||||
* @param int $cid
|
||||
* Contact id.
|
||||
* @param $template
|
||||
* @param array $params
|
||||
* Params to build component whereclause.
|
||||
*
|
||||
* @param array|null $fieldTypes
|
||||
*/
|
||||
public static function buildCustomDisplay($gid, $name, $cid, &$template, &$params, $fieldTypes = NULL) {
|
||||
list($groupTitle, $values) = self::getProfileNameAndFields($gid, $cid, $params, $fieldTypes);
|
||||
if (!empty($values)) {
|
||||
$template->assign($name, $values);
|
||||
}
|
||||
$template->assign($name . "_grouptitle", $groupTitle);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a copy of a contribution page, including all the blocks in the page.
|
||||
*
|
||||
* @param int $id
|
||||
* The contribution page id to copy.
|
||||
*
|
||||
* @return CRM_Contribute_DAO_ContributionPage
|
||||
*/
|
||||
public static function copy($id) {
|
||||
$fieldsFix = array(
|
||||
'prefix' => array(
|
||||
'title' => ts('Copy of') . ' ',
|
||||
),
|
||||
);
|
||||
$copy = &CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_ContributionPage', array(
|
||||
'id' => $id,
|
||||
), NULL, $fieldsFix);
|
||||
|
||||
//copying all the blocks pertaining to the contribution page
|
||||
$copyPledgeBlock = &CRM_Core_DAO::copyGeneric('CRM_Pledge_DAO_PledgeBlock', array(
|
||||
'entity_id' => $id,
|
||||
'entity_table' => 'civicrm_contribution_page',
|
||||
), array(
|
||||
'entity_id' => $copy->id,
|
||||
));
|
||||
|
||||
$copyMembershipBlock = &CRM_Core_DAO::copyGeneric('CRM_Member_DAO_MembershipBlock', array(
|
||||
'entity_id' => $id,
|
||||
'entity_table' => 'civicrm_contribution_page',
|
||||
), array(
|
||||
'entity_id' => $copy->id,
|
||||
));
|
||||
|
||||
$copyUFJoin = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array(
|
||||
'entity_id' => $id,
|
||||
'entity_table' => 'civicrm_contribution_page',
|
||||
), array(
|
||||
'entity_id' => $copy->id,
|
||||
));
|
||||
|
||||
$copyWidget = &CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Widget', array(
|
||||
'contribution_page_id' => $id,
|
||||
), array(
|
||||
'contribution_page_id' => $copy->id,
|
||||
));
|
||||
|
||||
//copy price sets
|
||||
CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_contribution_page', $id, $copy->id);
|
||||
|
||||
$copyTellFriend = &CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend', array(
|
||||
'entity_id' => $id,
|
||||
'entity_table' => 'civicrm_contribution_page',
|
||||
), array(
|
||||
'entity_id' => $copy->id,
|
||||
));
|
||||
|
||||
$copyPersonalCampaignPages = &CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock', array(
|
||||
'entity_id' => $id,
|
||||
'entity_table' => 'civicrm_contribution_page',
|
||||
), array(
|
||||
'entity_id' => $copy->id,
|
||||
'target_entity_id' => $copy->id,
|
||||
));
|
||||
|
||||
$copyPremium = &CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Premium', array(
|
||||
'entity_id' => $id,
|
||||
'entity_table' => 'civicrm_contribution_page',
|
||||
), array(
|
||||
'entity_id' => $copy->id,
|
||||
));
|
||||
$premiumQuery = "
|
||||
SELECT id
|
||||
FROM civicrm_premiums
|
||||
WHERE entity_table = 'civicrm_contribution_page'
|
||||
AND entity_id ={$id}";
|
||||
|
||||
$premiumDao = CRM_Core_DAO::executeQuery($premiumQuery, CRM_Core_DAO::$_nullArray);
|
||||
while ($premiumDao->fetch()) {
|
||||
if ($premiumDao->id) {
|
||||
CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_PremiumsProduct', array(
|
||||
'premiums_id' => $premiumDao->id,
|
||||
), array(
|
||||
'premiums_id' => $copyPremium->id,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
$copy->save();
|
||||
|
||||
CRM_Utils_Hook::copy('ContributionPage', $copy);
|
||||
|
||||
return $copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get info for all sections enable/disable.
|
||||
*
|
||||
* @param array $contribPageIds
|
||||
* @return array
|
||||
* info regarding all sections.
|
||||
*/
|
||||
public static function getSectionInfo($contribPageIds = array()) {
|
||||
$info = array();
|
||||
$whereClause = NULL;
|
||||
if (is_array($contribPageIds) && !empty($contribPageIds)) {
|
||||
$whereClause = 'WHERE civicrm_contribution_page.id IN ( ' . implode(', ', $contribPageIds) . ' )';
|
||||
}
|
||||
|
||||
$sections = array(
|
||||
'settings',
|
||||
'amount',
|
||||
'membership',
|
||||
'custom',
|
||||
'thankyou',
|
||||
'friend',
|
||||
'pcp',
|
||||
'widget',
|
||||
'premium',
|
||||
);
|
||||
$query = "
|
||||
SELECT civicrm_contribution_page.id as id,
|
||||
civicrm_contribution_page.financial_type_id as settings,
|
||||
amount_block_is_active as amount,
|
||||
civicrm_membership_block.id as membership,
|
||||
civicrm_uf_join.id as custom,
|
||||
civicrm_contribution_page.thankyou_title as thankyou,
|
||||
civicrm_tell_friend.id as friend,
|
||||
civicrm_pcp_block.id as pcp,
|
||||
civicrm_contribution_widget.id as widget,
|
||||
civicrm_premiums.id as premium
|
||||
FROM civicrm_contribution_page
|
||||
LEFT JOIN civicrm_membership_block ON ( civicrm_membership_block.entity_id = civicrm_contribution_page.id
|
||||
AND civicrm_membership_block.entity_table = 'civicrm_contribution_page'
|
||||
AND civicrm_membership_block.is_active = 1 )
|
||||
LEFT JOIN civicrm_uf_join ON ( civicrm_uf_join.entity_id = civicrm_contribution_page.id
|
||||
AND civicrm_uf_join.entity_table = 'civicrm_contribution_page'
|
||||
AND module = 'CiviContribute'
|
||||
AND civicrm_uf_join.is_active = 1 )
|
||||
LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_contribution_page.id
|
||||
AND civicrm_tell_friend.entity_table = 'civicrm_contribution_page'
|
||||
AND civicrm_tell_friend.is_active = 1)
|
||||
LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_contribution_page.id
|
||||
AND civicrm_pcp_block.entity_table = 'civicrm_contribution_page'
|
||||
AND civicrm_pcp_block.is_active = 1 )
|
||||
LEFT JOIN civicrm_contribution_widget ON ( civicrm_contribution_widget.contribution_page_id = civicrm_contribution_page.id
|
||||
AND civicrm_contribution_widget.is_active = 1 )
|
||||
LEFT JOIN civicrm_premiums ON ( civicrm_premiums.entity_id = civicrm_contribution_page.id
|
||||
AND civicrm_premiums.entity_table = 'civicrm_contribution_page'
|
||||
AND civicrm_premiums.premiums_active = 1 )
|
||||
$whereClause";
|
||||
|
||||
$contributionPage = CRM_Core_DAO::executeQuery($query);
|
||||
while ($contributionPage->fetch()) {
|
||||
if (!isset($info[$contributionPage->id]) || !is_array($info[$contributionPage->id])) {
|
||||
$info[$contributionPage->id] = array_fill_keys(array_values($sections), FALSE);
|
||||
}
|
||||
foreach ($sections as $section) {
|
||||
if ($contributionPage->$section) {
|
||||
$info[$contributionPage->id][$section] = TRUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get options for a given field.
|
||||
* @see CRM_Core_DAO::buildOptions
|
||||
*
|
||||
* @param string $fieldName
|
||||
* @param string $context : @see CRM_Core_DAO::buildOptionsContext
|
||||
* @param array $props : whatever is known about this dao object
|
||||
*
|
||||
* @return array|bool
|
||||
*/
|
||||
public static function buildOptions($fieldName, $context = NULL, $props = array()) {
|
||||
$params = array();
|
||||
// Special logic for fields whose options depend on context or properties
|
||||
switch ($fieldName) {
|
||||
case 'financial_type_id':
|
||||
// Fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
|
||||
return CRM_Financial_BAO_FinancialType::getIncomeFinancialType();
|
||||
|
||||
break;
|
||||
}
|
||||
return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or Set honor/on_behalf params for processing module_data or setting default values.
|
||||
*
|
||||
* @param array $params :
|
||||
* @param bool $setDefault : If yes then returns array to used for setting default value afterward
|
||||
* @param string $module : processing module_data for which module? e.g. soft_credit, on_behalf
|
||||
*
|
||||
* @return array|string
|
||||
*/
|
||||
public static function formatModuleData($params, $setDefault = FALSE, $module) {
|
||||
$tsLocale = CRM_Core_I18n::getLocale();
|
||||
$config = CRM_Core_Config::singleton();
|
||||
$json = $jsonDecode = NULL;
|
||||
$domain = new CRM_Core_DAO_Domain();
|
||||
$domain->find(TRUE);
|
||||
|
||||
$moduleDataFormat = array(
|
||||
'soft_credit' => array(
|
||||
1 => 'soft_credit_types',
|
||||
'multilingual' => array(
|
||||
'honor_block_title',
|
||||
'honor_block_text',
|
||||
),
|
||||
),
|
||||
'on_behalf' => array(
|
||||
1 => 'is_for_organization',
|
||||
'multilingual' => array(
|
||||
'for_organization',
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
//When we are fetching the honor params respecting both multi and mono lingual state
|
||||
//and setting it to default param of Contribution Page's Main and Setting form
|
||||
if ($setDefault) {
|
||||
$jsonDecode = json_decode($params);
|
||||
$jsonDecode = (array) $jsonDecode->$module;
|
||||
if (!$domain->locales && !empty($jsonDecode['default'])) {
|
||||
//monolingual state
|
||||
$jsonDecode += (array) $jsonDecode['default'];
|
||||
unset($jsonDecode['default']);
|
||||
}
|
||||
elseif (!empty($jsonDecode[$tsLocale])) {
|
||||
//multilingual state
|
||||
foreach ($jsonDecode[$tsLocale] as $column => $value) {
|
||||
$jsonDecode[$column] = $value;
|
||||
}
|
||||
unset($jsonDecode[$tsLocale]);
|
||||
}
|
||||
return $jsonDecode;
|
||||
}
|
||||
|
||||
//check and handle multilingual honoree params
|
||||
if (!$domain->locales) {
|
||||
//if in singlelingual state simply return the array format
|
||||
$json = array($module => NULL);
|
||||
foreach ($moduleDataFormat[$module] as $key => $attribute) {
|
||||
if ($key === 'multilingual') {
|
||||
$json[$module]['default'] = array();
|
||||
foreach ($attribute as $attr) {
|
||||
$json[$module]['default'][$attr] = $params[$attr];
|
||||
}
|
||||
}
|
||||
else {
|
||||
$json[$module][$attribute] = $params[$attribute];
|
||||
}
|
||||
}
|
||||
$json = json_encode($json);
|
||||
}
|
||||
else {
|
||||
//if in multilingual state then retrieve the module_data against this contribution and
|
||||
//merge with earlier module_data json data to current so not to lose earlier multilingual module_data information
|
||||
$json = array($module => NULL);
|
||||
foreach ($moduleDataFormat[$module] as $key => $attribute) {
|
||||
if ($key === 'multilingual') {
|
||||
$json[$module][$config->lcMessages] = array();
|
||||
foreach ($attribute as $attr) {
|
||||
$json[$module][$config->lcMessages][$attr] = $params[$attr];
|
||||
}
|
||||
}
|
||||
else {
|
||||
$json[$module][$attribute] = $params[$attribute];
|
||||
}
|
||||
}
|
||||
|
||||
$ufJoinDAO = new CRM_Core_DAO_UFJoin();
|
||||
$ufJoinDAO->module = $module;
|
||||
$ufJoinDAO->entity_id = $params['id'];
|
||||
$ufJoinDAO->find(TRUE);
|
||||
$jsonData = json_decode($ufJoinDAO->module_data);
|
||||
if ($jsonData) {
|
||||
$json[$module] = array_merge((array) $jsonData->$module, $json[$module]);
|
||||
}
|
||||
$json = json_encode($json);
|
||||
}
|
||||
return $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate html for pdf in confirmation receipt email attachment.
|
||||
* @param int $contributionId
|
||||
* Contribution Page Id.
|
||||
* @param int $userID
|
||||
* Contact id for contributor.
|
||||
* @return array
|
||||
*/
|
||||
public static function addInvoicePdfToEmail($contributionId, $userID) {
|
||||
$contributionID = array($contributionId);
|
||||
$contactId = array($userID);
|
||||
$pdfParams = array(
|
||||
'output' => 'pdf_invoice',
|
||||
'forPage' => 'confirmpage',
|
||||
);
|
||||
$pdfHtml = CRM_Contribute_Form_Task_Invoice::printPDF($contributionID, $pdfParams, $contactId);
|
||||
return $pdfHtml;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to determine if the page supports separate membership payments.
|
||||
*
|
||||
* @param int $id form id
|
||||
*
|
||||
* @return bool
|
||||
* isSeparateMembershipPayment
|
||||
*/
|
||||
public static function getIsMembershipPayment($id) {
|
||||
$membershipBlocks = civicrm_api3('membership_block', 'get', array(
|
||||
'entity_table' => 'civicrm_contribution_page',
|
||||
'entity_id' => $id,
|
||||
'sequential' => TRUE,
|
||||
));
|
||||
if (!$membershipBlocks['count']) {
|
||||
return FALSE;
|
||||
}
|
||||
return $membershipBlocks['values'][0]['is_separate_payment'];
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,931 @@
|
|||
<?php
|
||||
/*
|
||||
+--------------------------------------------------------------------+
|
||||
| CiviCRM version 4.7 |
|
||||
+--------------------------------------------------------------------+
|
||||
| Copyright CiviCRM LLC (c) 2004-2017 |
|
||||
+--------------------------------------------------------------------+
|
||||
| This file is a part of CiviCRM. |
|
||||
| |
|
||||
| CiviCRM is free software; you can copy, modify, and distribute it |
|
||||
| under the terms of the GNU Affero General Public License |
|
||||
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
|
||||
| |
|
||||
| CiviCRM is distributed in the hope that it will be useful, but |
|
||||
| WITHOUT ANY WARRANTY; without even the implied warranty of |
|
||||
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
|
||||
| See the GNU Affero General Public License for more details. |
|
||||
| |
|
||||
| You should have received a copy of the GNU Affero General Public |
|
||||
| License and the CiviCRM Licensing Exception along |
|
||||
| with this program; if not, contact CiviCRM LLC |
|
||||
| at info[AT]civicrm[DOT]org. If you have questions about the |
|
||||
| GNU Affero General Public License or the licensing of CiviCRM, |
|
||||
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
|
||||
+--------------------------------------------------------------------+
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @package CRM
|
||||
* @copyright CiviCRM LLC (c) 2004-2017
|
||||
*/
|
||||
class CRM_Contribute_BAO_ContributionRecur extends CRM_Contribute_DAO_ContributionRecur {
|
||||
|
||||
/**
|
||||
* Create recurring contribution.
|
||||
*
|
||||
* @param array $params
|
||||
* (reference ) an assoc array of name/value pairs.
|
||||
*
|
||||
* @return object
|
||||
* activity contact object
|
||||
*/
|
||||
public static function create(&$params) {
|
||||
return self::add($params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes an associative array and creates a contribution object.
|
||||
*
|
||||
* the function extract all the params it needs to initialize the create a
|
||||
* contribution object. the params array could contain additional unused name/value
|
||||
* pairs
|
||||
*
|
||||
* @param array $params
|
||||
* (reference ) an assoc array of name/value pairs.
|
||||
*
|
||||
* @return CRM_Contribute_BAO_Contribution
|
||||
* @todo move hook calls / extended logic to create - requires changing calls to call create not add
|
||||
*/
|
||||
public static function add(&$params) {
|
||||
if (!empty($params['id'])) {
|
||||
CRM_Utils_Hook::pre('edit', 'ContributionRecur', $params['id'], $params);
|
||||
}
|
||||
else {
|
||||
CRM_Utils_Hook::pre('create', 'ContributionRecur', NULL, $params);
|
||||
}
|
||||
|
||||
// make sure we're not creating a new recurring contribution with the same transaction ID
|
||||
// or invoice ID as an existing recurring contribution
|
||||
$duplicates = array();
|
||||
if (self::checkDuplicate($params, $duplicates)) {
|
||||
$error = CRM_Core_Error::singleton();
|
||||
$d = implode(', ', $duplicates);
|
||||
$error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION,
|
||||
'Fatal',
|
||||
array($d),
|
||||
"Found matching recurring contribution(s): $d"
|
||||
);
|
||||
return $error;
|
||||
}
|
||||
|
||||
$recurring = new CRM_Contribute_BAO_ContributionRecur();
|
||||
$recurring->copyValues($params);
|
||||
$recurring->id = CRM_Utils_Array::value('id', $params);
|
||||
|
||||
// set currency for CRM-1496
|
||||
if (empty($params['id']) && !isset($recurring->currency)) {
|
||||
$config = CRM_Core_Config::singleton();
|
||||
$recurring->currency = $config->defaultCurrency;
|
||||
}
|
||||
$result = $recurring->save();
|
||||
|
||||
if (!empty($params['id'])) {
|
||||
CRM_Utils_Hook::post('edit', 'ContributionRecur', $recurring->id, $recurring);
|
||||
}
|
||||
else {
|
||||
CRM_Utils_Hook::post('create', 'ContributionRecur', $recurring->id, $recurring);
|
||||
}
|
||||
|
||||
if (!empty($params['custom']) &&
|
||||
is_array($params['custom'])
|
||||
) {
|
||||
CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution_recur', $recurring->id);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there is a recurring contribution with the same trxn_id or invoice_id.
|
||||
*
|
||||
* @param array $params
|
||||
* (reference ) an assoc array of name/value pairs.
|
||||
* @param array $duplicates
|
||||
* (reference ) store ids of duplicate contributions.
|
||||
*
|
||||
* @return bool
|
||||
* true if duplicate, false otherwise
|
||||
*/
|
||||
public static function checkDuplicate($params, &$duplicates) {
|
||||
$id = CRM_Utils_Array::value('id', $params);
|
||||
$trxn_id = CRM_Utils_Array::value('trxn_id', $params);
|
||||
$invoice_id = CRM_Utils_Array::value('invoice_id', $params);
|
||||
|
||||
$clause = array();
|
||||
$params = array();
|
||||
|
||||
if ($trxn_id) {
|
||||
$clause[] = "trxn_id = %1";
|
||||
$params[1] = array($trxn_id, 'String');
|
||||
}
|
||||
|
||||
if ($invoice_id) {
|
||||
$clause[] = "invoice_id = %2";
|
||||
$params[2] = array($invoice_id, 'String');
|
||||
}
|
||||
|
||||
if (empty($clause)) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
$clause = implode(' OR ', $clause);
|
||||
if ($id) {
|
||||
$clause = "( $clause ) AND id != %3";
|
||||
$params[3] = array($id, 'Integer');
|
||||
}
|
||||
|
||||
$query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
|
||||
$dao = CRM_Core_DAO::executeQuery($query, $params);
|
||||
$result = FALSE;
|
||||
while ($dao->fetch()) {
|
||||
$duplicates[] = $dao->id;
|
||||
$result = TRUE;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the payment processor (array) for a recurring processor.
|
||||
*
|
||||
* @param int $id
|
||||
* @param string $mode
|
||||
* - Test or NULL - all other variants are ignored.
|
||||
*
|
||||
* @return array|null
|
||||
*/
|
||||
public static function getPaymentProcessor($id, $mode = NULL) {
|
||||
$sql = "
|
||||
SELECT r.payment_processor_id
|
||||
FROM civicrm_contribution_recur r
|
||||
WHERE r.id = %1";
|
||||
$params = array(1 => array($id, 'Integer'));
|
||||
$paymentProcessorID = CRM_Core_DAO::singleValueQuery($sql,
|
||||
$params
|
||||
);
|
||||
if (!$paymentProcessorID) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of installment done/completed for each recurring contribution.
|
||||
*
|
||||
* @param array $ids
|
||||
* (reference ) an array of recurring contribution ids.
|
||||
*
|
||||
* @return array
|
||||
* an array of recurring ids count
|
||||
*/
|
||||
public static function getCount(&$ids) {
|
||||
$recurID = implode(',', $ids);
|
||||
$totalCount = array();
|
||||
|
||||
$query = "
|
||||
SELECT contribution_recur_id, count( contribution_recur_id ) as commpleted
|
||||
FROM civicrm_contribution
|
||||
WHERE contribution_recur_id IN ( {$recurID}) AND is_test = 0
|
||||
GROUP BY contribution_recur_id";
|
||||
|
||||
$res = CRM_Core_DAO::executeQuery($query);
|
||||
|
||||
while ($res->fetch()) {
|
||||
$totalCount[$res->contribution_recur_id] = $res->commpleted;
|
||||
}
|
||||
return $totalCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete Recurring contribution.
|
||||
*
|
||||
* @param int $recurId
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function deleteRecurContribution($recurId) {
|
||||
$result = FALSE;
|
||||
if (!$recurId) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$recur = new CRM_Contribute_DAO_ContributionRecur();
|
||||
$recur->id = $recurId;
|
||||
$result = $recur->delete();
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel Recurring contribution.
|
||||
*
|
||||
* @param int $recurId
|
||||
* Recur contribution id.
|
||||
* @param array $objects
|
||||
* An array of objects that is to be cancelled like.
|
||||
* contribution, membership, event. At least contribution object is a must.
|
||||
*
|
||||
* @param array $activityParams
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function cancelRecurContribution($recurId, $objects, $activityParams = array()) {
|
||||
if (!$recurId) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
|
||||
$canceledId = array_search('Cancelled', $contributionStatus);
|
||||
$recur = new CRM_Contribute_DAO_ContributionRecur();
|
||||
$recur->id = $recurId;
|
||||
$recur->whereAdd("contribution_status_id != $canceledId");
|
||||
|
||||
if ($recur->find(TRUE)) {
|
||||
$transaction = new CRM_Core_Transaction();
|
||||
$recur->contribution_status_id = $canceledId;
|
||||
$recur->start_date = CRM_Utils_Date::isoToMysql($recur->start_date);
|
||||
$recur->create_date = CRM_Utils_Date::isoToMysql($recur->create_date);
|
||||
$recur->modified_date = CRM_Utils_Date::isoToMysql($recur->modified_date);
|
||||
$recur->cancel_date = date('YmdHis');
|
||||
$recur->save();
|
||||
|
||||
$dao = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurId);
|
||||
if ($dao && $dao->recur_id) {
|
||||
$details = CRM_Utils_Array::value('details', $activityParams);
|
||||
if ($dao->auto_renew && $dao->membership_id) {
|
||||
// its auto-renewal membership mode
|
||||
$membershipTypes = CRM_Member_PseudoConstant::membershipType();
|
||||
$membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id, 'membership_type_id');
|
||||
$membershipType = CRM_Utils_Array::value($membershipType, $membershipTypes);
|
||||
$details .= '
|
||||
<br/>' . ts('Automatic renewal of %1 membership cancelled.', array(1 => $membershipType));
|
||||
}
|
||||
else {
|
||||
$details .= '
|
||||
<br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(
|
||||
1 => $dao->amount,
|
||||
2 => $dao->frequency_interval,
|
||||
3 => $dao->frequency_unit,
|
||||
));
|
||||
}
|
||||
$activityParams = array(
|
||||
'source_contact_id' => $dao->contact_id,
|
||||
'source_record_id' => CRM_Utils_Array::value('source_record_id', $activityParams),
|
||||
'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Cancel Recurring Contribution'),
|
||||
'subject' => CRM_Utils_Array::value('subject', $activityParams, ts('Recurring contribution cancelled')),
|
||||
'details' => $details,
|
||||
'activity_date_time' => date('YmdHis'),
|
||||
'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
|
||||
);
|
||||
$session = CRM_Core_Session::singleton();
|
||||
$cid = $session->get('userID');
|
||||
if ($cid) {
|
||||
$activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
|
||||
$activityParams['source_contact_id'] = $cid;
|
||||
}
|
||||
// @todo use the api & do less wrangling above
|
||||
CRM_Activity_BAO_Activity::create($activityParams);
|
||||
}
|
||||
|
||||
// if there are associated objects, cancel them as well
|
||||
if (!$objects) {
|
||||
$transaction->commit();
|
||||
return TRUE;
|
||||
}
|
||||
else {
|
||||
// @todo - this is bad! Get the function out of the ipn.
|
||||
$baseIPN = new CRM_Core_Payment_BaseIPN();
|
||||
return $baseIPN->cancelled($objects, $transaction);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// if already cancelled, return true
|
||||
$recur->whereAdd();
|
||||
$recur->whereAdd("contribution_status_id = $canceledId");
|
||||
if ($recur->find(TRUE)) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of recurring contribution of contact Ids.
|
||||
*
|
||||
* @param int $contactId
|
||||
* Contact ID.
|
||||
*
|
||||
* @return array
|
||||
* list of recurring contribution fields
|
||||
*
|
||||
*/
|
||||
public static function getRecurContributions($contactId) {
|
||||
$params = array();
|
||||
$recurDAO = new CRM_Contribute_DAO_ContributionRecur();
|
||||
$recurDAO->contact_id = $contactId;
|
||||
$recurDAO->find();
|
||||
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
|
||||
|
||||
while ($recurDAO->fetch()) {
|
||||
$params[$recurDAO->id]['id'] = $recurDAO->id;
|
||||
$params[$recurDAO->id]['contactId'] = $recurDAO->contact_id;
|
||||
$params[$recurDAO->id]['start_date'] = $recurDAO->start_date;
|
||||
$params[$recurDAO->id]['end_date'] = $recurDAO->end_date;
|
||||
$params[$recurDAO->id]['next_sched_contribution_date'] = $recurDAO->next_sched_contribution_date;
|
||||
$params[$recurDAO->id]['amount'] = $recurDAO->amount;
|
||||
$params[$recurDAO->id]['currency'] = $recurDAO->currency;
|
||||
$params[$recurDAO->id]['frequency_unit'] = $recurDAO->frequency_unit;
|
||||
$params[$recurDAO->id]['frequency_interval'] = $recurDAO->frequency_interval;
|
||||
$params[$recurDAO->id]['installments'] = $recurDAO->installments;
|
||||
$params[$recurDAO->id]['contribution_status_id'] = $recurDAO->contribution_status_id;
|
||||
$params[$recurDAO->id]['contribution_status'] = CRM_Utils_Array::value($recurDAO->contribution_status_id, $contributionStatus);
|
||||
$params[$recurDAO->id]['is_test'] = $recurDAO->is_test;
|
||||
$params[$recurDAO->id]['payment_processor_id'] = $recurDAO->payment_processor_id;
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $entityID
|
||||
* @param string $entity
|
||||
*
|
||||
* @return null|Object
|
||||
*/
|
||||
public static function getSubscriptionDetails($entityID, $entity = 'recur') {
|
||||
$sql = "
|
||||
SELECT rec.id as recur_id,
|
||||
rec.processor_id as subscription_id,
|
||||
rec.frequency_interval,
|
||||
rec.installments,
|
||||
rec.frequency_unit,
|
||||
rec.amount,
|
||||
rec.is_test,
|
||||
rec.auto_renew,
|
||||
rec.currency,
|
||||
rec.campaign_id,
|
||||
rec.financial_type_id,
|
||||
rec.next_sched_contribution_date,
|
||||
rec.failure_retry_date,
|
||||
rec.cycle_day,
|
||||
con.id as contribution_id,
|
||||
con.contribution_page_id,
|
||||
rec.contact_id,
|
||||
mp.membership_id";
|
||||
|
||||
if ($entity == 'recur') {
|
||||
$sql .= "
|
||||
FROM civicrm_contribution_recur rec
|
||||
LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
|
||||
LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
|
||||
WHERE rec.id = %1";
|
||||
}
|
||||
elseif ($entity == 'contribution') {
|
||||
$sql .= "
|
||||
FROM civicrm_contribution con
|
||||
INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
|
||||
LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
|
||||
WHERE con.id = %1";
|
||||
}
|
||||
elseif ($entity == 'membership') {
|
||||
$sql .= "
|
||||
FROM civicrm_membership_payment mp
|
||||
INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
|
||||
INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
|
||||
INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
|
||||
WHERE mp.membership_id = %1";
|
||||
}
|
||||
|
||||
$dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($entityID, 'Integer')));
|
||||
if ($dao->fetch()) {
|
||||
return $dao;
|
||||
}
|
||||
else {
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the recurring contribution support financial type change.
|
||||
*
|
||||
* This is conditional on there being only one line item or if there are no contributions as yet.
|
||||
*
|
||||
* (This second is a bit of an unusual condition but might occur in the context of a
|
||||
*
|
||||
* @param int $id
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function supportsFinancialTypeChange($id) {
|
||||
// At this stage only sites with no Financial ACLs will have the opportunity to edit the financial type.
|
||||
// this is to limit the scope of the change and because financial ACLs are still fairly new & settling down.
|
||||
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
|
||||
return FALSE;
|
||||
}
|
||||
$contribution = self::getTemplateContribution($id);
|
||||
return CRM_Contribute_BAO_Contribution::isSingleLineItem($contribution['id']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the contribution to be used as the template for later contributions.
|
||||
*
|
||||
* Later we might merge in data stored against the contribution recur record rather than just return the contribution.
|
||||
*
|
||||
* @param int $id
|
||||
* @param array $overrides
|
||||
* Parameters that should be overriden. Add unit tests if using parameters other than total_amount & financial_type_id.
|
||||
*
|
||||
* @return array
|
||||
* @throws \CiviCRM_API3_Exception
|
||||
*/
|
||||
public static function getTemplateContribution($id, $overrides = array()) {
|
||||
$templateContribution = civicrm_api3('Contribution', 'get', array(
|
||||
'contribution_recur_id' => $id,
|
||||
'options' => array('limit' => 1, 'sort' => array('id DESC')),
|
||||
'sequential' => 1,
|
||||
'contribution_test' => '',
|
||||
));
|
||||
if ($templateContribution['count']) {
|
||||
$result = array_merge($templateContribution['values'][0], $overrides);
|
||||
$result['line_item'] = CRM_Contribute_BAO_ContributionRecur::calculateRecurLineItems($id, $result['total_amount'], $result['financial_type_id']);
|
||||
return $result;
|
||||
}
|
||||
return array();
|
||||
}
|
||||
|
||||
public static function setSubscriptionContext() {
|
||||
// handle context redirection for subscription url
|
||||
$session = CRM_Core_Session::singleton();
|
||||
if ($session->get('userID')) {
|
||||
$url = FALSE;
|
||||
$cid = CRM_Utils_Request::retrieve('cid', 'Integer');
|
||||
$mid = CRM_Utils_Request::retrieve('mid', 'Integer');
|
||||
$qfkey = CRM_Utils_Request::retrieve('key', 'String');
|
||||
$context = CRM_Utils_Request::retrieve('context', 'String');
|
||||
if ($cid) {
|
||||
switch ($context) {
|
||||
case 'contribution':
|
||||
$url = CRM_Utils_System::url('civicrm/contact/view',
|
||||
"reset=1&selectedChild=contribute&cid={$cid}"
|
||||
);
|
||||
break;
|
||||
|
||||
case 'membership':
|
||||
$url = CRM_Utils_System::url('civicrm/contact/view',
|
||||
"reset=1&selectedChild=member&cid={$cid}"
|
||||
);
|
||||
break;
|
||||
|
||||
case 'dashboard':
|
||||
$url = CRM_Utils_System::url('civicrm/user', "reset=1&id={$cid}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($mid) {
|
||||
switch ($context) {
|
||||
case 'dashboard':
|
||||
$url = CRM_Utils_System::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
|
||||
break;
|
||||
|
||||
case 'search':
|
||||
$url = CRM_Utils_System::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($url) {
|
||||
$session->pushUserContext($url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
|
||||
*
|
||||
* @param array $fields
|
||||
* The input form values.
|
||||
* @param array $files
|
||||
* The uploaded files if any.
|
||||
* @param CRM_Core_Form $self
|
||||
* @param array $errors
|
||||
*/
|
||||
public static function validateRecurContribution($fields, $files, $self, &$errors) {
|
||||
if (!empty($fields['is_recur'])) {
|
||||
if ($fields['frequency_interval'] <= 0) {
|
||||
$errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
|
||||
}
|
||||
if ($fields['frequency_unit'] == '0') {
|
||||
$errors['frequency_unit'] = ts('Please select a period (e.g. months, years ...) for how often you want to make this recurring contribution (EXAMPLE: Every 3 MONTHS).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send start or end notification for recurring payments.
|
||||
*
|
||||
* @param array $ids
|
||||
* @param CRM_Contribute_BAO_ContributionRecur $recur
|
||||
* @param bool $isFirstOrLastRecurringPayment
|
||||
*/
|
||||
public static function sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment) {
|
||||
if ($isFirstOrLastRecurringPayment) {
|
||||
$autoRenewMembership = FALSE;
|
||||
if ($recur->id &&
|
||||
isset($ids['membership']) && $ids['membership']
|
||||
) {
|
||||
$autoRenewMembership = TRUE;
|
||||
}
|
||||
|
||||
//send recurring Notification email for user
|
||||
CRM_Contribute_BAO_ContributionPage::recurringNotify($isFirstOrLastRecurringPayment,
|
||||
$ids['contact'],
|
||||
$ids['contributionPage'],
|
||||
$recur,
|
||||
$autoRenewMembership
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy custom data of the initial contribution into its recurring contributions.
|
||||
*
|
||||
* @param int $recurId
|
||||
* @param int $targetContributionId
|
||||
*/
|
||||
static public function copyCustomValues($recurId, $targetContributionId) {
|
||||
if ($recurId && $targetContributionId) {
|
||||
// get the initial contribution id of recur id
|
||||
$sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
|
||||
|
||||
// if the same contribution is being processed then return
|
||||
if ($sourceContributionId == $targetContributionId) {
|
||||
return;
|
||||
}
|
||||
// check if proper recurring contribution record is being processed
|
||||
$targetConRecurId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
|
||||
if ($targetConRecurId != $recurId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// copy custom data
|
||||
$extends = array('Contribution');
|
||||
$groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
|
||||
if ($groupTree) {
|
||||
foreach ($groupTree as $groupID => $group) {
|
||||
$table[$groupTree[$groupID]['table_name']] = array('entity_id');
|
||||
foreach ($group['fields'] as $fieldID => $field) {
|
||||
$table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($table as $tableName => $tableColumns) {
|
||||
$insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
|
||||
$tableColumns[0] = $targetContributionId;
|
||||
$select = 'SELECT ' . implode(', ', $tableColumns);
|
||||
$from = ' FROM ' . $tableName;
|
||||
$where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
|
||||
$query = $insert . $select . $from . $where;
|
||||
CRM_Core_DAO::executeQuery($query);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add soft credit to for recurring payment.
|
||||
*
|
||||
* copy soft credit record of first recurring contribution.
|
||||
* and add new soft credit against $targetContributionId
|
||||
*
|
||||
* @param int $recurId
|
||||
* @param int $targetContributionId
|
||||
*/
|
||||
public static function addrecurSoftCredit($recurId, $targetContributionId) {
|
||||
$soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
|
||||
$soft_contribution->contribution_id = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
|
||||
|
||||
// Check if first recurring contribution has any associated soft credit.
|
||||
if ($soft_contribution->find(TRUE)) {
|
||||
$soft_contribution->contribution_id = $targetContributionId;
|
||||
unset($soft_contribution->id);
|
||||
$soft_contribution->save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add line items for recurring contribution.
|
||||
*
|
||||
* @param int $recurId
|
||||
* @param $contribution
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function addRecurLineItems($recurId, $contribution) {
|
||||
$foundLineItems = FALSE;
|
||||
|
||||
$lineSets = self::calculateRecurLineItems($recurId, $contribution->total_amount, $contribution->financial_type_id);
|
||||
foreach ($lineSets as $lineItems) {
|
||||
if (!empty($lineItems)) {
|
||||
foreach ($lineItems as $key => $value) {
|
||||
if ($value['entity_table'] == 'civicrm_membership') {
|
||||
try {
|
||||
// @todo this should be done by virtue of editing the line item as this link
|
||||
// is deprecated. This may be the case but needs testing.
|
||||
civicrm_api3('membership_payment', 'create', array(
|
||||
'membership_id' => $value['entity_id'],
|
||||
'contribution_id' => $contribution->id,
|
||||
'is_transactional' => FALSE,
|
||||
));
|
||||
}
|
||||
catch (CiviCRM_API3_Exception $e) {
|
||||
// we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
|
||||
// this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
|
||||
}
|
||||
}
|
||||
}
|
||||
$foundLineItems = TRUE;
|
||||
}
|
||||
}
|
||||
if (!$foundLineItems) {
|
||||
CRM_Price_BAO_LineItem::processPriceSet($contribution->id, $lineSets, $contribution);
|
||||
}
|
||||
return $lineSets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update pledge associated with a recurring contribution.
|
||||
*
|
||||
* If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
|
||||
*
|
||||
* If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
|
||||
* should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
|
||||
* it should be assumed they
|
||||
* do so with the intention that all payments will be linked
|
||||
*
|
||||
* The pledge payment record should already exist & will need to be updated with the new contribution ID.
|
||||
* If not the contribution will also need to be linked to the pledge
|
||||
*
|
||||
* @param int $contributionID
|
||||
* @param int $contributionRecurID
|
||||
* @param int $contributionStatusID
|
||||
* @param float $contributionAmount
|
||||
*
|
||||
* @throws \CiviCRM_API3_Exception
|
||||
*/
|
||||
public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
|
||||
$returnProperties = array('id', 'pledge_id');
|
||||
$paymentDetails = $paymentIDs = array();
|
||||
|
||||
if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
|
||||
$paymentDetails, $returnProperties
|
||||
)
|
||||
) {
|
||||
foreach ($paymentDetails as $key => $value) {
|
||||
$paymentIDs[] = $value['id'];
|
||||
$pledgeId = $value['pledge_id'];
|
||||
}
|
||||
}
|
||||
else {
|
||||
//payment is not already linked - if it is linked with a pledge we need to create a link.
|
||||
// return if it is not recurring contribution
|
||||
if (!$contributionRecurID) {
|
||||
return;
|
||||
}
|
||||
|
||||
$relatedContributions = new CRM_Contribute_DAO_Contribution();
|
||||
$relatedContributions->contribution_recur_id = $contributionRecurID;
|
||||
$relatedContributions->find();
|
||||
|
||||
while ($relatedContributions->fetch()) {
|
||||
CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
|
||||
$paymentDetails, $returnProperties
|
||||
);
|
||||
}
|
||||
|
||||
if (empty($paymentDetails)) {
|
||||
// payment is not linked with a pledge and neither are any other contributions on this
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($paymentDetails as $key => $value) {
|
||||
$pledgeId = $value['pledge_id'];
|
||||
}
|
||||
|
||||
// we have a pledge now we need to get the oldest unpaid payment
|
||||
$paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
|
||||
if (empty($paymentDetails['id'])) {
|
||||
// we can assume this pledge is now completed
|
||||
// return now so we don't create a core error & roll back
|
||||
return;
|
||||
}
|
||||
$paymentDetails['contribution_id'] = $contributionID;
|
||||
$paymentDetails['status_id'] = $contributionStatusID;
|
||||
$paymentDetails['actual_amount'] = $contributionAmount;
|
||||
|
||||
// put contribution against it
|
||||
$payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
|
||||
$paymentIDs[] = $payment['id'];
|
||||
}
|
||||
|
||||
// update pledge and corresponding payment statuses
|
||||
CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
|
||||
NULL, $contributionAmount
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $form
|
||||
*/
|
||||
public static function recurringContribution(&$form) {
|
||||
// Recurring contribution fields
|
||||
foreach (self::getRecurringFields() as $key => $label) {
|
||||
if ($key == 'contribution_recur_payment_made' && !empty($form->_formValues) &&
|
||||
!CRM_Utils_System::isNull(CRM_Utils_Array::value($key, $form->_formValues))
|
||||
) {
|
||||
$form->assign('contribution_recur_pane_open', TRUE);
|
||||
break;
|
||||
}
|
||||
CRM_Core_Form_Date::buildDateRange($form, $key, 1, '_low', '_high');
|
||||
// If data has been entered for a recurring field, tell the tpl layer to open the pane
|
||||
if (!empty($form->_formValues) && !empty($form->_formValues[$key . '_relative']) || !empty($form->_formValues[$key . '_low']) || !empty($form->_formValues[$key . '_high'])) {
|
||||
$form->assign('contribution_recur_pane_open', TRUE);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Add field to check if payment is made for recurring contribution
|
||||
$recurringPaymentOptions = array(
|
||||
1 => ts('All recurring contributions'),
|
||||
2 => ts('Recurring contributions with at least one payment'),
|
||||
);
|
||||
$form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, array('allowClear' => TRUE));
|
||||
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_start_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
|
||||
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_end_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
|
||||
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_modified_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
|
||||
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_next_sched_contribution_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
|
||||
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_failure_retry_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
|
||||
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_cancel_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
|
||||
|
||||
// Add field for contribution status
|
||||
$form->addSelect('contribution_recur_contribution_status_id',
|
||||
array('entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => CRM_Contribute_PseudoConstant::contributionStatus())
|
||||
);
|
||||
|
||||
$form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
|
||||
$form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
|
||||
|
||||
CRM_Core_BAO_Query::addCustomFormFields($form, array('ContributionRecur'));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Get fields for recurring contributions.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function getRecurringFields() {
|
||||
return array(
|
||||
'contribution_recur_payment_made' => ts(''),
|
||||
'contribution_recur_start_date' => ts('Recurring Contribution Start Date'),
|
||||
'contribution_recur_next_sched_contribution_date' => ts('Next Scheduled Recurring Contribution'),
|
||||
'contribution_recur_cancel_date' => ts('Recurring Contribution Cancel Date'),
|
||||
'contribution_recur_end_date' => ts('Recurring Contribution End Date'),
|
||||
'contribution_recur_create_date' => ('Recurring Contribution Create Date'),
|
||||
'contribution_recur_modified_date' => ('Recurring Contribution Modified Date'),
|
||||
'contribution_recur_failure_retry_date' => ts('Failed Recurring Contribution Retry Date'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update recurring contribution based on incoming payment.
|
||||
*
|
||||
* Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
|
||||
*
|
||||
* @param int $recurringContributionID
|
||||
* @param string $paymentStatus
|
||||
* Payment status - this correlates to the machine name of the contribution status ID ie
|
||||
* - Completed
|
||||
* - Failed
|
||||
*
|
||||
* @throws \CiviCRM_API3_Exception
|
||||
*/
|
||||
public static function updateOnNewPayment($recurringContributionID, $paymentStatus, $effectiveDate) {
|
||||
|
||||
$effectiveDate = $effectiveDate ? date('Y-m-d', strtotime($effectiveDate)) : date('Y-m-d');
|
||||
if (!in_array($paymentStatus, array('Completed', 'Failed'))) {
|
||||
return;
|
||||
}
|
||||
$params = array(
|
||||
'id' => $recurringContributionID,
|
||||
'return' => array(
|
||||
'contribution_status_id',
|
||||
'next_sched_contribution_date',
|
||||
'frequency_unit',
|
||||
'frequency_interval',
|
||||
'installments',
|
||||
'failure_count',
|
||||
),
|
||||
);
|
||||
|
||||
$existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
|
||||
|
||||
if ($paymentStatus == 'Completed'
|
||||
&& CRM_Contribute_PseudoConstant::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
|
||||
$params['contribution_status_id'] = 'In Progress';
|
||||
}
|
||||
if ($paymentStatus == 'Failed') {
|
||||
$params['failure_count'] = $existing['failure_count'];
|
||||
}
|
||||
$params['modified_date'] = date('Y-m-d H:i:s');
|
||||
|
||||
if (!empty($existing['installments']) && self::isComplete($recurringContributionID, $existing['installments'])) {
|
||||
$params['contribution_status_id'] = 'Completed';
|
||||
}
|
||||
else {
|
||||
// Only update next sched date if it's empty or 'just now' because payment processors may be managing
|
||||
// the scheduled date themselves as core did not previously provide any help.
|
||||
if (empty($existing['next_sched_contribution_date']) || strtotime($existing['next_sched_contribution_date']) ==
|
||||
strtotime($effectiveDate)) {
|
||||
$params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit'], strtotime($effectiveDate)));
|
||||
}
|
||||
}
|
||||
civicrm_api3('ContributionRecur', 'create', $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this recurring contribution now complete.
|
||||
*
|
||||
* Have all the payments expected been received now.
|
||||
*
|
||||
* @param int $recurringContributionID
|
||||
* @param int $installments
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected static function isComplete($recurringContributionID, $installments) {
|
||||
$paidInstallments = CRM_Core_DAO::singleValueQuery(
|
||||
'SELECT count(*) FROM civicrm_contribution
|
||||
WHERE contribution_recur_id = %1
|
||||
AND contribution_status_id = ' . CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
|
||||
array(1 => array($recurringContributionID, 'Integer'))
|
||||
);
|
||||
if ($paidInstallments >= $installments) {
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate line items for the relevant recurring calculation.
|
||||
*
|
||||
* @param int $recurId
|
||||
* @param string $total_amount
|
||||
* @param int $financial_type_id
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
|
||||
$originalContributionID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
|
||||
$lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContributionID);
|
||||
$lineSets = array();
|
||||
if (count($lineItems) == 1) {
|
||||
foreach ($lineItems as $index => $lineItem) {
|
||||
if ($financial_type_id) {
|
||||
// CRM-17718 allow for possibility of changed financial type ID having been set prior to calling this.
|
||||
$lineItem['financial_type_id'] = $financial_type_id;
|
||||
}
|
||||
if ($lineItem['line_total'] != $total_amount) {
|
||||
// We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
|
||||
// if there is only one line item, and the UI should prevent this situation for those with more than one.
|
||||
$lineItem['line_total'] = $total_amount;
|
||||
$lineItem['unit_price'] = round($total_amount / $lineItem['qty'], 2);
|
||||
}
|
||||
$priceField = new CRM_Price_DAO_PriceField();
|
||||
$priceField->id = $lineItem['price_field_id'];
|
||||
$priceField->find(TRUE);
|
||||
$lineSets[$priceField->price_set_id][] = $lineItem;
|
||||
}
|
||||
}
|
||||
// CRM-19309 if more than one then just pass them through:
|
||||
elseif (count($lineItems) > 1) {
|
||||
foreach ($lineItems as $index => $lineItem) {
|
||||
$lineSets[$index][] = $lineItem;
|
||||
}
|
||||
}
|
||||
|
||||
return $lineSets;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,602 @@
|
|||
<?php
|
||||
/*
|
||||
+--------------------------------------------------------------------+
|
||||
| CiviCRM version 4.7 |
|
||||
+--------------------------------------------------------------------+
|
||||
| Copyright CiviCRM LLC (c) 2004-2017 |
|
||||
+--------------------------------------------------------------------+
|
||||
| This file is a part of CiviCRM. |
|
||||
| |
|
||||
| CiviCRM is free software; you can copy, modify, and distribute it |
|
||||
| under the terms of the GNU Affero General Public License |
|
||||
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
|
||||
| |
|
||||
| CiviCRM is distributed in the hope that it will be useful, but |
|
||||
| WITHOUT ANY WARRANTY; without even the implied warranty of |
|
||||
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
|
||||
| See the GNU Affero General Public License for more details. |
|
||||
| |
|
||||
| You should have received a copy of the GNU Affero General Public |
|
||||
| License and the CiviCRM Licensing Exception along |
|
||||
| with this program; if not, contact CiviCRM LLC |
|
||||
| at info[AT]civicrm[DOT]org. If you have questions about the |
|
||||
| GNU Affero General Public License or the licensing of CiviCRM, |
|
||||
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
|
||||
+--------------------------------------------------------------------+
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @package CRM
|
||||
* @copyright CiviCRM LLC (c) 2004-2017
|
||||
*/
|
||||
class CRM_Contribute_BAO_ContributionSoft extends CRM_Contribute_DAO_ContributionSoft {
|
||||
|
||||
/**
|
||||
* Construct method.
|
||||
*/
|
||||
public function __construct() {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add contribution soft credit record.
|
||||
*
|
||||
* @param array $params
|
||||
* (reference ) an assoc array of name/value pairs.
|
||||
*
|
||||
* @return object
|
||||
* soft contribution of object that is added
|
||||
*/
|
||||
public static function add(&$params) {
|
||||
$contributionSoft = new CRM_Contribute_DAO_ContributionSoft();
|
||||
$contributionSoft->copyValues($params);
|
||||
|
||||
// set currency for CRM-1496
|
||||
if (!isset($contributionSoft->currency)) {
|
||||
$config = CRM_Core_Config::singleton();
|
||||
$contributionSoft->currency = $config->defaultCurrency;
|
||||
}
|
||||
return $contributionSoft->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the soft contribution and/or link to personal campaign page.
|
||||
*
|
||||
* @param array $params
|
||||
* @param object $contribution CRM_Contribute_DAO_Contribution
|
||||
*
|
||||
*/
|
||||
public static function processSoftContribution($params, $contribution) {
|
||||
//retrieve existing soft-credit and pcp id(s) if any against $contribution
|
||||
$softIDs = self::getSoftCreditIds($contribution->id);
|
||||
$pcpId = self::getSoftCreditIds($contribution->id, TRUE);
|
||||
|
||||
if ($pcp = CRM_Utils_Array::value('pcp', $params)) {
|
||||
$softParams = array();
|
||||
$softParams['id'] = $pcpId ? $pcpId : NULL;
|
||||
$softParams['contribution_id'] = $contribution->id;
|
||||
$softParams['pcp_id'] = $pcp['pcp_made_through_id'];
|
||||
$softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
|
||||
$pcp['pcp_made_through_id'], 'contact_id'
|
||||
);
|
||||
$softParams['currency'] = $contribution->currency;
|
||||
$softParams['amount'] = $contribution->total_amount;
|
||||
$softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
|
||||
$softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
|
||||
$softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
|
||||
$softParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
|
||||
$contributionSoft = self::add($softParams);
|
||||
//Send notification to owner for PCP
|
||||
if ($contributionSoft->pcp_id && empty($pcpId)) {
|
||||
CRM_Contribute_Form_Contribution_Confirm::pcpNotifyOwner($contribution, $contributionSoft);
|
||||
}
|
||||
}
|
||||
//Delete PCP against this contribution and create new on submitted PCP information
|
||||
elseif (array_key_exists('pcp', $params) && $pcpId) {
|
||||
civicrm_api3('ContributionSoft', 'delete', array('id' => $pcpId));
|
||||
}
|
||||
if (isset($params['soft_credit'])) {
|
||||
$softParams = $params['soft_credit'];
|
||||
foreach ($softParams as $softParam) {
|
||||
if (!empty($softIDs)) {
|
||||
$key = key($softIDs);
|
||||
$softParam['id'] = $softIDs[$key];
|
||||
unset($softIDs[$key]);
|
||||
}
|
||||
$softParam['contribution_id'] = $contribution->id;
|
||||
$softParam['currency'] = $contribution->currency;
|
||||
//case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
|
||||
if (empty($softParam['amount'])) {
|
||||
$softParam['amount'] = $contribution->total_amount;
|
||||
}
|
||||
CRM_Contribute_BAO_ContributionSoft::add($softParam);
|
||||
}
|
||||
|
||||
// delete any extra soft-credit while updating back-office contribution
|
||||
foreach ((array) $softIDs as $softID) {
|
||||
if (!in_array($softID, $params['soft_credit_ids'])) {
|
||||
civicrm_api3('ContributionSoft', 'delete', array('id' => $softID));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function used to save pcp / soft credit entry.
|
||||
*
|
||||
* This is used by contribution and also event pcps
|
||||
*
|
||||
* @param array $params
|
||||
* @param object $form
|
||||
* Form object.
|
||||
*/
|
||||
public static function formatSoftCreditParams(&$params, &$form) {
|
||||
$pcp = $softParams = $softIDs = array();
|
||||
if (!empty($params['pcp_made_through_id'])) {
|
||||
$fields = array(
|
||||
'pcp_made_through_id',
|
||||
'pcp_display_in_roll',
|
||||
'pcp_roll_nickname',
|
||||
'pcp_personal_note',
|
||||
);
|
||||
foreach ($fields as $f) {
|
||||
$pcp[$f] = CRM_Utils_Array::value($f, $params);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($form->_values['honoree_profile_id']) && !empty($params['soft_credit_type_id'])) {
|
||||
$honorId = NULL;
|
||||
|
||||
// @todo fix use of deprecated function.
|
||||
$contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
|
||||
//check if there is any duplicate contact
|
||||
// honoree should never be the donor
|
||||
$exceptKeys = array(
|
||||
'contactID' => 0,
|
||||
'onbehalf_contact_id' => 0,
|
||||
);
|
||||
$except = array_values(array_intersect_key($params, $exceptKeys));
|
||||
$ids = CRM_Contact_BAO_Contact::getDuplicateContacts(
|
||||
$params['honor'],
|
||||
CRM_Core_BAO_UFGroup::getContactType($form->_values['honoree_profile_id']),
|
||||
'Unsupervised',
|
||||
$except,
|
||||
FALSE
|
||||
);
|
||||
if (count($ids)) {
|
||||
$honorId = CRM_Utils_Array::value(0, $ids);
|
||||
}
|
||||
|
||||
$honorId = CRM_Contact_BAO_Contact::createProfileContact(
|
||||
$params['honor'], CRM_Core_DAO::$_nullArray,
|
||||
$honorId, NULL,
|
||||
$form->_values['honoree_profile_id']
|
||||
);
|
||||
$softParams[] = array(
|
||||
'contact_id' => $honorId,
|
||||
'soft_credit_type_id' => $params['soft_credit_type_id'],
|
||||
);
|
||||
|
||||
if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) {
|
||||
$form->_values['honor'] = array(
|
||||
'soft_credit_type' => CRM_Utils_Array::value(
|
||||
$params['soft_credit_type_id'],
|
||||
CRM_Core_OptionGroup::values("soft_credit_type")
|
||||
),
|
||||
'honor_id' => $honorId,
|
||||
'honor_profile_id' => $form->_values['honoree_profile_id'],
|
||||
'honor_profile_values' => $params['honor'],
|
||||
);
|
||||
}
|
||||
}
|
||||
elseif (!empty($params['soft_credit_contact_id'])) {
|
||||
//build soft credit params
|
||||
foreach ($params['soft_credit_contact_id'] as $key => $val) {
|
||||
if ($val && $params['soft_credit_amount'][$key]) {
|
||||
$softParams[$key]['contact_id'] = $val;
|
||||
$softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
|
||||
$softParams[$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
|
||||
if (!empty($params['soft_credit_id'][$key])) {
|
||||
$softIDs[] = $softParams[$key]['id'] = $params['soft_credit_id'][$key];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$params['pcp'] = !empty($pcp) ? $pcp : NULL;
|
||||
$params['soft_credit'] = $softParams;
|
||||
$params['soft_credit_ids'] = $softIDs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch object based on array of properties.
|
||||
*
|
||||
* @param array $params
|
||||
* (reference ) an assoc array of name/value pairs.
|
||||
* @param array $defaults
|
||||
* (reference ) an assoc array to hold the flattened values.
|
||||
*
|
||||
* @return CRM_Contribute_BAO_ContributionSoft
|
||||
*/
|
||||
public static function retrieve(&$params, &$defaults) {
|
||||
$contributionSoft = new CRM_Contribute_DAO_ContributionSoft();
|
||||
$contributionSoft->copyValues($params);
|
||||
if ($contributionSoft->find(TRUE)) {
|
||||
CRM_Core_DAO::storeValues($contributionSoft, $defaults);
|
||||
return $contributionSoft;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $contact_id
|
||||
* @param int $isTest
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function getSoftContributionTotals($contact_id, $isTest = 0) {
|
||||
|
||||
$whereClause = "AND cc.cancel_date IS NULL";
|
||||
|
||||
$query = "
|
||||
SELECT SUM(amount) as amount, AVG(total_amount) as average, cc.currency
|
||||
FROM civicrm_contribution_soft ccs
|
||||
LEFT JOIN civicrm_contribution cc ON ccs.contribution_id = cc.id
|
||||
WHERE cc.is_test = %2 AND ccs.contact_id = %1 {$whereClause}
|
||||
GROUP BY currency";
|
||||
|
||||
$params = array(
|
||||
1 => array($contact_id, 'Integer'),
|
||||
2 => array($isTest, 'Integer'),
|
||||
);
|
||||
|
||||
$cs = CRM_Core_DAO::executeQuery($query, $params);
|
||||
|
||||
$count = 0;
|
||||
$amount = $average = $cancelAmount = array();
|
||||
|
||||
while ($cs->fetch()) {
|
||||
if ($cs->amount > 0) {
|
||||
$count++;
|
||||
$amount[] = $cs->amount;
|
||||
$average[] = $cs->average;
|
||||
$currency[] = $cs->currency;
|
||||
}
|
||||
}
|
||||
|
||||
//to get cancel amount
|
||||
$cancelAmountWhereClause = "AND cc.cancel_date IS NOT NULL";
|
||||
$query = str_replace($whereClause, $cancelAmountWhereClause, $query);
|
||||
$cancelAmountSQL = CRM_Core_DAO::executeQuery($query, $params);
|
||||
while ($cancelAmountSQL->fetch()) {
|
||||
if ($cancelAmountSQL->amount > 0) {
|
||||
$count++;
|
||||
$cancelAmount[] = $cancelAmountSQL->amount;
|
||||
}
|
||||
}
|
||||
|
||||
if ($count > 0) {
|
||||
return array(
|
||||
implode(', ', $amount),
|
||||
implode(', ', $average),
|
||||
implode(', ', $currency),
|
||||
implode(', ', $cancelAmount),
|
||||
);
|
||||
}
|
||||
return array(0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve soft contributions for contribution record.
|
||||
*
|
||||
* @param int $contributionID
|
||||
* @param bool $all
|
||||
* Include PCP data.
|
||||
*
|
||||
* @return array
|
||||
* Array of soft contribution ids, amounts, and associated contact ids
|
||||
*/
|
||||
public static function getSoftContribution($contributionID, $all = FALSE) {
|
||||
$pcpFields = array(
|
||||
'pcp_id',
|
||||
'pcp_title',
|
||||
'pcp_display_in_roll',
|
||||
'pcp_roll_nickname',
|
||||
'pcp_personal_note',
|
||||
);
|
||||
|
||||
$query = '
|
||||
SELECT ccs.id, pcp_id, cpcp.title as pcp_title, pcp_display_in_roll, pcp_roll_nickname, pcp_personal_note, ccs.currency as currency, amount, ccs.contact_id as contact_id, c.display_name, ccs.soft_credit_type_id
|
||||
FROM civicrm_contribution_soft ccs INNER JOIN civicrm_contact c on c.id = ccs.contact_id
|
||||
LEFT JOIN civicrm_pcp cpcp ON ccs.pcp_id = cpcp.id
|
||||
WHERE contribution_id = %1;
|
||||
';
|
||||
|
||||
$params = array(1 => array($contributionID, 'Integer'));
|
||||
|
||||
$dao = CRM_Core_DAO::executeQuery($query, $params);
|
||||
|
||||
$softContribution = array();
|
||||
$count = 1;
|
||||
while ($dao->fetch()) {
|
||||
if ($dao->pcp_id) {
|
||||
if ($all) {
|
||||
foreach ($pcpFields as $val) {
|
||||
$softContribution[$val] = $dao->$val;
|
||||
}
|
||||
$softContribution['pcp_soft_credit_to_name'] = $dao->display_name;
|
||||
$softContribution['pcp_soft_credit_to_id'] = $dao->contact_id;
|
||||
}
|
||||
}
|
||||
else {
|
||||
$softContribution['soft_credit'][$count] = array(
|
||||
'contact_id' => $dao->contact_id,
|
||||
'soft_credit_id' => $dao->id,
|
||||
'currency' => $dao->currency,
|
||||
'amount' => $dao->amount,
|
||||
'contact_name' => $dao->display_name,
|
||||
'soft_credit_type' => $dao->soft_credit_type_id,
|
||||
'soft_credit_type_label' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $dao->soft_credit_type_id),
|
||||
);
|
||||
$count++;
|
||||
}
|
||||
}
|
||||
|
||||
return $softContribution;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $contributionID
|
||||
* @param bool $isPCP
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function getSoftCreditIds($contributionID, $isPCP = FALSE) {
|
||||
$query = "
|
||||
SELECT id
|
||||
FROM civicrm_contribution_soft
|
||||
WHERE contribution_id = %1
|
||||
";
|
||||
|
||||
if ($isPCP) {
|
||||
$query .= " AND pcp_id IS NOT NULL";
|
||||
}
|
||||
else {
|
||||
$query .= " AND pcp_id IS NULL";
|
||||
}
|
||||
$params = array(1 => array($contributionID, 'Integer'));
|
||||
|
||||
$dao = CRM_Core_DAO::executeQuery($query, $params);
|
||||
$id = array();
|
||||
$type = '';
|
||||
while ($dao->fetch()) {
|
||||
if ($isPCP) {
|
||||
return $dao->id;
|
||||
}
|
||||
$id[] = $dao->id;
|
||||
}
|
||||
return $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper for ajax soft contribution selector.
|
||||
*
|
||||
* @param array $params
|
||||
* Associated array for params.
|
||||
*
|
||||
* @return array
|
||||
* Associated array of soft contributions
|
||||
*/
|
||||
public static function getSoftContributionSelector($params) {
|
||||
$isTest = 0;
|
||||
if (!empty($params['isTest'])) {
|
||||
$isTest = $params['isTest'];
|
||||
}
|
||||
// Format the params.
|
||||
$params['offset'] = ($params['page'] - 1) * $params['rp'];
|
||||
$params['rowCount'] = $params['rp'];
|
||||
$params['sort'] = CRM_Utils_Array::value('sortBy', $params);
|
||||
$contactId = $params['cid'];
|
||||
|
||||
$filter = NULL;
|
||||
if ($params['context'] == 'membership' && !empty($params['entityID']) && $contactId) {
|
||||
$filter = " AND cc.id IN (SELECT contribution_id FROM civicrm_membership_payment WHERE membership_id = {$params['entityID']})";
|
||||
}
|
||||
|
||||
$softCreditList = self::getSoftContributionList($contactId, $filter, $isTest, $params);
|
||||
|
||||
$softCreditListDT = array();
|
||||
$softCreditListDT['data'] = array_values($softCreditList);
|
||||
$softCreditListDT['recordsTotal'] = $params['total'];
|
||||
$softCreditListDT['recordsFiltered'] = $params['total'];
|
||||
|
||||
return $softCreditListDT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to retrieve the list of soft contributions for given contact.
|
||||
*
|
||||
* @param int $contact_id
|
||||
* Contact id.
|
||||
* @param string $filter
|
||||
* @param int $isTest
|
||||
* Additional filter criteria, later used in where clause.
|
||||
* @param array $dTParams
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function getSoftContributionList($contact_id, $filter = NULL, $isTest = 0, &$dTParams = NULL) {
|
||||
$config = CRM_Core_Config::singleton();
|
||||
$links = array(
|
||||
CRM_Core_Action::VIEW => array(
|
||||
'name' => ts('View'),
|
||||
'url' => 'civicrm/contact/view/contribution',
|
||||
'qs' => 'reset=1&id=%%contributionid%%&cid=%%contactId%%&action=view&context=contribution&selectedChild=contribute',
|
||||
'title' => ts('View related contribution'),
|
||||
),
|
||||
);
|
||||
$orderBy = 'cc.receive_date DESC';
|
||||
if (!empty($dTParams['sort'])) {
|
||||
$orderBy = $dTParams['sort'];
|
||||
}
|
||||
$limit = '';
|
||||
if (!empty($dTParams['rowCount']) && $dTParams['rowCount'] > 0) {
|
||||
$limit = " LIMIT {$dTParams['offset']}, {$dTParams['rowCount']} ";
|
||||
}
|
||||
$softOgId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'soft_credit_type', 'id', 'name');
|
||||
$statusOgId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'contribution_status', 'id', 'name');
|
||||
|
||||
$query = '
|
||||
SELECT SQL_CALC_FOUND_ROWS ccs.id, ccs.amount as amount,
|
||||
ccs.contribution_id,
|
||||
ccs.pcp_id,
|
||||
ccs.pcp_display_in_roll,
|
||||
ccs.pcp_roll_nickname,
|
||||
ccs.pcp_personal_note,
|
||||
ccs.soft_credit_type_id,
|
||||
sov.label as sct_label,
|
||||
cc.receive_date,
|
||||
cc.contact_id as contributor_id,
|
||||
cc.contribution_status_id as contribution_status_id,
|
||||
cov.label as contribution_status,
|
||||
cp.title as pcp_title,
|
||||
cc.currency,
|
||||
contact.display_name as contributor_name,
|
||||
cct.name as financial_type
|
||||
FROM civicrm_contribution_soft ccs
|
||||
LEFT JOIN civicrm_contribution cc
|
||||
ON ccs.contribution_id = cc.id
|
||||
LEFT JOIN civicrm_pcp cp
|
||||
ON ccs.pcp_id = cp.id
|
||||
LEFT JOIN civicrm_contact contact ON
|
||||
ccs.contribution_id = cc.id AND cc.contact_id = contact.id
|
||||
LEFT JOIN civicrm_financial_type cct ON cc.financial_type_id = cct.id
|
||||
LEFT JOIN civicrm_option_value sov ON sov.option_group_id = %3 AND ccs.soft_credit_type_id = sov.value
|
||||
LEFT JOIN civicrm_option_value cov ON cov.option_group_id = %4 AND cc.contribution_status_id = cov.value
|
||||
';
|
||||
|
||||
$where = "
|
||||
WHERE cc.is_test = %2 AND ccs.contact_id = %1";
|
||||
if ($filter) {
|
||||
$where .= $filter;
|
||||
}
|
||||
|
||||
$query .= "{$where} ORDER BY {$orderBy} {$limit}";
|
||||
|
||||
$params = array(
|
||||
1 => array($contact_id, 'Integer'),
|
||||
2 => array($isTest, 'Integer'),
|
||||
3 => array($softOgId, 'Integer'),
|
||||
4 => array($statusOgId, 'Integer'),
|
||||
);
|
||||
$cs = CRM_Core_DAO::executeQuery($query, $params);
|
||||
|
||||
$dTParams['total'] = CRM_Core_DAO::singleValueQuery('SELECT FOUND_ROWS()');
|
||||
$result = array();
|
||||
while ($cs->fetch()) {
|
||||
$result[$cs->id]['amount'] = CRM_Utils_Money::format($cs->amount, $cs->currency);
|
||||
$result[$cs->id]['currency'] = $cs->currency;
|
||||
$result[$cs->id]['contributor_id'] = $cs->contributor_id;
|
||||
$result[$cs->id]['contribution_id'] = $cs->contribution_id;
|
||||
$result[$cs->id]['contributor_name'] = CRM_Utils_System::href(
|
||||
$cs->contributor_name,
|
||||
'civicrm/contact/view',
|
||||
"reset=1&cid={$cs->contributor_id}"
|
||||
);
|
||||
$result[$cs->id]['financial_type'] = $cs->financial_type;
|
||||
$result[$cs->id]['receive_date'] = CRM_Utils_Date::customFormat($cs->receive_date, $config->dateformatDatetime);
|
||||
$result[$cs->id]['pcp_id'] = $cs->pcp_id;
|
||||
$result[$cs->id]['pcp_title'] = ($cs->pcp_title) ? $cs->pcp_title : 'n/a';
|
||||
$result[$cs->id]['pcp_display_in_roll'] = $cs->pcp_display_in_roll;
|
||||
$result[$cs->id]['pcp_roll_nickname'] = $cs->pcp_roll_nickname;
|
||||
$result[$cs->id]['pcp_personal_note'] = $cs->pcp_personal_note;
|
||||
$result[$cs->id]['contribution_status'] = $cs->contribution_status;
|
||||
$result[$cs->id]['sct_label'] = $cs->sct_label;
|
||||
$replace = array(
|
||||
'contributionid' => $cs->contribution_id,
|
||||
'contactId' => $cs->contributor_id,
|
||||
);
|
||||
$result[$cs->id]['links'] = CRM_Core_Action::formLink($links, NULL, $replace);
|
||||
|
||||
if ($isTest) {
|
||||
$result[$cs->id]['contribution_status'] = $result[$cs->id]['contribution_status'] . '<br /> (test)';
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to assign honor profile fields to template/form, if $honorId (as soft-credit's contact_id)
|
||||
* is passed then whole honoreeprofile fields with title/value assoc array assigned or only honoreeName
|
||||
* is assigned
|
||||
*
|
||||
* @param CRM_Core_Form $form
|
||||
* @param array $params
|
||||
* @param int $honorId
|
||||
*/
|
||||
public static function formatHonoreeProfileFields($form, $params, $honorId = NULL) {
|
||||
if (empty($form->_values['honoree_profile_id'])) {
|
||||
return;
|
||||
}
|
||||
$profileContactType = CRM_Core_BAO_UFGroup::getContactType($form->_values['honoree_profile_id']);
|
||||
$profileFields = CRM_Core_BAO_UFGroup::getFields($form->_values['honoree_profile_id']);
|
||||
$honoreeProfileFields = $values = array();
|
||||
$honorName = NULL;
|
||||
|
||||
if ($honorId) {
|
||||
CRM_Core_BAO_UFGroup::getValues($honorId, $profileFields, $values, FALSE, $params);
|
||||
if (empty($params)) {
|
||||
foreach ($profileFields as $name => $field) {
|
||||
$title = $field['title'];
|
||||
$params[$field['name']] = $values[$title];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//remove name related fields and construct name string with prefix/suffix
|
||||
//which will be later assigned to template
|
||||
switch ($profileContactType) {
|
||||
case 'Individual':
|
||||
if (array_key_exists('prefix_id', $params)) {
|
||||
$honorName = CRM_Utils_Array::value(CRM_Utils_Array::value('prefix_id', $params),
|
||||
CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id')
|
||||
);
|
||||
unset($profileFields['prefix_id']);
|
||||
}
|
||||
$honorName .= ' ' . $params['first_name'] . ' ' . $params['last_name'];
|
||||
unset($profileFields['first_name']);
|
||||
unset($profileFields['last_name']);
|
||||
if (array_key_exists('suffix_id', $params)) {
|
||||
$honorName .= ' ' . CRM_Utils_Array::value(CRM_Utils_Array::value('suffix_id', $params),
|
||||
CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id')
|
||||
);
|
||||
unset($profileFields['suffix_id']);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'Organization':
|
||||
$honorName = $params['organization_name'];
|
||||
unset($profileFields['organization_name']);
|
||||
break;
|
||||
|
||||
case 'Household':
|
||||
$honorName = $params['household_name'];
|
||||
unset($profileFields['household_name']);
|
||||
break;
|
||||
}
|
||||
|
||||
if ($honorId) {
|
||||
$honoreeProfileFields['Name'] = $honorName;
|
||||
foreach ($profileFields as $name => $field) {
|
||||
$title = $field['title'];
|
||||
$honoreeProfileFields[$title] = $values[$title];
|
||||
}
|
||||
$form->assign('honoreeProfile', $honoreeProfileFields);
|
||||
}
|
||||
else {
|
||||
$form->assign('honorName', $honorName);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
142
sites/all/modules/civicrm/CRM/Contribute/BAO/ManagePremiums.php
Normal file
142
sites/all/modules/civicrm/CRM/Contribute/BAO/ManagePremiums.php
Normal file
|
@ -0,0 +1,142 @@
|
|||
<?php
|
||||
/*
|
||||
+--------------------------------------------------------------------+
|
||||
| CiviCRM version 4.7 |
|
||||
+--------------------------------------------------------------------+
|
||||
| Copyright CiviCRM LLC (c) 2004-2017 |
|
||||
+--------------------------------------------------------------------+
|
||||
| This file is a part of CiviCRM. |
|
||||
| |
|
||||
| CiviCRM is free software; you can copy, modify, and distribute it |
|
||||
| under the terms of the GNU Affero General Public License |
|
||||
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
|
||||
| |
|
||||
| CiviCRM is distributed in the hope that it will be useful, but |
|
||||
| WITHOUT ANY WARRANTY; without even the implied warranty of |
|
||||
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
|
||||
| See the GNU Affero General Public License for more details. |
|
||||
| |
|
||||
| You should have received a copy of the GNU Affero General Public |
|
||||
| License and the CiviCRM Licensing Exception along |
|
||||
| with this program; if not, contact CiviCRM LLC |
|
||||
| at info[AT]civicrm[DOT]org. If you have questions about the |
|
||||
| GNU Affero General Public License or the licensing of CiviCRM, |
|
||||
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
|
||||
+--------------------------------------------------------------------+
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @package CRM
|
||||
* @copyright CiviCRM LLC (c) 2004-2017
|
||||
*/
|
||||
class CRM_Contribute_BAO_ManagePremiums extends CRM_Contribute_DAO_Product {
|
||||
|
||||
/**
|
||||
* Static holder for the default LT.
|
||||
*/
|
||||
static $_defaultContributionType = NULL;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch object based on array of properties.
|
||||
*
|
||||
* @param array $params
|
||||
* (reference ) an assoc array of name/value pairs.
|
||||
* @param array $defaults
|
||||
* (reference ) an assoc array to hold the flattened values.
|
||||
*
|
||||
* @return CRM_Contribute_BAO_ManagePremium
|
||||
*/
|
||||
public static function retrieve(&$params, &$defaults) {
|
||||
$premium = new CRM_Contribute_DAO_Product();
|
||||
$premium->copyValues($params);
|
||||
if ($premium->find(TRUE)) {
|
||||
$premium->product_name = $premium->name;
|
||||
CRM_Core_DAO::storeValues($premium, $defaults);
|
||||
return $premium;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the is_active flag in the db.
|
||||
*
|
||||
* @param int $id
|
||||
* Id of the database record.
|
||||
* @param bool $is_active
|
||||
* Value we want to set the is_active field.
|
||||
*
|
||||
* @return Object
|
||||
* DAO object on success, null otherwise
|
||||
*/
|
||||
public static function setIsActive($id, $is_active) {
|
||||
if (!$is_active) {
|
||||
$dao = new CRM_Contribute_DAO_PremiumsProduct();
|
||||
$dao->product_id = $id;
|
||||
$dao->delete();
|
||||
}
|
||||
return CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Product', $id, 'is_active', $is_active);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a premium product to the database, and return it.
|
||||
*
|
||||
* @param array $params
|
||||
* Reference array contains the values submitted by the form.
|
||||
* @param array $ids
|
||||
* Reference array contains the id.
|
||||
*
|
||||
* @return CRM_Contribute_DAO_Product
|
||||
*/
|
||||
public static function add(&$params, &$ids) {
|
||||
$params = array_merge(array(
|
||||
'id' => CRM_Utils_Array::value('premium', $ids),
|
||||
'image' => '',
|
||||
'thumbnail' => '',
|
||||
'is_active' => 0,
|
||||
'is_deductible' => FALSE,
|
||||
'currency' => CRM_Core_Config::singleton()->defaultCurrency,
|
||||
), $params);
|
||||
|
||||
// Modify the submitted values for 'image' and 'thumbnail' so that we use
|
||||
// local URLs for these images when possible.
|
||||
$params['image'] = CRM_Utils_String::simplifyURL($params['image'], TRUE);
|
||||
$params['thumbnail'] = CRM_Utils_String::simplifyURL($params['thumbnail'], TRUE);
|
||||
|
||||
// Save and return
|
||||
$premium = new CRM_Contribute_DAO_Product();
|
||||
$premium->copyValues($params);
|
||||
$premium->save();
|
||||
return $premium;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete premium Types.
|
||||
*
|
||||
* @param int $productID
|
||||
*/
|
||||
public static function del($productID) {
|
||||
//check dependencies
|
||||
$premiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
|
||||
$premiumsProduct->product_id = $productID;
|
||||
if ($premiumsProduct->find(TRUE)) {
|
||||
$session = CRM_Core_Session::singleton();
|
||||
$message .= ts('This Premium is being linked to <a href=\'%1\'>Online Contribution page</a>. Please remove it in order to delete this Premium.', array(1 => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1')), ts('Deletion Error'), 'error');
|
||||
CRM_Core_Session::setStatus($message);
|
||||
return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/contribute/managePremiums', 'reset=1&action=browse'));
|
||||
}
|
||||
|
||||
//delete from financial Type table
|
||||
$premium = new CRM_Contribute_DAO_Product();
|
||||
$premium->id = $productID;
|
||||
$premium->delete();
|
||||
}
|
||||
|
||||
}
|
269
sites/all/modules/civicrm/CRM/Contribute/BAO/Premium.php
Normal file
269
sites/all/modules/civicrm/CRM/Contribute/BAO/Premium.php
Normal file
|
@ -0,0 +1,269 @@
|
|||
<?php
|
||||
/*
|
||||
+--------------------------------------------------------------------+
|
||||
| CiviCRM version 4.7 |
|
||||
+--------------------------------------------------------------------+
|
||||
| Copyright CiviCRM LLC (c) 2004-2017 |
|
||||
+--------------------------------------------------------------------+
|
||||
| This file is a part of CiviCRM. |
|
||||
| |
|
||||
| CiviCRM is free software; you can copy, modify, and distribute it |
|
||||
| under the terms of the GNU Affero General Public License |
|
||||
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
|
||||
| |
|
||||
| CiviCRM is distributed in the hope that it will be useful, but |
|
||||
| WITHOUT ANY WARRANTY; without even the implied warranty of |
|
||||
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
|
||||
| See the GNU Affero General Public License for more details. |
|
||||
| |
|
||||
| You should have received a copy of the GNU Affero General Public |
|
||||
| License and the CiviCRM Licensing Exception along |
|
||||
| with this program; if not, contact CiviCRM LLC |
|
||||
| at info[AT]civicrm[DOT]org. If you have questions about the |
|
||||
| GNU Affero General Public License or the licensing of CiviCRM, |
|
||||
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
|
||||
+--------------------------------------------------------------------+
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @package CRM
|
||||
* @copyright CiviCRM LLC (c) 2004-2017
|
||||
*/
|
||||
class CRM_Contribute_BAO_Premium extends CRM_Contribute_DAO_Premium {
|
||||
|
||||
/**
|
||||
* Product information.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private static $productInfo;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch object based on array of properties.
|
||||
*
|
||||
* @param array $params
|
||||
* (reference ) an assoc array of name/value pairs.
|
||||
* @param array $defaults
|
||||
* (reference ) an assoc array to hold the flattened values.
|
||||
*
|
||||
* @return CRM_Contribute_DAO_Product
|
||||
*/
|
||||
public static function retrieve(&$params, &$defaults) {
|
||||
$premium = new CRM_Contribute_DAO_Product();
|
||||
$premium->copyValues($params);
|
||||
if ($premium->find(TRUE)) {
|
||||
CRM_Core_DAO::storeValues($premium, $defaults);
|
||||
return $premium;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the is_active flag in the db.
|
||||
*
|
||||
* @param int $id
|
||||
* Id of the database record.
|
||||
* @param bool $is_active
|
||||
* Value we want to set the is_active field.
|
||||
*
|
||||
* @return Object
|
||||
* DAO object on success, null otherwise
|
||||
*/
|
||||
public static function setIsActive($id, $is_active) {
|
||||
return CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Premium', $id, 'premiums_active ', $is_active);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete financial Types.
|
||||
*
|
||||
* @param int $premiumID
|
||||
*/
|
||||
public static function del($premiumID) {
|
||||
$premium = new CRM_Contribute_DAO_Premium();
|
||||
$premium->id = $premiumID;
|
||||
$premium->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Premium Block im Contribution Pages.
|
||||
*
|
||||
* @param CRM_Core_Form $form
|
||||
* @param int $pageID
|
||||
* @param bool $formItems
|
||||
* @param int $selectedProductID
|
||||
* @param string $selectedOption
|
||||
*/
|
||||
public static function buildPremiumBlock(&$form, $pageID, $formItems = FALSE, $selectedProductID = NULL, $selectedOption = NULL) {
|
||||
$form->add('hidden', "selectProduct", $selectedProductID, array('id' => 'selectProduct'));
|
||||
|
||||
$dao = new CRM_Contribute_DAO_Premium();
|
||||
$dao->entity_table = 'civicrm_contribution_page';
|
||||
$dao->entity_id = $pageID;
|
||||
$dao->premiums_active = 1;
|
||||
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::ADD);
|
||||
$addWhere = "financial_type_id IN (0)";
|
||||
if (!empty($financialTypes)) {
|
||||
$addWhere = "financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
|
||||
}
|
||||
|
||||
if ($dao->find(TRUE)) {
|
||||
$premiumID = $dao->id;
|
||||
$premiumBlock = array();
|
||||
CRM_Core_DAO::storeValues($dao, $premiumBlock);
|
||||
|
||||
$dao = new CRM_Contribute_DAO_PremiumsProduct();
|
||||
$dao->premiums_id = $premiumID;
|
||||
$dao->whereAdd($addWhere);
|
||||
$dao->orderBy('weight');
|
||||
$dao->find();
|
||||
|
||||
$products = array();
|
||||
$radio = array();
|
||||
while ($dao->fetch()) {
|
||||
$productDAO = new CRM_Contribute_DAO_Product();
|
||||
$productDAO->id = $dao->product_id;
|
||||
$productDAO->is_active = 1;
|
||||
if ($productDAO->find(TRUE)) {
|
||||
if ($selectedProductID != NULL) {
|
||||
if ($selectedProductID == $productDAO->id) {
|
||||
if ($selectedOption) {
|
||||
$productDAO->options = ts('Selected Option') . ': ' . $selectedOption;
|
||||
}
|
||||
else {
|
||||
$productDAO->options = NULL;
|
||||
}
|
||||
CRM_Core_DAO::storeValues($productDAO, $products[$productDAO->id]);
|
||||
}
|
||||
}
|
||||
else {
|
||||
CRM_Core_DAO::storeValues($productDAO, $products[$productDAO->id]);
|
||||
}
|
||||
}
|
||||
$options = $temp = array();
|
||||
$temp = explode(',', $productDAO->options);
|
||||
foreach ($temp as $value) {
|
||||
$options[trim($value)] = trim($value);
|
||||
}
|
||||
if ($temp[0] != '') {
|
||||
$form->addElement('select', 'options_' . $productDAO->id, NULL, $options);
|
||||
}
|
||||
}
|
||||
if (count($products)) {
|
||||
$form->assign('showPremium', $formItems);
|
||||
$form->assign('showSelectOptions', $formItems);
|
||||
$form->assign('products', $products);
|
||||
$form->assign('premiumBlock', $premiumBlock);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Premium B im Contribution Pages.
|
||||
*
|
||||
* @param CRM_Core_Form $form
|
||||
* @param int $productID
|
||||
* @param int $premiumProductID
|
||||
*/
|
||||
public function buildPremiumPreviewBlock($form, $productID, $premiumProductID = NULL) {
|
||||
if ($premiumProductID) {
|
||||
$dao = new CRM_Contribute_DAO_PremiumsProduct();
|
||||
$dao->id = $premiumProductID;
|
||||
$dao->find(TRUE);
|
||||
$productID = $dao->product_id;
|
||||
}
|
||||
$productDAO = new CRM_Contribute_DAO_Product();
|
||||
$productDAO->id = $productID;
|
||||
$productDAO->is_active = 1;
|
||||
if ($productDAO->find(TRUE)) {
|
||||
CRM_Core_DAO::storeValues($productDAO, $products[$productDAO->id]);
|
||||
}
|
||||
|
||||
$radio[$productDAO->id] = $form->createElement('radio', NULL, NULL, NULL, $productDAO->id, NULL);
|
||||
$options = $temp = array();
|
||||
$temp = explode(',', $productDAO->options);
|
||||
foreach ($temp as $value) {
|
||||
$options[$value] = $value;
|
||||
}
|
||||
if ($temp[0] != '') {
|
||||
$form->add('select', 'options_' . $productDAO->id, NULL, $options);
|
||||
}
|
||||
|
||||
$form->addGroup($radio, 'selectProduct', NULL);
|
||||
|
||||
$form->assign('showRadio', TRUE);
|
||||
$form->assign('showSelectOptions', TRUE);
|
||||
$form->assign('products', $products);
|
||||
$form->assign('preview', TRUE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete premium associated w/ contribution page.
|
||||
*
|
||||
* @param int $contributionPageID
|
||||
*/
|
||||
public static function deletePremium($contributionPageID) {
|
||||
if (!$contributionPageID) {
|
||||
return;
|
||||
}
|
||||
|
||||
//need to delete entries from civicrm_premiums
|
||||
//as well as from civicrm_premiums_product, CRM-4586
|
||||
|
||||
$params = array(
|
||||
'entity_id' => $contributionPageID,
|
||||
'entity_table' => 'civicrm_contribution_page',
|
||||
);
|
||||
|
||||
$premium = new CRM_Contribute_DAO_Premium();
|
||||
$premium->copyValues($params);
|
||||
$premium->find();
|
||||
while ($premium->fetch()) {
|
||||
//lets delete from civicrm_premiums_product
|
||||
$premiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
|
||||
$premiumsProduct->premiums_id = $premium->id;
|
||||
$premiumsProduct->delete();
|
||||
|
||||
//now delete premium
|
||||
$premium->delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve premium product and their options.
|
||||
*
|
||||
* @return array
|
||||
* product and option arrays
|
||||
*/
|
||||
public static function getPremiumProductInfo() {
|
||||
if (!self::$productInfo) {
|
||||
$products = $options = array();
|
||||
|
||||
$dao = new CRM_Contribute_DAO_Product();
|
||||
$dao->is_active = 1;
|
||||
$dao->find();
|
||||
|
||||
while ($dao->fetch()) {
|
||||
$products[$dao->id] = $dao->name . " ( " . $dao->sku . " )";
|
||||
$opts = explode(',', $dao->options);
|
||||
foreach ($opts as $k => $v) {
|
||||
$ops[$k] = trim($v);
|
||||
}
|
||||
if ($ops[0] != '') {
|
||||
$options[$dao->id] = $opts;
|
||||
}
|
||||
}
|
||||
|
||||
self::$productInfo = array($products, $options);
|
||||
}
|
||||
return self::$productInfo;
|
||||
}
|
||||
|
||||
}
|
1170
sites/all/modules/civicrm/CRM/Contribute/BAO/Query.php
Normal file
1170
sites/all/modules/civicrm/CRM/Contribute/BAO/Query.php
Normal file
File diff suppressed because it is too large
Load diff
210
sites/all/modules/civicrm/CRM/Contribute/BAO/Widget.php
Normal file
210
sites/all/modules/civicrm/CRM/Contribute/BAO/Widget.php
Normal file
|
@ -0,0 +1,210 @@
|
|||
<?php
|
||||
/*
|
||||
+--------------------------------------------------------------------+
|
||||
| CiviCRM version 4.7 |
|
||||
+--------------------------------------------------------------------+
|
||||
| Copyright CiviCRM LLC (c) 2004-2017 |
|
||||
+--------------------------------------------------------------------+
|
||||
| This file is a part of CiviCRM. |
|
||||
| |
|
||||
| CiviCRM is free software; you can copy, modify, and distribute it |
|
||||
| under the terms of the GNU Affero General Public License |
|
||||
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
|
||||
| |
|
||||
| CiviCRM is distributed in the hope that it will be useful, but |
|
||||
| WITHOUT ANY WARRANTY; without even the implied warranty of |
|
||||
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
|
||||
| See the GNU Affero General Public License for more details. |
|
||||
| |
|
||||
| You should have received a copy of the GNU Affero General Public |
|
||||
| License and the CiviCRM Licensing Exception along |
|
||||
| with this program; if not, contact CiviCRM LLC |
|
||||
| at info[AT]civicrm[DOT]org. If you have questions about the |
|
||||
| GNU Affero General Public License or the licensing of CiviCRM, |
|
||||
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
|
||||
+--------------------------------------------------------------------+
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @package CRM
|
||||
* @copyright CiviCRM LLC (c) 2004-2017
|
||||
*/
|
||||
|
||||
/**
|
||||
* Class to retrieve information about a contribution page.
|
||||
*/
|
||||
class CRM_Contribute_BAO_Widget extends CRM_Contribute_DAO_Widget {
|
||||
|
||||
/**
|
||||
* Gets all campaign related data and returns it as a std class.
|
||||
*
|
||||
* @param int $contributionPageID
|
||||
* @param int $widgetID
|
||||
* @param bool $includePending
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public static function getContributionPageData($contributionPageID, $widgetID, $includePending = FALSE) {
|
||||
$config = CRM_Core_Config::singleton();
|
||||
|
||||
$data = array();
|
||||
$data['currencySymbol'] = $config->defaultCurrencySymbol;
|
||||
|
||||
if (empty($contributionPageID) ||
|
||||
CRM_Utils_Type::validate($contributionPageID, 'Integer') == NULL
|
||||
) {
|
||||
$data['is_error'] = TRUE;
|
||||
CRM_Core_Error::debug_log_message("$contributionPageID is not set");
|
||||
return $data;
|
||||
}
|
||||
|
||||
$widget = new CRM_Contribute_DAO_Widget();
|
||||
$widget->contribution_page_id = $contributionPageID;
|
||||
if (!$widget->find(TRUE)) {
|
||||
$data['is_error'] = TRUE;
|
||||
CRM_Core_Error::debug_log_message("$contributionPageID is not found");
|
||||
return $data;
|
||||
}
|
||||
|
||||
$data['is_error'] = FALSE;
|
||||
if (!$widget->is_active) {
|
||||
$data['is_active'] = FALSE;
|
||||
}
|
||||
|
||||
$data['is_active'] = TRUE;
|
||||
$data['title'] = $widget->title;
|
||||
$data['logo'] = $widget->url_logo;
|
||||
$data['button_title'] = $widget->button_title;
|
||||
$data['about'] = $widget->about;
|
||||
|
||||
//check if pending status needs to be included
|
||||
$status = '1';
|
||||
if ($includePending) {
|
||||
$status = '1,2';
|
||||
}
|
||||
|
||||
$query = "
|
||||
SELECT count( id ) as count,
|
||||
sum( total_amount) as amount
|
||||
FROM civicrm_contribution
|
||||
WHERE is_test = 0
|
||||
AND contribution_status_id IN ({$status})
|
||||
AND contribution_page_id = %1";
|
||||
$params = array(1 => array($contributionPageID, 'Integer'));
|
||||
$dao = CRM_Core_DAO::executeQuery($query, $params);
|
||||
if ($dao->fetch()) {
|
||||
$data['num_donors'] = (int) $dao->count;
|
||||
$data['money_raised'] = (int) $dao->amount;
|
||||
}
|
||||
else {
|
||||
$data['num_donors'] = $data['money_raised'] = $data->money_raised = 0;
|
||||
}
|
||||
|
||||
$query = "
|
||||
SELECT goal_amount, start_date, end_date, is_active
|
||||
FROM civicrm_contribution_page
|
||||
WHERE id = %1";
|
||||
$params = array(1 => array($contributionPageID, 'Integer'));
|
||||
$dao = CRM_Core_DAO::executeQuery($query, $params);
|
||||
|
||||
$data['campaign_start'] = '';
|
||||
$startDate = NULL;
|
||||
if ($dao->fetch()) {
|
||||
$data['money_target'] = (int) $dao->goal_amount;
|
||||
|
||||
// conditions that needs to be handled
|
||||
// 1. Campaign is not active - no text
|
||||
// 2. Campaign start date greater than today - show start date
|
||||
// 3. Campaign end date is set and greater than today - show end date
|
||||
// 4. If no start and end date or no end date and start date greater than today, then it's ongoing
|
||||
if ($dao->is_active) {
|
||||
$data['campaign_start'] = ts('Campaign is ongoing');
|
||||
|
||||
// check for time being between start and end date
|
||||
$now = time();
|
||||
if ($dao->start_date) {
|
||||
$startDate = CRM_Utils_Date::unixTime($dao->start_date);
|
||||
if ($startDate &&
|
||||
$startDate >= $now
|
||||
) {
|
||||
$data['is_active'] = FALSE;
|
||||
$data['campaign_start'] = ts('Campaign starts on %1', array(
|
||||
1 => CRM_Utils_Date::customFormat($dao->start_date, $config->dateformatFull),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if ($dao->end_date) {
|
||||
$endDate = CRM_Utils_Date::unixTime($dao->end_date);
|
||||
if ($endDate &&
|
||||
$endDate < $now
|
||||
) {
|
||||
$data['is_active'] = FALSE;
|
||||
$data['campaign_start'] = ts('Campaign ended on %1',
|
||||
array(
|
||||
1 => CRM_Utils_Date::customFormat($dao->end_date, $config->dateformatFull),
|
||||
)
|
||||
);
|
||||
}
|
||||
elseif ($startDate >= $now) {
|
||||
$data['campaign_start'] = ts('Campaign starts on %1',
|
||||
array(
|
||||
1 => CRM_Utils_Date::customFormat($dao->start_date, $config->dateformatFull),
|
||||
)
|
||||
);
|
||||
}
|
||||
else {
|
||||
$data['campaign_start'] = ts('Campaign ends on %1',
|
||||
array(
|
||||
1 => CRM_Utils_Date::customFormat($dao->end_date, $config->dateformatFull),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
$data['is_active'] = FALSE;
|
||||
}
|
||||
}
|
||||
else {
|
||||
$data['is_active'] = FALSE;
|
||||
}
|
||||
|
||||
$data['money_raised_percentage'] = 0;
|
||||
if ($data['money_target'] > 0) {
|
||||
$percent = $data['money_raised'] / $data['money_target'];
|
||||
$data['money_raised_percentage'] = (round($percent, 2)) * 100 . "%";
|
||||
$data['money_target_display'] = CRM_Utils_Money::format($data['money_target']);
|
||||
$data['money_raised'] = ts('Raised %1 of %2', array(
|
||||
1 => CRM_Utils_Money::format($data['money_raised']),
|
||||
2 => $data['money_target_display'],
|
||||
));
|
||||
}
|
||||
else {
|
||||
$data['money_raised'] = ts('Raised %1', array(1 => CRM_Utils_Money::format($data['money_raised'])));
|
||||
}
|
||||
|
||||
$data['money_low'] = 0;
|
||||
$data['num_donors'] = $data['num_donors'] . " " . ts('Donors');
|
||||
$data['home_url'] = "<a href='{$config->userFrameworkBaseURL}' class='crm-home-url' style='color:" . $widget->color_homepage_link . "'>" . ts('Learn more.') . "</a>";
|
||||
|
||||
// if is_active is false, show this link and hide the contribute button
|
||||
$data['homepage_link'] = $widget->url_homepage;
|
||||
|
||||
$data['colors'] = array();
|
||||
|
||||
$data['colors']["title"] = $widget->color_title;
|
||||
$data['colors']["button"] = $widget->color_button;
|
||||
$data['colors']["bar"] = $widget->color_bar;
|
||||
$data['colors']["main_text"] = $widget->color_main_text;
|
||||
$data['colors']["main"] = $widget->color_main;
|
||||
$data['colors']["main_bg"] = $widget->color_main_bg;
|
||||
$data['colors']["bg"] = $widget->color_bg;
|
||||
$data['colors']["about_link"] = $widget->color_about_link;
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue