3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 * Static field to hold financial trxn id's.
54 static $_trxnIDs = NULL;
57 * Field for all the objects related to this contribution
58 * @var array of objects (e.g membership object, participant object)
60 public $_relatedObjects = array();
63 * Field for the component - either 'event' (participant) or 'contribute'
64 * (any item related to a contribution page e.g. membership, pledge, contribution)
65 * This is used for composing messages because they have dependency on the
66 * contribution_page or event page - although over time we may eliminate that
68 * @var string component or event
70 public $_component = NULL;
73 * Possibly obsolete variable.
75 * If you use it please explain why it is set in the create function here.
79 public $trxn_result_code;
84 public function __construct() {
85 parent
::__construct();
89 * Takes an associative array and creates a contribution object.
91 * the function extract all the params it needs to initialize the create a
92 * contribution object. the params array could contain additional unused name/value
95 * @param array $params
96 * (reference ) an assoc array of name/value pairs.
98 * The array that holds all the db ids.
100 * @return \CRM_Contribute_BAO_Contribution
101 * @throws \CRM_Core_Exception
103 public static function add(&$params, $ids = array()) {
104 if (empty($params)) {
107 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
108 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
109 $duplicates = array();
110 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
111 $message = ts("Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: " . implode(', ', $duplicates));
112 throw new CRM_Core_Exception($message);
115 // first clean up all the money fields
116 $moneyFields = array(
120 'non_deductible_amount',
123 //if priceset is used, no need to cleanup money
124 if (!empty($params['skipCleanMoney'])) {
128 // @todo put a deprecated here - this should be done in the form layer.
129 $params['skipCleanMoney'] = FALSE;
130 Civi
::log()->warning('Deprecated code path. Money should always be clean before it hits the BAO.', array('civi.tag' => 'deprecated'));
133 foreach ($moneyFields as $field) {
134 if (isset($params[$field])) {
135 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
139 //set defaults in create mode
140 if (!$contributionID) {
141 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
143 if (empty($params['invoice_number'])) {
144 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
145 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
149 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
150 //if contribution is created with cancelled or refunded status, add credit note id
151 if (!empty($params['contribution_status_id'])) {
152 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
153 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
154 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
156 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
157 $params['creditnote_id'] = self
::createCreditNoteId();
162 // Since the fee amount is expecting this (later on) ensure it is always set.
163 // It would only not be set for an update where it is unchanged.
164 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id'));
168 && CRM_Utils_Array
::value('membership_id', $params)
169 && self
::checkContributeSettings('deferred_revenue_enabled')
171 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
172 if ($memberStartDate) {
173 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
176 self
::calculateMissingAmountParams($params, $contributionID);
178 if (!empty($params['payment_instrument_id'])) {
179 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
180 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
181 $params['check_number'] = 'null';
185 $setPrevContribution = TRUE;
186 // CRM-13964 partial payment
187 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
188 $partialAmtTotal = $params['partial_payment_total'];
189 $partialAmtPay = $params['partial_amount_to_pay'];
190 $params['total_amount'] = $partialAmtTotal;
191 if ($partialAmtPay < $partialAmtTotal) {
192 $params['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
193 $params['is_pay_later'] = 0;
194 $setPrevContribution = FALSE;
197 if ($contributionID && $setPrevContribution) {
198 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
201 if ($contributionID && !empty($params['revenue_recognition_date']) && !empty($params['prevContribution'])
202 && !($contributionStatus[$params['prevContribution']->contribution_status_id
] == 'Pending')
203 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
205 unset($params['revenue_recognition_date']);
208 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
209 isset($params['financial_type_id']))) {
210 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
213 if ($contributionID) {
214 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
217 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
219 $contribution = new CRM_Contribute_BAO_Contribution();
220 $contribution->copyValues($params);
222 $contribution->id
= $contributionID;
224 if (empty($contribution->id
)) {
225 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
226 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
227 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
231 $result = $contribution->save();
233 // Add financial_trxn details as part of fix for CRM-4724
234 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
235 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
237 //add Account details
238 $params['contribution'] = $contribution;
239 self
::recordFinancialAccounts($params);
241 if (self
::isUpdateToRecurringContribution($params)) {
242 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
243 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
244 $contributionStatus[$params['contribution_status_id']],
245 CRM_Utils_Array
::value('receive_date', $params)
249 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
251 if ($contributionID) {
252 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
255 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
262 * Is this contribution updating an existing recurring contribution.
264 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
265 * pending payment is being confirmed (or failing).
267 * @param array $params
271 public static function isUpdateToRecurringContribution($params) {
272 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
275 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
278 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
281 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
282 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
289 * Get defaults for new entity.
292 public static function getDefaults() {
294 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
295 FALSE, FALSE, FALSE, 'AND is_default = 1')
297 'contribution_status_id' => CRM_Core_Pseudoconstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
302 * Fetch the object and store the values in the values array.
304 * @param array $params
305 * Input parameters to find object.
306 * @param array $values
307 * Output values of the object.
309 * The array that holds all the db ids.
311 * @return CRM_Contribute_BAO_Contribution|null
312 * The found object or null
314 public static function getValues($params, &$values, &$ids) {
315 if (empty($params)) {
318 $contribution = new CRM_Contribute_BAO_Contribution();
320 $contribution->copyValues($params);
322 if ($contribution->find(TRUE)) {
323 $ids['contribution'] = $contribution->id
;
325 CRM_Core_DAO
::storeValues($contribution, $values);
327 return $contribution;
329 $null = NULL; // return by reference
334 * Get the values and resolve the most common mappings.
336 * Since contribution status is resolved in almost every function that calls getValues it makes
337 * sense to have an extra function to resolve it rather than repeat the code.
339 * Think carefully before adding more mappings to be resolved as there could be performance implications
340 * if this function starts to be called from more iterative functions.
342 * @param array $params
343 * Input parameters to find object.
346 * Array of the found contribution.
347 * @throws CRM_Core_Exception
349 public static function getValuesWithMappings($params) {
350 $values = $ids = array();
351 $contribution = self
::getValues($params, $values, $ids);
352 if (is_null($contribution)) {
353 throw new CRM_Core_Exception('No contribution found');
355 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
360 * Calculate net_amount & fee_amount if they are not set.
362 * Net amount should be total - fee.
363 * This should only be called for new contributions.
365 * @param array $params
366 * Params for a new contribution before they are saved.
367 * @param int|null $contributionID
368 * Contribution ID if we are dealing with an update.
370 * @throws \CiviCRM_API3_Exception
372 public static function calculateMissingAmountParams(&$params, $contributionID) {
373 if (!$contributionID && !isset($params['fee_amount'])) {
374 if (isset($params['total_amount']) && isset($params['net_amount'])) {
375 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
378 $params['fee_amount'] = 0;
381 if (!isset($params['net_amount'])) {
382 if (!$contributionID) {
383 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
386 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
387 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
388 // net_amount may need adjusting.
389 $contribution = civicrm_api3('Contribution', 'getsingle', array(
390 'id' => $contributionID,
391 'return' => array('total_amount', 'net_amount'),
393 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
394 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
395 $params['net_amount'] = $totalAmount - $feeAmount;
403 * @param $billingLocationTypeID
407 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
408 $hasBillingField = FALSE;
409 $billingFields = array(
417 //build address array
418 $addressParams = array();
419 $addressParams['location_type_id'] = $billingLocationTypeID;
420 $addressParams['is_billing'] = 1;
422 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
423 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
424 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
425 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
427 foreach ($billingFields as $value) {
428 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
429 if (!empty($addressParams[$value])) {
430 $hasBillingField = TRUE;
433 return array($hasBillingField, $addressParams);
437 * Get address params ready to be passed to the payment processor.
439 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
440 * To create an address we need state_province_id.
442 * @param array $params
443 * @param int $billingLocationTypeID
447 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
448 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
449 foreach ($addressParams as $name => $field) {
450 if (substr($name, 0, 8) == 'billing_') {
451 $addressParams[substr($name, 9)] = $addressParams[$field];
454 return array($hasBillingField, $addressParams);
458 * Get the number of terms for this contribution for a given membership type
459 * based on querying the line item table and relevant price field values
460 * Note that any one contribution should only be able to have one line item relating to a particular membership
463 * @param int $membershipTypeID
465 * @param int $contributionID
469 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
470 $numTerms = CRM_Core_DAO
::singleValueQuery("
471 SELECT membership_num_terms FROM civicrm_line_item li
472 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
473 WHERE contribution_id = %1 AND membership_type_id = %2",
474 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
476 // default of 1 is precautionary
477 return empty($numTerms) ?
1 : $numTerms;
481 * Takes an associative array and creates a contribution object.
483 * @param array $params
484 * (reference ) an assoc array of name/value pairs.
486 * The array that holds all the db ids.
488 * @return CRM_Contribute_BAO_Contribution
490 public static function create(&$params, $ids = array()) {
491 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date', 'revenue_recognition_date');
492 foreach ($dateFields as $df) {
493 if (isset($params[$df])) {
494 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
498 //if contribution is created with cancelled or refunded status, add credit note id
499 if (!empty($params['contribution_status_id'])) {
500 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
502 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
503 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
505 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
506 $params['creditnote_id'] = self
::createCreditNoteId();
511 $transaction = new CRM_Core_Transaction();
514 $contribution = self
::add($params, $ids);
516 catch (CRM_Core_Exception
$e) {
517 $transaction->rollback();
521 $params['contribution_id'] = $contribution->id
;
523 if (!empty($params['custom']) &&
524 is_array($params['custom'])
526 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
529 $session = CRM_Core_Session
::singleton();
531 if (!empty($params['note'])) {
533 'entity_table' => 'civicrm_contribution',
534 'note' => $params['note'],
535 'entity_id' => $contribution->id
,
536 'contact_id' => $session->get('userID'),
537 'modified_date' => date('Ymd'),
539 if (!$noteParams['contact_id']) {
540 $noteParams['contact_id'] = $params['contact_id'];
542 CRM_Core_BAO_Note
::add($noteParams);
545 // make entry in batch entity batch table
546 if (!empty($params['batch_id'])) {
547 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
548 $titleFields = array(
554 $retrieveRequired = 0;
555 foreach ($titleFields as $titleField) {
556 if (!isset($contribution->$titleField)) {
557 $retrieveRequired = 1;
561 if ($retrieveRequired == 1) {
562 $contribution->find(TRUE);
566 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
568 $transaction->commit();
570 $activity = civicrm_api3('Activity', 'get', array(
571 'source_record_id' => $contribution->id
,
572 'options' => array('limit' => 1),
574 'activity_type_id' => 'Contribution',
575 'return' => array('id', 'campaign'),
578 //CRM-18406: Update activity when edit contribution.
579 if ($activity['count']) {
580 // CRM-13237 : if activity record found, update it with campaign id of contribution
581 // @todo compare campaign ids first.
582 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
583 $contribution->activity_id
= $activity['id'];
586 if (empty($contribution->contact_id
)) {
587 $contribution->find(TRUE);
589 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
591 // do not add to recent items for import, CRM-4399
592 if (empty($params['skipRecentView'])) {
593 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
594 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
596 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
597 $titleFields = array(
603 $retrieveRequired = 0;
604 foreach ($titleFields as $titleField) {
605 if (!isset($contribution->$titleField)) {
606 $retrieveRequired = 1;
610 if ($retrieveRequired == 1) {
611 $contribution->find(TRUE);
613 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
614 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
616 $recentOther = array();
617 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
618 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
619 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
623 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
624 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
625 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
629 // add the recently created Contribution
630 CRM_Utils_Recent
::add($title,
634 $contribution->contact_id
,
640 return $contribution;
644 * Get the values for pseudoconstants for name->value and reverse.
646 * @param array $defaults
647 * (reference) the default values, some of which need to be resolved.
648 * @param bool $reverse
649 * True if we want to resolve the values in the reverse direction (value -> name).
651 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
652 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
653 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
654 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
655 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
659 * Convert associative array names to values and vice-versa.
661 * This function is used by both the web form layer and the api. Note that
662 * the api needs the name => value conversion, also the view layer typically
663 * requires value => name conversion
665 * @param array $defaults
666 * @param string $property
667 * @param array $lookup
668 * @param bool $reverse
672 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
673 $id = $property . '_id';
675 $src = $reverse ?
$property : $id;
676 $dst = $reverse ?
$id : $property;
678 if (!array_key_exists($src, $defaults)) {
682 $look = $reverse ?
array_flip($lookup) : $lookup;
684 if (is_array($look)) {
685 if (!array_key_exists($defaults[$src], $look)) {
689 $defaults[$dst] = $look[$defaults[$src]];
694 * Retrieve DB object based on input parameters.
696 * It also stores all the retrieved values in the default array.
698 * @param array $params
699 * (reference ) an assoc array of name/value pairs.
700 * @param array $defaults
701 * (reference ) an assoc array to hold the name / value pairs.
702 * in a hierarchical manner
704 * (reference) the array that holds all the db ids.
706 * @return CRM_Contribute_BAO_Contribution
708 public static function retrieve(&$params, &$defaults, &$ids) {
709 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
710 return $contribution;
714 * Combine all the importable fields from the lower levels object.
716 * The ordering is important, since currently we do not have a weight
717 * scheme. Adding weight is super important and should be done in the
718 * next week or so, before this can be called complete.
720 * @param string $contactType
721 * @param bool $status
724 * array of importable Fields
726 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
727 if (!self
::$_importableFields) {
728 if (!self
::$_importableFields) {
729 self
::$_importableFields = array();
733 $fields = array('' => array('title' => ts('- do not import -')));
736 $fields = array('' => array('title' => ts('- Contribution Fields -')));
739 $note = CRM_Core_DAO_Note
::import();
740 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
741 unset($tmpFields['option_value']);
742 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
743 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
745 // Using new Dedupe rule.
747 'contact_type' => $contactType,
748 'used' => 'Unsupervised',
750 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
751 $tmpContactField = array();
752 if (is_array($fieldsArray)) {
753 foreach ($fieldsArray as $value) {
754 //skip if there is no dupe rule
755 if ($value == 'none') {
758 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
763 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
764 $tmpContactField[trim($value)] = $contactFields[trim($value)];
766 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
769 $title = $tmpContactField[trim($value)]['title'];
771 $tmpContactField[trim($value)]['title'] = $title;
775 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
776 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
777 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
778 $fields = array_merge($fields, $tmpContactField);
779 $fields = array_merge($fields, $tmpFields);
780 $fields = array_merge($fields, $note);
781 $fields = array_merge($fields, $optionFields);
782 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
783 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
784 self
::$_importableFields = $fields;
786 return self
::$_importableFields;
790 * Get exportable fields with pseudoconstants rendered as an extra field.
792 public static function getExportableFieldsWithPseudoConstants() {
793 $fields = self
::exportableFields();
794 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
799 * Combine all the exportable fields from the lower level objects.
801 * @param bool $checkPermission
804 * array of exportable Fields
806 public static function &exportableFields($checkPermission = TRUE) {
807 if (!self
::$_exportableFields) {
808 if (!self
::$_exportableFields) {
809 self
::$_exportableFields = array();
812 $impFields = CRM_Contribute_DAO_Contribution
::export();
813 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
814 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
815 $typeField = CRM_Financial_DAO_FinancialType
::export();
816 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
818 $contributionPage = array(
819 'contribution_page' => array(
820 'title' => ts('Contribution Page'),
821 'name' => 'contribution_page',
822 'where' => 'civicrm_contribution_page.title',
823 'data_type' => CRM_Utils_Type
::T_STRING
,
827 $contributionNote = array(
828 'contribution_note' => array(
829 'title' => ts('Contribution Note'),
830 'name' => 'contribution_note',
831 'data_type' => CRM_Utils_Type
::T_TEXT
,
835 $extraFields = array(
836 'contribution_batch' => array(
837 'title' => ts('Batch Name'),
842 $campaignTitle = array(
843 'contribution_campaign_title' => array(
844 'title' => ts('Campaign Title'),
845 'name' => 'campaign_title',
846 'where' => 'civicrm_campaign.title',
847 'data_type' => CRM_Utils_Type
::T_STRING
,
850 $softCreditFields = array(
851 'contribution_soft_credit_name' => array(
852 'name' => 'contribution_soft_credit_name',
853 'title' => ts('Soft Credit For'),
854 'where' => 'civicrm_contact_d.display_name',
855 'data_type' => CRM_Utils_Type
::T_STRING
,
857 'contribution_soft_credit_amount' => array(
858 'name' => 'contribution_soft_credit_amount',
859 'title' => ts('Soft Credit Amount'),
860 'where' => 'civicrm_contribution_soft.amount',
861 'data_type' => CRM_Utils_Type
::T_MONEY
,
863 'contribution_soft_credit_type' => array(
864 'name' => 'contribution_soft_credit_type',
865 'title' => ts('Soft Credit Type'),
866 'where' => 'contribution_softcredit_type.label',
867 'data_type' => CRM_Utils_Type
::T_STRING
,
869 'contribution_soft_credit_contribution_id' => array(
870 'name' => 'contribution_soft_credit_contribution_id',
871 'title' => ts('Soft Credit For Contribution ID'),
872 'where' => 'civicrm_contribution_soft.contribution_id',
873 'data_type' => CRM_Utils_Type
::T_INT
,
875 'contribution_soft_credit_contact_id' => array(
876 'name' => 'contribution_soft_credit_contact_id',
877 'title' => ts('Soft Credit For Contact ID'),
878 'where' => 'civicrm_contact_d.id',
879 'data_type' => CRM_Utils_Type
::T_INT
,
883 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
885 'contribution_product_id' => array(
886 'title' => ts('Premium'),
887 'name' => 'contribution_product_id',
888 'where' => 'civicrm_product.id',
889 'data_type' => CRM_Utils_Type
::T_INT
,
893 $fields = array_merge($impFields, $typeField, $contributionPage, $expFieldProduct,
894 $expFieldsContrib, $contributionNote, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
895 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
898 self
::$_exportableFields = $fields;
901 return self
::$_exportableFields;
905 * @param null $status
906 * @param null $startDate
907 * @param null $endDate
911 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
915 $where[] = 'contribution_status_id = 1';
919 $where[] = 'contribution_status_id = 3';
924 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
927 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
929 $financialTypeACLJoin = '';
930 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
931 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
932 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
933 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
934 if ($financialTypes) {
935 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
936 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
939 $where[] = "c.financial_type_id IN (0)";
943 $whereCond = implode(' AND ', $where);
946 SELECT sum( total_amount ) as total_amount,
947 count( c.id ) as total_count,
949 FROM civicrm_contribution c
950 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
951 $financialTypeACLJoin
953 AND ( is_test = 0 OR is_test IS NULL )
954 AND contact.is_deleted = 0
958 $dao = CRM_Core_DAO
::executeQuery($query);
961 while ($dao->fetch()) {
962 $count +
= $dao->total_count
;
963 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
967 'amount' => implode(', ', $amount),
975 * Delete the indirect records associated with this contribution first.
980 * $results no of deleted Contribution on success, false otherwise
982 public static function deleteContribution($id) {
983 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
985 $transaction = new CRM_Core_Transaction();
988 //delete activity record
990 'source_record_id' => $id,
991 // activity type id for contribution
992 'activity_type_id' => 6,
995 CRM_Activity_BAO_Activity
::deleteActivity($params);
997 //delete billing address if exists for this contribution.
998 self
::deleteAddress($id);
1000 //update pledge and pledge payment, CRM-3961
1001 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1003 // remove entry from civicrm_price_set_entity, CRM-5095
1004 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1005 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1007 // cleanup line items.
1008 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1010 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1011 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1013 if ($participantId) {
1014 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1017 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1021 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1022 $noteId = key($note);
1024 CRM_Core_BAO_Note
::del($noteId, FALSE);
1027 $dao = new CRM_Contribute_DAO_Contribution();
1030 $results = $dao->delete();
1032 $transaction->commit();
1034 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1036 // delete the recently created Contribution
1037 $contributionRecent = array(
1039 'type' => 'Contribution',
1041 CRM_Utils_Recent
::del($contributionRecent);
1047 * React to a financial transaction (payment) failure.
1049 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1050 * payments is important for forensic and outreach reasons.
1052 * @param int $contributionID
1053 * @param int $contactID
1054 * @param string $message
1056 * @throws \CiviCRM_API3_Exception
1058 public static function failPayment($contributionID, $contactID, $message) {
1059 civicrm_api3('activity', 'create', array(
1060 'activity_type_id' => 'Failed Payment',
1061 'details' => $message,
1062 'subject' => ts('Payment failed at payment processor'),
1063 'source_record_id' => $contributionID,
1064 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1068 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1069 civicrm_api3('contribution', 'create', array(
1070 'id' => $contributionID,
1071 'contribution_status_id' => 'Failed',
1076 * Check if there is a contribution with the same trxn_id or invoice_id.
1078 * @param array $input
1079 * An assoc array of name/value pairs.
1080 * @param array $duplicates
1081 * (reference) store ids of duplicate contribs.
1085 * true if duplicate, false otherwise
1087 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1089 $id = CRM_Utils_Array
::value('id', $input);
1091 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1092 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1098 $clause[] = "trxn_id = %1";
1099 $input[1] = array($trxn_id, 'String');
1103 $clause[] = "invoice_id = %2";
1104 $input[2] = array($invoice_id, 'String');
1107 if (empty($clause)) {
1111 $clause = implode(' OR ', $clause);
1113 $clause = "( $clause ) AND id != %3";
1114 $input[3] = array($id, 'Integer');
1117 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1118 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1120 while ($dao->fetch()) {
1121 $duplicates[] = $dao->id
;
1128 * Takes an associative array and creates a contribution_product object.
1130 * the function extract all the params it needs to initialize the create a
1131 * contribution_product object. the params array could contain additional unused name/value
1134 * @param array $params
1135 * (reference) an assoc array of name/value pairs.
1137 * @return CRM_Contribute_DAO_ContributionProduct
1139 public static function addPremium(&$params) {
1140 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1141 $contributionProduct->copyValues($params);
1142 return $contributionProduct->save();
1146 * Get list of contribution fields for profile.
1147 * For now we only allow custom contribution fields to be in
1150 * @param bool $addExtraFields
1151 * True if special fields needs to be added.
1154 * the list of contribution fields
1156 public static function getContributionFields($addExtraFields = TRUE) {
1157 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1158 // @todo remove this - this line was added because payment_instrument_id was not
1159 // set to exportable - but now it is.
1160 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1162 if ($addExtraFields) {
1163 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1166 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1168 foreach ($contributionFields as $key => $var) {
1169 if ($key == 'contribution_contact_id') {
1172 elseif ($key == 'contribution_campaign_id') {
1173 $var['title'] = ts('Campaign');
1175 $fields[$key] = $var;
1178 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1183 * Add extra fields specific to contribution.
1185 public static function getSpecialContributionFields() {
1186 $extraFields = array(
1187 'contribution_soft_credit_name' => array(
1188 'name' => 'contribution_soft_credit_name',
1189 'title' => ts('Soft Credit Name'),
1190 'headerPattern' => '/^soft_credit_name$/i',
1191 'where' => 'civicrm_contact_d.display_name',
1193 'contribution_soft_credit_email' => array(
1194 'name' => 'contribution_soft_credit_email',
1195 'title' => ts('Soft Credit Email'),
1196 'headerPattern' => '/^soft_credit_email$/i',
1197 'where' => 'soft_email.email',
1199 'contribution_soft_credit_phone' => array(
1200 'name' => 'contribution_soft_credit_phone',
1201 'title' => ts('Soft Credit Phone'),
1202 'headerPattern' => '/^soft_credit_phone$/i',
1203 'where' => 'soft_phone.phone',
1205 'contribution_soft_credit_contact_id' => array(
1206 'name' => 'contribution_soft_credit_contact_id',
1207 'title' => ts('Soft Credit Contact ID'),
1208 'headerPattern' => '/^soft_credit_contact_id$/i',
1209 'where' => 'civicrm_contribution_soft.contact_id',
1211 'contribution_pcp_title' => array(
1212 'name' => 'contribution_pcp_title',
1213 'title' => ts('Personal Campaign Page Title'),
1214 'headerPattern' => '/^contribution_pcp_title$/i',
1215 'where' => 'contribution_pcp.title',
1219 return $extraFields;
1223 * @param int $pageID
1227 public static function getCurrentandGoalAmount($pageID) {
1229 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1230 FROM civicrm_contribution_page p,
1231 civicrm_contribution c
1232 WHERE p.id = c.contribution_page_id
1234 AND c.cancel_date is null
1238 $config = CRM_Core_Config
::singleton();
1239 $params = array(1 => array($pageID, 'Integer'));
1240 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1242 if ($dao->fetch()) {
1243 return array($dao->goal
, $dao->total
);
1246 return array(NULL, NULL);
1251 * Get list of contributions which credit the passed in contact ID.
1253 * The returned array provides details about the original contribution & donor.
1255 * @todo - this is a confusing function called from one place. It has a test. It would be
1256 * nice to deprecate it.
1258 * @param int $honorId
1259 * In Honor of Contact ID.
1262 * list of contribution fields
1264 public static function getHonorContacts($honorId) {
1266 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1267 $honorDAO->contact_id
= $honorId;
1270 $type = CRM_Contribute_PseudoConstant
::financialType();
1272 while ($honorDAO->fetch()) {
1273 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1274 $contributionDAO->id
= $honorDAO->contribution_id
;
1276 if ($contributionDAO->find(TRUE)) {
1277 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1278 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1279 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1280 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1281 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1282 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1283 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1284 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1285 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1293 * Get the sort name of a contact for a particular contribution.
1296 * Id of the contribution.
1298 * @return null|string
1299 * sort name of the contact if found
1301 public static function sortName($id) {
1302 $id = CRM_Utils_Type
::escape($id, 'Integer');
1305 SELECT civicrm_contact.sort_name
1306 FROM civicrm_contribution, civicrm_contact
1307 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1308 AND civicrm_contribution.id = {$id}
1310 return CRM_Core_DAO
::singleValueQuery($query);
1314 * @param int $contactID
1318 public static function annual($contactID) {
1319 if (is_array($contactID)) {
1320 $contactIDs = implode(',', $contactID);
1323 $contactIDs = $contactID;
1326 $config = CRM_Core_Config
::singleton();
1327 $startDate = $endDate = NULL;
1329 $currentMonth = date('m');
1330 $currentDay = date('d');
1331 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1332 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1333 (int ) $config->fiscalYearStart
['d'] > $currentDay
1336 $year = date('Y') - 1;
1341 $nextYear = $year +
1;
1343 if ($config->fiscalYearStart
) {
1344 $newFiscalYearStart = $config->fiscalYearStart
;
1345 if ($newFiscalYearStart['M'] < 10) {
1346 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1348 if ($newFiscalYearStart['d'] < 10) {
1349 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1351 $config->fiscalYearStart
= $newFiscalYearStart;
1352 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1357 $startDate = "$year$monthDay";
1358 $endDate = "$nextYear$monthDay";
1359 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1360 $additionalWhere = " AND b.financial_type_id IN (0)";
1361 $liWhere = " AND i.financial_type_id IN (0)";
1362 if (!empty($financialTypes)) {
1363 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1364 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1367 SELECT count(*) as count,
1368 sum(total_amount) as amount,
1369 avg(total_amount) as average,
1371 FROM civicrm_contribution b
1372 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1373 WHERE b.contact_id IN ( $contactIDs )
1374 AND b.contribution_status_id = 1
1376 AND b.receive_date >= $startDate
1377 AND b.receive_date < $endDate
1381 $dao = CRM_Core_DAO
::executeQuery($query);
1383 $amount = $average = array();
1384 while ($dao->fetch()) {
1385 if ($dao->count
> 0 && $dao->amount
> 0) {
1386 $count +
= $dao->count
;
1387 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1388 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1394 implode(', ', $amount),
1395 implode(', ', $average),
1398 return array(0, 0, 0);
1402 * Check if there is a contribution with the params passed in.
1404 * Used for trxn_id,invoice_id and contribution_id
1406 * @param array $params
1407 * An assoc array of name/value pairs.
1410 * contribution id if success else NULL
1412 public static function checkDuplicateIds($params) {
1413 $dao = new CRM_Contribute_DAO_Contribution();
1417 foreach ($params as $k => $v) {
1419 $clause[] = "$k = '$v'";
1422 $clause = implode(' AND ', $clause);
1423 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1424 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1426 while ($dao->fetch()) {
1434 * Get the contribution details for component export.
1436 * @param int $exportMode
1438 * @param array $componentIds
1444 public static function getContributionDetails($exportMode, $componentIds) {
1445 $paymentDetails = array();
1446 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1448 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1449 $componentSelect = " civicrm_participant_payment.participant_id id";
1450 $additionalClause = "
1451 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1452 AND civicrm_participant_payment.participant_id {$componentClause} )
1455 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1456 $componentSelect = " civicrm_membership_payment.membership_id id";
1457 $additionalClause = "
1458 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1459 AND civicrm_membership_payment.membership_id {$componentClause} )
1462 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1463 $componentSelect = " civicrm_pledge_payment.id id";
1464 $additionalClause = "
1465 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1466 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1470 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1471 trxn_id, {$componentSelect}
1472 FROM civicrm_contribution
1473 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1474 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1475 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1476 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1477 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1478 AND option_group_contribution_status.id = contribution_status.option_group_id )
1482 $dao = CRM_Core_DAO
::executeQuery($query);
1484 while ($dao->fetch()) {
1485 $paymentDetails[$dao->id
] = array(
1486 'total_amount' => $dao->total_amount
,
1487 'contribution_status' => $dao->status
,
1488 'receive_date' => $dao->receive_date
,
1489 'pay_instru' => $dao->payment_instrument
,
1490 'trxn_id' => $dao->trxn_id
,
1494 return $paymentDetails;
1498 * Create address associated with contribution record.
1500 * As long as there is one or more billing field in the parameters we will create the address.
1502 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1505 * @param array $params
1506 * @param int $billingLocationTypeID
1511 public static function createAddress($params, $billingLocationTypeID) {
1512 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1513 if ($hasBillingField) {
1514 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1515 return $address->id
;
1522 * Delete billing address record related contribution.
1524 * @param int $contributionId
1525 * @param int $contactId
1527 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1529 $contactJoin = NULL;
1531 if ($contributionId) {
1532 $clauses[] = "cc.id = {$contributionId}";
1536 $clauses[] = "cco.id = {$contactId}";
1537 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1540 if (empty($clauses)) {
1541 CRM_Core_Error
::fatal();
1544 $condition = implode(' OR ', $clauses);
1548 FROM civicrm_address ca
1549 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1553 $dao = CRM_Core_DAO
::executeQuery($query);
1555 while ($dao->fetch()) {
1556 $params = array('id' => $dao->id
);
1557 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1562 * This function check online pending contribution associated w/
1563 * Online Event Registration or Online Membership signup.
1565 * @param int $componentId
1566 * Participant/membership id.
1567 * @param string $componentName
1571 * pending contribution id.
1573 public static function checkOnlinePendingContribution($componentId, $componentName) {
1574 $contributionId = NULL;
1575 if (!$componentId ||
1576 !in_array($componentName, array('Event', 'Membership'))
1578 return $contributionId;
1581 if ($componentName == 'Event') {
1582 $idName = 'participant_id';
1583 $componentTable = 'civicrm_participant';
1584 $paymentTable = 'civicrm_participant_payment';
1585 $source = ts('Online Event Registration');
1588 if ($componentName == 'Membership') {
1589 $idName = 'membership_id';
1590 $componentTable = 'civicrm_membership';
1591 $paymentTable = 'civicrm_membership_payment';
1592 $source = ts('Online Contribution');
1595 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1598 SELECT component.id as {$idName},
1599 componentPayment.contribution_id as contribution_id,
1600 contribution.source source,
1601 contribution.contribution_status_id as contribution_status_id,
1602 contribution.is_pay_later as is_pay_later
1603 FROM $componentTable component
1604 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1605 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1606 WHERE component.id = {$componentId}";
1608 $dao = CRM_Core_DAO
::executeQuery($query);
1610 while ($dao->fetch()) {
1611 if ($dao->contribution_id
&&
1612 $dao->is_pay_later
&&
1613 $dao->contribution_status_id
== $pendingStatusId &&
1614 strpos($dao->source
, $source) !== FALSE
1616 $contributionId = $dao->contribution_id
;
1621 return $contributionId;
1625 * Update contribution as well as related objects.
1627 * This function by-passes hooks - to address this - don't use this function.
1631 * Use api contribute.completetransaction
1632 * For failures use failPayment (preferably exposing by api in the process).
1634 * @param array $params
1635 * @param bool $processContributionObject
1638 * @throws \Exception
1640 public static function transitionComponents($params, $processContributionObject = FALSE) {
1641 // get minimum required values.
1642 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1643 $componentId = CRM_Utils_Array
::value('component_id', $params);
1644 $componentName = CRM_Utils_Array
::value('componentName', $params);
1645 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1646 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1648 // if we already processed contribution object pass previous status id.
1649 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1651 $updateResult = array();
1653 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1655 // we process only ( Completed, Cancelled, or Failed ) contributions.
1656 if (!$contributionId ||
1657 !in_array($contributionStatusId, array(
1658 array_search('Completed', $contributionStatuses),
1659 array_search('Cancelled', $contributionStatuses),
1660 array_search('Failed', $contributionStatuses),
1663 return $updateResult;
1666 if (!$componentName ||
!$componentId) {
1667 // get the related component details.
1668 $componentDetails = self
::getComponentDetails($contributionId);
1671 $componentDetails['contact_id'] = $contactId;
1672 $componentDetails['component'] = $componentName;
1674 if ($componentName == 'event') {
1675 $componentDetails['participant'] = $componentId;
1678 $componentDetails['membership'] = $componentId;
1682 if (!empty($componentDetails['contact_id'])) {
1683 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1689 // do check for required ids.
1690 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1691 return $updateResult;
1694 //now we are ready w/ required ids, start processing.
1696 $baseIPN = new CRM_Core_Payment_BaseIPN();
1698 $input = $ids = $objects = array();
1700 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1701 $ids['contribution'] = $contributionId;
1702 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1703 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1704 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1705 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1706 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1707 $ids['contributionRecur'] = NULL;
1708 $ids['contributionPage'] = NULL;
1710 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1711 CRM_Core_Error
::fatal();
1714 $memberships = &$objects['membership'];
1715 $participant = &$objects['participant'];
1716 $pledgePayment = &$objects['pledge_payment'];
1717 $contribution = &$objects['contribution'];
1719 if ($pledgePayment) {
1720 $pledgePaymentIDs = array();
1721 foreach ($pledgePayment as $key => $object) {
1722 $pledgePaymentIDs[] = $object->id
;
1724 $pledgeID = $pledgePayment[0]->pledge_id
;
1727 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1730 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1731 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1736 // we might want to process contribution object.
1737 $processContribution = FALSE;
1738 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1739 if (is_array($memberships)) {
1740 foreach ($memberships as $membership) {
1742 //Update Membership status if there is no other completed contribution associated with the membership.
1743 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1744 foreach ($relatedContributions as $contriId) {
1745 if ($contriId == $contributionId) {
1748 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1749 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1753 if ($membership && $update) {
1754 $newStatus = array_search('Cancelled', $membershipStatuses);
1757 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1758 $activityParam = array(
1759 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1760 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1761 'target_contact_id' => $membership->contact_id
,
1762 'source_record_id' => $membership->id
,
1763 'activity_type_id' => 'Change Membership Status',
1764 'status_id' => 'Completed',
1765 'priority_id' => 'Normal',
1766 'activity_date_time' => 'now',
1769 $membership->status_id
= $newStatus;
1770 $membership->is_override
= TRUE;
1771 $membership->status_override_end_date
= 'null';
1772 $membership->save();
1773 civicrm_api3('activity', 'create', $activityParam);
1775 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1776 if ($processContributionObject) {
1777 $processContribution = TRUE;
1784 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1785 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1787 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1788 if ($processContributionObject) {
1789 $processContribution = TRUE;
1793 if ($pledgePayment) {
1794 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1796 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1797 if ($processContributionObject) {
1798 $processContribution = TRUE;
1802 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1803 if (is_array($memberships)) {
1804 foreach ($memberships as $membership) {
1806 //Update Membership status if there is no other completed contribution associated with the membership.
1807 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1808 foreach ($relatedContributions as $contriId) {
1809 if ($contriId == $contributionId) {
1812 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1813 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1817 if ($membership && $update) {
1818 $membership->status_id
= array_search('Expired', $membershipStatuses);
1819 $membership->is_override
= TRUE;
1820 $membership->status_override_end_date
= 'null';
1821 $membership->save();
1823 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1824 if ($processContributionObject) {
1825 $processContribution = TRUE;
1831 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1832 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1834 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1835 if ($processContributionObject) {
1836 $processContribution = TRUE;
1840 if ($pledgePayment) {
1841 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1843 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1844 if ($processContributionObject) {
1845 $processContribution = TRUE;
1849 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1851 // only pending contribution related object processed.
1852 if ($previousContriStatusId &&
1853 !in_array($contributionStatuses[$previousContriStatusId], array('Pending', 'Partially paid'))
1855 // this is case when we already processed contribution object.
1856 return $updateResult;
1858 elseif (!$previousContriStatusId &&
1859 !in_array($contributionStatuses[$contribution->contribution_status_id
], array('Pending', 'Partially paid'))
1861 // this is case when we are going to process contribution object later.
1862 return $updateResult;
1865 if (is_array($memberships)) {
1866 foreach ($memberships as $membership) {
1871 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1872 $membership->membership_type_id
,
1873 $membership->is_test
, $membership->id
1876 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1877 // this picks up membership type changes during renewals
1879 SELECT membership_type_id
1880 FROM civicrm_membership_log
1881 WHERE membership_id=$membership->id
1884 $dao = new CRM_Core_DAO();
1886 if ($dao->fetch()) {
1887 if (!empty($dao->membership_type_id
)) {
1888 $membership->membership_type_id
= $dao->membership_type_id
;
1889 $membership->save();
1892 // else fall back to using current membership type
1895 // Figure out number of terms
1897 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
1898 foreach ($lineitems as $lineitem) {
1899 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1900 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1902 // in case membership_num_terms comes through as null or zero
1903 $numterms = $numterms >= 1 ?
$numterms : 1;
1908 // CRM-15735-to update the membership status as per the contribution receive date
1910 $oldStatus = $membership->status_id
;
1911 if (!empty($params['receive_date'])) {
1912 $joinDate = $params['receive_date'];
1913 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1914 $membership->end_date
,
1915 $membership->join_date
,
1916 $params['receive_date'],
1918 $membership->membership_type_id
,
1921 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1922 $membership->save();
1925 if ($currentMembership) {
1926 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1927 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1928 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1931 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1934 //get the status for membership.
1935 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1937 $dates['join_date'],
1940 $membership->membership_type_id
,
1944 $formattedParams = array(
1945 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1946 array_search('Current', $membershipStatuses)
1948 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1949 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1950 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1953 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1955 $membership->copyValues($formattedParams);
1956 $membership->save();
1958 //updating the membership log
1959 $membershipLog = array();
1960 $membershipLog = $formattedParams;
1961 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1962 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1964 $membershipLog['start_date'] = $logStartDate;
1965 $membershipLog['membership_id'] = $membership->id
;
1966 $membershipLog['modified_id'] = $membership->contact_id
;
1967 $membershipLog['modified_date'] = date('Ymd');
1968 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1970 CRM_Member_BAO_MembershipLog
::add($membershipLog);
1972 //update related Memberships.
1973 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1975 foreach (array('Membership Signup', 'Membership Renewal') as $activityType) {
1976 $scheduledActivityID = CRM_Utils_Array
::value('id',
1977 civicrm_api3('Activity', 'Get',
1979 'source_record_id' => $membership->id
,
1980 'activity_type_id' => $activityType,
1981 'status_id' => 'Scheduled',
1984 'sort' => 'id DESC',
1989 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
1990 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
1991 if ($scheduledActivityID) {
1992 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, array('id' => $scheduledActivityID));
1997 // track membership status change if any
1998 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
1999 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2000 CRM_Activity_BAO_Activity
::addActivity($membership,
2001 'Change Membership Status',
2004 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2005 'source_contact_id' => $membershipLog['modified_id'],
2006 'priority_id' => 'Normal',
2011 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
2014 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2015 if ($processContributionObject) {
2016 $processContribution = TRUE;
2019 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2025 $updatedStatusId = array_search('Registered', $participantStatuses);
2026 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2028 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2029 if ($processContributionObject) {
2030 $processContribution = TRUE;
2034 if ($pledgePayment) {
2035 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2037 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2038 if ($processContributionObject) {
2039 $processContribution = TRUE;
2044 // process contribution object.
2045 if ($processContribution) {
2046 $contributionParams = array();
2053 'payment_instrument_id',
2056 'financial_type_id',
2057 'contribution_status_id',
2058 'non_deductible_amount',
2062 foreach ($fields as $field) {
2063 if (empty($params[$field])) {
2066 $contributionParams[$field] = $params[$field];
2069 $ids = array('contribution' => $contributionId);
2070 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2073 return $updateResult;
2077 * Returns all contribution related object ids.
2079 * @param $contributionId
2083 public static function getComponentDetails($contributionId) {
2084 $componentDetails = $pledgePayment = array();
2085 if (!$contributionId) {
2086 return $componentDetails;
2090 SELECT c.id as contribution_id,
2091 c.contact_id as contact_id,
2092 c.contribution_recur_id,
2093 mp.membership_id as membership_id,
2094 m.membership_type_id as membership_type_id,
2095 pp.participant_id as participant_id,
2096 p.event_id as event_id,
2097 pgp.id as pledge_payment_id
2098 FROM civicrm_contribution c
2099 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2100 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2101 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2102 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2103 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2104 WHERE c.id = $contributionId";
2106 $dao = CRM_Core_DAO
::executeQuery($query);
2107 $componentDetails = array();
2109 while ($dao->fetch()) {
2110 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2111 $componentDetails['contact_id'] = $dao->contact_id
;
2112 if ($dao->event_id
) {
2113 $componentDetails['event'] = $dao->event_id
;
2115 if ($dao->participant_id
) {
2116 $componentDetails['participant'] = $dao->participant_id
;
2118 if ($dao->membership_id
) {
2119 if (!isset($componentDetails['membership'])) {
2120 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2122 $componentDetails['membership'][] = $dao->membership_id
;
2123 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2125 if ($dao->pledge_payment_id
) {
2126 $pledgePayment[] = $dao->pledge_payment_id
;
2128 if ($dao->contribution_recur_id
) {
2129 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2133 if ($pledgePayment) {
2134 $componentDetails['pledge_payment'] = $pledgePayment;
2137 return $componentDetails;
2141 * @param int $contactId
2142 * @param bool $includeSoftCredit
2144 * @return null|string
2146 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2150 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2151 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2152 $liWhere = " AND i.financial_type_id IN (0)";
2153 if (!empty($financialTypes)) {
2154 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2155 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2157 $contactContributionsSQL = "
2158 SELECT contribution.id AS id
2159 FROM civicrm_contribution contribution
2160 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2161 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2165 $contactSoftCreditContributionsSQL = "
2166 SELECT contribution.id
2167 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2168 ON ( contribution.id = softContribution.contribution_id )
2169 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2170 $query = "SELECT count( x.id ) count FROM ( ";
2171 $query .= $contactContributionsSQL;
2173 if ($includeSoftCredit) {
2174 $query .= " UNION ";
2175 $query .= $contactSoftCreditContributionsSQL;
2180 return CRM_Core_DAO
::singleValueQuery($query);
2184 * Repeat a transaction as part of a recurring series.
2186 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2187 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2188 * subsequent call to the contribution.completetransaction api.
2190 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2192 * @param CRM_Contribute_BAO_Contribution $contribution
2193 * @param array $input
2194 * @param array $contributionParams
2195 * @param int $paymentProcessorID
2198 * @throws CiviCRM_API3_Exception
2200 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2201 if (!empty($contribution->id
)) {
2204 if (empty($contribution->id
)) {
2205 // Unclear why this would only be set for repeats.
2206 if (!empty($input['amount'])) {
2207 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2210 if (!empty($contributionParams['contribution_recur_id'])) {
2211 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2212 'id' => $contributionParams['contribution_recur_id'],
2214 if (!empty($recurringContribution['campaign_id'])) {
2215 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2216 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2218 if (!empty($recurringContribution['financial_type_id'])) {
2219 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2220 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2223 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2224 $contributionParams['contribution_recur_id'],
2225 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2227 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2229 $contributionParams['status_id'] = 'Pending';
2230 if (isset($contributionParams['financial_type_id'])) {
2231 // Give precedence to passed in type.
2232 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2235 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2237 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2238 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2240 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2241 //do not create CC or BCC emails or profile notifications.
2242 //The if is just to be safe. Not sure if we can ever arrive with this unset
2243 // but per CRM-19478 it seems it can be 'null'
2244 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2245 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2248 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2249 $contribution->id
= $createContribution['id'];
2250 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2256 * Get individual id for onbehalf contribution.
2258 * @param int $contributionId
2260 * @param int $contributorId
2264 * containing organization id and individual id
2266 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2270 if (!$contributionId) {
2274 // fetch contributor id if null
2275 if (!$contributorId) {
2276 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2277 $contributionId, 'contact_id'
2281 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2282 $activityTypeId = array_search('Contribution', $activityTypeIds);
2284 if ($activityTypeId && $contributorId) {
2286 SELECT civicrm_activity_contact.contact_id
2287 FROM civicrm_activity_contact
2288 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2289 WHERE civicrm_activity.activity_type_id = %1
2290 AND civicrm_activity.source_record_id = %2
2291 AND civicrm_activity_contact.record_type_id = %3
2294 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2295 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2298 1 => array($activityTypeId, 'Integer'),
2299 2 => array($contributionId, 'Integer'),
2300 3 => array($sourceID, 'Integer'),
2303 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2305 // for on behalf contribution source is individual and contributor is organization
2306 if ($sourceContactId && $sourceContactId != $contributorId) {
2307 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2308 // get rel type id for employee of relation
2309 foreach ($relationshipTypeIds as $id => $typeVals) {
2310 if ($typeVals['name_a_b'] == 'Employee of') {
2311 $relationshipTypeId = $id;
2316 $rel = new CRM_Contact_DAO_Relationship();
2317 $rel->relationship_type_id
= $relationshipTypeId;
2318 $rel->contact_id_a
= $sourceContactId;
2319 $rel->contact_id_b
= $contributorId;
2320 if ($rel->find(TRUE)) {
2321 $ids['individual_id'] = $rel->contact_id_a
;
2322 $ids['organization_id'] = $rel->contact_id_b
;
2333 public static function getContributionDates() {
2334 $config = CRM_Core_Config
::singleton();
2335 $currentMonth = date('m');
2336 $currentDay = date('d');
2337 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2338 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2339 (int ) $config->fiscalYearStart
['d'] > $currentDay
2342 $year = date('Y') - 1;
2347 $year = array('Y' => $year);
2348 $yearDate = $config->fiscalYearStart
;
2349 $yearDate = array_merge($year, $yearDate);
2350 $yearDate = CRM_Utils_Date
::format($yearDate);
2352 $monthDate = date('Ym') . '01';
2358 'yearDate' => $yearDate,
2359 'monthDate' => $monthDate,
2364 * Load objects relations to contribution object.
2365 * Objects are stored in the $_relatedObjects property
2366 * In the first instance we are just moving functionality from BASEIpn -
2367 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2369 * Note that the unit test for the BaseIPN class tests this function
2371 * @param array $input
2372 * Input as delivered from Payment Processor.
2374 * Ids as Loaded by Payment Processor.
2375 * @param bool $loadAll
2376 * Load all related objects - even where id not passed in? (allows API to call this).
2381 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2383 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2384 if (empty($ids['contact']) && isset($this->contact_id
)) {
2385 $ids['contact'] = $this->contact_id
;
2388 if (empty($this->_component
)) {
2389 if (!empty($ids['event'])) {
2390 $this->_component
= 'event';
2393 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2397 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2398 // refactoring than anything else, and has unit test coverage.
2399 if (empty($this->financial_type_id
)) {
2403 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2408 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2409 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2410 $this->contribution_page_id
,
2413 if ($paymentProcessorID) {
2414 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2418 $ids['contributionType'] = $this->financial_type_id
;
2419 $ids['financialType'] = $this->financial_type_id
;
2420 if ($this->contribution_page_id
) {
2421 $ids['contributionPage'] = $this->contribution_page_id
;
2424 $this->loadRelatedEntitiesByID($ids);
2426 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2427 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2430 if (!empty($ids['pledge_payment'])) {
2431 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2432 if (empty($paymentID)) {
2435 $payment = new CRM_Pledge_BAO_PledgePayment();
2436 $payment->id
= $paymentID;
2437 if (!$payment->find(TRUE)) {
2438 throw new Exception("Could not find pledge payment record: " . $paymentID);
2440 $this->_relatedObjects
['pledge_payment'][] = $payment;
2444 $ids = $this->loadRelatedMembershipObjects($ids);
2446 if ($this->_component
!= 'contribute') {
2447 // we are in event mode
2448 // make sure event exists and is valid
2449 $event = new CRM_Event_BAO_Event();
2450 $event->id
= $ids['event'];
2451 if ($ids['event'] &&
2454 throw new Exception("Could not find event: " . $ids['event']);
2457 $this->_relatedObjects
['event'] = &$event;
2459 $participant = new CRM_Event_BAO_Participant();
2460 $participant->id
= $ids['participant'];
2461 if ($ids['participant'] &&
2462 !$participant->find(TRUE)
2464 throw new Exception("Could not find participant: " . $ids['participant']);
2466 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2468 $this->_relatedObjects
['participant'] = &$participant;
2470 // get the payment processor id from event - this is inaccurate see CRM-16923
2471 // in future we should look at throwing an exception here rather than an dubious guess.
2472 if (!$paymentProcessorID) {
2473 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2474 if ($paymentProcessorID) {
2475 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2480 if ($paymentProcessorID) {
2481 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2482 $this->is_test ?
'test' : 'live'
2484 $ids['paymentProcessor'] = $paymentProcessorID;
2485 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2488 // Add contribution id to $ids. CRM-20401
2489 $ids['contribution'] = $this->id
;
2494 * Create array of message information - ie. return html version, txt version, to field
2496 * @param array $input
2497 * Incoming information.
2498 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2499 * just check presence of recur object but maintaining legacy approach
2502 * IDs of related objects.
2503 * @param array $values
2504 * Any values that may have already been compiled by calling process.
2505 * This is augmented by values 'gathered' by gatherMessageValues
2506 * @param bool $returnMessageText
2507 * Distinguishes between whether to send message or return.
2508 * message text. We are working towards this function ALWAYS returning message text & calling
2509 * function doing emails / pdfs with it
2515 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2516 $this->loadRelatedObjects($input, $ids);
2518 if (empty($this->_component
)) {
2519 $this->_component
= CRM_Utils_Array
::value('component', $input);
2522 //not really sure what params might be passed in but lets merge em into values
2523 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2524 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2525 if (!empty($input['receipt_date'])) {
2526 $values['receipt_date'] = $input['receipt_date'];
2529 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2530 //what does recur 'mean here - to do with payment processor return functionality but
2531 // what is the importance
2532 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2533 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2535 $entityID = $entity = NULL;
2536 if (isset($ids['contribution'])) {
2537 $entity = 'contribution';
2538 $entityID = $ids['contribution'];
2540 if (!empty($ids['membership'])) {
2541 //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
2542 // 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
2543 // line having loaded an array
2544 $ids['membership'] = (array) $ids['membership'];
2545 $entity = 'membership';
2546 $entityID = $ids['membership'][0];
2549 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2550 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2551 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2553 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2554 //direct mode showing billing block, so use directIPN for temporary
2555 $template->assign('contributeMode', 'directIPN');
2558 // todo remove strtolower - check consistency
2559 if (strtolower($this->_component
) == 'event') {
2560 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2561 $values['event'] = array();
2563 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2565 //get location details
2566 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2567 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2569 $ufJoinParams = array(
2570 'entity_table' => 'civicrm_event',
2571 'entity_id' => $ids['event'],
2572 'module' => 'CiviEvent',
2575 list($custom_pre_id,
2577 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2579 $values['custom_pre_id'] = $custom_pre_id;
2580 $values['custom_post_id'] = $custom_post_ids;
2581 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2582 //and cases involving status updation through ipn
2583 // whatever that means!
2584 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2585 // perhaps we should throw an e-notice if amount is set & force total_amount?
2586 if (!empty($input['amount'])) {
2587 $values['totalAmount'] = $input['amount'];
2589 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2590 if ($values['event']['is_email_confirm']) {
2591 $values['is_email_receipt'] = 1;
2594 if (!empty($ids['contribution'])) {
2595 $values['contributionId'] = $ids['contribution'];
2598 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2599 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2603 $values['contribution_id'] = $this->id
;
2604 if (!empty($ids['related_contact'])) {
2605 $values['related_contact'] = $ids['related_contact'];
2606 if (isset($ids['onbehalf_dupe_alert'])) {
2607 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2609 $entityBlock = array(
2610 'contact_id' => $ids['contact'],
2611 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2612 'Home', 'id', 'name'
2615 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2616 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2619 if ($this->is_test
) {
2622 if (!empty($this->_relatedObjects
['membership'])) {
2623 foreach ($this->_relatedObjects
['membership'] as $membership) {
2624 if ($membership->id
) {
2625 $values['membership_id'] = $membership->id
;
2626 $values['isMembership'] = TRUE;
2627 $values['membership_assign'] = TRUE;
2629 // need to set the membership values here
2630 $template->assign('membership_name',
2631 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2633 $template->assign('mem_start_date', $membership->start_date
);
2634 $template->assign('mem_join_date', $membership->join_date
);
2635 $template->assign('mem_end_date', $membership->end_date
);
2636 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2637 $template->assign('mem_status', $membership_status);
2638 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2639 $values['is_pay_later'] = 1;
2641 // Pass amount to floatval as string '0.00' is considered a
2642 // valid amount and includes Fee section in the mail.
2643 if (isset($values['amount'])) {
2644 $values['amount'] = floatval($values['amount']);
2647 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2648 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2649 $template->assign('cancelSubscriptionUrl', $url);
2650 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2651 $template->assign('updateSubscriptionBillingUrl', $url);
2652 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2653 $template->assign('updateSubscriptionUrl', $url);
2656 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2659 // otherwise if its about sending emails, continue sending without return, as we
2660 // don't want to exit the loop.
2665 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2671 * Gather values for contribution mail - this function has been created
2672 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2673 * Values related to the contribution in question are gathered
2675 * @param array $input
2676 * Input into function (probably from payment processor).
2677 * @param array $values
2679 * The set of ids related to the input.
2683 public function _gatherMessageValues($input, &$values, $ids = array()) {
2684 // set display address of contributor
2685 if ($this->address_id
) {
2686 $addressParams = array('id' => $this->address_id
);
2687 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2688 $addressDetails = array_values($addressDetails);
2690 // Else we assign the billing address of the contribution contact.
2692 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2693 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2694 $addressDetails = array_values($addressDetails);
2697 if (!empty($addressDetails[0]['display'])) {
2698 $values['address'] = $addressDetails[0]['display'];
2701 if ($this->_component
== 'contribute') {
2702 //get soft contributions
2703 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2704 if (!empty($softContributions)) {
2705 $values['softContributions'] = $softContributions['soft_credit'];
2707 if (isset($this->contribution_page_id
)) {
2708 // This is a call we want to use less, in favour of loading related objects.
2709 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2710 if ($this->contribution_page_id
) {
2711 // This is precautionary as there are some legacy flows, but it should really be
2713 if (!isset($this->_relatedObjects
['contributionPage'])) {
2714 $this->loadRelatedEntitiesByID(array('contributionPage' => $this->contribution_page_id
));
2716 // CRM-8254 - override default currency if applicable
2717 $config = CRM_Core_Config
::singleton();
2718 $config->defaultCurrency
= CRM_Utils_Array
::value(
2721 $config->defaultCurrency
2725 // no contribution page -probably back office
2727 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2728 $values['title'] = 'Contribution';
2730 // set lineItem for contribution
2732 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2733 if (!empty($lineItems)) {
2734 $firstLineItem = reset($lineItems);
2735 $priceSet = array();
2736 if (CRM_Utils_Array
::value('price_set_id', $firstLineItem)) {
2737 $priceSet = civicrm_api3('PriceSet', 'getsingle', array('id' => $firstLineItem['price_set_id'], 'return' => 'is_quick_config, id'));
2738 $values['priceSetID'] = $priceSet['id'];
2740 foreach ($lineItems as &$eachItem) {
2741 if (isset($this->_relatedObjects
['membership'])
2742 && is_array($this->_relatedObjects
['membership'])
2743 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2744 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2745 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2746 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2748 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2749 // However, that does create upgrade pain so would be better to be phased in.
2750 $values['useForMember'] = empty($priceSet['is_quick_config']);
2752 $values['lineItem'][0] = $lineItems;
2756 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2760 // if this is onbehalf of contribution then set related contact
2761 if (!empty($relatedContact['individual_id'])) {
2762 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2767 $eventParams = array(
2768 'id' => $this->_relatedObjects
['event']->id
,
2770 $values['event'] = array();
2772 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2773 // add custom fields for event
2774 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $this->_relatedObjects
['event']->id
);
2776 $eventCustomGroup = array();
2777 foreach ($eventGroupTree as $key => $group) {
2778 if ($key === 'info') {
2782 foreach ($group['fields'] as $k => $customField) {
2783 $groupLabel = $group['title'];
2784 if (!empty($customField['customValue'])) {
2785 foreach ($customField['customValue'] as $customFieldValues) {
2786 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2791 $values['event']['customGroup'] = $eventCustomGroup;
2793 //get participant details
2794 $participantParams = array(
2795 'id' => $this->_relatedObjects
['participant']->id
,
2798 $values['participant'] = array();
2800 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2801 // add custom fields for event
2802 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $this->_relatedObjects
['participant']->id
);
2803 $participantCustomGroup = array();
2804 foreach ($participantGroupTree as $key => $group) {
2805 if ($key === 'info') {
2809 foreach ($group['fields'] as $k => $customField) {
2810 $groupLabel = $group['title'];
2811 if (!empty($customField['customValue'])) {
2812 foreach ($customField['customValue'] as $customFieldValues) {
2813 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2818 $values['participant']['customGroup'] = $participantCustomGroup;
2820 //get location details
2821 $locationParams = array(
2822 'entity_id' => $this->_relatedObjects
['event']->id
,
2823 'entity_table' => 'civicrm_event',
2825 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2827 $ufJoinParams = array(
2828 'entity_table' => 'civicrm_event',
2829 'entity_id' => $ids['event'],
2830 'module' => 'CiviEvent',
2833 list($custom_pre_id,
2835 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2837 $values['custom_pre_id'] = $custom_pre_id;
2838 $values['custom_post_id'] = $custom_post_ids;
2840 // set lineItem for event contribution
2842 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2843 if (!empty($participantIds)) {
2844 foreach ($participantIds as $pIDs) {
2845 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2846 if (!CRM_Utils_System
::isNull($lineItem)) {
2847 $values['lineItem'][] = $lineItem;
2854 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
2856 $customGroup = array();
2857 foreach ($groupTree as $key => $group) {
2858 if ($key === 'info') {
2862 foreach ($group['fields'] as $k => $customField) {
2863 $groupLabel = $group['title'];
2864 if (!empty($customField['customValue'])) {
2865 foreach ($customField['customValue'] as $customFieldValues) {
2866 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2871 $values['customGroup'] = $customGroup;
2873 $values['is_pay_later'] = $this->is_pay_later
;
2879 * Assign message variables to template but try to break the habit.
2881 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2882 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2883 * multiple recurring payments for processors like IATS that use tokens.
2885 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2886 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2887 * Note we send directly from this function in some cases because it is only partly refactored.
2889 * Don't call this function directly as the signature will change.
2893 * @param bool $returnMessageText
2897 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
2898 // @todo - this should have a better separation of concerns - ie.
2899 // gatherMessageValues should build an array of values to be assigned to the template
2900 // and this function should assign them (assigning null if not set).
2901 // the way the pcpParams & honor Params section works is a baby-step towards this.
2902 $template = CRM_Core_Smarty
::singleton();
2903 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2904 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2905 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2907 // For some unit tests contribution cannot contain paymentProcessor information
2908 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
2909 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
2911 //assign honor information to receipt message
2912 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2914 $honorParams = ['soft_credit_type' => NULL, 'honor_block_is_active' => NULL];
2915 if (isset($softRecord['soft_credit'])) {
2916 //if id of contribution page is present
2917 if (!empty($values['id'])) {
2918 $values['honor'] = array(
2919 'honor_profile_values' => array(),
2920 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2921 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2924 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
2925 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
2928 //offline contribution
2929 $softCreditTypes = $softCredits = array();
2930 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2931 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2932 $softCredits[$key] = array(
2933 'Name' => $softCredit['contact_name'],
2934 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2937 $template->assign('softCreditTypes', $softCreditTypes);
2938 $template->assign('softCredits', $softCredits);
2942 $dao = new CRM_Contribute_DAO_ContributionProduct();
2943 $dao->contribution_id
= $this->id
;
2944 if ($dao->find(TRUE)) {
2945 $premiumId = $dao->product_id
;
2946 $template->assign('option', $dao->product_option
);
2948 $productDAO = new CRM_Contribute_DAO_Product();
2949 $productDAO->id
= $premiumId;
2950 $productDAO->find(TRUE);
2951 $template->assign('selectPremium', TRUE);
2952 $template->assign('product_name', $productDAO->name
);
2953 $template->assign('price', $productDAO->price
);
2954 $template->assign('sku', $productDAO->sku
);
2956 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2957 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2958 if (!$values['amount'] && isset($this->total_amount
)) {
2959 $values['amount'] = $this->total_amount
;
2962 $pcpParams = ['pcpBlock' => NULL, 'pcp_display_in_roll' => NULL, 'pcp_roll_nickname' => NULL, 'pcp_personal_note' => NULL, 'title' => NULL];
2964 if (strtolower($this->_component
) == 'contribute') {
2966 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2967 $softDAO->contribution_id
= $this->id
;
2968 if ($softDAO->find(TRUE)) {
2969 $pcpParams['pcpBlock'] = TRUE;
2970 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
2971 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
2972 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
2974 //assign the pcp page title for email subject
2975 $pcpDAO = new CRM_PCP_DAO_PCP();
2976 $pcpDAO->id
= $softDAO->pcp_id
;
2977 if ($pcpDAO->find(TRUE)) {
2978 $pcpParams['title'] = $pcpDAO->title
;
2982 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
2983 $template->assign($templateKey, $templateValue);
2986 if ($this->financial_type_id
) {
2987 $values['financial_type_id'] = $this->financial_type_id
;
2990 $template->assign('trxn_id', $this->trxn_id
);
2991 $template->assign('receive_date',
2992 CRM_Utils_Date
::processDate($this->receive_date
)
2994 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
2995 $template->assign('action', $this->is_test ?
1024 : 1);
2996 $template->assign('receipt_text',
2997 CRM_Utils_Array
::value('receipt_text',
3001 $template->assign('is_monetary', 1);
3002 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3003 $template->assign('currency', $this->currency
);
3004 $template->assign('address', CRM_Utils_Address
::format($input));
3005 if (!empty($values['customGroup'])) {
3006 $template->assign('customGroup', $values['customGroup']);
3008 if (!empty($values['softContributions'])) {
3009 $template->assign('softContributions', $values['softContributions']);
3011 if ($this->_component
== 'event') {
3012 $template->assign('title', $values['event']['title']);
3013 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3014 $viewRoles = array();
3015 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3016 $viewRoles[] = $participantRoles[$v];
3018 $values['event']['participant_role'] = implode(', ', $viewRoles);
3019 $template->assign('event', $values['event']);
3020 $template->assign('participant', $values['participant']);
3021 $template->assign('location', $values['location']);
3022 $template->assign('customPre', $values['custom_pre_id']);
3023 $template->assign('customPost', $values['custom_post_id']);
3026 if ($this->_relatedObjects
['participant']->is_test
) {
3030 $values['params'] = array();
3031 //to get email of primary participant.
3032 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3033 $primaryAmount[] = array(
3034 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3035 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3037 //build an array of cId/pId of participants
3038 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3039 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3040 //send receipt to additional participant if exists
3041 if (count($additionalIDs)) {
3042 $template->assign('isPrimary', 0);
3043 $template->assign('customProfile', NULL);
3044 //set additionalParticipant true
3045 $values['params']['additionalParticipant'] = TRUE;
3046 foreach ($additionalIDs as $pId => $cId) {
3048 //to change the status pending to completed
3049 $additional = new CRM_Event_DAO_Participant();
3050 $additional->id
= $pId;
3051 $additional->contact_id
= $cId;
3052 $additional->find(TRUE);
3053 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3054 $additional->status_id
= 1;
3055 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3056 //if additional participant dont have email
3058 if (!$additionalParticipantInfo) {
3059 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3061 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
3062 $primaryAmount[] = array(
3063 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3064 'amount' => $additional->fee_amount
,
3066 $additional->save();
3067 $additional->free();
3068 $template->assign('amount', $amount);
3069 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3073 //build an array of custom profile and assigning it to template
3074 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3076 if (count($customProfile)) {
3077 $template->assign('customProfile', $customProfile);
3080 // for primary contact
3081 $values['params']['additionalParticipant'] = FALSE;
3082 $template->assign('isPrimary', 1);
3083 $template->assign('amount', $primaryAmount);
3084 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3085 if ($this->payment_instrument_id
) {
3086 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3087 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3089 // carry paylater, since we did not created billing,
3090 // so need to pull email from primary location, CRM-4395
3091 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3097 * Check whether payment processor supports
3098 * cancellation of contribution subscription
3100 * @param int $contributionId
3103 * @param bool $isNotCancelled
3107 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3108 $cacheKeyString = "$contributionId";
3109 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3111 static $supportsCancel = array();
3113 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3114 $supportsCancel[$cacheKeyString] = FALSE;
3115 $isCancelled = FALSE;
3117 if ($isNotCancelled) {
3118 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3121 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3122 if (!empty($paymentObject)) {
3123 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3126 return $supportsCancel[$cacheKeyString];
3130 * Check whether subscription is already cancelled.
3132 * @param int $contributionId
3136 * contribution status
3138 public static function isSubscriptionCancelled($contributionId) {
3140 SELECT cr.contribution_status_id
3141 FROM civicrm_contribution_recur cr
3142 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3143 WHERE con.id = %1 LIMIT 1";
3144 $params = array(1 => array($contributionId, 'Integer'));
3145 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3146 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3147 if ($status == 'Cancelled') {
3154 * Create all financial accounts entry.
3156 * @param array $params
3157 * Contribution object, line item array and params for trxn.
3160 * @param array $financialTrxnValues
3162 * @return null|object
3164 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3165 $skipRecords = $update = $return = $isRelatedId = FALSE;
3167 $additionalParticipantId = array();
3168 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3169 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3171 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3172 $entityId = $params['participant_id'];
3173 $entityTable = 'civicrm_participant';
3174 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3176 elseif (!empty($params['membership_id'])) {
3177 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3178 // are created off one contribution should be handled elsewhere
3179 $entityId = $params['membership_id'];
3180 $entityTable = 'civicrm_membership';
3183 $entityId = $params['contribution']->id
;
3184 $entityTable = 'civicrm_contribution';
3187 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3188 $isRelatedId = TRUE;
3191 $entityID[] = $entityId;
3192 if (!empty($additionalParticipantId)) {
3193 $entityID +
= $additionalParticipantId;
3195 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3196 if (empty($params['prevContribution'])) {
3203 $statusId = $params['contribution']->contribution_status_id
;
3204 // CRM-13964 partial payment
3205 if ($contributionStatus == 'Partially paid'
3206 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3208 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3209 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3211 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['financial_type_id'], 'Accounts Receivable Account is');
3212 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3213 $params['total_amount'] = $partialAmtPay;
3215 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3216 if (empty($balanceTrxnInfo['trxn_id'])) {
3217 // create new balance transaction record
3218 $toFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['financial_type_id'], 'Accounts Receivable Account is');
3220 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3221 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3222 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3223 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3224 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3225 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3226 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3227 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3228 $balanceTrxnParams['status_id'] = $statusId;
3229 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3230 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3231 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3232 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3233 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3234 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3236 $balanceTrxnParams['is_payment'] = 1;
3238 if (!empty($params['payment_processor'])) {
3239 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3241 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3245 // build line item array if its not set in $params
3246 if (empty($params['line_item']) ||
$additionalParticipantId) {
3247 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3250 if ($contributionStatus != 'Failed' &&
3251 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3253 $skipRecords = TRUE;
3254 $pendingStatus = array(
3258 if (in_array($contributionStatus, $pendingStatus)) {
3259 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3260 $params['financial_type_id'],
3261 'Accounts Receivable Account is'
3264 elseif (!empty($params['payment_processor'])) {
3265 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3266 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array(
3267 'id' => $params['payment_processor'],
3268 'return' => 'payment_instrument_id',
3271 elseif (!empty($params['payment_instrument_id'])) {
3272 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3275 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3276 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3277 $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);
3280 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3281 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3282 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3284 //build financial transaction params
3285 $trxnParams = array(
3286 'contribution_id' => $params['contribution']->id
,
3287 'to_financial_account_id' => $params['to_financial_account_id'],
3288 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3289 'total_amount' => $totalAmount,
3290 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3291 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3292 'currency' => $params['contribution']->currency
,
3293 'trxn_id' => $params['contribution']->trxn_id
,
3294 'status_id' => $statusId,
3295 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3296 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3297 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $params),
3298 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $params),
3300 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3301 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3302 if (isset($params['refund_trxn_id'])) {
3303 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3304 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3307 //CRM-16259, set is_payment flag for non pending status
3308 if (!in_array($contributionStatus, $pendingStatus)) {
3309 $trxnParams['is_payment'] = 1;
3311 if (!empty($params['payment_processor'])) {
3312 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3315 if (isset($fromFinancialAccountId)) {
3316 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3319 // consider external values passed for recording transaction entry
3320 if (!empty($financialTrxnValues)) {
3321 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3323 if (empty($trxnParams['payment_processor_id'])) {
3324 unset($trxnParams['payment_processor_id']);
3327 $params['trxnParams'] = $trxnParams;
3329 if (!empty($params['prevContribution'])) {
3331 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3332 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3333 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3334 if (!isset($params['trxnParams']['trxn_id'])) {
3335 // Actually I have no idea why we are overwriting any values from the previous contribution.
3336 // (filling makes sense to me). However, only protecting this value as I really really know we
3337 // don't want this one overwritten.
3339 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3341 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3343 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3344 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3345 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3347 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3348 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3351 //if financial type is changed
3352 if (!empty($params['financial_type_id']) &&
3353 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3355 $accountRelationship = 'Income Account is';
3356 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3357 $accountRelationship = 'Deferred Revenue Account is';
3359 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['prevContribution']->financial_type_id
, $accountRelationship);
3360 $newFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['financial_type_id'], $accountRelationship);
3361 if ($oldFinancialAccount != $newFinancialAccount) {
3362 $params['total_amount'] = 0;
3363 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3364 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
3365 $params['prevContribution']->financial_type_id
, $accountRelationship);
3368 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3369 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3370 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3373 self
::updateFinancialAccounts($params, 'changeFinancialType');
3374 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3375 $params['financial_account_id'] = $newFinancialAccount;
3376 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3377 self
::updateFinancialAccounts($params);
3378 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3380 $params['deferred_financial_account_id'] = $newFinancialAccount;
3384 //Update contribution status
3385 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3386 if (!isset($params['refund_trxn_id'])) {
3387 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3388 // gets preference over another so I am only 'protecting' a very specific tested flow
3389 // and letting natural justice take care of the rest.
3390 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3392 if (!empty($params['contribution_status_id']) &&
3393 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3395 //Update Financial Records
3396 self
::updateFinancialAccounts($params, 'changedStatus');
3400 // change Payment Instrument for a Completed contribution
3401 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3402 // instrument is null and now new payment instrument is added along with the payment
3403 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3404 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3406 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3407 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3410 //if Change contribution amount
3411 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3412 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3413 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3414 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3415 if (isset($totalAmount) &&
3416 $totalAmount != $params['prevContribution']->total_amount
3418 //Update Financial Records
3419 $params['trxnParams']['from_financial_account_id'] = NULL;
3420 self
::updateFinancialAccounts($params, 'changedAmount');
3425 // Looks like we might have a data correction update.
3426 // This would be a case where a transaction id has been entered but it is incorrect &
3427 // the person goes back in & fixes it, as opposed to a new transaction.
3428 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3429 // the data fix scenario.
3431 if (isset($params['refund_trxn_id'])) {
3432 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3433 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3434 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3437 $cardType = CRM_Utils_Array
::value('card_type_id', $params);
3438 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3439 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3444 // records finanical trxn and entity financial trxn
3445 // also make it available as return value
3446 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3447 $trxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3448 $trxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3449 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3450 $params['entity_id'] = $financialTxn->id
;
3451 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3452 self
::$_trxnIDs[] = $financialTxn->id
;
3456 // record line items and financial items
3457 if (empty($params['skipLineItem'])) {
3458 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3461 // create batch entry if batch_id is passed and
3462 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3463 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3464 $entityParams = array(
3465 'batch_id' => $params['batch_id'],
3466 'entity_table' => 'civicrm_financial_trxn',
3467 'entity_id' => $financialTxn->id
,
3469 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3472 // when a fee is charged
3473 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3474 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3477 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3478 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3480 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3481 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3482 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3484 unset($params['line_item']);
3485 self
::$_trxnIDs = NULL;
3490 * Update all financial accounts entry.
3492 * @param array $params
3493 * Contribution object, line item array and params for trxn.
3495 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3496 * adds unpredictability.
3498 * @param string $context
3502 public static function updateFinancialAccounts(&$params, $context = NULL) {
3504 $inputParams = $params;
3506 $currentContributionStatus = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
3507 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3509 if (($previousContributionStatus == 'Pending'
3510 ||
$previousContributionStatus == 'In Progress')
3511 && $currentContributionStatus == 'Completed'
3512 && $context == 'changePaymentInstrument'
3516 if ((($previousContributionStatus == 'Partially paid'
3517 && $currentContributionStatus == 'Completed')
3518 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3519 && $currentContributionStatus == 'Partially paid'))
3520 && $context == 'changedStatus'
3524 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3525 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3526 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3528 if ($context == 'changedStatus') {
3529 if ($previousContributionStatus == 'Completed'
3530 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3533 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3534 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3535 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3536 $creditNoteId = self
::createCreditNoteId();
3537 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3540 elseif (($previousContributionStatus == 'Pending'
3541 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3543 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3544 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
3546 if ($currentContributionStatus == 'Cancelled') {
3547 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3548 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3549 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3550 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3551 $creditNoteId = self
::createCreditNoteId();
3552 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3556 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3557 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3562 if ($context == 'changedStatus') {
3563 if (($previousContributionStatus == 'Pending'
3564 ||
$previousContributionStatus == 'In Progress')
3565 && ($currentContributionStatus == 'Completed')
3567 if (empty($params['line_item'])) {
3569 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3570 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3571 // & this can be removed
3574 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3575 // This is an update so original currency if none passed in.
3576 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
3578 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
3579 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3580 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3581 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
3582 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3583 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3585 $entityParams = array(
3586 'entity_table' => 'civicrm_financial_item',
3588 foreach ($params['line_item'] as $fieldId => $fields) {
3589 foreach ($fields as $fieldValueId => $lineItemDetails) {
3591 1 => array(CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'), 'Integer'),
3592 2 => array($lineItemDetails['id'], 'Integer'),
3594 CRM_Core_DAO
::executeQuery($query, $fparams);
3596 1 => array($lineItemDetails['id'], 'Integer'),
3598 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3599 while ($financialItem->fetch()) {
3600 $entityParams['entity_id'] = $financialItem->id
;
3601 $entityParams['amount'] = $financialItem->amount
;
3602 foreach (self
::$_trxnIDs as $tID) {
3603 $entityParams['financial_trxn_id'] = $tID;
3604 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3613 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3614 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3615 $params['entity_id'] = $trxn->id
;
3616 if ($context != 'changePaymentInstrument') {
3617 $itemParams['entity_table'] = 'civicrm_line_item';
3618 $trxnIds['id'] = $params['entity_id'];
3619 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3620 foreach ($params['line_item'] as $fieldId => $fields) {
3621 foreach ($fields as $fieldValueId => $lineItemDetails) {
3622 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
3623 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3624 if ($params['contribution']->receive_date
) {
3625 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3628 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
3630 $currency = $params['prevContribution']->currency
;
3631 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3632 if ($params['contribution']->currency
) {
3633 $currency = $params['contribution']->currency
;
3635 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3636 $itemParams = array(
3637 'transaction_date' => $receiveDate,
3638 'contact_id' => $params['prevContribution']->contact_id
,
3639 'currency' => $currency,
3640 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
3641 'description' => CRM_Utils_Array
::value('description', $prevFinancialItem),
3642 'status_id' => $prevFinancialItem['status_id'],
3643 'financial_account_id' => $financialAccount,
3644 'entity_table' => 'civicrm_line_item',
3645 'entity_id' => $lineItemDetails['id'],
3647 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3648 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3649 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
3650 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3652 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
3653 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3654 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3655 $taxAmount = (float) $lineItemDetails['tax_amount'];
3656 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
3657 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
3658 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3660 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
3661 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3663 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
3664 $itemParams['description'] = $taxTerm;
3665 if ($lineItemDetails['financial_type_id']) {
3666 $itemParams['financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
3667 $lineItemDetails['financial_type_id'],
3668 'Sales Tax Account is'
3671 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3676 if ($context == 'changeFinancialType') {
3677 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3678 $params['skipLineItem'] = FALSE;
3679 foreach ($params['line_item'] as &$lineItems) {
3680 foreach ($lineItems as &$line) {
3681 $line['financial_type_id'] = $params['financial_type_id'];
3686 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3690 * Is this contribution status a reversal.
3692 * If so we would expect to record a negative value in the financial_trxn table.
3694 * @param int $status_id
3698 public static function isContributionStatusNegative($status_id) {
3699 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3700 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3704 * Check status validation on update of a contribution.
3706 * @param array $values
3707 * Previous form values before submit.
3709 * @param array $fields
3710 * The input form values.
3712 * @param array $errors
3717 public static function checkStatusValidation($values, &$fields, &$errors) {
3718 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3719 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3720 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3724 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3725 $checkStatus = array(
3726 'Cancelled' => array('Completed', 'Refunded'),
3727 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3728 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3729 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3730 'Refunded' => array('Cancelled', 'Completed'),
3731 'Partially paid' => array('Completed'),
3734 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3735 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3737 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3738 1 => $contributionStatuses[$values['contribution_status_id']],
3739 2 => $contributionStatuses[$fields['contribution_status_id']],
3745 * Delete contribution of contact.
3749 * @param int $contactId
3753 public static function deleteContactContribution($contactId) {
3754 $contribution = new CRM_Contribute_DAO_Contribution();
3755 $contribution->contact_id
= $contactId;
3756 $contribution->find();
3757 while ($contribution->fetch()) {
3758 self
::deleteContribution($contribution->id
);
3763 * Get options for a given contribution field.
3764 * @see CRM_Core_DAO::buildOptions
3766 * @param string $fieldName
3767 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3768 * @param array $props whatever is known about this dao object.
3770 * @return array|bool
3772 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3773 $className = __CLASS__
;
3775 if (isset($props['orderColumn'])) {
3776 $params['orderColumn'] = $props['orderColumn'];
3778 switch ($fieldName) {
3779 // This field is not part of this object but the api supports it
3780 case 'payment_processor':
3781 $className = 'CRM_Contribute_BAO_ContributionPage';
3782 // Filter results by contribution page
3783 if (!empty($props['contribution_page_id'])) {
3784 $page = civicrm_api('contribution_page', 'getsingle', array(
3786 'id' => ($props['contribution_page_id']),
3788 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3789 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3793 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3794 case 'honor_type_id':
3795 $className = 'CRM_Contribute_BAO_ContributionSoft';
3796 $fieldName = 'soft_credit_type_id';
3797 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3800 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3804 * Validate financial type.
3808 * @param int $financialTypeId
3809 * Financial Type id.
3811 * @param string $relationName
3813 * @return array|bool
3815 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3816 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3818 if (!$financialAccount) {
3819 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3826 * Function to record additional payment for partial and refund contributions.
3828 * @param int $contributionId
3829 * is the invoice contribution id (got created after processing participant payment).
3830 * @param array $trxnsData
3831 * to take user provided input of transaction details.
3832 * @param string $paymentType
3833 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3834 * @param int $participantId
3835 * @param bool $updateStatus
3837 * @return null|object
3839 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3840 $getInfoOf['id'] = $contributionId;
3841 $defaults = array();
3842 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3843 if (!$participantId) {
3844 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id', 'contribution_id');
3847 // load related memberships on basis of $contributionDAO object
3848 $contributionDAO->loadRelatedMembershipObjects();
3850 // build params for recording financial trxn entry
3851 $params['contribution'] = $contributionDAO;
3852 $params = array_merge($defaults, $params);
3853 $params['skipLineItem'] = TRUE;
3854 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3855 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contributionDAO->financial_type_id
, 'Accounts Receivable Account is');
3857 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3858 $paidStatus = CRM_Core_PseudoConstant
::getKey('CRM_Financial_DAO_FinancialItem', 'status_id', 'Paid');
3860 if ($paymentType == 'owed') {
3861 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3862 $params['partial_amount_to_pay'] = $trxnsData['total_amount'];
3863 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3864 $params['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $trxnsData);
3865 $params['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $trxnsData);
3868 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3869 $toFinancialAccount = $arAccountId;
3870 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3871 if (!empty($trxnId)) {
3872 $trxnId = $trxnId['trxn_id'];
3874 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3875 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3878 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3879 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3880 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3884 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3885 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3886 FROM civicrm_financial_trxn ft
3887 LEFT JOIN civicrm_entity_financial_trxn eft
3888 ON (ft.id = eft.financial_trxn_id)
3889 WHERE eft.entity_table = 'civicrm_contribution'
3890 AND eft.entity_id = {$contributionId}
3891 AND ft.to_financial_account_id != {$toFinancialAccount}
3892 AND ft.status_id = {$completedStatusId}
3894 $query = CRM_Core_DAO
::executeQuery($sql);
3896 $sumOfPayments = $query->sum_of_payments
;
3899 if ($contributionDAO->total_amount
== $sumOfPayments) {
3900 // update contribution status and
3901 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3902 $contributionDAO->contribution_status_id
= $completedStatusId;
3903 $contributionDAO->cancel_date
= 'null';
3904 $contributionDAO->cancel_reason
= NULL;
3905 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3906 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3907 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3908 $contributionDAO->save();
3910 //Change status of financial record too
3911 $financialTrxn->status_id
= $completedStatusId;
3912 $financialTrxn->save();
3914 // note : not using the self::add method,
3915 // the reason because it performs 'status change' related code execution for financial records
3916 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3917 // are coded below i.e. just updating financial_item status to 'Paid'
3919 if ($participantId) {
3920 // update participant status
3921 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3922 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3923 foreach ($ids as $val) {
3924 $participantUpdate['id'] = $val;
3925 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3926 CRM_Event_BAO_Participant
::add($participantUpdate);
3930 self
::updateMembershipBasedOnCompletionOfContribution(
3933 $trxnsData['trxn_date']
3936 // update financial item statuses
3937 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3938 $sqlFinancialItemUpdate = "
3939 UPDATE civicrm_financial_item fi
3940 LEFT JOIN civicrm_entity_financial_trxn eft
3941 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3942 SET status_id = {$paidStatus}
3943 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3945 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3948 elseif ($paymentType == 'refund') {
3949 $trxnsData['total_amount'] = $trxnsData['net_amount'] = -$trxnsData['total_amount'];
3950 $trxnsData['from_financial_account_id'] = $arAccountId;
3951 $trxnsData['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
3953 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3955 // note : not using the self::add method,
3956 // the reason because it performs 'status change' related code execution for financial records
3957 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3958 // are coded below i.e. just updating financial_item status to 'Paid'
3959 if ($updateStatus) {
3960 CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
3962 // add financial item entry
3963 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionDAO->id
);
3964 if (!empty($lineItems)) {
3965 foreach ($lineItems as $lineItemId => $lineItemValue) {
3966 // don't record financial item for cancelled line-item
3967 if ($lineItemValue['qty'] == 0) {
3970 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount
/ $contributionDAO->total_amount
);
3971 $addFinancialEntry = array(
3972 'transaction_date' => $financialTrxn->trxn_date
,
3973 'contact_id' => $contributionDAO->contact_id
,
3974 'amount' => round($paid, 2),
3975 'currency' => $contributionDAO->currency
,
3976 'status_id' => $paidStatus,
3977 'entity_id' => $lineItemId,
3978 'entity_table' => 'civicrm_line_item',
3980 $trxnIds['id'] = $financialTrxn->id
;
3981 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3984 if ($participantId) {
3985 // update participant status
3986 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3987 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3988 foreach ($ids as $val) {
3989 $participantUpdate['id'] = $val;
3990 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3991 CRM_Event_BAO_Participant
::add($participantUpdate);
3996 // activity creation
3997 if (!empty($financialTrxn)) {
3998 if ($participantId) {
3999 $inputParams['id'] = $participantId;
4002 $component = 'event';
4003 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
4004 $entityObj = $entityObj[$participantId];
4007 $entityObj = $contributionDAO;
4008 $component = 'contribution';
4010 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
4012 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
4013 return $financialTrxn;
4021 * @param $activityType
4023 * @param int $contributionId
4025 * @throws CRM_Core_Exception
4027 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
4028 if ($component == 'event') {
4029 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
4032 $title = ts('Contribution');
4034 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
4035 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
4036 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
4037 $targetCid = $entityObj->contact_id
;
4038 // source record id would be the contribution id
4039 $srcRecId = $contributionId;
4042 $activityParams = array(
4043 'source_contact_id' => $targetCid,
4044 'source_record_id' => $srcRecId,
4045 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
4046 'subject' => $subject,
4047 'activity_date_time' => $date,
4048 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
4049 'skipRecentView' => TRUE,
4052 // create activity with target contacts
4053 $session = CRM_Core_Session
::singleton();
4054 $id = $session->get('userID');
4056 $activityParams['source_contact_id'] = $id;
4057 $activityParams['target_contact_id'][] = $targetCid;
4060 CRM_Activity_BAO_Activity
::create($activityParams);
4064 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4068 * @param bool $getTrxnInfo
4069 * @param bool $usingLineTotal
4073 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
4074 if ($component == 'event') {
4075 $entity = 'participant';
4076 $entityTable = 'civicrm_participant';
4077 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4079 if (!$contributionId) {
4080 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4081 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4082 $id = $primaryParticipantId;
4084 if (!$contributionId) {
4089 elseif ($component == 'membership') {
4090 $entity = $component;
4091 $entityTable = 'civicrm_membership';
4092 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4095 $contributionId = $id;
4096 $entity = 'contribution';
4097 $entityTable = 'civicrm_contribution';
4100 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4101 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4103 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4104 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4106 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
4107 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4110 $baseTrxnId = $total['trxn_id'];
4111 $total = $total['total_amount'];
4114 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
4115 $contribution = civicrm_api3('Contribution', 'getsingle', array('id' => $contributionId, 'return' => array('is_pay_later', 'contribution_status_id', 'financial_type_id')));
4117 $info['payLater'] = $contribution['is_pay_later'];
4118 $info['contribution_status'] = $contribution['contribution_status'];
4120 $financialTypeId = $contribution['financial_type_id'];
4121 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
4123 if ($paymentBalance == 0 && $info['payLater']) {
4124 // @todo - review - this looks very unlikely to be correct.
4125 // the balance should be correct based on payment transactions not
4127 $paymentBalance = $total;
4130 $info['total'] = $total;
4131 $info['paid'] = $total - $paymentBalance;
4132 $info['balance'] = $paymentBalance;
4134 $info['component'] = $component;
4136 if ($getTrxnInfo && $baseTrxnId) {
4137 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4139 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4141 ft.payment_instrument_id,
4142 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
4144 FROM civicrm_contribution con
4145 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4146 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4147 AND ft.to_financial_account_id != %2
4148 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4149 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4150 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4152 WHERE con.id = %1 AND ft.is_payment = 1
4154 $queryParams = array(
4155 1 => array($contributionId, 'Integer'),
4156 2 => array($feeFinancialAccount, 'Integer'),
4158 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4159 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4161 while ($resultDAO->fetch()) {
4162 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4163 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4164 if ($resultDAO->card_type_id
) {
4165 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
4166 $pantruncation = '';
4167 if ($resultDAO->pan_truncation
) {
4168 $pantruncation = ": {$resultDAO->pan_truncation}";
4170 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4173 // show payment edit link only for payments done via backoffice form
4174 $paymentEditLink = '';
4175 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
4177 CRM_Core_Action
::UPDATE
=> array(
4178 'name' => "<i class='crm-i fa-pencil'></i>",
4179 'url' => 'civicrm/payment/edit',
4180 'class' => 'medium-popup',
4181 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4182 'title' => ts('Edit Payment'),
4185 $paymentEditLink = CRM_Core_Action
::formLink(
4187 CRM_Core_Action
::mask(array(CRM_Core_Permission
::EDIT
)),
4189 'id' => $resultDAO->id
,
4190 'contribution_id' => $contributionId,
4196 'id' => $resultDAO->id
,
4197 'total_amount' => $resultDAO->total_amount
,
4198 'financial_type' => $resultDAO->financial_account
,
4199 'payment_instrument' => $paidByLabel,
4200 'receive_date' => $resultDAO->trxn_date
,
4201 'trxn_id' => $resultDAO->trxn_id
,
4202 'status' => $statuses[$resultDAO->status_id
],
4203 'currency' => $resultDAO->currency
,
4204 'action' => $paymentEditLink,
4206 if ($paidByName == 'Check') {
4207 $val['check_number'] = $resultDAO->check_number
;
4211 $info['transaction'] = $rows;
4214 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4219 * Get the tax amount (misnamed function).
4221 * @param array $params
4222 * @param bool $isLineItem
4226 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4227 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4229 // This function should be only called after standardisation (removal of
4230 // thousand separator & using a decimal point for cents separator.
4231 // However, we don't know if that is always true :-(
4232 // There is a deprecation notice tho :-)
4233 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4234 // Update contribution.
4235 if (!empty($params['id'])) {
4236 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4237 // there are no tax implications - early return.
4238 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4241 if (empty($params['prevContribution'])) {
4242 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4245 foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) {
4246 if (!isset($params[$field])) {
4247 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4248 // Tax amount gets added back on later....
4249 $params['total_amount'] = $params['prevContribution']->total_amount
-
4250 $params['prevContribution']->tax_amount
;
4253 $params[$field] = $params['prevContribution']->$field;
4254 if ($params[$field] != $params['prevContribution']->$field) {
4260 self
::calculateMissingAmountParams($params, $params['id']);
4261 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4262 // Assign tax Amount on update of contribution
4263 if (!empty($params['prevContribution']->tax_amount
)) {
4264 $params['tax_amount'] = 'null';
4265 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4266 foreach ($params['line_item'] as $setID => $priceField) {
4267 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4268 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4275 // New Contribution and update of contribution with tax rate financial type
4276 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4277 empty($params['skipLineItem']) && !$isLineItem
4279 $taxRateParams = $taxRates[$params['financial_type_id']];
4280 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4281 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4283 // Get Line Item on update of contribution
4284 if (isset($params['id'])) {
4285 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4288 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4290 foreach ($params['line_item'] as $setID => $priceField) {
4291 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4292 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4295 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4297 elseif (isset($params['api.line_item.create'])) {
4298 // Update total amount of contribution using lineItem
4299 $taxAmountArray = array();
4300 foreach ($params['api.line_item.create'] as $key => $value) {
4301 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4302 $taxRate = $taxRates[$value['financial_type_id']];
4303 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4304 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4307 $params['tax_amount'] = array_sum($taxAmountArray);
4308 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4311 // update line item of contrbution
4312 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4313 $taxRate = $taxRates[$params['financial_type_id']];
4314 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4315 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4322 * Check financial type validation on update of a contribution.
4324 * @param Integer $financialTypeId
4325 * Value of latest Financial Type.
4327 * @param Integer $contributionId
4330 * @param array $errors
4335 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4336 if (!empty($financialTypeId)) {
4337 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4338 if ($oldFinancialTypeId == $financialTypeId) {
4342 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4344 '1' => array($contributionId, 'Integer'),
4346 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4347 if ($result->N
> 1) {
4348 $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.');
4353 * Update related pledge payment payments.
4355 * This function has been refactored out of the back office contribution form and may
4356 * still overlap with other functions.
4358 * @param string $action
4359 * @param int $pledgePaymentID
4360 * @param int $contributionID
4361 * @param bool $adjustTotalAmount
4362 * @param float $total_amount
4363 * @param float $original_total_amount
4364 * @param int $contribution_status_id
4365 * @param int $original_contribution_status_id
4367 public static function updateRelatedPledge(
4373 $original_total_amount,
4374 $contribution_status_id,
4375 $original_contribution_status_id
4377 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4381 if ($pledgePaymentID) {
4382 //store contribution id in payment record.
4383 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4386 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4393 if (!$pledgePaymentID) {
4396 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4402 $updatePledgePaymentStatus = FALSE;
4404 // If either the status or the amount has changed we update the pledge status.
4405 if ($action & CRM_Core_Action
::ADD
) {
4406 $updatePledgePaymentStatus = TRUE;
4408 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4409 ($original_total_amount != $total_amount))
4411 $updatePledgePaymentStatus = TRUE;
4414 if ($updatePledgePaymentStatus) {
4415 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4416 array($pledgePaymentID),
4417 $contribution_status_id,
4426 * Compute the stats values
4428 * @param string $stat either 'mode' or 'median'
4429 * @param string $sql
4430 * @param string $alias of civicrm_contribution
4432 * @return array|null
4434 public static function computeStats($stat, $sql, $alias = NULL) {
4435 $mode = $median = array();
4438 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4439 while ($modeDAO->fetch()) {
4440 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4441 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4450 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4451 foreach ($currencies as $currency => $val) {
4453 $where = "AND {$alias}.currency = '{$currency}'";
4454 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4458 $medianRow = floor($rowCount / 2);
4459 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4465 $medianValue = "SELECT {$alias}.total_amount as median
4467 ORDER BY median LIMIT {$medianRow},{$offset}";
4468 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4469 while ($medianValDAO->fetch()) {
4471 $midValue = $midValue +
$medianValDAO->median
;
4474 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4478 $midValue = $midValue / 2;
4479 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4490 * Is there only one line item attached to the contribution.
4496 * @throws \CiviCRM_API3_Exception
4498 public static function isSingleLineItem($id) {
4499 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4500 return ($lineItemCount == 1);
4504 * Complete an order.
4506 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4508 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4510 * Moving it out of the BaseIPN class is just the first step.
4512 * @param array $input
4514 * @param array $objects
4515 * @param CRM_Core_Transaction $transaction
4517 * @param CRM_Contribute_BAO_Contribution $contribution
4521 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution) {
4522 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4523 // The previous details are used when calculating line items so keep it before any code that 'does something'
4524 if (!empty($contribution->id
)) {
4525 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4526 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4528 $inputContributionWhiteList = array(
4533 'payment_instrument_id',
4538 'contribution_status_id',
4542 if (self
::isSingleLineItem($primaryContributionID)) {
4543 $inputContributionWhiteList[] = 'financial_type_id';
4546 $participant = CRM_Utils_Array
::value('participant', $objects);
4547 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4548 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4549 $event = CRM_Utils_Array
::value('event', $objects);
4551 $paymentProcessorId = '';
4552 if (isset($objects['paymentProcessor'])) {
4553 if (is_array($objects['paymentProcessor'])) {
4554 $paymentProcessorId = $objects['paymentProcessor']['id'];
4557 $paymentProcessorId = $objects['paymentProcessor']->id
;
4561 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4563 $contributionParams = array_merge(array(
4564 'contribution_status_id' => $completedContributionStatusID,
4565 'source' => self
::getRecurringContributionDescription($contribution, $event),
4566 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4569 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4570 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4571 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4574 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4576 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4577 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4578 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4579 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4582 if ($recurringContributionID) {
4583 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4585 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4587 if (empty($contributionParams['receive_date']) && $changeDate) {
4588 $contributionParams['receive_date'] = $changeDate;
4591 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4592 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4595 if (isset($input['is_email_receipt'])) {
4596 $values['is_email_receipt'] = $input['is_email_receipt'];
4599 if ($input['component'] == 'contribute') {
4600 if ($contribution->contribution_page_id
) {
4601 // Figure out what we gain from this.
4602 // Note that we may have overwritten the is_email_receipt input, fix that below.
4603 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4605 elseif ($recurContrib && $recurringContributionID) {
4606 $values['amount'] = $recurContrib->amount
;
4607 $values['financial_type_id'] = $objects['contributionType']->id
;
4608 $values['title'] = $source = ts('Offline Recurring Contribution');
4611 if (isset($input['is_email_receipt'])) {
4612 // CRM-19601 - we may have overwritten this above.
4613 $values['is_email_receipt'] = $input['is_email_receipt'];
4615 elseif ($recurContrib && $recurringContributionID) {
4616 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4617 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4618 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4621 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4622 self
::updateMembershipBasedOnCompletionOfContribution(
4624 $primaryContributionID,
4630 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4631 if ($event->is_email_confirm
) {
4632 // @todo this should be set by the function that sends the mail after sending.
4633 $contributionParams['receipt_date'] = $changeDate;
4635 $participantParams['id'] = $participant->id
;
4636 $participantParams['status_id'] = 'Registered';
4637 civicrm_api3('Participant', 'create', $participantParams);
4641 $contributionParams['id'] = $contribution->id
;
4643 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4644 // unsetting it here does NOT cause any other contribution test to fail!
4645 unset($contributionParams['financial_type_id']);
4646 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4648 // Add new soft credit against current $contribution.
4649 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4650 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4653 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4654 'labelColumn' => 'name',
4657 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4658 $input['payment_processor'] = $paymentProcessorId;
4661 if (!empty($contribution->_relatedObjects
['participant'])) {
4662 $input['contribution_mode'] = 'participant';
4663 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4665 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4666 $input['contribution_mode'] = 'membership';
4667 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4668 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4669 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4672 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4673 $transaction->commit();
4675 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4676 $contributionParams['contribution_status_id'], $input['amount']);
4678 // create an activity record
4679 if ($input['component'] == 'contribute') {
4681 $targetContactID = NULL;
4682 if (!empty($ids['related_contact'])) {
4683 $targetContactID = $contribution->contact_id
;
4684 $contribution->contact_id
= $ids['related_contact'];
4686 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4689 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4690 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4691 if (!array_key_exists('is_email_receipt', $values) ||
4692 $values['is_email_receipt'] == 1
4694 civicrm_api3('Contribution', 'sendconfirmation', array(
4695 'id' => $contribution->id
,
4696 'payment_processor_id' => $paymentProcessorId,
4698 CRM_Core_Error
::debug_log_message("Receipt sent");
4701 CRM_Core_Error
::debug_log_message("Success: Database updated");
4702 return $contributionResult;
4706 * Send receipt from contribution.
4708 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4710 * Note that the compose message part has been moved to contribution
4711 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4713 * @param array $input
4714 * Incoming data from Payment processor.
4716 * Related object IDs.
4717 * @param int $contributionID
4718 * @param array $values
4719 * Values related to objects that have already been loaded.
4720 * @param bool $returnMessageText
4721 * Should text be returned instead of sent. This.
4722 * is because the function is also used to generate pdfs
4725 * @throws \CRM_Core_Exception
4726 * @throws \CiviCRM_API3_Exception
4728 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4729 $returnMessageText = FALSE) {
4731 $contribution = new CRM_Contribute_BAO_Contribution();
4732 $contribution->id
= $contributionID;
4733 if (!$contribution->find(TRUE)) {
4734 throw new CRM_Core_Exception('Contribution does not exist');
4736 $contribution->loadRelatedObjects($input, $ids, TRUE);
4737 // set receipt from e-mail and name in value
4738 if (!$returnMessageText) {
4739 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4741 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4742 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4743 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4744 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4750 * Generate From email and from name in an array values
4751 * @param array $input
4752 * @param \CRM_Contribute_BAO_Contribution $contribution
4755 public static function generateFromEmailAndName($input, $contribution) {
4756 // Use input value if supplied.
4757 if (!empty($input['receipt_from_email'])) {
4758 return array(CRM_Utils_array
::value('receipt_from_name', $input, ''), $input['receipt_from_email']);
4760 // if we are still empty see if we can use anything from a contribution page.
4761 $pageValues = array();
4762 if (!empty($contribution->contribution_page_id
)) {
4763 $pageValues = civicrm_api3('ContributionPage', 'getsingle', array('id' => $contribution->contribution_page_id
));
4765 // if we are still empty see if we can use anything from a contribution page.
4766 if (!empty($pageValues['receipt_from_email'])) {
4767 return array($pageValues['receipt_from_name'], $pageValues['receipt_from_email']);
4769 // If we are still empty fall back to the domain or logged in user information.
4770 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4774 * Generate credit note id with next avaible number
4779 public static function createCreditNoteId() {
4780 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4782 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4783 $creditNoteId = NULL;
4787 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4788 $result = civicrm_api3('Contribution', 'getcount', array(
4790 'creditnote_id' => $creditNoteId,
4792 } while ($result > 0);
4794 return $creditNoteId;
4798 * Load related memberships.
4800 * Note that in theory it should be possible to retrieve these from the line_item table
4801 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4802 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4803 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4804 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4806 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4810 * @return array $ids
4814 public function loadRelatedMembershipObjects($ids = []) {
4816 SELECT membership_id
4817 FROM civicrm_membership_payment
4818 WHERE contribution_id = %1 ";
4819 $params = array(1 => array($this->id
, 'Integer'));
4820 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, array());
4822 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4823 while ($dao->fetch()) {
4824 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4825 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4829 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4830 foreach ($ids['membership'] as $id) {
4832 $membership = new CRM_Member_BAO_Membership();
4833 $membership->id
= $id;
4834 if (!$membership->find(TRUE)) {
4835 throw new Exception("Could not find membership record: $id");
4837 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4838 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4839 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4840 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4841 $membership->free();
4849 * This function is used to record partial payments for contribution
4851 * @param array $contribution
4853 * @param array $params
4855 * @return CRM_Financial_DAO_FinancialTrxn
4857 public static function recordPartialPayment($contribution, $params) {
4858 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4859 $pendingStatus = array(
4860 array_search('Pending', $contributionStatuses),
4861 array_search('In Progress', $contributionStatuses),
4863 $statusId = array_search('Completed', $contributionStatuses);
4864 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4865 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is');
4867 elseif (!empty($params['payment_processor'])) {
4868 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['payment_processor'], NULL, 'civicrm_payment_processor');
4870 elseif (!empty($params['payment_instrument_id'])) {
4871 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4874 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4875 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4876 $balanceTrxnParams['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);
4878 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is');
4879 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4880 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4881 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4882 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4883 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4884 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4885 $balanceTrxnParams['currency'] = $contribution['currency'];
4886 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4887 $balanceTrxnParams['status_id'] = $statusId;
4888 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4889 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4890 if ($fromFinancialAccountId != NULL &&
4891 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4893 $balanceTrxnParams['is_payment'] = 1;
4895 if (!empty($params['payment_processor'])) {
4896 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4898 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4902 * Get the description (source field) for the recurring contribution.
4904 * @param CRM_Contribute_BAO_Contribution $contribution
4905 * @param CRM_Event_DAO_Event|null $event
4908 * @throws \CiviCRM_API3_Exception
4910 protected static function getRecurringContributionDescription($contribution, $event) {
4911 if (!empty($contribution->source
)) {
4912 return $contribution->source
;
4914 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4915 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4916 'id' => $contribution->contribution_page_id
,
4917 'return' => 'title',
4919 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4922 return ts('Online Event Registration') . ': ' . $event->title
;
4924 elseif (!empty($contribution->contribution_recur_id
)) {
4925 return 'recurring contribution';
4931 * Function to add payments for contribution
4932 * for Partially Paid status
4934 * @param array $contributions
4935 * @param string $contributionStatusId
4938 public static function addPayments($contributions, $contributionStatusId = NULL) {
4939 // get financial trxn which is a payment
4940 $ftSql = "SELECT ft.id, ft.total_amount
4941 FROM civicrm_financial_trxn ft
4942 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4943 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4944 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4945 'labelColumn' => 'name',
4947 foreach ($contributions as $contribution) {
4948 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4949 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4953 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4956 // store financial item Proportionaly.
4957 $trxnParams = array(
4958 'total_amount' => $ftDao->total_amount
,
4959 'contribution_id' => $contribution->id
,
4961 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
4966 * Function use to store line item proportionaly in
4967 * in entity financial trxn table
4969 * @param array $trxnParams
4971 * @param Integer $trxnId
4973 * @param float $contributionTotalAmount
4976 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4977 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4978 if (!empty($lineItems)) {
4979 // get financial item
4980 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4981 $entityParams = array(
4982 'contribution_total_amount' => $contributionTotalAmount,
4983 'trxn_total_amount' => $trxnParams['total_amount'],
4984 'trxn_id' => $trxnId,
4986 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4991 * Function to check line items.
4993 * @param array $params
4994 * array of order params.
4996 * @throws \API_Exception
4998 public static function checkLineItems(&$params) {
4999 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
5000 $lineItemAmount = 0;
5002 foreach ($params['line_items'] as &$lineItems) {
5003 foreach ($lineItems['line_item'] as &$item) {
5004 if (empty($item['financial_type_id'])) {
5005 $item['financial_type_id'] = $params['financial_type_id'];
5007 $lineItemAmount +
= $item['line_total'];
5011 if (!isset($totalAmount)) {
5012 $params['total_amount'] = $lineItemAmount;
5015 $currency = CRM_Utils_Array
::value('currency', $params, '');
5017 if (empty($currency)) {
5018 $currency = CRM_Core_Config
::singleton()->defaultCurrency
;
5021 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
5022 throw new CRM_Contribute_Exception_CheckLineItemsException();
5028 * Get the financial account for the item associated with the new transaction.
5030 * @param array $params
5031 * @param int $default
5035 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
5037 if (!empty($params['financial_account_id'])) {
5038 return $params['financial_account_id'];
5041 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
5042 $preferredAccountsRelationships = array(
5043 'Refunded' => 'Credit/Contra Revenue Account is',
5044 'Chargeback' => 'Chargeback Account is',
5047 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
5048 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
5049 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
5051 $preferredAccountsRelationships[$contributionStatus]
5059 * ContributionPage values were being imposed onto values.
5061 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
5062 * REALLY didn't want superimposed. The rest are left there in their overkill out
5065 * The rationale for making this explicit is that it was a case of carefully set values being
5066 * seemingly randonly overwritten without much care. In general I think array randomly setting
5067 * variables en mass is risky.
5069 * @param array $values
5073 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
5074 $contributionPageValues = array();
5075 CRM_Contribute_BAO_ContributionPage
::setValues(
5076 $this->contribution_page_id
,
5077 $contributionPageValues
5079 $valuesToCopy = array(
5080 // These are the values that I believe to be useful.
5083 'pay_later_receipt',
5085 'receipt_from_email',
5086 'receipt_from_name',
5090 'honoree_profile_id',
5091 'onbehalf_profile_id',
5092 'honor_block_is_active',
5093 // Kinda might be - but would be on the contribution...
5096 // Included for 'fear of regression' but can't justify any use for these....
5098 'payment_processor',
5099 'financial_type_id',
5100 'amount_block_is_active',
5105 'default_amount_id',
5109 'initial_amount_help_text',
5110 'initial_amount_label',
5112 'is_allow_other_amount',
5113 'is_billing_required',
5114 'is_confirm_enabled',
5115 'is_credit_card_only',
5117 'is_partial_payment',
5118 'is_recur_installments',
5119 'is_recur_interval',
5123 'min_initial_amount',
5124 'recur_frequency_unit',
5131 foreach ($valuesToCopy as $valueToCopy) {
5132 if (isset($contributionPageValues[$valueToCopy])) {
5133 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5140 * Get values of CiviContribute Settings
5141 * and check if its enabled or not.
5142 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5143 * in serialized form. Usually this should be stored as flat settings for each form fields
5144 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5145 * settings we will live with an inconsistency because it's too hard to change for now.
5146 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5149 * @param string $name
5150 * @param bool $checkInvoicing
5154 public static function checkContributeSettings($name = NULL, $checkInvoicing = FALSE) {
5155 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5157 if ($checkInvoicing && !CRM_Utils_Array
::value('invoicing', $contributeSettings)) {
5162 return CRM_Utils_Array
::value($name, $contributeSettings);
5164 return $contributeSettings;
5168 * This function process contribution related objects.
5170 * @param int $contributionId
5171 * @param int $statusId
5172 * @param int|null $previousStatusId
5174 * @param string $receiveDate
5176 * @return null|string
5178 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5180 if (!$contributionId ||
!$statusId) {
5185 'contribution_id' => $contributionId,
5186 'contribution_status_id' => $statusId,
5187 'previous_contribution_status_id' => $previousStatusId,
5188 'receive_date' => $receiveDate,
5191 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5193 if (!is_array($updateResult) ||
5194 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5195 !is_array($updatedComponents) ||
5196 empty($updatedComponents)
5201 // get the user display name.
5203 SELECT display_name as displayName
5204 FROM civicrm_contact
5205 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5206 WHERE civicrm_contribution.id = {$contributionId}";
5207 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5209 // get the status message for user.
5210 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5212 if ($componentName == 'CiviMember') {
5213 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5214 CRM_Member_PseudoConstant
::membershipStatus()
5216 if ($updatedStatusName == 'Cancelled') {
5217 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
5219 elseif ($updatedStatusName == 'Expired') {
5220 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
5223 $endDate = CRM_Utils_Array
::value('membership_end_date', $updateResult);
5225 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
5227 1 => $userDisplayName,
5235 if ($componentName == 'CiviEvent') {
5236 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5237 CRM_Event_PseudoConstant
::participantStatus()
5239 if ($updatedStatusName == 'Cancelled') {
5240 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
5242 elseif ($updatedStatusName == 'Registered') {
5243 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
5247 if ($componentName == 'CiviPledge') {
5248 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5249 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5251 if ($updatedStatusName == 'Cancelled') {
5252 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
5254 elseif ($updatedStatusName == 'Failed') {
5255 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
5257 elseif ($updatedStatusName == 'Completed') {
5258 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
5267 * Get the contribution as it is in the database before being updated.
5269 * @param int $contributionID
5271 * @return \CRM_Contribute_BAO_Contribution|null
5273 private static function getOriginalContribution($contributionID) {
5274 return self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
5278 * Get the amount for the financial item row.
5280 * Helper function to start to break down recordFinancialTransactions for readability.
5282 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5284 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5285 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5288 * @todo move recordFinancialAccounts & helper functions to their own class?
5290 * @param array $params
5291 * Params as passed to contribution.create
5293 * @param string $context
5294 * changeFinancialType| changedAmount
5295 * @param array $lineItemDetails
5297 * @param bool $isARefund
5298 * Is this a refund / negative transaction.
5302 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5303 if ($context == 'changedAmount') {
5304 $lineTotal = $lineItemDetails['line_total'];
5305 if ($lineTotal != $previousLineItemTotal) {
5306 $lineTotal -= $previousLineItemTotal;
5310 elseif ($context == 'changeFinancialType') {
5311 return -$lineItemDetails['line_total'];
5313 elseif ($context == 'changedStatus') {
5314 $cancelledTaxAmount = 0;
5316 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5318 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5320 elseif ($context === NULL) {
5321 // erm, yes because? but, hey, it's tested.
5322 return $lineItemDetails['line_total'];
5324 elseif (empty($lineItemDetails['line_total'])) {
5325 // follow legacy code path
5327 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', array('civi.tag' => 'deprecated'));
5328 return $params['total_amount'];
5331 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5336 * Get the multiplier for adjusting rows.
5338 * If we are dealing with a refund or cancellation then it will be a negative
5339 * amount to reflect the negative transaction.
5341 * If we are changing Financial Type it will be a negative amount to
5342 * adjust down the old type.
5344 * @param int $contribution_status_id
5345 * @param string $context
5349 protected static function getMultiplier($contribution_status_id, $context) {
5350 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5357 * Does this transaction reflect a payment instrument change.
5359 * @param array $params
5360 * @param array $pendingStatuses
5364 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5365 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5367 if (array_key_exists('payment_instrument_id', $params)) {
5368 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5369 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5371 //check if status is changed from Pending to Completed
5372 // do not update payment instrument changes for Pending to Completed
5373 if (!($contributionStatus == 'Completed' &&
5374 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5379 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5380 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5381 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5385 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5386 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5388 // another special case when check number is changed, create new financial records
5389 // create financial trxn with negative amount
5397 * Update the memberships associated with a contribution if it has been completed.
5399 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5400 * load them in this function. Code clean up would compensate for any minor performance implication.
5402 * @param \CRM_Contribute_BAO_Contribution $contribution
5403 * @param int $primaryContributionID
5404 * @param string $changeDate
5406 * @throws \CRM_Core_Exception
5407 * @throws \CiviCRM_API3_Exception
5409 protected static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5410 $contribution->loadRelatedMembershipObjects();
5411 if (empty($contribution->_relatedObjects
['membership'])) {
5414 $memberships = $contribution->_relatedObjects
['membership'];
5415 foreach ($memberships as $membershipTypeIdKey => $membership) {
5417 $membershipParams = array(
5418 'id' => $membership->id
,
5419 'contact_id' => $membership->contact_id
,
5420 'is_test' => $membership->is_test
,
5421 'membership_type_id' => $membership->membership_type_id
,
5422 'membership_activity_status' => 'Completed',
5425 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5426 $membershipParams['membership_type_id'],
5427 $membershipParams['is_test'],
5428 $membershipParams['id']
5431 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5432 // this picks up membership type changes during renewals
5433 // @todo this is almost certainly an obsolete sql call, the pre-change
5434 // membership is accessible via $this->_relatedObjects
5436 SELECT membership_type_id
5437 FROM civicrm_membership_log
5438 WHERE membership_id={$membershipParams['id']}
5441 $dao = CRM_Core_DAO
::executeQuery($sql);
5442 if ($dao->fetch()) {
5443 if (!empty($dao->membership_type_id
)) {
5444 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5449 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5450 $membershipParams['membership_type_id'],
5451 $primaryContributionID
5453 // @todo remove all this stuff in favour of letting the api call further down handle in
5454 // (it is a duplication of what the api does).
5455 $dates = array_fill_keys(array(
5460 if ($currentMembership) {
5462 * Fixed FOR CRM-4433
5463 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5464 * when Contribution mode is notify and membership is for renewal )
5466 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5468 // @todo - we should pass membership_type_id instead of null here but not
5469 // adding as not sure of testing
5470 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5471 $changeDate, NULL, $membershipParams['num_terms']
5473 $dates['join_date'] = $currentMembership['join_date'];
5476 //get the status for membership.
5477 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5479 $dates['join_date'],
5482 $membershipParams['membership_type_id'],
5486 unset($dates['end_date']);
5487 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5488 //we might be renewing membership,
5489 //so make status override false.
5490 $membershipParams['is_override'] = FALSE;
5491 $membershipParams['status_override_end_date'] = 'null';
5493 //CRM-17723 - reset static $relatedContactIds array()
5494 // @todo move it to Civi Statics.
5496 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
5497 civicrm_api3('Membership', 'create', $membershipParams);
5503 * Get payment links as they relate to a contribution.
5505 * If a payment can be made then include a payment link & if a refund is appropriate
5506 * then a refund link.
5509 * @param float $balance
5510 * @param string $contributionStatus
5512 * @return array $actionLinks Links array containing:
5516 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5517 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5518 // In general the balance is the best way to determine if a payment can be added or not,
5519 // but not for Failed contributions, where we don't accept additional payments at the moment.
5520 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5521 // do accept more payments agains them.
5524 $actionLinks = array();
5525 if ((int) $balance > 0) {
5526 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5527 $actionLinks[] = array(
5528 'url' => CRM_Utils_System
::url('civicrm/payment', array(
5534 'title' => ts('Submit Credit Card payment'),
5537 $actionLinks[] = array(
5538 'url' => CRM_Utils_System
::url('civicrm/payment', array(
5543 'title' => ts('Record Payment'),
5546 elseif ((int) $balance < 0) {
5547 $actionLinks[] = array(
5548 'url' => CRM_Utils_System
::url('civicrm/payment', array(
5553 'title' => ts('Record Refund'),
5556 return $actionLinks;
5560 * Assign Test Value.
5562 * @param string $fieldName
5563 * @param array $fieldDef
5564 * @param int $counter
5566 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5567 if ($fieldName == 'tax_amount') {
5568 $this->{$fieldName} = "0.00";
5570 elseif ($fieldName == 'net_amount') {
5571 $this->{$fieldName} = "2.00";
5573 elseif ($fieldName == 'total_amount') {
5574 $this->{$fieldName} = "3.00";
5576 elseif ($fieldName == 'fee_amount') {
5577 $this->{$fieldName} = "1.00";
5580 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5585 * Check if contribution has participant/membership payment.
5587 * @param int $contributionId
5592 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5593 // get line item for contribution
5594 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5595 // check if line item is for membership or participant
5596 foreach ($lineItems as $items) {
5597 if ($items['entity_table'] == 'civicrm_participant') {
5601 elseif ($items['entity_table'] == 'civicrm_membership') {
5613 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5615 * @param array $trxnParams
5616 * Financial trxn params
5617 * @param array $contributionParams
5618 * Contribution Params
5622 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5623 if (!self
::checkContributeSettings('always_post_to_accounts_receivable')) {
5626 $statusId = $contributionParams['contribution']->contribution_status_id
;
5627 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5628 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5629 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5630 // Return if contribution status is not completed.
5631 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5632 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5633 && $contributionParams['prevContribution']->is_pay_later
== 0
5639 $params = $trxnParams;
5640 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5641 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5642 $params['to_financial_account_id'] = $arAccountId;
5643 $params['status_id'] = array_search('Pending', $contributionStatuses);
5644 $params['is_payment'] = FALSE;
5645 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5646 self
::$_trxnIDs[] = $trxn->id
;
5647 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5651 * Calculate financial item amount when contribution is updated.
5653 * @param array $params
5654 * contribution params
5655 * @param array $amountParams
5657 * @param string $context
5661 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5662 if (!empty($params['is_quick_config'])) {
5663 $amount = $amountParams['item_amount'];
5665 $amount = $params['total_amount'];
5666 if ($context === NULL) {
5667 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5672 $amount = $amountParams['line_total'];
5673 if ($context == 'changedAmount') {
5674 $amount -= $amountParams['previous_line_total'];
5676 $amount *= $amountParams['diff'];
5682 * Retrieve Sales Tax Financial Accounts.
5688 public static function getSalesTaxFinancialAccounts() {
5689 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5690 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5691 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5692 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5693 $queryParams = array(1 => array($accountRel, 'Integer'));
5694 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5695 $financialAccount = array();
5696 while ($dao->fetch()) {
5697 $financialAccount[$dao->id
] = $dao->id
;
5699 return $financialAccount;
5703 * Create tax entry in civicrm_entity_financial_trxn table.
5705 * @param array $entityParams
5707 * @param array $eftParams
5710 public static function createProportionalEntry($entityParams, $eftParams) {
5712 if ($entityParams['contribution_total_amount'] != 0) {
5713 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5715 // Record Entity Financial Trxn; CRM-20145
5716 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5717 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5721 * Create array of last financial item id's.
5723 * @param int $contributionId
5727 public static function getLastFinancialItemIds($contributionId) {
5728 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5729 FROM civicrm_financial_item fi
5730 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5731 WHERE li.contribution_id = %1";
5732 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contributionId, 'Integer')));
5733 $ftIds = $taxItems = array();
5734 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5735 while ($dao->fetch()) {
5736 /* if sales tax item*/
5737 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5738 $taxItems[$dao->price_field_value_id
] = array(
5739 'financial_item_id' => $dao->id
,
5740 'amount' => $dao->tax_amount
,
5744 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5747 return array($ftIds, $taxItems);
5751 * Create proportional entries in civicrm_entity_financial_trxn.
5753 * @param array $entityParams
5755 * @param array $lineItems
5757 * @param array $ftIds
5759 * @param array $taxItems
5762 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5764 'entity_table' => 'civicrm_financial_item',
5765 'financial_trxn_id' => $entityParams['trxn_id'],
5767 foreach ($lineItems as $key => $value) {
5768 if ($value['qty'] == 0) {
5771 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5772 $entityParams['line_item_amount'] = $value['line_total'];
5773 self
::createProportionalEntry($entityParams, $eftParams);
5774 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5775 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5776 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5777 self
::createProportionalEntry($entityParams, $eftParams);
5783 * Load entities related to the contribution into $this->_relatedObjects.
5787 * @throws \CRM_Core_Exception
5789 protected function loadRelatedEntitiesByID($ids) {
5791 'contact' => 'CRM_Contact_BAO_Contact',
5792 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5793 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5794 'financialType' => 'CRM_Financial_BAO_FinancialType',
5795 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5797 foreach ($entities as $entity => $bao) {
5798 if (!empty($ids[$entity])) {
5799 $this->_relatedObjects
[$entity] = new $bao();
5800 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5801 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5802 throw new CRM_Core_Exception($entity . ' could not be loaded');
5809 * Should an email receipt be sent for this contribution when complete.
5811 * @param array $input
5815 protected function isEmailReceipt($input) {
5816 if (isset($input['is_email_receipt'])) {
5817 return $input['is_email_receipt'];
5819 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5820 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5826 * Function to replace contribution tokens.
5828 * @param array $contributionIds
5830 * @param string $subject
5832 * @param array $subjectToken
5834 * @param string $text
5836 * @param string $html
5838 * @param array $messageToken
5840 * @param bool $escapeSmarty
5844 public static function replaceContributionTokens(
5853 if (empty($contributionIds)) {
5856 $contributionDetails = array();
5857 foreach ($contributionIds as $id) {
5858 $result = civicrm_api3('Contribution', 'get', array('id' => $id));
5859 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5860 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5861 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5863 return $contributionDetails;
5867 * Get invoice_number for contribution.
5869 * @param int $contributionID
5873 public static function getInvoiceNumber($contributionID) {
5874 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix', TRUE)) {
5875 return $invoicePrefix . $contributionID;