3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
33 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
36 * Static field for all the contribution information that we can potentially import
40 static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 static $_exportableFields = NULL;
50 * Field for all the objects related to this contribution
51 * @var array of objects (e.g membership object, participant object)
53 public $_relatedObjects = array();
56 * Field for the component - either 'event' (participant) or 'contribute'
57 * (any item related to a contribution page e.g. membership, pledge, contribution)
58 * This is used for composing messages because they have dependency on the
59 * contribution_page or event page - although over time we may eliminate that
61 * @var string component or event
63 public $_component = NULL;
66 * Possibly obsolete variable.
68 * If you use it please explain why it is set in the create function here.
72 public $trxn_result_code;
77 * @return \CRM_Contribute_DAO_Contribution
81 public function __construct() {
82 parent
::__construct();
86 * Takes an associative array and creates a contribution object.
88 * the function extract all the params it needs to initialize the create a
89 * contribution object. the params array could contain additional unused name/value
92 * @param array $params
93 * (reference ) an assoc array of name/value pairs.
95 * The array that holds all the db ids.
97 * @return CRM_Contribute_BAO_Contribution|void
99 public static function add(&$params, $ids = array()) {
100 if (empty($params)) {
103 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
104 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
105 $duplicates = array();
106 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
107 $error = CRM_Core_Error
::singleton();
108 $d = implode(', ', $duplicates);
109 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
112 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
117 // first clean up all the money fields
118 $moneyFields = array(
122 'non_deductible_amount',
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
127 unset($moneyFields[0]);
130 foreach ($moneyFields as $field) {
131 if (isset($params[$field])) {
132 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
136 //set defaults in create mode
137 if (!$contributionID) {
138 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
140 self
::calculateMissingAmountParams($params, $contributionID);
142 if (!empty($params['payment_instrument_id'])) {
143 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
144 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
145 $params['check_number'] = 'null';
149 $setPrevContribution = TRUE;
150 // CRM-13964 partial payment
151 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
152 $partialAmtTotal = $params['partial_payment_total'];
153 $partialAmtPay = $params['partial_amount_pay'];
154 $params['total_amount'] = $partialAmtTotal;
155 if ($partialAmtPay < $partialAmtTotal) {
156 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
157 $params['is_pay_later'] = 0;
158 $setPrevContribution = FALSE;
162 if ($contributionID) {
163 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
166 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
168 $contribution = new CRM_Contribute_BAO_Contribution();
169 $contribution->copyValues($params);
171 $contribution->id
= $contributionID;
173 if (empty($contribution->id
)) {
174 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
175 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
176 $config = CRM_Core_Config
::singleton();
177 $contribution->currency
= $config->defaultCurrency
;
181 if ($contributionID && $setPrevContribution) {
182 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
185 $result = $contribution->save();
187 // Add financial_trxn details as part of fix for CRM-4724
188 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
189 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
191 //add Account details
192 $params['contribution'] = $contribution;
193 self
::recordFinancialAccounts($params);
195 // reset the group contact cache for this group
196 CRM_Contact_BAO_GroupContactCache
::remove();
198 if ($contributionID) {
199 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
202 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
209 * Get defaults for new entity.
212 public static function getDefaults() {
214 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
215 FALSE, FALSE, FALSE, 'AND is_default = 1')
217 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
222 * Given the list of params in the params array, fetch the object
223 * and store the values in the values array
225 * @param array $params
226 * Input parameters to find object.
227 * @param array $values
228 * Output values of the object.
230 * The array that holds all the db ids.
232 * @return CRM_Contribute_BAO_Contribution|null
233 * The found object or null
235 public static function getValues($params, &$values, &$ids) {
236 if (empty($params)) {
239 $contribution = new CRM_Contribute_BAO_Contribution();
241 $contribution->copyValues($params);
243 if ($contribution->find(TRUE)) {
244 $ids['contribution'] = $contribution->id
;
246 CRM_Core_DAO
::storeValues($contribution, $values);
248 return $contribution;
250 $null = NULL; // return by reference
255 * Calculate net_amount & fee_amount if they are not set.
257 * Net amount should be total - fee.
258 * This should only be called for new contributions.
260 * @param array $params
261 * Params for a new contribution before they are saved.
262 * @param int|null $contributionID
263 * Contribution ID if we are dealing with an update.
265 * @throws \CiviCRM_API3_Exception
267 public static function calculateMissingAmountParams(&$params, $contributionID) {
268 if (!$contributionID && !isset($params['fee_amount'])) {
269 if (isset($params['total_amount']) && isset($params['net_amount'])) {
270 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
273 $params['fee_amount'] = 0;
276 if (!isset($params['net_amount'])) {
277 if (!$contributionID) {
278 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
281 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
282 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
283 // net_amount may need adjusting.
284 $contribution = civicrm_api3('Contribution', 'getsingle', array(
285 'id' => $contributionID,
286 'return' => array('total_amount', 'net_amount'),
288 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
289 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
290 $params['net_amount'] = $totalAmount - $feeAmount;
298 * @param $billingLocationTypeID
302 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
303 $hasBillingField = FALSE;
304 $billingFields = array(
312 //build address array
313 $addressParams = array();
314 $addressParams['location_type_id'] = $billingLocationTypeID;
315 $addressParams['is_billing'] = 1;
317 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
318 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
319 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
320 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
322 foreach ($billingFields as $value) {
323 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
324 if (!empty($addressParams[$value])) {
325 $hasBillingField = TRUE;
328 return array($hasBillingField, $addressParams);
332 * Get address params ready to be passed to the payment processor.
334 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
335 * To create an address we need state_province_id.
337 * @param array $params
338 * @param int $billingLocationTypeID
342 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
343 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
344 foreach ($addressParams as $name => $field) {
345 if (substr($name, 0, 8) == 'billing_') {
346 $addressParams[substr($name, 9)] = $addressParams[$field];
349 return array($hasBillingField, $addressParams);
353 * Get the number of terms for this contribution for a given membership type
354 * based on querying the line item table and relevant price field values
355 * Note that any one contribution should only be able to have one line item relating to a particular membership
358 * @param int $membershipTypeID
360 * @param int $contributionID
364 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
365 $numTerms = CRM_Core_DAO
::singleValueQuery("
366 SELECT membership_num_terms FROM civicrm_line_item li
367 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
368 WHERE contribution_id = %1 AND membership_type_id = %2",
369 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
371 // default of 1 is precautionary
372 return empty($numTerms) ?
1 : $numTerms;
376 * Takes an associative array and creates a contribution object.
378 * @param array $params
379 * (reference ) an assoc array of name/value pairs.
381 * The array that holds all the db ids.
383 * @return CRM_Contribute_BAO_Contribution
385 public static function create(&$params, $ids = array()) {
386 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
387 foreach ($dateFields as $df) {
388 if (isset($params[$df])) {
389 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
393 $transaction = new CRM_Core_Transaction();
395 $contribution = self
::add($params, $ids);
397 if (is_a($contribution, 'CRM_Core_Error')) {
398 $transaction->rollback();
399 return $contribution;
402 $params['contribution_id'] = $contribution->id
;
404 if (!empty($params['custom']) &&
405 is_array($params['custom'])
407 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
410 $session = CRM_Core_Session
::singleton();
412 if (!empty($params['note'])) {
414 'entity_table' => 'civicrm_contribution',
415 'note' => $params['note'],
416 'entity_id' => $contribution->id
,
417 'contact_id' => $session->get('userID'),
418 'modified_date' => date('Ymd'),
420 if (!$noteParams['contact_id']) {
421 $noteParams['contact_id'] = $params['contact_id'];
423 CRM_Core_BAO_Note
::add($noteParams);
426 // make entry in batch entity batch table
427 if (!empty($params['batch_id'])) {
428 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
429 $titleFields = array(
435 $retrieveRequired = 0;
436 foreach ($titleFields as $titleField) {
437 if (!isset($contribution->$titleField)) {
438 $retrieveRequired = 1;
442 if ($retrieveRequired == 1) {
443 $contribution->find(TRUE);
447 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
449 $transaction->commit();
451 // check if activity record exist for this contribution, if
453 $activity = new CRM_Activity_DAO_Activity();
454 $activity->source_record_id
= $contribution->id
;
455 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
459 if (!$activity->find(TRUE)) {
460 if (empty($contribution->contact_id
)) {
461 $contribution->find(TRUE);
463 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
466 // CRM-13237 : if activity record found, update it with campaign id of contribution
467 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
470 // do not add to recent items for import, CRM-4399
471 if (empty($params['skipRecentView'])) {
472 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
473 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
475 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
476 $titleFields = array(
482 $retrieveRequired = 0;
483 foreach ($titleFields as $titleField) {
484 if (!isset($contribution->$titleField)) {
485 $retrieveRequired = 1;
489 if ($retrieveRequired == 1) {
490 $contribution->find(TRUE);
492 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
493 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
495 $recentOther = array();
496 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
497 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
498 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
502 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
503 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
504 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
508 // add the recently created Contribution
509 CRM_Utils_Recent
::add($title,
513 $contribution->contact_id
,
519 return $contribution;
523 * Get the values for pseudoconstants for name->value and reverse.
525 * @param array $defaults
526 * (reference) the default values, some of which need to be resolved.
527 * @param bool $reverse
528 * True if we want to resolve the values in the reverse direction (value -> name).
530 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
531 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
532 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
533 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
534 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
538 * Convert associative array names to values and vice-versa.
540 * This function is used by both the web form layer and the api. Note that
541 * the api needs the name => value conversion, also the view layer typically
542 * requires value => name conversion
544 * @param array $defaults
545 * @param string $property
546 * @param array $lookup
547 * @param bool $reverse
551 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
552 $id = $property . '_id';
554 $src = $reverse ?
$property : $id;
555 $dst = $reverse ?
$id : $property;
557 if (!array_key_exists($src, $defaults)) {
561 $look = $reverse ?
array_flip($lookup) : $lookup;
563 if (is_array($look)) {
564 if (!array_key_exists($defaults[$src], $look)) {
568 $defaults[$dst] = $look[$defaults[$src]];
573 * Retrieve DB object based on input parameters.
575 * It also stores all the retrieved values in the default array.
577 * @param array $params
578 * (reference ) an assoc array of name/value pairs.
579 * @param array $defaults
580 * (reference ) an assoc array to hold the name / value pairs.
581 * in a hierarchical manner
583 * (reference) the array that holds all the db ids.
585 * @return CRM_Contribute_BAO_Contribution
587 public static function retrieve(&$params, &$defaults, &$ids) {
588 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
589 return $contribution;
593 * Combine all the importable fields from the lower levels object.
595 * The ordering is important, since currently we do not have a weight
596 * scheme. Adding weight is super important and should be done in the
597 * next week or so, before this can be called complete.
599 * @param string $contactType
600 * @param bool $status
603 * array of importable Fields
605 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
606 if (!self
::$_importableFields) {
607 if (!self
::$_importableFields) {
608 self
::$_importableFields = array();
612 $fields = array('' => array('title' => ts('- do not import -')));
615 $fields = array('' => array('title' => ts('- Contribution Fields -')));
618 $note = CRM_Core_DAO_Note
::import();
619 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
620 unset($tmpFields['option_value']);
621 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
622 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
624 // Using new Dedupe rule.
626 'contact_type' => $contactType,
627 'used' => 'Unsupervised',
629 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
630 $tmpContactField = array();
631 if (is_array($fieldsArray)) {
632 foreach ($fieldsArray as $value) {
633 //skip if there is no dupe rule
634 if ($value == 'none') {
637 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
642 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
643 $tmpContactField[trim($value)] = $contactFields[trim($value)];
645 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
648 $title = $tmpContactField[trim($value)]['title'];
650 $tmpContactField[trim($value)]['title'] = $title;
654 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
655 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
656 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
657 $fields = array_merge($fields, $tmpContactField);
658 $fields = array_merge($fields, $tmpFields);
659 $fields = array_merge($fields, $note);
660 $fields = array_merge($fields, $optionFields);
661 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
662 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
663 self
::$_importableFields = $fields;
665 return self
::$_importableFields;
671 public static function &exportableFields() {
672 if (!self
::$_exportableFields) {
673 if (!self
::$_exportableFields) {
674 self
::$_exportableFields = array();
677 $impFields = CRM_Contribute_DAO_Contribution
::export();
678 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
679 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
680 $typeField = CRM_Financial_DAO_FinancialType
::export();
681 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
682 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
683 $contributionStatus = array(
684 'contribution_status' => array(
685 'title' => ts('Contribution Status'),
686 'name' => 'contribution_status',
687 'data_type' => CRM_Utils_Type
::T_STRING
,
691 $contributionPage = array(
692 'contribution_page' => array(
693 'title' => ts('Contribution Page'),
694 'name' => 'contribution_page',
695 'where' => 'civicrm_contribution_page.title',
696 'data_type' => CRM_Utils_Type
::T_STRING
,
700 $contributionNote = array(
701 'contribution_note' => array(
702 'title' => ts('Contribution Note'),
703 'name' => 'contribution_note',
704 'data_type' => CRM_Utils_Type
::T_TEXT
,
708 $contributionRecurId = array(
709 'contribution_recur_id' => array(
710 'title' => ts('Recurring Contributions ID'),
711 'name' => 'contribution_recur_id',
712 'where' => 'civicrm_contribution.contribution_recur_id',
713 'data_type' => CRM_Utils_Type
::T_INT
,
717 $extraFields = array(
718 'contribution_batch' => array(
719 'title' => ts('Batch Name'),
723 $softCreditFields = array(
724 'contribution_soft_credit_name' => array(
725 'name' => 'contribution_soft_credit_name',
726 'title' => 'Soft Credit For',
727 'where' => 'civicrm_contact_d.display_name',
728 'data_type' => CRM_Utils_Type
::T_STRING
,
730 'contribution_soft_credit_amount' => array(
731 'name' => 'contribution_soft_credit_amount',
732 'title' => 'Soft Credit Amount',
733 'where' => 'civicrm_contribution_soft.amount',
734 'data_type' => CRM_Utils_Type
::T_MONEY
,
736 'contribution_soft_credit_type' => array(
737 'name' => 'contribution_soft_credit_type',
738 'title' => 'Soft Credit Type',
739 'where' => 'contribution_softcredit_type.label',
740 'data_type' => CRM_Utils_Type
::T_STRING
,
742 'contribution_soft_credit_contribution_id' => array(
743 'name' => 'contribution_soft_credit_contribution_id',
744 'title' => 'Soft Credit For Contribution ID',
745 'where' => 'civicrm_contribution_soft.contribution_id',
746 'data_type' => CRM_Utils_Type
::T_INT
,
750 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
752 'contribution_product_id' => array(
753 'title' => ts('Premium'),
754 'name' => 'contribution_product_id',
755 'where' => 'civicrm_product.id',
756 'data_type' => CRM_Utils_Type
::T_INT
,
760 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
761 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums,
762 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
765 self
::$_exportableFields = $fields;
768 return self
::$_exportableFields;
772 * @param null $status
773 * @param null $startDate
774 * @param null $endDate
778 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
782 $where[] = 'contribution_status_id = 1';
786 $where[] = 'contribution_status_id = 3';
791 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
794 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
797 $whereCond = implode(' AND ', $where);
800 SELECT sum( total_amount ) as total_amount,
801 count( civicrm_contribution.id ) as total_count,
803 FROM civicrm_contribution
804 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
806 AND ( is_test = 0 OR is_test IS NULL )
807 AND contact.is_deleted = 0
811 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
814 while ($dao->fetch()) {
815 $count +
= $dao->total_count
;
816 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
820 'amount' => implode(', ', $amount),
828 * Delete the indirect records associated with this contribution first.
833 * $results no of deleted Contribution on success, false otherwise
835 public static function deleteContribution($id) {
836 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
838 $transaction = new CRM_Core_Transaction();
841 //delete activity record
843 'source_record_id' => $id,
844 // activity type id for contribution
845 'activity_type_id' => 6,
848 CRM_Activity_BAO_Activity
::deleteActivity($params);
850 //delete billing address if exists for this contribution.
851 self
::deleteAddress($id);
853 //update pledge and pledge payment, CRM-3961
854 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
856 // remove entry from civicrm_price_set_entity, CRM-5095
857 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
858 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
860 // cleanup line items.
861 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
863 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
864 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
866 if ($participantId) {
867 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
870 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
874 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
875 $noteId = key($note);
877 CRM_Core_BAO_Note
::del($noteId, FALSE);
880 $dao = new CRM_Contribute_DAO_Contribution();
883 $results = $dao->delete();
885 $transaction->commit();
887 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
889 // delete the recently created Contribution
890 $contributionRecent = array(
892 'type' => 'Contribution',
894 CRM_Utils_Recent
::del($contributionRecent);
900 * React to a financial transaction (payment) failure.
902 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
903 * payments is important for forensic and outreach reasons.
905 * @param int $contributionID
906 * @param string $message
908 public static function failPayment($contributionID, $contactID, $message) {
909 civicrm_api3('activity', 'create', array(
910 'activity_type_id' => 'Failed Payment',
911 'details' => $message,
912 'subject' => ts('Payment failed at payment processor'),
913 'source_record_id' => $contributionID,
914 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
920 * Check if there is a contribution with the same trxn_id or invoice_id.
922 * @param array $input
923 * An assoc array of name/value pairs.
924 * @param array $duplicates
925 * (reference) store ids of duplicate contribs.
929 * true if duplicate, false otherwise
931 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
933 $id = CRM_Utils_Array
::value('id', $input);
935 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
936 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
942 $clause[] = "trxn_id = %1";
943 $input[1] = array($trxn_id, 'String');
947 $clause[] = "invoice_id = %2";
948 $input[2] = array($invoice_id, 'String');
951 if (empty($clause)) {
955 $clause = implode(' OR ', $clause);
957 $clause = "( $clause ) AND id != %3";
958 $input[3] = array($id, 'Integer');
961 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
962 $dao = CRM_Core_DAO
::executeQuery($query, $input);
964 while ($dao->fetch()) {
965 $duplicates[] = $dao->id
;
972 * Takes an associative array and creates a contribution_product object.
974 * the function extract all the params it needs to initialize the create a
975 * contribution_product object. the params array could contain additional unused name/value
978 * @param array $params
979 * (reference) an assoc array of name/value pairs.
981 * @return CRM_Contribute_DAO_ContributionProduct
983 public static function addPremium(&$params) {
984 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
985 $contributionProduct->copyValues($params);
986 return $contributionProduct->save();
990 * Get list of contribution fields for profile.
991 * For now we only allow custom contribution fields to be in
994 * @param bool $addExtraFields
995 * True if special fields needs to be added.
998 * the list of contribution fields
1000 public static function getContributionFields($addExtraFields = TRUE) {
1001 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1002 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1004 if ($addExtraFields) {
1005 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1008 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1010 foreach ($contributionFields as $key => $var) {
1011 if ($key == 'contribution_contact_id') {
1014 elseif ($key == 'contribution_campaign_id') {
1015 $var['title'] = ts('Campaign');
1017 $fields[$key] = $var;
1020 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1025 * Add extra fields specific to contribution.
1027 public static function getSpecialContributionFields() {
1028 $extraFields = array(
1029 'contribution_soft_credit_name' => array(
1030 'name' => 'contribution_soft_credit_name',
1031 'title' => 'Soft Credit Name',
1032 'headerPattern' => '/^soft_credit_name$/i',
1033 'where' => 'civicrm_contact_d.display_name',
1035 'contribution_soft_credit_email' => array(
1036 'name' => 'contribution_soft_credit_email',
1037 'title' => 'Soft Credit Email',
1038 'headerPattern' => '/^soft_credit_email$/i',
1039 'where' => 'soft_email.email',
1041 'contribution_soft_credit_phone' => array(
1042 'name' => 'contribution_soft_credit_phone',
1043 'title' => 'Soft Credit Phone',
1044 'headerPattern' => '/^soft_credit_phone$/i',
1045 'where' => 'soft_phone.phone',
1047 'contribution_soft_credit_contact_id' => array(
1048 'name' => 'contribution_soft_credit_contact_id',
1049 'title' => 'Soft Credit Contact ID',
1050 'headerPattern' => '/^soft_credit_contact_id$/i',
1051 'where' => 'civicrm_contribution_soft.contact_id',
1055 return $extraFields;
1059 * @param int $pageID
1063 public static function getCurrentandGoalAmount($pageID) {
1065 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1066 FROM civicrm_contribution_page p,
1067 civicrm_contribution c
1068 WHERE p.id = c.contribution_page_id
1070 AND c.cancel_date is null
1074 $config = CRM_Core_Config
::singleton();
1075 $params = array(1 => array($pageID, 'Integer'));
1076 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1078 if ($dao->fetch()) {
1079 return array($dao->goal
, $dao->total
);
1082 return array(NULL, NULL);
1087 * Get list of contribution In Honor of contact Ids.
1089 * @param int $honorId
1090 * In Honor of Contact ID.
1093 * list of contribution fields
1095 public static function getHonorContacts($honorId) {
1097 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1098 $honorDAO->contact_id
= $honorId;
1101 $type = CRM_Contribute_PseudoConstant
::financialType();
1103 while ($honorDAO->fetch()) {
1104 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1105 $contributionDAO->id
= $honorDAO->contribution_id
;
1107 if ($contributionDAO->find(TRUE)) {
1108 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1109 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1110 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1111 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1112 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1113 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1114 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1115 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1116 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1124 * Get the sort name of a contact for a particular contribution.
1127 * Id of the contribution.
1129 * @return null|string
1130 * sort name of the contact if found
1132 public static function sortName($id) {
1133 $id = CRM_Utils_Type
::escape($id, 'Integer');
1136 SELECT civicrm_contact.sort_name
1137 FROM civicrm_contribution, civicrm_contact
1138 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1139 AND civicrm_contribution.id = {$id}
1141 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1145 * @param int $contactID
1149 public static function annual($contactID) {
1150 if (is_array($contactID)) {
1151 $contactIDs = implode(',', $contactID);
1154 $contactIDs = $contactID;
1157 $config = CRM_Core_Config
::singleton();
1158 $startDate = $endDate = NULL;
1160 $currentMonth = date('m');
1161 $currentDay = date('d');
1162 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1163 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1164 (int ) $config->fiscalYearStart
['d'] > $currentDay
1167 $year = date('Y') - 1;
1172 $nextYear = $year +
1;
1174 if ($config->fiscalYearStart
) {
1175 if ($config->fiscalYearStart
['M'] < 10) {
1176 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1178 if ($config->fiscalYearStart
['d'] < 10) {
1179 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1181 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1186 $startDate = "$year$monthDay";
1187 $endDate = "$nextYear$monthDay";
1190 SELECT count(*) as count,
1191 sum(total_amount) as amount,
1192 avg(total_amount) as average,
1194 FROM civicrm_contribution b
1195 WHERE b.contact_id IN ( $contactIDs )
1196 AND b.contribution_status_id = 1
1198 AND b.receive_date >= $startDate
1199 AND b.receive_date < $endDate
1202 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1204 $amount = $average = array();
1205 while ($dao->fetch()) {
1206 if ($dao->count
> 0 && $dao->amount
> 0) {
1207 $count +
= $dao->count
;
1208 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1209 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1215 implode(', ', $amount),
1216 implode(', ', $average),
1219 return array(0, 0, 0);
1223 * Check if there is a contribution with the params passed in.
1225 * Used for trxn_id,invoice_id and contribution_id
1227 * @param array $params
1228 * An assoc array of name/value pairs.
1231 * contribution id if success else NULL
1233 public static function checkDuplicateIds($params) {
1234 $dao = new CRM_Contribute_DAO_Contribution();
1238 foreach ($params as $k => $v) {
1240 $clause[] = "$k = '$v'";
1243 $clause = implode(' AND ', $clause);
1244 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1245 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1247 while ($dao->fetch()) {
1255 * Get the contribution details for component export.
1257 * @param int $exportMode
1259 * @param string $componentIds
1265 public static function getContributionDetails($exportMode, $componentIds) {
1266 $paymentDetails = array();
1267 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1269 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1270 $componentSelect = " civicrm_participant_payment.participant_id id";
1271 $additionalClause = "
1272 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1273 AND civicrm_participant_payment.participant_id {$componentClause} )
1276 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1277 $componentSelect = " civicrm_membership_payment.membership_id id";
1278 $additionalClause = "
1279 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1280 AND civicrm_membership_payment.membership_id {$componentClause} )
1283 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1284 $componentSelect = " civicrm_pledge_payment.id id";
1285 $additionalClause = "
1286 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1287 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1291 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1292 trxn_id, {$componentSelect}
1293 FROM civicrm_contribution
1294 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1295 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1296 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1297 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1298 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1299 AND option_group_contribution_status.id = contribution_status.option_group_id )
1303 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1305 while ($dao->fetch()) {
1306 $paymentDetails[$dao->id
] = array(
1307 'total_amount' => $dao->total_amount
,
1308 'contribution_status' => $dao->status
,
1309 'receive_date' => $dao->receive_date
,
1310 'pay_instru' => $dao->payment_instrument
,
1311 'trxn_id' => $dao->trxn_id
,
1315 return $paymentDetails;
1319 * Create address associated with contribution record.
1321 * As long as there is one or more billing field in the parameters we will create the address.
1323 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1326 * @param array $params
1327 * @param int $billingLocationTypeID
1332 public static function createAddress($params, $billingLocationTypeID) {
1333 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1334 if ($hasBillingField) {
1335 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1336 return $address->id
;
1343 * Delete billing address record related contribution.
1345 * @param int $contributionId
1346 * @param int $contactId
1348 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1350 $contactJoin = NULL;
1352 if ($contributionId) {
1353 $clauses[] = "cc.id = {$contributionId}";
1357 $clauses[] = "cco.id = {$contactId}";
1358 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1361 if (empty($clauses)) {
1362 CRM_Core_Error
::fatal();
1365 $condition = implode(' OR ', $clauses);
1369 FROM civicrm_address ca
1370 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1374 $dao = CRM_Core_DAO
::executeQuery($query);
1376 while ($dao->fetch()) {
1377 $params = array('id' => $dao->id
);
1378 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1383 * This function check online pending contribution associated w/
1384 * Online Event Registration or Online Membership signup.
1386 * @param int $componentId
1387 * Participant/membership id.
1388 * @param string $componentName
1392 * pending contribution id.
1394 public static function checkOnlinePendingContribution($componentId, $componentName) {
1395 $contributionId = NULL;
1396 if (!$componentId ||
1397 !in_array($componentName, array('Event', 'Membership'))
1399 return $contributionId;
1402 if ($componentName == 'Event') {
1403 $idName = 'participant_id';
1404 $componentTable = 'civicrm_participant';
1405 $paymentTable = 'civicrm_participant_payment';
1406 $source = ts('Online Event Registration');
1409 if ($componentName == 'Membership') {
1410 $idName = 'membership_id';
1411 $componentTable = 'civicrm_membership';
1412 $paymentTable = 'civicrm_membership_payment';
1413 $source = ts('Online Contribution');
1416 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1419 SELECT component.id as {$idName},
1420 componentPayment.contribution_id as contribution_id,
1421 contribution.source source,
1422 contribution.contribution_status_id as contribution_status_id,
1423 contribution.is_pay_later as is_pay_later
1424 FROM $componentTable component
1425 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1426 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1427 WHERE component.id = {$componentId}";
1429 $dao = CRM_Core_DAO
::executeQuery($query);
1431 while ($dao->fetch()) {
1432 if ($dao->contribution_id
&&
1433 $dao->is_pay_later
&&
1434 $dao->contribution_status_id
== $pendingStatusId &&
1435 strpos($dao->source
, $source) !== FALSE
1437 $contributionId = $dao->contribution_id
;
1442 return $contributionId;
1446 * Update contribution as well as related objects.
1448 * This function by-passes hooks - to address this - don't use this function.
1452 * Use api contribute.completetransaction
1453 * For failures use failPayment (preferably exposing by api in the process).
1455 * @param array $params
1456 * @param bool $processContributionObject
1459 * @throws \Exception
1461 public static function transitionComponents($params, $processContributionObject = FALSE) {
1462 // get minimum required values.
1463 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1464 $componentId = CRM_Utils_Array
::value('component_id', $params);
1465 $componentName = CRM_Utils_Array
::value('componentName', $params);
1466 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1467 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1469 // if we already processed contribution object pass previous status id.
1470 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1472 $updateResult = array();
1474 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1476 // we process only ( Completed, Cancelled, or Failed ) contributions.
1477 if (!$contributionId ||
1478 !in_array($contributionStatusId, array(
1479 array_search('Completed', $contributionStatuses),
1480 array_search('Cancelled', $contributionStatuses),
1481 array_search('Failed', $contributionStatuses),
1484 return $updateResult;
1487 if (!$componentName ||
!$componentId) {
1488 // get the related component details.
1489 $componentDetails = self
::getComponentDetails($contributionId);
1492 $componentDetails['contact_id'] = $contactId;
1493 $componentDetails['component'] = $componentName;
1495 if ($componentName == 'event') {
1496 $componentDetails['participant'] = $componentId;
1499 $componentDetails['membership'] = $componentId;
1503 if (!empty($componentDetails['contact_id'])) {
1504 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1510 // do check for required ids.
1511 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1512 return $updateResult;
1515 //now we are ready w/ required ids, start processing.
1517 $baseIPN = new CRM_Core_Payment_BaseIPN();
1519 $input = $ids = $objects = array();
1521 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1522 $ids['contribution'] = $contributionId;
1523 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1524 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1525 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1526 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1527 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1528 $ids['contributionRecur'] = NULL;
1529 $ids['contributionPage'] = NULL;
1531 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1532 CRM_Core_Error
::fatal();
1535 $memberships = &$objects['membership'];
1536 $participant = &$objects['participant'];
1537 $pledgePayment = &$objects['pledge_payment'];
1538 $contribution = &$objects['contribution'];
1540 if ($pledgePayment) {
1541 $pledgePaymentIDs = array();
1542 foreach ($pledgePayment as $key => $object) {
1543 $pledgePaymentIDs[] = $object->id
;
1545 $pledgeID = $pledgePayment[0]->pledge_id
;
1548 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1551 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1552 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1557 // we might want to process contribution object.
1558 $processContribution = FALSE;
1559 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1560 if (is_array($memberships)) {
1561 foreach ($memberships as $membership) {
1563 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1564 $membership->save();
1566 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1567 if ($processContributionObject) {
1568 $processContribution = TRUE;
1575 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1576 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1578 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1579 if ($processContributionObject) {
1580 $processContribution = TRUE;
1584 if ($pledgePayment) {
1585 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1587 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1588 if ($processContributionObject) {
1589 $processContribution = TRUE;
1593 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1594 if (is_array($memberships)) {
1595 foreach ($memberships as $membership) {
1597 $membership->status_id
= array_search('Expired', $membershipStatuses);
1598 $membership->save();
1600 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1601 if ($processContributionObject) {
1602 $processContribution = TRUE;
1608 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1609 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1611 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1612 if ($processContributionObject) {
1613 $processContribution = TRUE;
1617 if ($pledgePayment) {
1618 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1620 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1621 if ($processContributionObject) {
1622 $processContribution = TRUE;
1626 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1628 // only pending contribution related object processed.
1629 if ($previousContriStatusId &&
1630 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1632 // this is case when we already processed contribution object.
1633 return $updateResult;
1635 elseif (!$previousContriStatusId &&
1636 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1638 // this is case when we are going to process contribution object later.
1639 return $updateResult;
1642 if (is_array($memberships)) {
1643 foreach ($memberships as $membership) {
1648 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1649 $membership->membership_type_id
,
1650 $membership->is_test
, $membership->id
1653 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1654 // this picks up membership type changes during renewals
1656 SELECT membership_type_id
1657 FROM civicrm_membership_log
1658 WHERE membership_id=$membership->id
1661 $dao = new CRM_Core_DAO();
1663 if ($dao->fetch()) {
1664 if (!empty($dao->membership_type_id
)) {
1665 $membership->membership_type_id
= $dao->membership_type_id
;
1666 $membership->save();
1669 // else fall back to using current membership type
1672 // Figure out number of terms
1674 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1675 foreach ($lineitems as $lineitem) {
1676 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1677 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1679 // in case membership_num_terms comes through as null or zero
1680 $numterms = $numterms >= 1 ?
$numterms : 1;
1685 // CRM-15735-to update the membership status as per the contribution receive date
1687 if (!empty($params['receive_date'])) {
1688 $joinDate = $params['receive_date'];
1689 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1690 $membership->end_date
,
1691 $membership->join_date
,
1692 $params['receive_date'],
1694 $membership->membership_type_id
,
1697 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1698 $membership->save();
1701 if ($currentMembership) {
1702 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1703 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1704 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1707 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1710 //get the status for membership.
1711 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1713 $dates['join_date'],
1716 $membership->membership_type_id
,
1720 $formattedParams = array(
1721 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1722 array_search('Current', $membershipStatuses)
1724 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1725 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1726 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1729 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1731 $membership->copyValues($formattedParams);
1732 $membership->save();
1734 //updating the membership log
1735 $membershipLog = array();
1736 $membershipLog = $formattedParams;
1737 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1738 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1740 $membershipLog['start_date'] = $logStartDate;
1741 $membershipLog['membership_id'] = $membership->id
;
1742 $membershipLog['modified_id'] = $membership->contact_id
;
1743 $membershipLog['modified_date'] = date('Ymd');
1744 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1746 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1748 //update related Memberships.
1749 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1751 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1754 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1755 if ($processContributionObject) {
1756 $processContribution = TRUE;
1759 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1765 $updatedStatusId = array_search('Registered', $participantStatuses);
1766 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1768 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1769 if ($processContributionObject) {
1770 $processContribution = TRUE;
1774 if ($pledgePayment) {
1775 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1777 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1778 if ($processContributionObject) {
1779 $processContribution = TRUE;
1784 // process contribution object.
1785 if ($processContribution) {
1786 $contributionParams = array();
1793 'payment_instrument_id',
1796 'financial_type_id',
1797 'contribution_status_id',
1798 'non_deductible_amount',
1802 foreach ($fields as $field) {
1803 if (empty($params[$field])) {
1806 $contributionParams[$field] = $params[$field];
1809 $ids = array('contribution' => $contributionId);
1810 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1813 return $updateResult;
1817 * Returns all contribution related object ids.
1819 * @param $contributionId
1823 public static function getComponentDetails($contributionId) {
1824 $componentDetails = $pledgePayment = array();
1825 if (!$contributionId) {
1826 return $componentDetails;
1830 SELECT c.id as contribution_id,
1831 c.contact_id as contact_id,
1832 c.contribution_recur_id,
1833 mp.membership_id as membership_id,
1834 m.membership_type_id as membership_type_id,
1835 pp.participant_id as participant_id,
1836 p.event_id as event_id,
1837 pgp.id as pledge_payment_id
1838 FROM civicrm_contribution c
1839 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1840 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1841 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1842 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1843 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1844 WHERE c.id = $contributionId";
1846 $dao = CRM_Core_DAO
::executeQuery($query);
1847 $componentDetails = array();
1849 while ($dao->fetch()) {
1850 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1851 $componentDetails['contact_id'] = $dao->contact_id
;
1852 if ($dao->event_id
) {
1853 $componentDetails['event'] = $dao->event_id
;
1855 if ($dao->participant_id
) {
1856 $componentDetails['participant'] = $dao->participant_id
;
1858 if ($dao->membership_id
) {
1859 if (!isset($componentDetails['membership'])) {
1860 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1862 $componentDetails['membership'][] = $dao->membership_id
;
1863 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1865 if ($dao->pledge_payment_id
) {
1866 $pledgePayment[] = $dao->pledge_payment_id
;
1868 if ($dao->contribution_recur_id
) {
1869 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1873 if ($pledgePayment) {
1874 $componentDetails['pledge_payment'] = $pledgePayment;
1877 return $componentDetails;
1881 * @param int $contactId
1882 * @param bool $includeSoftCredit
1884 * @return null|string
1886 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1891 $contactContributionsSQL = "
1892 SELECT contribution.id AS id
1893 FROM civicrm_contribution contribution
1894 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1896 $contactSoftCreditContributionsSQL = "
1897 SELECT contribution.id
1898 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1899 ON ( contribution.id = softContribution.contribution_id )
1900 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1901 $query = "SELECT count( x.id ) count FROM ( ";
1902 $query .= $contactContributionsSQL;
1904 if ($includeSoftCredit) {
1905 $query .= " UNION ";
1906 $query .= $contactSoftCreditContributionsSQL;
1911 return CRM_Core_DAO
::singleValueQuery($query);
1915 * Repeat a transaction as part of a recurring series.
1917 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
1918 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
1919 * subsequent call to the contribution.completetransaction api.
1921 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
1923 * @param CRM_Contribute_BAO_Contribution $contribution
1924 * @param array $input
1925 * @param array $contributionParams
1929 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
1930 if (!empty($contribution->id
)) {
1933 if (empty($contribution->id
)) {
1934 // Unclear why this would only be set for repeats.
1935 if (!empty($input['amount'])) {
1936 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
1938 $templateContribution = civicrm_api3('Contribution', 'getsingle', array(
1939 'contribution_recur_id' => $contributionParams['contribution_recur_id'],
1940 'options' => array('limit' => 1),
1942 $contributionParams['skipLineItem'] = TRUE;
1943 $contributionParams['status_id'] = 'Pending';
1944 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
1945 $contributionParams['contact_id'] = $templateContribution['contact_id'];
1946 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
1947 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
1948 $contribution->id
= $createContribution['id'];
1949 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
1950 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
1956 * Get individual id for onbehalf contribution.
1958 * @param int $contributionId
1960 * @param int $contributorId
1964 * containing organization id and individual id
1966 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1970 if (!$contributionId) {
1974 // fetch contributor id if null
1975 if (!$contributorId) {
1976 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1977 $contributionId, 'contact_id'
1981 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1982 $activityTypeId = array_search('Contribution', $activityTypeIds);
1984 if ($activityTypeId && $contributorId) {
1986 SELECT civicrm_activity_contact.contact_id
1987 FROM civicrm_activity_contact
1988 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1989 WHERE civicrm_activity.activity_type_id = %1
1990 AND civicrm_activity.source_record_id = %2
1991 AND civicrm_activity_contact.record_type_id = %3
1994 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1995 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1998 1 => array($activityTypeId, 'Integer'),
1999 2 => array($contributionId, 'Integer'),
2000 3 => array($sourceID, 'Integer'),
2003 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2005 // for on behalf contribution source is individual and contributor is organization
2006 if ($sourceContactId && $sourceContactId != $contributorId) {
2007 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2008 // get rel type id for employee of relation
2009 foreach ($relationshipTypeIds as $id => $typeVals) {
2010 if ($typeVals['name_a_b'] == 'Employee of') {
2011 $relationshipTypeId = $id;
2016 $rel = new CRM_Contact_DAO_Relationship();
2017 $rel->relationship_type_id
= $relationshipTypeId;
2018 $rel->contact_id_a
= $sourceContactId;
2019 $rel->contact_id_b
= $contributorId;
2020 if ($rel->find(TRUE)) {
2021 $ids['individual_id'] = $rel->contact_id_a
;
2022 $ids['organization_id'] = $rel->contact_id_b
;
2033 public static function getContributionDates() {
2034 $config = CRM_Core_Config
::singleton();
2035 $currentMonth = date('m');
2036 $currentDay = date('d');
2037 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2038 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2039 (int ) $config->fiscalYearStart
['d'] > $currentDay
2042 $year = date('Y') - 1;
2047 $year = array('Y' => $year);
2048 $yearDate = $config->fiscalYearStart
;
2049 $yearDate = array_merge($year, $yearDate);
2050 $yearDate = CRM_Utils_Date
::format($yearDate);
2052 $monthDate = date('Ym') . '01';
2058 'yearDate' => $yearDate,
2059 'monthDate' => $monthDate,
2064 * Load objects relations to contribution object.
2065 * Objects are stored in the $_relatedObjects property
2066 * In the first instance we are just moving functionality from BASEIpn -
2067 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2069 * Note that the unit test for the BaseIPN class tests this function
2071 * @param array $input
2072 * Input as delivered from Payment Processor.
2074 * Ids as Loaded by Payment Processor.
2075 * @param bool $loadAll
2076 * Load all related objects - even where id not passed in? (allows API to call this).
2081 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2083 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2084 if (empty($ids['contact']) && isset($this->contact_id
)) {
2085 $ids['contact'] = $this->contact_id
;
2088 if (empty($this->_component
)) {
2089 if (!empty($ids['event'])) {
2090 $this->_component
= 'event';
2093 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2097 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2098 // refactoring than anything else, and has unit test coverage.
2099 if (empty($this->financial_type_id
)) {
2103 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2108 if (!$paymentProcessorID && $this->contribution_page_id
) {
2109 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2110 $this->contribution_page_id
,
2113 if ($paymentProcessorID) {
2114 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2118 $ids['contributionType'] = $this->financial_type_id
;
2119 $ids['financialType'] = $this->financial_type_id
;
2122 'contact' => 'CRM_Contact_BAO_Contact',
2123 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2124 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2125 'financialType' => 'CRM_Financial_BAO_FinancialType',
2127 foreach ($entities as $entity => $bao) {
2128 if (!empty($ids[$entity])) {
2129 $this->_relatedObjects
[$entity] = new $bao();
2130 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2131 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2132 throw new CRM_Core_Exception($entity . ' could not be loaded');
2137 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2138 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2141 if (!empty($ids['pledge_payment'])) {
2142 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2143 if (empty($paymentID)) {
2146 $payment = new CRM_Pledge_BAO_PledgePayment();
2147 $payment->id
= $paymentID;
2148 if (!$payment->find(TRUE)) {
2149 throw new Exception("Could not find pledge payment record: " . $paymentID);
2151 $this->_relatedObjects
['pledge_payment'][] = $payment;
2155 if ($this->_component
== 'contribute') {
2156 // retrieve the other optional objects first so
2157 // stuff down the line can use this info and do things
2159 //in any case get the memberships associated with the contribution
2160 //because we now support multiple memberships w/ price set
2161 // see if there are any other memberships to be considered for same contribution.
2163 SELECT membership_id
2164 FROM civicrm_membership_payment
2165 WHERE contribution_id = %1 ";
2166 $params = array(1 => array($this->id
, 'Integer'));
2168 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2169 while ($dao->fetch()) {
2170 if ($dao->membership_id
) {
2171 if (!is_array($ids['membership'])) {
2172 $ids['membership'] = array();
2174 $ids['membership'][] = $dao->membership_id
;
2178 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2179 foreach ($ids['membership'] as $id) {
2181 $membership = new CRM_Member_BAO_Membership();
2182 $membership->id
= $id;
2183 if (!$membership->find(TRUE)) {
2184 throw new Exception("Could not find membership record: $id");
2186 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2187 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2188 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2189 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2190 $membership->free();
2196 // we are in event mode
2197 // make sure event exists and is valid
2198 $event = new CRM_Event_BAO_Event();
2199 $event->id
= $ids['event'];
2200 if ($ids['event'] &&
2203 throw new Exception("Could not find event: " . $ids['event']);
2206 $this->_relatedObjects
['event'] = &$event;
2208 $participant = new CRM_Event_BAO_Participant();
2209 $participant->id
= $ids['participant'];
2210 if ($ids['participant'] &&
2211 !$participant->find(TRUE)
2213 throw new Exception("Could not find participant: " . $ids['participant']);
2215 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2217 $this->_relatedObjects
['participant'] = &$participant;
2219 // get the payment processor id from event - this is inaccurate see CRM-16923
2220 // in future we should look at throwing an exception here rather than an dubious guess.
2221 if (!$paymentProcessorID) {
2222 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2223 if ($paymentProcessorID) {
2224 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2229 if ($paymentProcessorID) {
2230 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2231 $this->is_test ?
'test' : 'live'
2233 $ids['paymentProcessor'] = $paymentProcessorID;
2234 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2240 * Create array of message information - ie. return html version, txt version, to field
2242 * @param array $input
2243 * Incoming information.
2244 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2245 * just check presence of recur object but maintaining legacy approach
2248 * IDs of related objects.
2249 * @param array $values
2250 * Any values that may have already been compiled by calling process.
2251 * This is augmented by values 'gathered' by gatherMessageValues
2252 * @param bool $recur
2253 * @param bool $returnMessageText
2254 * Distinguishes between whether to send message or return.
2255 * message text. We are working towards this function ALWAYS returning message text & calling
2256 * function doing emails / pdfs with it
2262 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2263 $this->loadRelatedObjects($input, $ids);
2265 if (empty($this->_component
)) {
2266 $this->_component
= CRM_Utils_Array
::value('component', $input);
2269 //not really sure what params might be passed in but lets merge em into values
2270 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2271 $template = CRM_Core_Smarty
::singleton();
2272 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2273 //what does recur 'mean here - to do with payment processor return functionality but
2274 // what is the importance
2275 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2276 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2278 $entityID = $entity = NULL;
2279 if (isset($ids['contribution'])) {
2280 $entity = 'contribution';
2281 $entityID = $ids['contribution'];
2283 if (!empty($ids['membership'])) {
2284 //not sure whether is is possible for this not to be an array - load related contacts loads an array but this code was expecting a string
2285 // the addition of the casting is in case it could get here & be a string. Added in 4.6 - maybe remove later? This AuthorizeNetIPN & PaypalIPN tests hit this
2286 // line having loaded an array
2287 $ids['membership'] = (array) $ids['membership'];
2288 $entity = 'membership';
2289 $entityID = $ids['membership'][0];
2292 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity));
2293 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2294 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2296 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2297 //direct mode showing billing block, so use directIPN for temporary
2298 $template->assign('contributeMode', 'directIPN');
2301 // todo remove strtolower - check consistency
2302 if (strtolower($this->_component
) == 'event') {
2303 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2304 $values['event'] = array();
2306 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2308 //get location details
2309 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2310 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2312 $ufJoinParams = array(
2313 'entity_table' => 'civicrm_event',
2314 'entity_id' => $ids['event'],
2315 'module' => 'CiviEvent',
2318 list($custom_pre_id,
2320 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2322 $values['custom_pre_id'] = $custom_pre_id;
2323 $values['custom_post_id'] = $custom_post_ids;
2324 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
2325 //and cases involving status updation through ipn
2326 // whatever that means!
2327 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2328 // perhaps we should throw an e-notice if amount is set & force total_amount?
2329 if (!empty($input['amount'])) {
2330 $values['totalAmount'] = $input['amount'];
2333 if ($values['event']['is_email_confirm']) {
2334 $values['is_email_receipt'] = 1;
2336 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2337 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2341 $values['contribution_id'] = $this->id
;
2342 if (!empty($ids['related_contact'])) {
2343 $values['related_contact'] = $ids['related_contact'];
2344 if (isset($ids['onbehalf_dupe_alert'])) {
2345 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2347 $entityBlock = array(
2348 'contact_id' => $ids['contact'],
2349 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2350 'Home', 'id', 'name'
2353 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2354 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2357 if ($this->is_test
) {
2360 if (!empty($this->_relatedObjects
['membership'])) {
2361 foreach ($this->_relatedObjects
['membership'] as $membership) {
2362 if ($membership->id
) {
2363 $values['isMembership'] = TRUE;
2365 // need to set the membership values here
2366 $template->assign('membership_assign', 1);
2367 $template->assign('membership_name',
2368 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2370 $template->assign('mem_start_date', $membership->start_date
);
2371 $template->assign('mem_join_date', $membership->join_date
);
2372 $template->assign('mem_end_date', $membership->end_date
);
2373 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2374 $template->assign('mem_status', $membership_status);
2375 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2376 $template->assign('is_pay_later', 1);
2379 // if separate payment there are two contributions recorded and the
2380 // admin will need to send a receipt for each of them separately.
2381 // we dont link the two in the db (but can potentially infer it if needed)
2382 $template->assign('is_separate_payment', 0);
2384 if ($recur && $paymentObject) {
2385 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2386 $template->assign('cancelSubscriptionUrl', $url);
2387 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2388 $template->assign('updateSubscriptionBillingUrl', $url);
2389 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2390 $template->assign('updateSubscriptionUrl', $url);
2393 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2396 // otherwise if its about sending emails, continue sending without return, as we
2397 // don't want to exit the loop.
2402 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2408 * Gather values for contribution mail - this function has been created
2409 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2410 * Values related to the contribution in question are gathered
2412 * @param array $input
2413 * Input into function (probably from payment processor).
2414 * @param array $values
2416 * The set of ids related to the input.
2420 public function _gatherMessageValues($input, &$values, $ids = array()) {
2421 // set display address of contributor
2422 if ($this->address_id
) {
2423 $addressParams = array('id' => $this->address_id
);
2424 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2425 $addressDetails = array_values($addressDetails);
2426 $values['address'] = $addressDetails[0]['display'];
2428 if ($this->_component
== 'contribute') {
2429 //get soft contributions
2430 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2431 if (!empty($softContributions)) {
2432 $values['softContributions'] = $softContributions['soft_credit'];
2434 if (isset($this->contribution_page_id
)) {
2435 CRM_Contribute_BAO_ContributionPage
::setValues(
2436 $this->contribution_page_id
,
2439 if ($this->contribution_page_id
) {
2440 // CRM-8254 - override default currency if applicable
2441 $config = CRM_Core_Config
::singleton();
2442 $config->defaultCurrency
= CRM_Utils_Array
::value(
2445 $config->defaultCurrency
2449 // no contribution page -probably back office
2451 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2452 $values['is_email_receipt'] = 1;
2453 $values['title'] = 'Contribution';
2455 // set lineItem for contribution
2457 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2458 if (!empty($lineItem)) {
2459 $itemId = key($lineItem);
2460 foreach ($lineItem as &$eachItem) {
2461 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2462 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2463 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2464 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2467 $values['lineItem'][0] = $lineItem;
2468 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2472 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2476 // if this is onbehalf of contribution then set related contact
2477 if (!empty($relatedContact['individual_id'])) {
2478 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2483 $eventParams = array(
2484 'id' => $this->_relatedObjects
['event']->id
,
2486 $values['event'] = array();
2488 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2489 // add custom fields for event
2490 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2492 $eventCustomGroup = array();
2493 foreach ($eventGroupTree as $key => $group) {
2494 if ($key === 'info') {
2498 foreach ($group['fields'] as $k => $customField) {
2499 $groupLabel = $group['title'];
2500 if (!empty($customField['customValue'])) {
2501 foreach ($customField['customValue'] as $customFieldValues) {
2502 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2507 $values['event']['customGroup'] = $eventCustomGroup;
2509 //get participant details
2510 $participantParams = array(
2511 'id' => $this->_relatedObjects
['participant']->id
,
2514 $values['participant'] = array();
2516 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2517 // add custom fields for event
2518 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2519 $participantCustomGroup = array();
2520 foreach ($participantGroupTree as $key => $group) {
2521 if ($key === 'info') {
2525 foreach ($group['fields'] as $k => $customField) {
2526 $groupLabel = $group['title'];
2527 if (!empty($customField['customValue'])) {
2528 foreach ($customField['customValue'] as $customFieldValues) {
2529 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2534 $values['participant']['customGroup'] = $participantCustomGroup;
2536 //get location details
2537 $locationParams = array(
2538 'entity_id' => $this->_relatedObjects
['event']->id
,
2539 'entity_table' => 'civicrm_event',
2541 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2543 $ufJoinParams = array(
2544 'entity_table' => 'civicrm_event',
2545 'entity_id' => $ids['event'],
2546 'module' => 'CiviEvent',
2549 list($custom_pre_id,
2551 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2553 $values['custom_pre_id'] = $custom_pre_id;
2554 $values['custom_post_id'] = $custom_post_ids;
2556 // set lineItem for event contribution
2558 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2559 if (!empty($participantIds)) {
2560 foreach ($participantIds as $pIDs) {
2561 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2562 if (!CRM_Utils_System
::isNull($lineItem)) {
2563 $values['lineItem'][] = $lineItem;
2570 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2572 $customGroup = array();
2573 foreach ($groupTree as $key => $group) {
2574 if ($key === 'info') {
2578 foreach ($group['fields'] as $k => $customField) {
2579 $groupLabel = $group['title'];
2580 if (!empty($customField['customValue'])) {
2581 foreach ($customField['customValue'] as $customFieldValues) {
2582 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2587 $values['customGroup'] = $customGroup;
2593 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2594 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2595 * Note we send directly from this function in some cases because it is only partly refactored
2596 * Don't call this function directly as the signature will change
2600 * @param CRM_Core_SMARTY $template
2601 * @param bool $recur
2602 * @param bool $returnMessageText
2606 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2607 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2608 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2609 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2610 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2611 $template->assign('useForMember', TRUE);
2613 //assign honor information to receipt message
2614 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2616 if (isset($softRecord['soft_credit'])) {
2617 //if id of contribution page is present
2618 if (!empty($values['id'])) {
2619 $values['honor'] = array(
2620 'honor_profile_values' => array(),
2621 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2622 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2624 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2626 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2627 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2630 //offline contribution
2631 $softCreditTypes = $softCredits = array();
2632 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2633 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2634 $softCredits[$key] = array(
2635 'Name' => $softCredit['contact_name'],
2636 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2639 $template->assign('softCreditTypes', $softCreditTypes);
2640 $template->assign('softCredits', $softCredits);
2644 $dao = new CRM_Contribute_DAO_ContributionProduct();
2645 $dao->contribution_id
= $this->id
;
2646 if ($dao->find(TRUE)) {
2647 $premiumId = $dao->product_id
;
2648 $template->assign('option', $dao->product_option
);
2650 $productDAO = new CRM_Contribute_DAO_Product();
2651 $productDAO->id
= $premiumId;
2652 $productDAO->find(TRUE);
2653 $template->assign('selectPremium', TRUE);
2654 $template->assign('product_name', $productDAO->name
);
2655 $template->assign('price', $productDAO->price
);
2656 $template->assign('sku', $productDAO->sku
);
2658 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2659 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2660 if (empty($amount) && isset($this->total_amount
)) {
2661 $amount = $this->total_amount
;
2663 $template->assign('amount', $amount);
2664 // add the new contribution values
2665 if (strtolower($this->_component
) == 'contribute') {
2667 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2668 $softDAO->contribution_id
= $this->id
;
2669 if ($softDAO->find(TRUE)) {
2670 $template->assign('pcpBlock', TRUE);
2671 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2672 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2673 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2675 //assign the pcp page title for email subject
2676 $pcpDAO = new CRM_PCP_DAO_PCP();
2677 $pcpDAO->id
= $softDAO->pcp_id
;
2678 if ($pcpDAO->find(TRUE)) {
2679 $template->assign('title', $pcpDAO->title
);
2684 if ($this->financial_type_id
) {
2685 $values['financial_type_id'] = $this->financial_type_id
;
2688 $template->assign('trxn_id', $this->trxn_id
);
2689 $template->assign('receive_date',
2690 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2692 $template->assign('contributeMode', 'notify');
2693 $template->assign('action', $this->is_test ?
1024 : 1);
2694 $template->assign('receipt_text',
2695 CRM_Utils_Array
::value('receipt_text',
2699 $template->assign('is_monetary', 1);
2700 $template->assign('is_recur', (bool) $recur);
2701 $template->assign('currency', $this->currency
);
2702 $template->assign('address', CRM_Utils_Address
::format($input));
2703 if (!empty($values['customGroup'])) {
2704 $template->assign('customGroup', $values['customGroup']);
2706 if (!empty($values['softContributions'])) {
2707 $template->assign('softContributions', $values['softContributions']);
2709 if ($this->_component
== 'event') {
2710 $template->assign('title', $values['event']['title']);
2711 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2712 $viewRoles = array();
2713 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2714 $viewRoles[] = $participantRoles[$v];
2716 $values['event']['participant_role'] = implode(', ', $viewRoles);
2717 $template->assign('event', $values['event']);
2718 $template->assign('participant', $values['participant']);
2719 $template->assign('location', $values['location']);
2720 $template->assign('customPre', $values['custom_pre_id']);
2721 $template->assign('customPost', $values['custom_post_id']);
2724 if ($this->_relatedObjects
['participant']->is_test
) {
2728 $values['params'] = array();
2729 //to get email of primary participant.
2730 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2731 $primaryAmount[] = array(
2732 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2733 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2735 //build an array of cId/pId of participants
2736 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2737 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2738 //send receipt to additional participant if exists
2739 if (count($additionalIDs)) {
2740 $template->assign('isPrimary', 0);
2741 $template->assign('customProfile', NULL);
2742 //set additionalParticipant true
2743 $values['params']['additionalParticipant'] = TRUE;
2744 foreach ($additionalIDs as $pId => $cId) {
2746 //to change the status pending to completed
2747 $additional = new CRM_Event_DAO_Participant();
2748 $additional->id
= $pId;
2749 $additional->contact_id
= $cId;
2750 $additional->find(TRUE);
2751 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2752 $additional->status_id
= 1;
2753 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2754 //if additional participant dont have email
2756 if (!$additionalParticipantInfo) {
2757 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2759 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2760 $primaryAmount[] = array(
2761 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2762 'amount' => $additional->fee_amount
,
2764 $additional->save();
2765 $additional->free();
2766 $template->assign('amount', $amount);
2767 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2771 //build an array of custom profile and assigning it to template
2772 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2774 if (count($customProfile)) {
2775 $template->assign('customProfile', $customProfile);
2778 // for primary contact
2779 $values['params']['additionalParticipant'] = FALSE;
2780 $template->assign('isPrimary', 1);
2781 $template->assign('amount', $primaryAmount);
2782 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2783 if ($this->payment_instrument_id
) {
2784 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2785 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2787 // carry paylater, since we did not created billing,
2788 // so need to pull email from primary location, CRM-4395
2789 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2795 * Check whether payment processor supports
2796 * cancellation of contribution subscription
2798 * @param int $contributionId
2801 * @param bool $isNotCancelled
2805 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2806 $cacheKeyString = "$contributionId";
2807 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2809 static $supportsCancel = array();
2811 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2812 $supportsCancel[$cacheKeyString] = FALSE;
2813 $isCancelled = FALSE;
2815 if ($isNotCancelled) {
2816 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2819 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2820 if (!empty($paymentObject)) {
2821 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2824 return $supportsCancel[$cacheKeyString];
2828 * Check whether subscription is already cancelled.
2830 * @param int $contributionId
2834 * contribution status
2836 public static function isSubscriptionCancelled($contributionId) {
2838 SELECT cr.contribution_status_id
2839 FROM civicrm_contribution_recur cr
2840 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2841 WHERE con.id = %1 LIMIT 1";
2842 $params = array(1 => array($contributionId, 'Integer'));
2843 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2844 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2845 if ($status == 'Cancelled') {
2852 * Create all financial accounts entry.
2854 * @param array $params
2855 * Contribution object, line item array and params for trxn.
2858 * @param array $financialTrxnValues
2860 * @return null|object
2862 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2863 $skipRecords = $update = $return = $isRelatedId = FALSE;
2865 $additionalParticipantId = array();
2866 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2868 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2869 $entityId = $params['participant_id'];
2870 $entityTable = 'civicrm_participant';
2871 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2873 elseif (!empty($params['membership_id'])) {
2874 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2875 // are created off one contribution should be handled elsewhere
2876 $entityId = $params['membership_id'];
2877 $entityTable = 'civicrm_membership';
2880 $entityId = $params['contribution']->id
;
2881 $entityTable = 'civicrm_contribution';
2884 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2885 $isRelatedId = TRUE;
2888 $entityID[] = $entityId;
2889 if (!empty($additionalParticipantId)) {
2890 $entityID +
= $additionalParticipantId;
2892 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2893 if (empty($params['prevContribution'])) {
2900 $statusId = $params['contribution']->contribution_status_id
;
2901 // CRM-13964 partial payment
2902 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2903 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2905 $partialAmtPay = $params['partial_amount_pay'];
2906 $partialAmtTotal = $params['partial_payment_total'];
2908 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2909 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2910 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2911 $params['total_amount'] = $partialAmtPay;
2913 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2914 if (empty($balanceTrxnInfo['trxn_id'])) {
2915 // create new balance transaction record
2916 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2917 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2919 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2920 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2921 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2922 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2923 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2924 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2925 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2926 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2927 $balanceTrxnParams['status_id'] = $statusId;
2928 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2929 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2930 if (!empty($params['payment_processor'])) {
2931 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2933 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2937 // build line item array if its not set in $params
2938 if (empty($params['line_item']) ||
$additionalParticipantId) {
2939 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2942 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2943 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2945 $skipRecords = TRUE;
2946 $pendingStatus = array(
2947 array_search('Pending', $contributionStatuses),
2948 array_search('In Progress', $contributionStatuses),
2950 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2951 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2952 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2954 elseif (!empty($params['payment_processor'])) {
2955 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2957 elseif (!empty($params['payment_instrument_id'])) {
2958 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2961 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2962 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2963 $params['to_financial_account_id'] = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
2966 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2967 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2968 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2971 //build financial transaction params
2972 $trxnParams = array(
2973 'contribution_id' => $params['contribution']->id
,
2974 'to_financial_account_id' => $params['to_financial_account_id'],
2975 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2976 'total_amount' => $totalAmount,
2977 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2978 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2979 'currency' => $params['contribution']->currency
,
2980 'trxn_id' => $params['contribution']->trxn_id
,
2981 'status_id' => $statusId,
2982 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2983 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2986 if (!empty($params['payment_processor'])) {
2987 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2990 if (isset($fromFinancialAccountId)) {
2991 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2994 // consider external values passed for recording transaction entry
2995 if (!empty($financialTrxnValues)) {
2996 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2999 $params['trxnParams'] = $trxnParams;
3001 if (!empty($params['prevContribution'])) {
3002 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3003 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3004 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3005 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3006 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3008 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3009 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3010 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3012 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3013 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3016 //if financial type is changed
3017 if (!empty($params['financial_type_id']) &&
3018 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3020 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3021 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3022 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3023 if ($oldFinancialAccount != $newFinancialAccount) {
3024 $params['total_amount'] = 0;
3025 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3026 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3027 $params['prevContribution']->financial_type_id
, $relationTypeId);
3030 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3031 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3032 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3035 self
::updateFinancialAccounts($params, 'changeFinancialType');
3036 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3037 $params['financial_account_id'] = $newFinancialAccount;
3038 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3039 self
::updateFinancialAccounts($params);
3040 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3044 //Update contribution status
3045 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3046 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3047 if (!empty($params['contribution_status_id']) &&
3048 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3050 //Update Financial Records
3051 self
::updateFinancialAccounts($params, 'changedStatus');
3054 // change Payment Instrument for a Completed contribution
3055 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3056 // instrument is null and now new payment instrument is added along with the payment
3057 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3058 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3059 if (array_key_exists('payment_instrument_id', $params)) {
3060 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3061 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3062 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3064 //check if status is changed from Pending to Completed
3065 // do not update payment instrument changes for Pending to Completed
3066 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3067 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3069 // for all other statuses create new financial records
3070 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3071 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3072 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3075 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3076 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3077 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3079 // for any other payment instrument changes create new financial records
3080 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3081 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3082 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3084 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3085 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3087 // another special case when check number is changed, create new financial records
3088 // create financial trxn with negative amount
3089 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3090 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3091 // create financial trxn with positive amount
3092 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3093 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3094 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3098 //if Change contribution amount
3099 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3100 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3101 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3102 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3103 if (isset($totalAmount) &&
3104 $totalAmount != $params['prevContribution']->total_amount
3106 //Update Financial Records
3107 $params['trxnParams']['from_financial_account_id'] = NULL;
3108 self
::updateFinancialAccounts($params, 'changedAmount');
3113 // records finanical trxn and entity financial trxn
3114 // also make it available as return value
3115 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3116 $params['entity_id'] = $financialTxn->id
;
3119 // record line items and financial items
3120 if (empty($params['skipLineItem'])) {
3121 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3124 // create batch entry if batch_id is passed and
3125 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3126 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3127 $entityParams = array(
3128 'batch_id' => $params['batch_id'],
3129 'entity_table' => 'civicrm_financial_trxn',
3130 'entity_id' => $financialTxn->id
,
3132 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3135 // when a fee is charged
3136 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3137 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3140 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3141 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3143 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3144 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3145 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3147 unset($params['line_item']);
3153 * Update all financial accounts entry.
3155 * @param array $params
3156 * Contribution object, line item array and params for trxn.
3158 * @param string $context
3161 * @param null $skipTrxn
3164 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3165 $itemAmount = $trxnID = NULL;
3166 //get all the statuses
3167 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3168 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3169 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3170 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3171 && $context == 'changePaymentInstrument'
3175 if (($params['prevContribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus))
3176 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3177 && $context == 'changedStatus'
3181 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3182 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3184 if ($context == 'changedStatus') {
3185 //get all the statuses
3186 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3188 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3189 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3190 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3192 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3194 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3195 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3197 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3198 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3199 $params['trxnParams']['to_financial_account_id'] = NULL;
3200 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3202 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3203 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3204 $financialTypeID, $relationTypeId);
3206 $itemAmount = $params['trxnParams']['total_amount'];
3208 elseif ($context == 'changePaymentInstrument') {
3209 if ($params['trxnParams']['total_amount'] < 0) {
3210 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3211 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3212 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3213 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3217 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3218 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3221 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3222 $params['entity_id'] = $trxn->id
;
3224 if ($context == 'changedStatus') {
3225 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3226 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3227 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3229 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3230 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3232 $entityParams = array(
3233 'entity_table' => 'civicrm_financial_item',
3234 'financial_trxn_id' => $trxn->id
,
3236 if (empty($params['line_item'])) {
3238 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3239 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3240 // & this can be removed
3243 foreach ($params['line_item'] as $fieldId => $fields) {
3244 foreach ($fields as $fieldValueId => $fieldValues) {
3246 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3247 2 => array($fieldValues['id'], 'Integer'),
3249 CRM_Core_DAO
::executeQuery($query, $fparams);
3251 1 => array($fieldValues['id'], 'Integer'),
3253 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3254 while ($financialItem->fetch()) {
3255 $entityParams['entity_id'] = $financialItem->id
;
3256 $entityParams['amount'] = $financialItem->amount
;
3257 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3264 if ($context != 'changePaymentInstrument') {
3265 $itemParams['entity_table'] = 'civicrm_line_item';
3266 $trxnIds['id'] = $params['entity_id'];
3267 foreach ($params['line_item'] as $fieldId => $fields) {
3268 foreach ($fields as $fieldValueId => $fieldValues) {
3269 $prevParams['entity_id'] = $fieldValues['id'];
3270 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3272 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3273 if ($params['contribution']->receive_date
) {
3274 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3277 $financialAccount = $prevfinancialItem->financial_account_id
;
3278 if (!empty($params['financial_account_id'])) {
3279 $financialAccount = $params['financial_account_id'];
3282 $currency = $params['prevContribution']->currency
;
3283 if ($params['contribution']->currency
) {
3284 $currency = $params['contribution']->currency
;
3287 if (!empty($params['is_quick_config'])) {
3288 $amount = $itemAmount;
3290 $amount = $params['total_amount'];
3294 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3295 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3299 $amount = $diff * $fieldValues['line_total'];
3302 $itemParams = array(
3303 'transaction_date' => $receiveDate,
3304 'contact_id' => $params['prevContribution']->contact_id
,
3305 'currency' => $currency,
3306 'amount' => $amount,
3307 'description' => $prevfinancialItem->description
,
3308 'status_id' => $prevfinancialItem->status_id
,
3309 'financial_account_id' => $financialAccount,
3310 'entity_table' => 'civicrm_line_item',
3311 'entity_id' => $fieldValues['id'],
3313 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3315 if ($fieldValues['tax_amount']) {
3316 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3317 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3318 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3319 $itemParams['description'] = $taxTerm;
3320 if ($fieldValues['financial_type_id']) {
3321 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3323 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3328 if ($context == 'changeFinancialType') {
3329 $params['skipLineItem'] = FALSE;
3330 foreach ($params['line_item'] as &$lineItems) {
3331 foreach ($lineItems as &$line) {
3332 $line['financial_type_id'] = $params['financial_type_id'];
3339 * Check status validation on update of a contribution.
3341 * @param array $values
3342 * Previous form values before submit.
3344 * @param array $fields
3345 * The input form values.
3347 * @param array $errors
3352 public static function checkStatusValidation($values, &$fields, &$errors) {
3353 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3354 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3355 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3359 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3360 $checkStatus = array(
3361 'Cancelled' => array('Completed', 'Refunded'),
3362 'Completed' => array('Cancelled', 'Refunded'),
3363 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3364 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3365 'Refunded' => array('Cancelled', 'Completed'),
3366 'Partially paid' => array('Completed'),
3369 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3370 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3371 1 => $contributionStatuses[$values['contribution_status_id']],
3372 2 => $contributionStatuses[$fields['contribution_status_id']],
3378 * Delete contribution of contact.
3382 * @param int $contactId
3386 public static function deleteContactContribution($contactId) {
3387 $contribution = new CRM_Contribute_DAO_Contribution();
3388 $contribution->contact_id
= $contactId;
3389 $contribution->find();
3390 while ($contribution->fetch()) {
3391 self
::deleteContribution($contribution->id
);
3396 * Get options for a given contribution field.
3397 * @see CRM_Core_DAO::buildOptions
3399 * @param string $fieldName
3400 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3401 * @param array $props whatever is known about this dao object.
3403 * @return array|bool
3405 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3406 $className = __CLASS__
;
3408 switch ($fieldName) {
3409 // This field is not part of this object but the api supports it
3410 case 'payment_processor':
3411 $className = 'CRM_Contribute_BAO_ContributionPage';
3412 // Filter results by contribution page
3413 if (!empty($props['contribution_page_id'])) {
3414 $page = civicrm_api('contribution_page', 'getsingle', array(
3416 'id' => ($props['contribution_page_id']),
3418 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3419 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3423 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3424 case 'honor_type_id':
3425 $className = 'CRM_Contribute_BAO_ContributionSoft';
3426 $fieldName = 'soft_credit_type_id';
3427 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3430 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3434 * Validate financial type.
3438 * @param int $financialTypeId
3439 * Financial Type id.
3441 * @param string $relationName
3443 * @return array|bool
3445 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3446 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3447 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3449 if (!$financialAccount) {
3450 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3457 * Function to record additional payment for partial and refund contributions.
3459 * @param int $contributionId
3460 * is the invoice contribution id (got created after processing participant payment).
3461 * @param array $trxnsData
3462 * to take user provided input of transaction details.
3463 * @param string $paymentType
3464 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3465 * @param int $participantId
3467 * @return null|object
3469 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3470 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3471 $getInfoOf['id'] = $contributionId;
3472 $defaults = array();
3473 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3475 if ($paymentType == 'owed') {
3476 // build params for recording financial trxn entry
3477 $params['contribution'] = $contributionDAO;
3478 $params = array_merge($defaults, $params);
3479 $params['skipLineItem'] = TRUE;
3480 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3481 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3482 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3483 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3486 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3487 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3488 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3490 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3491 if (!empty($trxnId)) {
3492 $trxnId = $trxnId['trxn_id'];
3494 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3495 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3498 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3499 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3500 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3504 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3505 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3506 FROM civicrm_financial_trxn ft
3507 LEFT JOIN civicrm_entity_financial_trxn eft
3508 ON (ft.id = eft.financial_trxn_id)
3509 WHERE eft.entity_table = 'civicrm_contribution'
3510 AND eft.entity_id = {$contributionId}
3511 AND ft.to_financial_account_id != {$toFinancialAccount}
3512 AND ft.status_id = {$statusId}
3514 $query = CRM_Core_DAO
::executeQuery($sql);
3516 $sumOfPayments = $query->sum_of_payments
;
3519 if ($contributionDAO->total_amount
== $sumOfPayments) {
3520 // update contribution status and
3521 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3522 $contributionDAO->contribution_status_id
= $statusId;
3523 $contributionDAO->cancel_date
= 'null';
3524 $contributionDAO->cancel_reason
= NULL;
3525 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3526 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3527 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3528 $contributionDAO->save();
3530 //Change status of financial record too
3531 $financialTrxn->status_id
= $statusId;
3532 $financialTrxn->save();
3534 // note : not using the self::add method,
3535 // the reason because it performs 'status change' related code execution for financial records
3536 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3537 // are coded below i.e. just updating financial_item status to 'Paid'
3539 if ($participantId) {
3540 // update participant status
3541 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3542 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3543 foreach ($ids as $val) {
3544 $participantUpdate['id'] = $val;
3545 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3546 CRM_Event_BAO_Participant
::add($participantUpdate);
3550 // update financial item statuses
3551 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3552 $paidStatus = array_search('Paid', $financialItemStatus);
3554 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3555 $sqlFinancialItemUpdate = "
3556 UPDATE civicrm_financial_item fi
3557 LEFT JOIN civicrm_entity_financial_trxn eft
3558 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3559 SET status_id = {$paidStatus}
3560 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3562 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3565 elseif ($paymentType == 'refund') {
3566 // build params for recording financial trxn entry
3567 $params['contribution'] = $contributionDAO;
3568 $params = array_merge($defaults, $params);
3569 $params['skipLineItem'] = TRUE;
3570 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3571 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3573 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3574 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3575 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3577 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3579 // note : not using the self::add method,
3580 // the reason because it performs 'status change' related code execution for financial records
3581 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3582 // are coded below i.e. just updating financial_item status to 'Paid'
3583 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3585 // add financial item entry
3586 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3587 $getLine['entity_id'] = $contributionDAO->id
;
3588 $getLine['entity_table'] = 'civicrm_contribution';
3589 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3590 if (!empty($lineItemId->id
)) {
3591 $addFinancialEntry = array(
3592 'transaction_date' => $financialTrxn->trxn_date
,
3593 'contact_id' => $contributionDAO->contact_id
,
3594 'amount' => $financialTrxn->total_amount
,
3595 'status_id' => array_search('Paid', $financialItemStatus),
3596 'entity_id' => $lineItemId->id
,
3597 'entity_table' => 'civicrm_line_item',
3599 $trxnIds['id'] = $financialTrxn->id
;
3600 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3602 if ($participantId) {
3603 // update participant status
3604 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3605 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3606 foreach ($ids as $val) {
3607 $participantUpdate['id'] = $val;
3608 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3609 CRM_Event_BAO_Participant
::add($participantUpdate);
3614 // activity creation
3615 if (!empty($financialTrxn)) {
3616 if ($participantId) {
3617 $inputParams['id'] = $participantId;
3620 $component = 'event';
3621 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3622 $entityObj = $entityObj[$participantId];
3624 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3626 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3628 return $financialTrxn;
3634 * @param $activityType
3636 * @param int $contributionId
3638 * @throws CRM_Core_Exception
3640 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3641 if ($component == 'event') {
3642 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3643 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3644 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3645 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3646 $targetCid = $entityObj->contact_id
;
3647 // source record id would be the contribution id
3648 $srcRecId = $contributionId;
3652 $activityParams = array(
3653 'source_contact_id' => $targetCid,
3654 'source_record_id' => $srcRecId,
3655 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3659 'subject' => $subject,
3660 'activity_date_time' => $date,
3661 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3665 'skipRecentView' => TRUE,
3668 // create activity with target contacts
3669 $session = CRM_Core_Session
::singleton();
3670 $id = $session->get('userID');
3672 $activityParams['source_contact_id'] = $id;
3673 $activityParams['target_contact_id'][] = $targetCid;
3675 CRM_Activity_BAO_Activity
::create($activityParams);
3679 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3683 * @param bool $getTrxnInfo
3684 * @param bool $usingLineTotal
3688 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3689 if ($component == 'event') {
3690 $entity = 'participant';
3691 $entityTable = 'civicrm_participant';
3692 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3694 if (!$contributionId) {
3695 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3696 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3697 $id = $primaryParticipantId;
3699 if (!$contributionId) {
3704 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3705 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3711 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3712 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3715 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3716 // for additional participants
3717 if ($entityTable == 'civicrm_participant') {
3718 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3720 foreach ($ids as $val) {
3721 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3725 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3729 $baseTrxnId = $total['trxn_id'];
3730 $total = $total['total_amount'];
3733 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3734 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3736 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3737 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3738 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3740 if ($paymentBalance == 0 && $contributionIsPayLater) {
3741 $paymentBalance = $total;
3744 $info['total'] = $total;
3745 $info['paid'] = $total - $paymentBalance;
3746 $info['balance'] = $paymentBalance;
3748 $info['component'] = $component;
3749 $info['payLater'] = $contributionIsPayLater;
3751 if ($getTrxnInfo && $baseTrxnId) {
3752 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3754 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3755 FROM civicrm_contribution con
3756 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3757 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3758 WHERE con.id = {$contributionId}
3761 // conditioned WHERE clause
3763 // if balance trxn exists don't include details of it in transaction info
3764 $sql .= " AND ft.id != {$baseTrxnId} ";
3766 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3768 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3769 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3770 while ($resultDAO->fetch()) {
3771 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3772 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3774 'total_amount' => $resultDAO->total_amount
,
3775 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3776 'payment_instrument' => $paidByLabel,
3777 'receive_date' => $resultDAO->trxn_date
,
3778 'trxn_id' => $resultDAO->trxn_id
,
3779 'status' => $statuses[$resultDAO->status_id
],
3781 if ($paidByName == 'Check') {
3782 $val['check_number'] = $resultDAO->check_number
;
3786 $info['transaction'] = $rows;
3792 * Get financial account id has 'Sales Tax Account is'
3793 * account relationship with financial type
3795 * @param int $financialTypeId
3797 * @return FinancialAccountId
3799 public static function getFinancialAccountId($financialTypeId) {
3800 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3801 $searchParams = array(
3802 'entity_table' => 'civicrm_financial_type',
3803 'entity_id' => $financialTypeId,
3804 'account_relationship' => $accountRel,
3807 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3809 return CRM_Utils_Array
::value('financial_account_id', $result);
3815 * @param array $params
3816 * @param bool $isLineItem
3820 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3821 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3823 // Update contribution.
3824 if (!empty($params['id'])) {
3825 $id = $params['id'];
3826 $values = $ids = array();
3827 $contrbutionParams = array('id' => $id);
3828 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3830 // To assign pervious finantial type on update of contribution
3831 if (!isset($params['financial_type_id'])) {
3832 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3834 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3835 // Assisn tax Amount on update of contrbution
3836 if (!empty($prevContributionValue->tax_amount
)) {
3837 $params['tax_amount'] = 'null';
3838 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3839 foreach ($params['line_item'] as $setID => $priceField) {
3840 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3841 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3848 // New Contrbution and update of contribution with tax rate financial type
3849 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3850 empty($params['skipLineItem']) && !$isLineItem
3852 $taxRateParams = $taxRates[$params['financial_type_id']];
3853 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3854 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3856 // Get Line Item on update of contribution
3857 if (isset($params['id'])) {
3858 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3861 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3863 foreach ($params['line_item'] as $setID => $priceField) {
3864 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3865 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3868 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3870 elseif (isset($params['api.line_item.create'])) {
3871 // Update total amount of contribution using lineItem
3872 $taxAmountArray = array();
3873 foreach ($params['api.line_item.create'] as $key => $value) {
3874 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3875 $taxRate = $taxRates[$value['financial_type_id']];
3876 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3877 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3880 $params['tax_amount'] = array_sum($taxAmountArray);
3881 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3884 // update line item of contrbution
3885 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3886 $taxRate = $taxRates[$params['financial_type_id']];
3887 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3888 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3895 * Check financial type validation on update of a contribution.
3897 * @param Integer $financialTypeId
3898 * Value of latest Financial Type.
3900 * @param Integer $contributionId
3903 * @param array $errors
3908 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3909 if (!empty($financialTypeId)) {
3910 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3911 if ($oldFinancialTypeId == $financialTypeId) {
3915 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3917 '1' => array($contributionId, 'Integer'),
3919 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3920 if ($result->N
> 1) {
3921 $errors['financial_type_id'] = ts('One or more line items have a different financial type than the contribution. Editing the financial type is not yet supported in this situation.');
3926 * Update related pledge payment payments.
3928 * This function has been refactored out of the back office contribution form and may
3929 * still overlap with other functions.
3931 * @param string $action
3932 * @param int $pledgePaymentID
3933 * @param int $contributionID
3934 * @param bool $adjustTotalAmount
3935 * @param float $total_amount
3936 * @param float $original_total_amount
3937 * @param int $contribution_status_id
3938 * @param int $original_contribution_status_id
3940 public static function updateRelatedPledge(
3946 $original_total_amount,
3947 $contribution_status_id,
3948 $original_contribution_status_id
3950 if (!$pledgePaymentID ||
$action & CRM_Core_Action
::ADD
&& !$contributionID) {
3954 if ($pledgePaymentID) {
3955 //store contribution id in payment record.
3956 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
3959 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3965 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3971 $updatePledgePaymentStatus = FALSE;
3973 // If either the status or the amount has changed we update the pledge status.
3974 if ($action & CRM_Core_Action
::ADD
) {
3975 $updatePledgePaymentStatus = TRUE;
3977 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
3978 ($original_total_amount != $total_amount))
3980 $updatePledgePaymentStatus = TRUE;
3983 if ($updatePledgePaymentStatus) {
3984 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
3985 array($pledgePaymentID),
3986 $contribution_status_id,
3995 * Compute the stats values
3997 * @param $stat either 'mode' or 'median'
3999 * @param $alias of civicrm_contribution
4001 public static function computeStats($stat, $sql, $alias = NULL) {
4002 $mode = $median = array();
4005 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4006 while ($modeDAO->fetch()) {
4007 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4008 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4017 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4018 foreach ($currencies as $currency => $val) {
4020 $where = "AND {$alias}.currency = '{$currency}'";
4021 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4025 $medianRow = floor($rowCount / 2);
4026 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4032 $medianValue = "SELECT {$alias}.total_amount as median
4034 ORDER BY median LIMIT {$medianRow},{$offset}";
4035 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4036 while ($medianValDAO->fetch()) {
4038 $midValue = $midValue +
$medianValDAO->median
;
4041 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4045 $midValue = $midValue / 2;
4046 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4057 * Complete an order.
4059 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4061 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4063 * Moving it out of the BaseIPN class is just the first step.
4065 * @param array $input
4067 * @param array $objects
4068 * @param CRM_Core_Transaction $transaction
4070 * @param CRM_Contribute_BAO_Contribution $contribution
4071 * @param bool $isRecurring
4072 * Duplication of param needs review. Only used by AuthorizeNetIPN
4073 * @param int $isFirstOrLastRecurringPayment
4074 * Deprecated param only used by AuthorizeNetIPN.
4076 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4077 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4078 // The previous details are used when calculating line items so keep it before any code that 'does something'
4079 if (!empty($contribution->id
)) {
4080 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4081 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4083 $inputContributionWhiteList = array(
4088 'payment_instrument_id',
4094 $contributionParams = array_merge(array(
4095 'contribution_status_id' => 'Completed',
4096 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4099 $participant = CRM_Utils_Array
::value('participant', $objects);
4100 $memberships = CRM_Utils_Array
::value('membership', $objects);
4101 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4102 if (!empty($recurContrib->id
)) {
4103 $contributionParams['contribution_recur_id'] = $recurContrib->id
;
4105 self
::repeatTransaction($contribution, $input, $contributionParams);
4107 if (is_numeric($memberships)) {
4108 $memberships = array($objects['membership']);
4111 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4114 if (isset($input['is_email_receipt'])) {
4115 $values['is_email_receipt'] = $input['is_email_receipt'];
4118 if ($input['component'] == 'contribute') {
4119 if ($contribution->contribution_page_id
) {
4120 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4121 $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
4123 elseif ($recurContrib && $recurContrib->id
) {
4124 $contributionParams['contribution_page_id'] = NULL;
4125 $values['amount'] = $recurContrib->amount
;
4126 $values['financial_type_id'] = $objects['contributionType']->id
;
4127 $values['title'] = $source = ts('Offline Recurring Contribution');
4128 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
4129 $values['receipt_from_name'] = $domainValues[0];
4130 $values['receipt_from_email'] = $domainValues[1];
4133 if (empty($contributionParams['receive_date']) && $changeDate) {
4134 $contributionParams['receive_date'] = $changeDate;
4137 if ($recurContrib && $recurContrib->id
&& !isset($input['is_email_receipt'])) {
4138 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4139 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4140 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4143 if (!empty($values['is_email_receipt'])) {
4144 $contributionParams['receipt_date'] = $changeDate;
4147 if (!empty($memberships)) {
4148 foreach ($memberships as $membershipTypeIdKey => $membership) {
4150 $membershipParams = array(
4151 'id' => $membership->id
,
4152 'contact_id' => $membership->contact_id
,
4153 'is_test' => $membership->is_test
,
4154 'membership_type_id' => $membership->membership_type_id
,
4157 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4158 $membershipParams['membership_type_id'],
4159 $membershipParams['is_test'],
4160 $membershipParams['id']
4163 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4164 // this picks up membership type changes during renewals
4166 SELECT membership_type_id
4167 FROM civicrm_membership_log
4168 WHERE membership_id={$membershipParams['id']}
4171 $dao = CRM_Core_DAO
::executeQuery($sql);
4172 if ($dao->fetch()) {
4173 if (!empty($dao->membership_type_id
)) {
4174 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4179 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4180 $membershipParams['membership_type_id'],
4181 $primaryContributionID
4183 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4184 if ($currentMembership) {
4186 * Fixed FOR CRM-4433
4187 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4188 * when Contribution mode is notify and membership is for renewal )
4190 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4192 // @todo - we should pass membership_type_id instead of null here but not
4193 // adding as not sure of testing
4194 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4195 $changeDate, NULL, $membershipParams['num_terms']
4198 $dates['join_date'] = $currentMembership['join_date'];
4201 //get the status for membership.
4202 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4204 $dates['join_date'],
4207 $membershipParams['membership_type_id'],
4211 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4212 //we might be renewing membership,
4213 //so make status override false.
4214 $membershipParams['is_override'] = FALSE;
4215 civicrm_api3('Membership', 'create', $membershipParams);
4217 //update related Memberships.
4218 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $membershipParams);
4224 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4225 $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id
));
4226 $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
4227 if ($eventDetail['is_email_confirm']) {
4228 // @todo this should be set by the function that sends the mail after sending.
4229 $contributionParams['receipt_date'] = $changeDate;
4231 $participantParams['id'] = $participant->id
;
4232 $participantParams['status_id'] = 'Registered';
4233 civicrm_api3('Participant', 'create', $participantParams);
4237 $contributionParams['id'] = $contribution->id
;
4239 civicrm_api3('Contribution', 'create', $contributionParams);
4241 // Add new soft credit against current $contribution.
4242 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4243 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4246 $paymentProcessorId = '';
4247 if (isset($objects['paymentProcessor'])) {
4248 if (is_array($objects['paymentProcessor'])) {
4249 $paymentProcessorId = $objects['paymentProcessor']['id'];
4252 $paymentProcessorId = $objects['paymentProcessor']->id
;
4256 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4257 'labelColumn' => 'name',
4260 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4261 $input['payment_processor'] = $paymentProcessorId;
4263 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4264 $input['total_amount'] = $input['amount'];
4265 $input['contribution'] = $contribution;
4266 $input['financial_type_id'] = $contribution->financial_type_id
;
4268 if (!empty($contribution->_relatedObjects
['participant'])) {
4269 $input['contribution_mode'] = 'participant';
4270 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4271 $input['skipLineItem'] = 1;
4273 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4274 $input['skipLineItem'] = TRUE;
4275 $input['contribution_mode'] = 'membership';
4277 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4278 // and subsequent payments. In this case the line items are created at
4279 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4280 // and since the contribution is saved prior to this line there is always a contribution-id,
4281 // however there is never a prevContribution (which appears to mean original contribution not previous
4282 // contribution - or preUpdateContributionObject most accurately)
4283 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4284 // to mean "are we updating an exisitng pending contribution"
4285 //I was able to make the unit test complete as fataling here doesn't prevent
4286 // the contribution being created - but activities would not be created or emails sent
4288 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4290 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4291 $transaction->commit();
4293 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution);
4295 // create an activity record
4296 if ($input['component'] == 'contribute') {
4298 $targetContactID = NULL;
4299 if (!empty($ids['related_contact'])) {
4300 $targetContactID = $contribution->contact_id
;
4301 $contribution->contact_id
= $ids['related_contact'];
4303 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4307 CRM_Activity_BAO_Activity
::addActivity($participant);
4310 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4311 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4312 if (!array_key_exists('is_email_receipt', $values) ||
4313 $values['is_email_receipt'] == 1
4315 self
::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
4316 CRM_Core_Error
::debug_log_message("Receipt sent");
4319 CRM_Core_Error
::debug_log_message("Success: Database updated");
4321 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4322 $isFirstOrLastRecurringPayment);
4327 * Send receipt from contribution.
4329 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4331 * Note that the compose message part has been moved to contribution
4332 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4334 * @param array $input
4335 * Incoming data from Payment processor.
4337 * Related object IDs.
4338 * @param CRM_Contribute_BAO_Contribution $contribution
4339 * @param array $values
4340 * Values related to objects that have already been loaded.
4341 * @param bool $recur
4342 * Is it part of a recurring contribution.
4343 * @param bool $returnMessageText
4344 * Should text be returned instead of sent. This.
4345 * is because the function is also used to generate pdfs
4349 public static function sendMail(&$input, &$ids, $contribution, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4350 $input['is_recur'] = $recur;
4351 // set receipt from e-mail and name in value
4352 if (!$returnMessageText) {
4353 $session = CRM_Core_Session
::singleton();
4354 $userID = $session->get('userID');
4355 if (!empty($userID)) {
4356 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4357 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4358 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4361 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);