3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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|void
102 public static function add(&$params, $ids = array()) {
103 if (empty($params)) {
106 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
107 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
108 $duplicates = array();
109 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
110 $error = CRM_Core_Error
::singleton();
111 $d = implode(', ', $duplicates);
112 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
115 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
120 // first clean up all the money fields
121 $moneyFields = array(
125 'non_deductible_amount',
128 //if priceset is used, no need to cleanup money
129 if (!empty($params['skipCleanMoney'])) {
130 unset($moneyFields[0]);
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());
144 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
145 //if contribution is created with cancelled or refunded status, add credit note id
146 if (!empty($params['contribution_status_id'])) {
147 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
148 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
149 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
151 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
152 $params['creditnote_id'] = self
::createCreditNoteId();
157 // Since the fee amount is expecting this (later on) ensure it is always set.
158 // It would only not be set for an update where it is unchanged.
159 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id'));
163 && CRM_Utils_Array
::value('membership_id', $params)
164 && self
::checkContributeSettings('deferred_revenue_enabled')
166 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
167 if ($memberStartDate) {
168 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
171 self
::calculateMissingAmountParams($params, $contributionID);
173 if (!empty($params['payment_instrument_id'])) {
174 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
175 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
176 $params['check_number'] = 'null';
180 $setPrevContribution = TRUE;
181 // CRM-13964 partial payment
182 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
183 $partialAmtTotal = $params['partial_payment_total'];
184 $partialAmtPay = $params['partial_amount_to_pay'];
185 $params['total_amount'] = $partialAmtTotal;
186 if ($partialAmtPay < $partialAmtTotal) {
187 $params['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
188 $params['is_pay_later'] = 0;
189 $setPrevContribution = FALSE;
192 if ($contributionID && $setPrevContribution) {
193 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
196 if ($contributionID && !empty($params['revenue_recognition_date']) && !empty($params['prevContribution'])
197 && !($contributionStatus[$params['prevContribution']->contribution_status_id
] == 'Pending')
198 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
200 unset($params['revenue_recognition_date']);
203 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
204 isset($params['financial_type_id']))) {
205 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
208 if ($contributionID) {
209 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
212 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
214 $contribution = new CRM_Contribute_BAO_Contribution();
215 $contribution->copyValues($params);
217 $contribution->id
= $contributionID;
219 if (empty($contribution->id
)) {
220 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
221 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
222 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
226 $result = $contribution->save();
228 // Add financial_trxn details as part of fix for CRM-4724
229 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
230 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
232 //add Account details
233 $params['contribution'] = $contribution;
234 self
::recordFinancialAccounts($params);
236 if (self
::isUpdateToRecurringContribution($params)) {
237 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
238 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
239 $contributionStatus[$params['contribution_status_id']],
240 CRM_Utils_Array
::value('receive_date', $params)
244 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
246 if ($contributionID) {
247 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
250 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
257 * Is this contribution updating an existing recurring contribution.
259 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
260 * pending payment is being confirmed (or failing).
262 * @param array $params
266 public static function isUpdateToRecurringContribution($params) {
267 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
270 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
273 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
276 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
277 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
284 * Get defaults for new entity.
287 public static function getDefaults() {
289 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
290 FALSE, FALSE, FALSE, 'AND is_default = 1')
292 'contribution_status_id' => CRM_Core_Pseudoconstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
297 * Fetch the object and store the values in the values array.
299 * @param array $params
300 * Input parameters to find object.
301 * @param array $values
302 * Output values of the object.
304 * The array that holds all the db ids.
306 * @return CRM_Contribute_BAO_Contribution|null
307 * The found object or null
309 public static function getValues($params, &$values, &$ids) {
310 if (empty($params)) {
313 $contribution = new CRM_Contribute_BAO_Contribution();
315 $contribution->copyValues($params);
317 if ($contribution->find(TRUE)) {
318 $ids['contribution'] = $contribution->id
;
320 CRM_Core_DAO
::storeValues($contribution, $values);
322 return $contribution;
324 $null = NULL; // return by reference
329 * Get the values and resolve the most common mappings.
331 * Since contribution status is resolved in almost every function that calls getValues it makes
332 * sense to have an extra function to resolve it rather than repeat the code.
334 * Think carefully before adding more mappings to be resolved as there could be performance implications
335 * if this function starts to be called from more iterative functions.
337 * @param array $params
338 * Input parameters to find object.
341 * Array of the found contribution.
342 * @throws CRM_Core_Exception
344 public static function getValuesWithMappings($params) {
345 $values = $ids = array();
346 $contribution = self
::getValues($params, $values, $ids);
347 if (is_null($contribution)) {
348 throw new CRM_Core_Exception('No contribution found');
350 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
355 * Calculate net_amount & fee_amount if they are not set.
357 * Net amount should be total - fee.
358 * This should only be called for new contributions.
360 * @param array $params
361 * Params for a new contribution before they are saved.
362 * @param int|null $contributionID
363 * Contribution ID if we are dealing with an update.
365 * @throws \CiviCRM_API3_Exception
367 public static function calculateMissingAmountParams(&$params, $contributionID) {
368 if (!$contributionID && !isset($params['fee_amount'])) {
369 if (isset($params['total_amount']) && isset($params['net_amount'])) {
370 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
373 $params['fee_amount'] = 0;
376 if (!isset($params['net_amount'])) {
377 if (!$contributionID) {
378 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
381 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
382 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
383 // net_amount may need adjusting.
384 $contribution = civicrm_api3('Contribution', 'getsingle', array(
385 'id' => $contributionID,
386 'return' => array('total_amount', 'net_amount'),
388 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
389 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
390 $params['net_amount'] = $totalAmount - $feeAmount;
398 * @param $billingLocationTypeID
402 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
403 $hasBillingField = FALSE;
404 $billingFields = array(
412 //build address array
413 $addressParams = array();
414 $addressParams['location_type_id'] = $billingLocationTypeID;
415 $addressParams['is_billing'] = 1;
417 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
418 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
419 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
420 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
422 foreach ($billingFields as $value) {
423 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
424 if (!empty($addressParams[$value])) {
425 $hasBillingField = TRUE;
428 return array($hasBillingField, $addressParams);
432 * Get address params ready to be passed to the payment processor.
434 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
435 * To create an address we need state_province_id.
437 * @param array $params
438 * @param int $billingLocationTypeID
442 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
443 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
444 foreach ($addressParams as $name => $field) {
445 if (substr($name, 0, 8) == 'billing_') {
446 $addressParams[substr($name, 9)] = $addressParams[$field];
449 return array($hasBillingField, $addressParams);
453 * Get the number of terms for this contribution for a given membership type
454 * based on querying the line item table and relevant price field values
455 * Note that any one contribution should only be able to have one line item relating to a particular membership
458 * @param int $membershipTypeID
460 * @param int $contributionID
464 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
465 $numTerms = CRM_Core_DAO
::singleValueQuery("
466 SELECT membership_num_terms FROM civicrm_line_item li
467 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
468 WHERE contribution_id = %1 AND membership_type_id = %2",
469 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
471 // default of 1 is precautionary
472 return empty($numTerms) ?
1 : $numTerms;
476 * Takes an associative array and creates a contribution object.
478 * @param array $params
479 * (reference ) an assoc array of name/value pairs.
481 * The array that holds all the db ids.
483 * @return CRM_Contribute_BAO_Contribution
485 public static function create(&$params, $ids = array()) {
486 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date', 'revenue_recognition_date');
487 foreach ($dateFields as $df) {
488 if (isset($params[$df])) {
489 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
493 //if contribution is created with cancelled or refunded status, add credit note id
494 if (!empty($params['contribution_status_id'])) {
495 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
497 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
498 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
500 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
501 $params['creditnote_id'] = self
::createCreditNoteId();
506 $transaction = new CRM_Core_Transaction();
508 $contribution = self
::add($params, $ids);
510 if (is_a($contribution, 'CRM_Core_Error')) {
511 $transaction->rollback();
512 return $contribution;
515 $params['contribution_id'] = $contribution->id
;
517 if (!empty($params['custom']) &&
518 is_array($params['custom'])
520 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
523 $session = CRM_Core_Session
::singleton();
525 if (!empty($params['note'])) {
527 'entity_table' => 'civicrm_contribution',
528 'note' => $params['note'],
529 'entity_id' => $contribution->id
,
530 'contact_id' => $session->get('userID'),
531 'modified_date' => date('Ymd'),
533 if (!$noteParams['contact_id']) {
534 $noteParams['contact_id'] = $params['contact_id'];
536 CRM_Core_BAO_Note
::add($noteParams);
539 // make entry in batch entity batch table
540 if (!empty($params['batch_id'])) {
541 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
542 $titleFields = array(
548 $retrieveRequired = 0;
549 foreach ($titleFields as $titleField) {
550 if (!isset($contribution->$titleField)) {
551 $retrieveRequired = 1;
555 if ($retrieveRequired == 1) {
556 $contribution->find(TRUE);
560 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
562 $transaction->commit();
564 $activity = civicrm_api3('Activity', 'get', array(
565 'source_record_id' => $contribution->id
,
566 'options' => array('limit' => 1),
568 'activity_type_id' => 'Contribution',
569 'return' => array('id', 'campaign'),
572 //CRM-18406: Update activity when edit contribution.
573 if ($activity['count']) {
574 // CRM-13237 : if activity record found, update it with campaign id of contribution
575 // @todo compare campaign ids first.
576 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
577 $contribution->activity_id
= $activity['id'];
580 if (empty($contribution->contact_id
)) {
581 $contribution->find(TRUE);
583 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
585 // do not add to recent items for import, CRM-4399
586 if (empty($params['skipRecentView'])) {
587 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
588 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
590 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
591 $titleFields = array(
597 $retrieveRequired = 0;
598 foreach ($titleFields as $titleField) {
599 if (!isset($contribution->$titleField)) {
600 $retrieveRequired = 1;
604 if ($retrieveRequired == 1) {
605 $contribution->find(TRUE);
607 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
608 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
610 $recentOther = array();
611 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
612 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
613 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
617 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
618 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
619 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
623 // add the recently created Contribution
624 CRM_Utils_Recent
::add($title,
628 $contribution->contact_id
,
634 return $contribution;
638 * Get the values for pseudoconstants for name->value and reverse.
640 * @param array $defaults
641 * (reference) the default values, some of which need to be resolved.
642 * @param bool $reverse
643 * True if we want to resolve the values in the reverse direction (value -> name).
645 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
646 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
647 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
648 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
649 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
653 * Convert associative array names to values and vice-versa.
655 * This function is used by both the web form layer and the api. Note that
656 * the api needs the name => value conversion, also the view layer typically
657 * requires value => name conversion
659 * @param array $defaults
660 * @param string $property
661 * @param array $lookup
662 * @param bool $reverse
666 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
667 $id = $property . '_id';
669 $src = $reverse ?
$property : $id;
670 $dst = $reverse ?
$id : $property;
672 if (!array_key_exists($src, $defaults)) {
676 $look = $reverse ?
array_flip($lookup) : $lookup;
678 if (is_array($look)) {
679 if (!array_key_exists($defaults[$src], $look)) {
683 $defaults[$dst] = $look[$defaults[$src]];
688 * Retrieve DB object based on input parameters.
690 * It also stores all the retrieved values in the default array.
692 * @param array $params
693 * (reference ) an assoc array of name/value pairs.
694 * @param array $defaults
695 * (reference ) an assoc array to hold the name / value pairs.
696 * in a hierarchical manner
698 * (reference) the array that holds all the db ids.
700 * @return CRM_Contribute_BAO_Contribution
702 public static function retrieve(&$params, &$defaults, &$ids) {
703 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
704 return $contribution;
708 * Combine all the importable fields from the lower levels object.
710 * The ordering is important, since currently we do not have a weight
711 * scheme. Adding weight is super important and should be done in the
712 * next week or so, before this can be called complete.
714 * @param string $contactType
715 * @param bool $status
718 * array of importable Fields
720 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
721 if (!self
::$_importableFields) {
722 if (!self
::$_importableFields) {
723 self
::$_importableFields = array();
727 $fields = array('' => array('title' => ts('- do not import -')));
730 $fields = array('' => array('title' => ts('- Contribution Fields -')));
733 $note = CRM_Core_DAO_Note
::import();
734 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
735 unset($tmpFields['option_value']);
736 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
737 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
739 // Using new Dedupe rule.
741 'contact_type' => $contactType,
742 'used' => 'Unsupervised',
744 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
745 $tmpContactField = array();
746 if (is_array($fieldsArray)) {
747 foreach ($fieldsArray as $value) {
748 //skip if there is no dupe rule
749 if ($value == 'none') {
752 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
757 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
758 $tmpContactField[trim($value)] = $contactFields[trim($value)];
760 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
763 $title = $tmpContactField[trim($value)]['title'];
765 $tmpContactField[trim($value)]['title'] = $title;
769 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
770 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
771 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
772 $fields = array_merge($fields, $tmpContactField);
773 $fields = array_merge($fields, $tmpFields);
774 $fields = array_merge($fields, $note);
775 $fields = array_merge($fields, $optionFields);
776 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
777 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
778 self
::$_importableFields = $fields;
780 return self
::$_importableFields;
784 * Get exportable fields with pseudoconstants rendered as an extra field.
786 public static function getExportableFieldsWithPseudoConstants() {
787 $fields = self
::exportableFields();
788 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
793 * Combine all the exportable fields from the lower level objects.
795 * @param bool $checkPermission
798 * array of exportable Fields
800 public static function &exportableFields($checkPermission = TRUE) {
801 if (!self
::$_exportableFields) {
802 if (!self
::$_exportableFields) {
803 self
::$_exportableFields = array();
806 $impFields = CRM_Contribute_DAO_Contribution
::export();
807 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
808 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
809 $typeField = CRM_Financial_DAO_FinancialType
::export();
810 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
812 $contributionPage = array(
813 'contribution_page' => array(
814 'title' => ts('Contribution Page'),
815 'name' => 'contribution_page',
816 'where' => 'civicrm_contribution_page.title',
817 'data_type' => CRM_Utils_Type
::T_STRING
,
821 $contributionNote = array(
822 'contribution_note' => array(
823 'title' => ts('Contribution Note'),
824 'name' => 'contribution_note',
825 'data_type' => CRM_Utils_Type
::T_TEXT
,
829 $extraFields = array(
830 'contribution_batch' => array(
831 'title' => ts('Batch Name'),
836 $campaignTitle = array(
837 'contribution_campaign_title' => array(
838 'title' => ts('Campaign Title'),
839 'name' => 'campaign_title',
840 'where' => 'civicrm_campaign.title',
841 'data_type' => CRM_Utils_Type
::T_STRING
,
844 $softCreditFields = array(
845 'contribution_soft_credit_name' => array(
846 'name' => 'contribution_soft_credit_name',
847 'title' => ts('Soft Credit For'),
848 'where' => 'civicrm_contact_d.display_name',
849 'data_type' => CRM_Utils_Type
::T_STRING
,
851 'contribution_soft_credit_amount' => array(
852 'name' => 'contribution_soft_credit_amount',
853 'title' => ts('Soft Credit Amount'),
854 'where' => 'civicrm_contribution_soft.amount',
855 'data_type' => CRM_Utils_Type
::T_MONEY
,
857 'contribution_soft_credit_type' => array(
858 'name' => 'contribution_soft_credit_type',
859 'title' => ts('Soft Credit Type'),
860 'where' => 'contribution_softcredit_type.label',
861 'data_type' => CRM_Utils_Type
::T_STRING
,
863 'contribution_soft_credit_contribution_id' => array(
864 'name' => 'contribution_soft_credit_contribution_id',
865 'title' => ts('Soft Credit For Contribution ID'),
866 'where' => 'civicrm_contribution_soft.contribution_id',
867 'data_type' => CRM_Utils_Type
::T_INT
,
869 'contribution_soft_credit_contact_id' => array(
870 'name' => 'contribution_soft_credit_contact_id',
871 'title' => ts('Soft Credit For Contact ID'),
872 'where' => 'civicrm_contact_d.id',
873 'data_type' => CRM_Utils_Type
::T_INT
,
877 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
879 'contribution_product_id' => array(
880 'title' => ts('Premium'),
881 'name' => 'contribution_product_id',
882 'where' => 'civicrm_product.id',
883 'data_type' => CRM_Utils_Type
::T_INT
,
887 $fields = array_merge($impFields, $typeField, $contributionPage, $expFieldProduct,
888 $expFieldsContrib, $contributionNote, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
889 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
892 self
::$_exportableFields = $fields;
895 return self
::$_exportableFields;
899 * @param null $status
900 * @param null $startDate
901 * @param null $endDate
905 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
909 $where[] = 'contribution_status_id = 1';
913 $where[] = 'contribution_status_id = 3';
918 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
921 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
923 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
924 if ($financialTypes) {
925 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
926 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
929 $where[] = "c.financial_type_id IN (0)";
932 $whereCond = implode(' AND ', $where);
935 SELECT sum( total_amount ) as total_amount,
936 count( c.id ) as total_count,
938 FROM civicrm_contribution c
939 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
940 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
942 AND ( is_test = 0 OR is_test IS NULL )
943 AND contact.is_deleted = 0
947 $dao = CRM_Core_DAO
::executeQuery($query);
950 while ($dao->fetch()) {
951 $count +
= $dao->total_count
;
952 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
956 'amount' => implode(', ', $amount),
964 * Delete the indirect records associated with this contribution first.
969 * $results no of deleted Contribution on success, false otherwise
971 public static function deleteContribution($id) {
972 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
974 $transaction = new CRM_Core_Transaction();
977 //delete activity record
979 'source_record_id' => $id,
980 // activity type id for contribution
981 'activity_type_id' => 6,
984 CRM_Activity_BAO_Activity
::deleteActivity($params);
986 //delete billing address if exists for this contribution.
987 self
::deleteAddress($id);
989 //update pledge and pledge payment, CRM-3961
990 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
992 // remove entry from civicrm_price_set_entity, CRM-5095
993 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
994 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
996 // cleanup line items.
997 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
999 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1000 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1002 if ($participantId) {
1003 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1006 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1010 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1011 $noteId = key($note);
1013 CRM_Core_BAO_Note
::del($noteId, FALSE);
1016 $dao = new CRM_Contribute_DAO_Contribution();
1019 $results = $dao->delete();
1021 $transaction->commit();
1023 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1025 // delete the recently created Contribution
1026 $contributionRecent = array(
1028 'type' => 'Contribution',
1030 CRM_Utils_Recent
::del($contributionRecent);
1036 * React to a financial transaction (payment) failure.
1038 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1039 * payments is important for forensic and outreach reasons.
1041 * @param int $contributionID
1042 * @param int $contactID
1043 * @param string $message
1045 * @throws \CiviCRM_API3_Exception
1047 public static function failPayment($contributionID, $contactID, $message) {
1048 civicrm_api3('activity', 'create', array(
1049 'activity_type_id' => 'Failed Payment',
1050 'details' => $message,
1051 'subject' => ts('Payment failed at payment processor'),
1052 'source_record_id' => $contributionID,
1053 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1057 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1058 civicrm_api3('contribution', 'create', array(
1059 'id' => $contributionID,
1060 'contribution_status_id' => 'Failed',
1065 * Check if there is a contribution with the same trxn_id or invoice_id.
1067 * @param array $input
1068 * An assoc array of name/value pairs.
1069 * @param array $duplicates
1070 * (reference) store ids of duplicate contribs.
1074 * true if duplicate, false otherwise
1076 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1078 $id = CRM_Utils_Array
::value('id', $input);
1080 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1081 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1087 $clause[] = "trxn_id = %1";
1088 $input[1] = array($trxn_id, 'String');
1092 $clause[] = "invoice_id = %2";
1093 $input[2] = array($invoice_id, 'String');
1096 if (empty($clause)) {
1100 $clause = implode(' OR ', $clause);
1102 $clause = "( $clause ) AND id != %3";
1103 $input[3] = array($id, 'Integer');
1106 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1107 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1109 while ($dao->fetch()) {
1110 $duplicates[] = $dao->id
;
1117 * Takes an associative array and creates a contribution_product object.
1119 * the function extract all the params it needs to initialize the create a
1120 * contribution_product object. the params array could contain additional unused name/value
1123 * @param array $params
1124 * (reference) an assoc array of name/value pairs.
1126 * @return CRM_Contribute_DAO_ContributionProduct
1128 public static function addPremium(&$params) {
1129 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1130 $contributionProduct->copyValues($params);
1131 return $contributionProduct->save();
1135 * Get list of contribution fields for profile.
1136 * For now we only allow custom contribution fields to be in
1139 * @param bool $addExtraFields
1140 * True if special fields needs to be added.
1143 * the list of contribution fields
1145 public static function getContributionFields($addExtraFields = TRUE) {
1146 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1147 // @todo remove this - this line was added because payment_instrument_id was not
1148 // set to exportable - but now it is.
1149 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1151 if ($addExtraFields) {
1152 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1155 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1157 foreach ($contributionFields as $key => $var) {
1158 if ($key == 'contribution_contact_id') {
1161 elseif ($key == 'contribution_campaign_id') {
1162 $var['title'] = ts('Campaign');
1164 $fields[$key] = $var;
1167 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1172 * Add extra fields specific to contribution.
1174 public static function getSpecialContributionFields() {
1175 $extraFields = array(
1176 'contribution_soft_credit_name' => array(
1177 'name' => 'contribution_soft_credit_name',
1178 'title' => ts('Soft Credit Name'),
1179 'headerPattern' => '/^soft_credit_name$/i',
1180 'where' => 'civicrm_contact_d.display_name',
1182 'contribution_soft_credit_email' => array(
1183 'name' => 'contribution_soft_credit_email',
1184 'title' => ts('Soft Credit Email'),
1185 'headerPattern' => '/^soft_credit_email$/i',
1186 'where' => 'soft_email.email',
1188 'contribution_soft_credit_phone' => array(
1189 'name' => 'contribution_soft_credit_phone',
1190 'title' => ts('Soft Credit Phone'),
1191 'headerPattern' => '/^soft_credit_phone$/i',
1192 'where' => 'soft_phone.phone',
1194 'contribution_soft_credit_contact_id' => array(
1195 'name' => 'contribution_soft_credit_contact_id',
1196 'title' => ts('Soft Credit Contact ID'),
1197 'headerPattern' => '/^soft_credit_contact_id$/i',
1198 'where' => 'civicrm_contribution_soft.contact_id',
1200 'contribution_pcp_title' => array(
1201 'name' => 'contribution_pcp_title',
1202 'title' => ts('Personal Campaign Page Title'),
1203 'headerPattern' => '/^contribution_pcp_title$/i',
1204 'where' => 'contribution_pcp.title',
1208 return $extraFields;
1212 * @param int $pageID
1216 public static function getCurrentandGoalAmount($pageID) {
1218 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1219 FROM civicrm_contribution_page p,
1220 civicrm_contribution c
1221 WHERE p.id = c.contribution_page_id
1223 AND c.cancel_date is null
1227 $config = CRM_Core_Config
::singleton();
1228 $params = array(1 => array($pageID, 'Integer'));
1229 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1231 if ($dao->fetch()) {
1232 return array($dao->goal
, $dao->total
);
1235 return array(NULL, NULL);
1240 * Get list of contributions which credit the passed in contact ID.
1242 * The returned array provides details about the original contribution & donor.
1244 * @todo - this is a confusing function called from one place. It has a test. It would be
1245 * nice to deprecate it.
1247 * @param int $honorId
1248 * In Honor of Contact ID.
1251 * list of contribution fields
1253 public static function getHonorContacts($honorId) {
1255 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1256 $honorDAO->contact_id
= $honorId;
1259 $type = CRM_Contribute_PseudoConstant
::financialType();
1261 while ($honorDAO->fetch()) {
1262 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1263 $contributionDAO->id
= $honorDAO->contribution_id
;
1265 if ($contributionDAO->find(TRUE)) {
1266 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1267 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1268 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1269 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1270 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1271 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1272 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1273 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1274 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1282 * Get the sort name of a contact for a particular contribution.
1285 * Id of the contribution.
1287 * @return null|string
1288 * sort name of the contact if found
1290 public static function sortName($id) {
1291 $id = CRM_Utils_Type
::escape($id, 'Integer');
1294 SELECT civicrm_contact.sort_name
1295 FROM civicrm_contribution, civicrm_contact
1296 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1297 AND civicrm_contribution.id = {$id}
1299 return CRM_Core_DAO
::singleValueQuery($query);
1303 * @param int $contactID
1307 public static function annual($contactID) {
1308 if (is_array($contactID)) {
1309 $contactIDs = implode(',', $contactID);
1312 $contactIDs = $contactID;
1315 $config = CRM_Core_Config
::singleton();
1316 $startDate = $endDate = NULL;
1318 $currentMonth = date('m');
1319 $currentDay = date('d');
1320 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1321 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1322 (int ) $config->fiscalYearStart
['d'] > $currentDay
1325 $year = date('Y') - 1;
1330 $nextYear = $year +
1;
1332 if ($config->fiscalYearStart
) {
1333 $newFiscalYearStart = $config->fiscalYearStart
;
1334 if ($newFiscalYearStart['M'] < 10) {
1335 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1337 if ($newFiscalYearStart['d'] < 10) {
1338 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1340 $config->fiscalYearStart
= $newFiscalYearStart;
1341 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1346 $startDate = "$year$monthDay";
1347 $endDate = "$nextYear$monthDay";
1348 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1349 $additionalWhere = " AND b.financial_type_id IN (0)";
1350 $liWhere = " AND i.financial_type_id IN (0)";
1351 if (!empty($financialTypes)) {
1352 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1353 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1356 SELECT count(*) as count,
1357 sum(total_amount) as amount,
1358 avg(total_amount) as average,
1360 FROM civicrm_contribution b
1361 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1362 WHERE b.contact_id IN ( $contactIDs )
1363 AND b.contribution_status_id = 1
1365 AND b.receive_date >= $startDate
1366 AND b.receive_date < $endDate
1370 $dao = CRM_Core_DAO
::executeQuery($query);
1372 $amount = $average = array();
1373 while ($dao->fetch()) {
1374 if ($dao->count
> 0 && $dao->amount
> 0) {
1375 $count +
= $dao->count
;
1376 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1377 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1383 implode(', ', $amount),
1384 implode(', ', $average),
1387 return array(0, 0, 0);
1391 * Check if there is a contribution with the params passed in.
1393 * Used for trxn_id,invoice_id and contribution_id
1395 * @param array $params
1396 * An assoc array of name/value pairs.
1399 * contribution id if success else NULL
1401 public static function checkDuplicateIds($params) {
1402 $dao = new CRM_Contribute_DAO_Contribution();
1406 foreach ($params as $k => $v) {
1408 $clause[] = "$k = '$v'";
1411 $clause = implode(' AND ', $clause);
1412 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1413 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1415 while ($dao->fetch()) {
1423 * Get the contribution details for component export.
1425 * @param int $exportMode
1427 * @param string $componentIds
1433 public static function getContributionDetails($exportMode, $componentIds) {
1434 $paymentDetails = array();
1435 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1437 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1438 $componentSelect = " civicrm_participant_payment.participant_id id";
1439 $additionalClause = "
1440 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1441 AND civicrm_participant_payment.participant_id {$componentClause} )
1444 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1445 $componentSelect = " civicrm_membership_payment.membership_id id";
1446 $additionalClause = "
1447 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1448 AND civicrm_membership_payment.membership_id {$componentClause} )
1451 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1452 $componentSelect = " civicrm_pledge_payment.id id";
1453 $additionalClause = "
1454 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1455 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1459 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1460 trxn_id, {$componentSelect}
1461 FROM civicrm_contribution
1462 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1463 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1464 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1465 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1466 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1467 AND option_group_contribution_status.id = contribution_status.option_group_id )
1471 $dao = CRM_Core_DAO
::executeQuery($query);
1473 while ($dao->fetch()) {
1474 $paymentDetails[$dao->id
] = array(
1475 'total_amount' => $dao->total_amount
,
1476 'contribution_status' => $dao->status
,
1477 'receive_date' => $dao->receive_date
,
1478 'pay_instru' => $dao->payment_instrument
,
1479 'trxn_id' => $dao->trxn_id
,
1483 return $paymentDetails;
1487 * Create address associated with contribution record.
1489 * As long as there is one or more billing field in the parameters we will create the address.
1491 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1494 * @param array $params
1495 * @param int $billingLocationTypeID
1500 public static function createAddress($params, $billingLocationTypeID) {
1501 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1502 if ($hasBillingField) {
1503 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1504 return $address->id
;
1511 * Delete billing address record related contribution.
1513 * @param int $contributionId
1514 * @param int $contactId
1516 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1518 $contactJoin = NULL;
1520 if ($contributionId) {
1521 $clauses[] = "cc.id = {$contributionId}";
1525 $clauses[] = "cco.id = {$contactId}";
1526 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1529 if (empty($clauses)) {
1530 CRM_Core_Error
::fatal();
1533 $condition = implode(' OR ', $clauses);
1537 FROM civicrm_address ca
1538 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1542 $dao = CRM_Core_DAO
::executeQuery($query);
1544 while ($dao->fetch()) {
1545 $params = array('id' => $dao->id
);
1546 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1551 * This function check online pending contribution associated w/
1552 * Online Event Registration or Online Membership signup.
1554 * @param int $componentId
1555 * Participant/membership id.
1556 * @param string $componentName
1560 * pending contribution id.
1562 public static function checkOnlinePendingContribution($componentId, $componentName) {
1563 $contributionId = NULL;
1564 if (!$componentId ||
1565 !in_array($componentName, array('Event', 'Membership'))
1567 return $contributionId;
1570 if ($componentName == 'Event') {
1571 $idName = 'participant_id';
1572 $componentTable = 'civicrm_participant';
1573 $paymentTable = 'civicrm_participant_payment';
1574 $source = ts('Online Event Registration');
1577 if ($componentName == 'Membership') {
1578 $idName = 'membership_id';
1579 $componentTable = 'civicrm_membership';
1580 $paymentTable = 'civicrm_membership_payment';
1581 $source = ts('Online Contribution');
1584 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1587 SELECT component.id as {$idName},
1588 componentPayment.contribution_id as contribution_id,
1589 contribution.source source,
1590 contribution.contribution_status_id as contribution_status_id,
1591 contribution.is_pay_later as is_pay_later
1592 FROM $componentTable component
1593 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1594 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1595 WHERE component.id = {$componentId}";
1597 $dao = CRM_Core_DAO
::executeQuery($query);
1599 while ($dao->fetch()) {
1600 if ($dao->contribution_id
&&
1601 $dao->is_pay_later
&&
1602 $dao->contribution_status_id
== $pendingStatusId &&
1603 strpos($dao->source
, $source) !== FALSE
1605 $contributionId = $dao->contribution_id
;
1610 return $contributionId;
1614 * Update contribution as well as related objects.
1616 * This function by-passes hooks - to address this - don't use this function.
1620 * Use api contribute.completetransaction
1621 * For failures use failPayment (preferably exposing by api in the process).
1623 * @param array $params
1624 * @param bool $processContributionObject
1627 * @throws \Exception
1629 public static function transitionComponents($params, $processContributionObject = FALSE) {
1630 // get minimum required values.
1631 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1632 $componentId = CRM_Utils_Array
::value('component_id', $params);
1633 $componentName = CRM_Utils_Array
::value('componentName', $params);
1634 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1635 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1637 // if we already processed contribution object pass previous status id.
1638 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1640 $updateResult = array();
1642 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1644 // we process only ( Completed, Cancelled, or Failed ) contributions.
1645 if (!$contributionId ||
1646 !in_array($contributionStatusId, array(
1647 array_search('Completed', $contributionStatuses),
1648 array_search('Cancelled', $contributionStatuses),
1649 array_search('Failed', $contributionStatuses),
1652 return $updateResult;
1655 if (!$componentName ||
!$componentId) {
1656 // get the related component details.
1657 $componentDetails = self
::getComponentDetails($contributionId);
1660 $componentDetails['contact_id'] = $contactId;
1661 $componentDetails['component'] = $componentName;
1663 if ($componentName == 'event') {
1664 $componentDetails['participant'] = $componentId;
1667 $componentDetails['membership'] = $componentId;
1671 if (!empty($componentDetails['contact_id'])) {
1672 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1678 // do check for required ids.
1679 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1680 return $updateResult;
1683 //now we are ready w/ required ids, start processing.
1685 $baseIPN = new CRM_Core_Payment_BaseIPN();
1687 $input = $ids = $objects = array();
1689 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1690 $ids['contribution'] = $contributionId;
1691 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1692 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1693 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1694 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1695 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1696 $ids['contributionRecur'] = NULL;
1697 $ids['contributionPage'] = NULL;
1699 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1700 CRM_Core_Error
::fatal();
1703 $memberships = &$objects['membership'];
1704 $participant = &$objects['participant'];
1705 $pledgePayment = &$objects['pledge_payment'];
1706 $contribution = &$objects['contribution'];
1708 if ($pledgePayment) {
1709 $pledgePaymentIDs = array();
1710 foreach ($pledgePayment as $key => $object) {
1711 $pledgePaymentIDs[] = $object->id
;
1713 $pledgeID = $pledgePayment[0]->pledge_id
;
1716 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1719 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1720 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1725 // we might want to process contribution object.
1726 $processContribution = FALSE;
1727 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1728 if (is_array($memberships)) {
1729 foreach ($memberships as $membership) {
1731 //Update Membership status if there is no other completed contribution associated with the membership.
1732 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1733 foreach ($relatedContributions as $contriId) {
1734 if ($contriId == $contributionId) {
1737 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1738 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1742 if ($membership && $update) {
1743 $newStatus = array_search('Cancelled', $membershipStatuses);
1746 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1747 $activityParam = array(
1748 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1749 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1750 'target_contact_id' => $membership->contact_id
,
1751 'source_record_id' => $membership->id
,
1752 'activity_type_id' => 'Change Membership Status',
1753 'status_id' => 'Completed',
1754 'priority_id' => 'Normal',
1755 'activity_date_time' => 'now',
1758 $membership->status_id
= $newStatus;
1759 $membership->save();
1760 civicrm_api3('activity', 'create', $activityParam);
1762 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1763 if ($processContributionObject) {
1764 $processContribution = TRUE;
1771 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1772 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1774 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1775 if ($processContributionObject) {
1776 $processContribution = TRUE;
1780 if ($pledgePayment) {
1781 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1783 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1784 if ($processContributionObject) {
1785 $processContribution = TRUE;
1789 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1790 if (is_array($memberships)) {
1791 foreach ($memberships as $membership) {
1793 //Update Membership status if there is no other completed contribution associated with the membership.
1794 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1795 foreach ($relatedContributions as $contriId) {
1796 if ($contriId == $contributionId) {
1799 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1800 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1804 if ($membership && $update) {
1805 $membership->status_id
= array_search('Expired', $membershipStatuses);
1806 $membership->save();
1808 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1809 if ($processContributionObject) {
1810 $processContribution = TRUE;
1816 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1817 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1819 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1820 if ($processContributionObject) {
1821 $processContribution = TRUE;
1825 if ($pledgePayment) {
1826 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1828 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1829 if ($processContributionObject) {
1830 $processContribution = TRUE;
1834 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1836 // only pending contribution related object processed.
1837 if ($previousContriStatusId &&
1838 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1840 // this is case when we already processed contribution object.
1841 return $updateResult;
1843 elseif (!$previousContriStatusId &&
1844 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1846 // this is case when we are going to process contribution object later.
1847 return $updateResult;
1850 if (is_array($memberships)) {
1851 foreach ($memberships as $membership) {
1856 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1857 $membership->membership_type_id
,
1858 $membership->is_test
, $membership->id
1861 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1862 // this picks up membership type changes during renewals
1864 SELECT membership_type_id
1865 FROM civicrm_membership_log
1866 WHERE membership_id=$membership->id
1869 $dao = new CRM_Core_DAO();
1871 if ($dao->fetch()) {
1872 if (!empty($dao->membership_type_id
)) {
1873 $membership->membership_type_id
= $dao->membership_type_id
;
1874 $membership->save();
1877 // else fall back to using current membership type
1880 // Figure out number of terms
1882 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
1883 foreach ($lineitems as $lineitem) {
1884 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1885 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1887 // in case membership_num_terms comes through as null or zero
1888 $numterms = $numterms >= 1 ?
$numterms : 1;
1893 // CRM-15735-to update the membership status as per the contribution receive date
1895 $oldStatus = $membership->status_id
;
1896 if (!empty($params['receive_date'])) {
1897 $joinDate = $params['receive_date'];
1898 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1899 $membership->end_date
,
1900 $membership->join_date
,
1901 $params['receive_date'],
1903 $membership->membership_type_id
,
1906 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1907 $membership->save();
1910 if ($currentMembership) {
1911 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1912 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1913 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1916 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1919 //get the status for membership.
1920 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1922 $dates['join_date'],
1925 $membership->membership_type_id
,
1929 $formattedParams = array(
1930 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1931 array_search('Current', $membershipStatuses)
1933 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1934 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1935 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1938 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1940 $membership->copyValues($formattedParams);
1941 $membership->save();
1943 //updating the membership log
1944 $membershipLog = array();
1945 $membershipLog = $formattedParams;
1946 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1947 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1949 $membershipLog['start_date'] = $logStartDate;
1950 $membershipLog['membership_id'] = $membership->id
;
1951 $membershipLog['modified_id'] = $membership->contact_id
;
1952 $membershipLog['modified_date'] = date('Ymd');
1953 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1955 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1957 //update related Memberships.
1958 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1960 foreach (array('Membership Signup', 'Membership Renewal') as $activityType) {
1961 $scheduledActivityID = CRM_Utils_Array
::value('id',
1962 civicrm_api3('Activity', 'Get',
1964 'source_record_id' => $membership->id
,
1965 'activity_type_id' => $activityType,
1966 'status_id' => 'Scheduled',
1969 'sort' => 'id DESC',
1974 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
1975 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
1976 if ($scheduledActivityID) {
1977 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, array('id' => $scheduledActivityID));
1982 // track membership status change if any
1983 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
1984 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1985 CRM_Activity_BAO_Activity
::addActivity($membership,
1986 'Change Membership Status',
1989 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
1990 'source_contact_id' => $membershipLog['modified_id'],
1991 'priority_id' => 'Normal',
1996 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1999 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2000 if ($processContributionObject) {
2001 $processContribution = TRUE;
2004 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2010 $updatedStatusId = array_search('Registered', $participantStatuses);
2011 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2013 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2014 if ($processContributionObject) {
2015 $processContribution = TRUE;
2019 if ($pledgePayment) {
2020 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2022 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2023 if ($processContributionObject) {
2024 $processContribution = TRUE;
2029 // process contribution object.
2030 if ($processContribution) {
2031 $contributionParams = array();
2038 'payment_instrument_id',
2041 'financial_type_id',
2042 'contribution_status_id',
2043 'non_deductible_amount',
2047 foreach ($fields as $field) {
2048 if (empty($params[$field])) {
2051 $contributionParams[$field] = $params[$field];
2054 $ids = array('contribution' => $contributionId);
2055 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2058 return $updateResult;
2062 * Returns all contribution related object ids.
2064 * @param $contributionId
2068 public static function getComponentDetails($contributionId) {
2069 $componentDetails = $pledgePayment = array();
2070 if (!$contributionId) {
2071 return $componentDetails;
2075 SELECT c.id as contribution_id,
2076 c.contact_id as contact_id,
2077 c.contribution_recur_id,
2078 mp.membership_id as membership_id,
2079 m.membership_type_id as membership_type_id,
2080 pp.participant_id as participant_id,
2081 p.event_id as event_id,
2082 pgp.id as pledge_payment_id
2083 FROM civicrm_contribution c
2084 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2085 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2086 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2087 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2088 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2089 WHERE c.id = $contributionId";
2091 $dao = CRM_Core_DAO
::executeQuery($query);
2092 $componentDetails = array();
2094 while ($dao->fetch()) {
2095 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2096 $componentDetails['contact_id'] = $dao->contact_id
;
2097 if ($dao->event_id
) {
2098 $componentDetails['event'] = $dao->event_id
;
2100 if ($dao->participant_id
) {
2101 $componentDetails['participant'] = $dao->participant_id
;
2103 if ($dao->membership_id
) {
2104 if (!isset($componentDetails['membership'])) {
2105 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2107 $componentDetails['membership'][] = $dao->membership_id
;
2108 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2110 if ($dao->pledge_payment_id
) {
2111 $pledgePayment[] = $dao->pledge_payment_id
;
2113 if ($dao->contribution_recur_id
) {
2114 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2118 if ($pledgePayment) {
2119 $componentDetails['pledge_payment'] = $pledgePayment;
2122 return $componentDetails;
2126 * @param int $contactId
2127 * @param bool $includeSoftCredit
2129 * @return null|string
2131 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2135 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2136 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2137 $liWhere = " AND i.financial_type_id IN (0)";
2138 if (!empty($financialTypes)) {
2139 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2140 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2142 $contactContributionsSQL = "
2143 SELECT contribution.id AS id
2144 FROM civicrm_contribution contribution
2145 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2146 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2150 $contactSoftCreditContributionsSQL = "
2151 SELECT contribution.id
2152 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2153 ON ( contribution.id = softContribution.contribution_id )
2154 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2155 $query = "SELECT count( x.id ) count FROM ( ";
2156 $query .= $contactContributionsSQL;
2158 if ($includeSoftCredit) {
2159 $query .= " UNION ";
2160 $query .= $contactSoftCreditContributionsSQL;
2165 return CRM_Core_DAO
::singleValueQuery($query);
2169 * Repeat a transaction as part of a recurring series.
2171 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2172 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2173 * subsequent call to the contribution.completetransaction api.
2175 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2177 * @param CRM_Contribute_BAO_Contribution $contribution
2178 * @param array $input
2179 * @param array $contributionParams
2180 * @param int $paymentProcessorID
2183 * @throws CiviCRM_API3_Exception
2185 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2186 if (!empty($contribution->id
)) {
2189 if (empty($contribution->id
)) {
2190 // Unclear why this would only be set for repeats.
2191 if (!empty($input['amount'])) {
2192 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2195 if (!empty($contributionParams['contribution_recur_id'])) {
2196 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2197 'id' => $contributionParams['contribution_recur_id'],
2199 if (!empty($recurringContribution['campaign_id'])) {
2200 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2201 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2203 if (!empty($recurringContribution['financial_type_id'])) {
2204 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2205 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2208 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2209 $contributionParams['contribution_recur_id'],
2210 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2212 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2214 $contributionParams['status_id'] = 'Pending';
2215 if (isset($contributionParams['financial_type_id'])) {
2216 // Give precedence to passed in type.
2217 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2220 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2222 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2223 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2225 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2226 //do not create CC or BCC emails or profile notifications.
2227 //The if is just to be safe. Not sure if we can ever arrive with this unset
2228 // but per CRM-19478 it seems it can be 'null'
2229 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2230 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2233 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2234 $contribution->id
= $createContribution['id'];
2235 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2241 * Get individual id for onbehalf contribution.
2243 * @param int $contributionId
2245 * @param int $contributorId
2249 * containing organization id and individual id
2251 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2255 if (!$contributionId) {
2259 // fetch contributor id if null
2260 if (!$contributorId) {
2261 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2262 $contributionId, 'contact_id'
2266 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2267 $activityTypeId = array_search('Contribution', $activityTypeIds);
2269 if ($activityTypeId && $contributorId) {
2271 SELECT civicrm_activity_contact.contact_id
2272 FROM civicrm_activity_contact
2273 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2274 WHERE civicrm_activity.activity_type_id = %1
2275 AND civicrm_activity.source_record_id = %2
2276 AND civicrm_activity_contact.record_type_id = %3
2279 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2280 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2283 1 => array($activityTypeId, 'Integer'),
2284 2 => array($contributionId, 'Integer'),
2285 3 => array($sourceID, 'Integer'),
2288 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2290 // for on behalf contribution source is individual and contributor is organization
2291 if ($sourceContactId && $sourceContactId != $contributorId) {
2292 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2293 // get rel type id for employee of relation
2294 foreach ($relationshipTypeIds as $id => $typeVals) {
2295 if ($typeVals['name_a_b'] == 'Employee of') {
2296 $relationshipTypeId = $id;
2301 $rel = new CRM_Contact_DAO_Relationship();
2302 $rel->relationship_type_id
= $relationshipTypeId;
2303 $rel->contact_id_a
= $sourceContactId;
2304 $rel->contact_id_b
= $contributorId;
2305 if ($rel->find(TRUE)) {
2306 $ids['individual_id'] = $rel->contact_id_a
;
2307 $ids['organization_id'] = $rel->contact_id_b
;
2318 public static function getContributionDates() {
2319 $config = CRM_Core_Config
::singleton();
2320 $currentMonth = date('m');
2321 $currentDay = date('d');
2322 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2323 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2324 (int ) $config->fiscalYearStart
['d'] > $currentDay
2327 $year = date('Y') - 1;
2332 $year = array('Y' => $year);
2333 $yearDate = $config->fiscalYearStart
;
2334 $yearDate = array_merge($year, $yearDate);
2335 $yearDate = CRM_Utils_Date
::format($yearDate);
2337 $monthDate = date('Ym') . '01';
2343 'yearDate' => $yearDate,
2344 'monthDate' => $monthDate,
2349 * Load objects relations to contribution object.
2350 * Objects are stored in the $_relatedObjects property
2351 * In the first instance we are just moving functionality from BASEIpn -
2352 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2354 * Note that the unit test for the BaseIPN class tests this function
2356 * @param array $input
2357 * Input as delivered from Payment Processor.
2359 * Ids as Loaded by Payment Processor.
2360 * @param bool $loadAll
2361 * Load all related objects - even where id not passed in? (allows API to call this).
2366 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2368 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2369 if (empty($ids['contact']) && isset($this->contact_id
)) {
2370 $ids['contact'] = $this->contact_id
;
2373 if (empty($this->_component
)) {
2374 if (!empty($ids['event'])) {
2375 $this->_component
= 'event';
2378 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2382 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2383 // refactoring than anything else, and has unit test coverage.
2384 if (empty($this->financial_type_id
)) {
2388 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2393 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2394 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2395 $this->contribution_page_id
,
2398 if ($paymentProcessorID) {
2399 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2403 $ids['contributionType'] = $this->financial_type_id
;
2404 $ids['financialType'] = $this->financial_type_id
;
2405 if ($this->contribution_page_id
) {
2406 $ids['contributionPage'] = $this->contribution_page_id
;
2409 $this->loadRelatedEntitiesByID($ids);
2411 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2412 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2415 if (!empty($ids['pledge_payment'])) {
2416 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2417 if (empty($paymentID)) {
2420 $payment = new CRM_Pledge_BAO_PledgePayment();
2421 $payment->id
= $paymentID;
2422 if (!$payment->find(TRUE)) {
2423 throw new Exception("Could not find pledge payment record: " . $paymentID);
2425 $this->_relatedObjects
['pledge_payment'][] = $payment;
2429 $this->loadRelatedMembershipObjects($ids);
2431 if ($this->_component
!= 'contribute') {
2432 // we are in event mode
2433 // make sure event exists and is valid
2434 $event = new CRM_Event_BAO_Event();
2435 $event->id
= $ids['event'];
2436 if ($ids['event'] &&
2439 throw new Exception("Could not find event: " . $ids['event']);
2442 $this->_relatedObjects
['event'] = &$event;
2444 $participant = new CRM_Event_BAO_Participant();
2445 $participant->id
= $ids['participant'];
2446 if ($ids['participant'] &&
2447 !$participant->find(TRUE)
2449 throw new Exception("Could not find participant: " . $ids['participant']);
2451 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2453 $this->_relatedObjects
['participant'] = &$participant;
2455 // get the payment processor id from event - this is inaccurate see CRM-16923
2456 // in future we should look at throwing an exception here rather than an dubious guess.
2457 if (!$paymentProcessorID) {
2458 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2459 if ($paymentProcessorID) {
2460 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2465 if ($paymentProcessorID) {
2466 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2467 $this->is_test ?
'test' : 'live'
2469 $ids['paymentProcessor'] = $paymentProcessorID;
2470 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2473 // Add contribution id to $ids. CRM-20401
2474 $ids['contribution'] = $this->id
;
2479 * Create array of message information - ie. return html version, txt version, to field
2481 * @param array $input
2482 * Incoming information.
2483 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2484 * just check presence of recur object but maintaining legacy approach
2487 * IDs of related objects.
2488 * @param array $values
2489 * Any values that may have already been compiled by calling process.
2490 * This is augmented by values 'gathered' by gatherMessageValues
2491 * @param bool $returnMessageText
2492 * Distinguishes between whether to send message or return.
2493 * message text. We are working towards this function ALWAYS returning message text & calling
2494 * function doing emails / pdfs with it
2500 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2501 $this->loadRelatedObjects($input, $ids);
2503 if (empty($this->_component
)) {
2504 $this->_component
= CRM_Utils_Array
::value('component', $input);
2507 //not really sure what params might be passed in but lets merge em into values
2508 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2509 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2510 if (!empty($input['receipt_date'])) {
2511 $values['receipt_date'] = $input['receipt_date'];
2514 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2515 //what does recur 'mean here - to do with payment processor return functionality but
2516 // what is the importance
2517 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2518 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2520 $entityID = $entity = NULL;
2521 if (isset($ids['contribution'])) {
2522 $entity = 'contribution';
2523 $entityID = $ids['contribution'];
2525 if (!empty($ids['membership'])) {
2526 //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
2527 // 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
2528 // line having loaded an array
2529 $ids['membership'] = (array) $ids['membership'];
2530 $entity = 'membership';
2531 $entityID = $ids['membership'][0];
2534 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2535 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2536 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2538 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2539 //direct mode showing billing block, so use directIPN for temporary
2540 $template->assign('contributeMode', 'directIPN');
2543 // todo remove strtolower - check consistency
2544 if (strtolower($this->_component
) == 'event') {
2545 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2546 $values['event'] = array();
2548 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2550 //get location details
2551 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2552 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2554 $ufJoinParams = array(
2555 'entity_table' => 'civicrm_event',
2556 'entity_id' => $ids['event'],
2557 'module' => 'CiviEvent',
2560 list($custom_pre_id,
2562 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2564 $values['custom_pre_id'] = $custom_pre_id;
2565 $values['custom_post_id'] = $custom_post_ids;
2566 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2567 //and cases involving status updation through ipn
2568 // whatever that means!
2569 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2570 // perhaps we should throw an e-notice if amount is set & force total_amount?
2571 if (!empty($input['amount'])) {
2572 $values['totalAmount'] = $input['amount'];
2574 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2575 if ($values['event']['is_email_confirm']) {
2576 $values['is_email_receipt'] = 1;
2579 if (!empty($ids['contribution'])) {
2580 $values['contributionId'] = $ids['contribution'];
2583 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2584 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2588 $values['contribution_id'] = $this->id
;
2589 if (!empty($ids['related_contact'])) {
2590 $values['related_contact'] = $ids['related_contact'];
2591 if (isset($ids['onbehalf_dupe_alert'])) {
2592 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2594 $entityBlock = array(
2595 'contact_id' => $ids['contact'],
2596 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2597 'Home', 'id', 'name'
2600 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2601 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2604 if ($this->is_test
) {
2607 if (!empty($this->_relatedObjects
['membership'])) {
2608 foreach ($this->_relatedObjects
['membership'] as $membership) {
2609 if ($membership->id
) {
2610 $values['isMembership'] = TRUE;
2611 $values['membership_assign'] = TRUE;
2613 // need to set the membership values here
2614 $template->assign('membership_name',
2615 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2617 $template->assign('mem_start_date', $membership->start_date
);
2618 $template->assign('mem_join_date', $membership->join_date
);
2619 $template->assign('mem_end_date', $membership->end_date
);
2620 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2621 $template->assign('mem_status', $membership_status);
2622 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2623 $values['is_pay_later'] = 1;
2625 // Pass amount to floatval as string '0.00' is considered a
2626 // valid amount and includes Fee section in the mail.
2627 if (isset($values['amount'])) {
2628 $values['amount'] = floatval($values['amount']);
2631 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2632 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2633 $template->assign('cancelSubscriptionUrl', $url);
2634 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2635 $template->assign('updateSubscriptionBillingUrl', $url);
2636 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2637 $template->assign('updateSubscriptionUrl', $url);
2640 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2643 // otherwise if its about sending emails, continue sending without return, as we
2644 // don't want to exit the loop.
2649 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2655 * Gather values for contribution mail - this function has been created
2656 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2657 * Values related to the contribution in question are gathered
2659 * @param array $input
2660 * Input into function (probably from payment processor).
2661 * @param array $values
2663 * The set of ids related to the input.
2667 public function _gatherMessageValues($input, &$values, $ids = array()) {
2668 // set display address of contributor
2669 if ($this->address_id
) {
2670 $addressParams = array('id' => $this->address_id
);
2671 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2672 $addressDetails = array_values($addressDetails);
2674 // Else we assign the billing address of the contribution contact.
2676 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2677 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2678 $addressDetails = array_values($addressDetails);
2681 if (!empty($addressDetails[0]['display'])) {
2682 $values['address'] = $addressDetails[0]['display'];
2685 if ($this->_component
== 'contribute') {
2686 //get soft contributions
2687 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2688 if (!empty($softContributions)) {
2689 $values['softContributions'] = $softContributions['soft_credit'];
2691 if (isset($this->contribution_page_id
)) {
2692 // This is a call we want to use less, in favour of loading related objects.
2693 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2694 if ($this->contribution_page_id
) {
2695 // This is precautionary as there are some legacy flows, but it should really be
2697 if (!isset($this->_relatedObjects
['contributionPage'])) {
2698 $this->loadRelatedEntitiesByID(array('contributionPage' => $this->contribution_page_id
));
2700 // CRM-8254 - override default currency if applicable
2701 $config = CRM_Core_Config
::singleton();
2702 $config->defaultCurrency
= CRM_Utils_Array
::value(
2705 $config->defaultCurrency
2709 // no contribution page -probably back office
2711 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2712 $values['title'] = 'Contribution';
2714 // set lineItem for contribution
2716 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2717 if (!empty($lineItems)) {
2718 $firstLineItem = reset($lineItems);
2719 $priceSet = array();
2720 if (CRM_Utils_Array
::value('price_set_id', $firstLineItem)) {
2721 $priceSet = civicrm_api3('PriceSet', 'getsingle', array('id' => $firstLineItem['price_set_id'], 'return' => 'is_quick_config, id'));
2722 $values['priceSetID'] = $priceSet['id'];
2724 foreach ($lineItems as &$eachItem) {
2725 if (isset($this->_relatedObjects
['membership'])
2726 && is_array($this->_relatedObjects
['membership'])
2727 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2728 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2729 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2730 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2732 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2733 // However, that does create upgrade pain so would be better to be phased in.
2734 $values['useForMember'] = empty($priceSet['is_quick_config']);
2736 $values['lineItem'][0] = $lineItems;
2740 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2744 // if this is onbehalf of contribution then set related contact
2745 if (!empty($relatedContact['individual_id'])) {
2746 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2751 $eventParams = array(
2752 'id' => $this->_relatedObjects
['event']->id
,
2754 $values['event'] = array();
2756 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2757 // add custom fields for event
2758 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $this->_relatedObjects
['event']->id
);
2760 $eventCustomGroup = array();
2761 foreach ($eventGroupTree as $key => $group) {
2762 if ($key === 'info') {
2766 foreach ($group['fields'] as $k => $customField) {
2767 $groupLabel = $group['title'];
2768 if (!empty($customField['customValue'])) {
2769 foreach ($customField['customValue'] as $customFieldValues) {
2770 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2775 $values['event']['customGroup'] = $eventCustomGroup;
2777 //get participant details
2778 $participantParams = array(
2779 'id' => $this->_relatedObjects
['participant']->id
,
2782 $values['participant'] = array();
2784 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2785 // add custom fields for event
2786 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $this->_relatedObjects
['participant']->id
);
2787 $participantCustomGroup = array();
2788 foreach ($participantGroupTree as $key => $group) {
2789 if ($key === 'info') {
2793 foreach ($group['fields'] as $k => $customField) {
2794 $groupLabel = $group['title'];
2795 if (!empty($customField['customValue'])) {
2796 foreach ($customField['customValue'] as $customFieldValues) {
2797 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2802 $values['participant']['customGroup'] = $participantCustomGroup;
2804 //get location details
2805 $locationParams = array(
2806 'entity_id' => $this->_relatedObjects
['event']->id
,
2807 'entity_table' => 'civicrm_event',
2809 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2811 $ufJoinParams = array(
2812 'entity_table' => 'civicrm_event',
2813 'entity_id' => $ids['event'],
2814 'module' => 'CiviEvent',
2817 list($custom_pre_id,
2819 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2821 $values['custom_pre_id'] = $custom_pre_id;
2822 $values['custom_post_id'] = $custom_post_ids;
2824 // set lineItem for event contribution
2826 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2827 if (!empty($participantIds)) {
2828 foreach ($participantIds as $pIDs) {
2829 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2830 if (!CRM_Utils_System
::isNull($lineItem)) {
2831 $values['lineItem'][] = $lineItem;
2838 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
2840 $customGroup = array();
2841 foreach ($groupTree as $key => $group) {
2842 if ($key === 'info') {
2846 foreach ($group['fields'] as $k => $customField) {
2847 $groupLabel = $group['title'];
2848 if (!empty($customField['customValue'])) {
2849 foreach ($customField['customValue'] as $customFieldValues) {
2850 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2855 $values['customGroup'] = $customGroup;
2857 $values['is_pay_later'] = $this->is_pay_later
;
2863 * Assign message variables to template but try to break the habit.
2865 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2866 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2867 * multiple recurring payments for processors like IATS that use tokens.
2869 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2870 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2871 * Note we send directly from this function in some cases because it is only partly refactored.
2873 * Don't call this function directly as the signature will change.
2877 * @param bool $returnMessageText
2881 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
2882 $template = CRM_Core_Smarty
::singleton();
2883 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2884 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2885 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2887 // For some unit tests contribution cannot contain paymentProcessor information
2888 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
2889 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
2891 //assign honor information to receipt message
2892 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2894 if (isset($softRecord['soft_credit'])) {
2895 //if id of contribution page is present
2896 if (!empty($values['id'])) {
2897 $values['honor'] = array(
2898 'honor_profile_values' => array(),
2899 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2900 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2903 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2904 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2907 //offline contribution
2908 $softCreditTypes = $softCredits = array();
2909 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2910 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2911 $softCredits[$key] = array(
2912 'Name' => $softCredit['contact_name'],
2913 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2916 $template->assign('softCreditTypes', $softCreditTypes);
2917 $template->assign('softCredits', $softCredits);
2921 $dao = new CRM_Contribute_DAO_ContributionProduct();
2922 $dao->contribution_id
= $this->id
;
2923 if ($dao->find(TRUE)) {
2924 $premiumId = $dao->product_id
;
2925 $template->assign('option', $dao->product_option
);
2927 $productDAO = new CRM_Contribute_DAO_Product();
2928 $productDAO->id
= $premiumId;
2929 $productDAO->find(TRUE);
2930 $template->assign('selectPremium', TRUE);
2931 $template->assign('product_name', $productDAO->name
);
2932 $template->assign('price', $productDAO->price
);
2933 $template->assign('sku', $productDAO->sku
);
2935 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2936 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2937 if (!$values['amount'] && isset($this->total_amount
)) {
2938 $values['amount'] = $this->total_amount
;
2941 // add the new contribution values
2942 if (strtolower($this->_component
) == 'contribute') {
2944 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2945 $softDAO->contribution_id
= $this->id
;
2946 if ($softDAO->find(TRUE)) {
2947 $template->assign('pcpBlock', TRUE);
2948 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2949 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2950 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2952 //assign the pcp page title for email subject
2953 $pcpDAO = new CRM_PCP_DAO_PCP();
2954 $pcpDAO->id
= $softDAO->pcp_id
;
2955 if ($pcpDAO->find(TRUE)) {
2956 $template->assign('title', $pcpDAO->title
);
2961 if ($this->financial_type_id
) {
2962 $values['financial_type_id'] = $this->financial_type_id
;
2965 $template->assign('trxn_id', $this->trxn_id
);
2966 $template->assign('receive_date',
2967 CRM_Utils_Date
::processDate($this->receive_date
)
2969 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
2970 $template->assign('action', $this->is_test ?
1024 : 1);
2971 $template->assign('receipt_text',
2972 CRM_Utils_Array
::value('receipt_text',
2976 $template->assign('is_monetary', 1);
2977 $template->assign('is_recur', !empty($this->contribution_recur_id
));
2978 $template->assign('currency', $this->currency
);
2979 $template->assign('address', CRM_Utils_Address
::format($input));
2980 if (!empty($values['customGroup'])) {
2981 $template->assign('customGroup', $values['customGroup']);
2983 if (!empty($values['softContributions'])) {
2984 $template->assign('softContributions', $values['softContributions']);
2986 if ($this->_component
== 'event') {
2987 $template->assign('title', $values['event']['title']);
2988 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2989 $viewRoles = array();
2990 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2991 $viewRoles[] = $participantRoles[$v];
2993 $values['event']['participant_role'] = implode(', ', $viewRoles);
2994 $template->assign('event', $values['event']);
2995 $template->assign('participant', $values['participant']);
2996 $template->assign('location', $values['location']);
2997 $template->assign('customPre', $values['custom_pre_id']);
2998 $template->assign('customPost', $values['custom_post_id']);
3001 if ($this->_relatedObjects
['participant']->is_test
) {
3005 $values['params'] = array();
3006 //to get email of primary participant.
3007 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3008 $primaryAmount[] = array(
3009 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3010 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3012 //build an array of cId/pId of participants
3013 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3014 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3015 //send receipt to additional participant if exists
3016 if (count($additionalIDs)) {
3017 $template->assign('isPrimary', 0);
3018 $template->assign('customProfile', NULL);
3019 //set additionalParticipant true
3020 $values['params']['additionalParticipant'] = TRUE;
3021 foreach ($additionalIDs as $pId => $cId) {
3023 //to change the status pending to completed
3024 $additional = new CRM_Event_DAO_Participant();
3025 $additional->id
= $pId;
3026 $additional->contact_id
= $cId;
3027 $additional->find(TRUE);
3028 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3029 $additional->status_id
= 1;
3030 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3031 //if additional participant dont have email
3033 if (!$additionalParticipantInfo) {
3034 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3036 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
3037 $primaryAmount[] = array(
3038 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3039 'amount' => $additional->fee_amount
,
3041 $additional->save();
3042 $additional->free();
3043 $template->assign('amount', $amount);
3044 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3048 //build an array of custom profile and assigning it to template
3049 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3051 if (count($customProfile)) {
3052 $template->assign('customProfile', $customProfile);
3055 // for primary contact
3056 $values['params']['additionalParticipant'] = FALSE;
3057 $template->assign('isPrimary', 1);
3058 $template->assign('amount', $primaryAmount);
3059 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3060 if ($this->payment_instrument_id
) {
3061 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3062 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3064 // carry paylater, since we did not created billing,
3065 // so need to pull email from primary location, CRM-4395
3066 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3072 * Check whether payment processor supports
3073 * cancellation of contribution subscription
3075 * @param int $contributionId
3078 * @param bool $isNotCancelled
3082 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3083 $cacheKeyString = "$contributionId";
3084 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3086 static $supportsCancel = array();
3088 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3089 $supportsCancel[$cacheKeyString] = FALSE;
3090 $isCancelled = FALSE;
3092 if ($isNotCancelled) {
3093 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3096 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3097 if (!empty($paymentObject)) {
3098 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3101 return $supportsCancel[$cacheKeyString];
3105 * Check whether subscription is already cancelled.
3107 * @param int $contributionId
3111 * contribution status
3113 public static function isSubscriptionCancelled($contributionId) {
3115 SELECT cr.contribution_status_id
3116 FROM civicrm_contribution_recur cr
3117 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3118 WHERE con.id = %1 LIMIT 1";
3119 $params = array(1 => array($contributionId, 'Integer'));
3120 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3121 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3122 if ($status == 'Cancelled') {
3129 * Create all financial accounts entry.
3131 * @param array $params
3132 * Contribution object, line item array and params for trxn.
3135 * @param array $financialTrxnValues
3137 * @return null|object
3139 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3140 $skipRecords = $update = $return = $isRelatedId = FALSE;
3142 $additionalParticipantId = array();
3143 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3144 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3146 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3147 $entityId = $params['participant_id'];
3148 $entityTable = 'civicrm_participant';
3149 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3151 elseif (!empty($params['membership_id'])) {
3152 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3153 // are created off one contribution should be handled elsewhere
3154 $entityId = $params['membership_id'];
3155 $entityTable = 'civicrm_membership';
3158 $entityId = $params['contribution']->id
;
3159 $entityTable = 'civicrm_contribution';
3162 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3163 $isRelatedId = TRUE;
3166 $entityID[] = $entityId;
3167 if (!empty($additionalParticipantId)) {
3168 $entityID +
= $additionalParticipantId;
3170 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3171 if (empty($params['prevContribution'])) {
3178 $statusId = $params['contribution']->contribution_status_id
;
3179 // CRM-13964 partial payment
3180 if ($contributionStatus == 'Partially paid'
3181 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3183 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3184 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3186 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['financial_type_id'], 'Accounts Receivable Account is');
3187 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3188 $params['total_amount'] = $partialAmtPay;
3190 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3191 if (empty($balanceTrxnInfo['trxn_id'])) {
3192 // create new balance transaction record
3193 $toFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['financial_type_id'], 'Accounts Receivable Account is');
3195 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3196 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3197 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3198 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3199 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3200 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3201 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3202 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3203 $balanceTrxnParams['status_id'] = $statusId;
3204 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3205 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3206 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3207 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3208 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3209 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3211 $balanceTrxnParams['is_payment'] = 1;
3213 if (!empty($params['payment_processor'])) {
3214 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3216 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3220 // build line item array if its not set in $params
3221 if (empty($params['line_item']) ||
$additionalParticipantId) {
3222 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3225 if ($contributionStatus != 'Failed' &&
3226 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3228 $skipRecords = TRUE;
3229 $pendingStatus = array(
3233 if (in_array($contributionStatus, $pendingStatus)) {
3234 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3235 $params['financial_type_id'],
3236 'Accounts Receivable Account is'
3239 elseif (!empty($params['payment_processor'])) {
3240 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3241 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array(
3242 'id' => $params['payment_processor'],
3243 'return' => 'payment_instrument_id',
3246 elseif (!empty($params['payment_instrument_id'])) {
3247 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3250 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3251 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3252 $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);
3255 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3256 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3257 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3259 //build financial transaction params
3260 $trxnParams = array(
3261 'contribution_id' => $params['contribution']->id
,
3262 'to_financial_account_id' => $params['to_financial_account_id'],
3263 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3264 'total_amount' => $totalAmount,
3265 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3266 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3267 'currency' => $params['contribution']->currency
,
3268 'trxn_id' => $params['contribution']->trxn_id
,
3269 'status_id' => $statusId,
3270 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3271 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3272 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $params),
3273 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $params),
3275 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3276 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3277 if (isset($params['refund_trxn_id'])) {
3278 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3279 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3282 //CRM-16259, set is_payment flag for non pending status
3283 if (!in_array($contributionStatus, $pendingStatus)) {
3284 $trxnParams['is_payment'] = 1;
3286 if (!empty($params['payment_processor'])) {
3287 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3290 if (isset($fromFinancialAccountId)) {
3291 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3294 // consider external values passed for recording transaction entry
3295 if (!empty($financialTrxnValues)) {
3296 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3298 if (empty($trxnParams['payment_processor_id'])) {
3299 unset($trxnParams['payment_processor_id']);
3302 $params['trxnParams'] = $trxnParams;
3304 if (!empty($params['prevContribution'])) {
3306 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3307 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3308 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3309 if (!isset($params['trxnParams']['trxn_id'])) {
3310 // Actually I have no idea why we are overwriting any values from the previous contribution.
3311 // (filling makes sense to me). However, only protecting this value as I really really know we
3312 // don't want this one overwritten.
3314 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3316 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3318 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3319 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3320 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3322 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3323 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3326 //if financial type is changed
3327 if (!empty($params['financial_type_id']) &&
3328 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3330 $accountRelationship = 'Income Account is';
3331 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3332 $accountRelationship = 'Deferred Revenue Account is';
3334 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['prevContribution']->financial_type_id
, $accountRelationship);
3335 $newFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['financial_type_id'], $accountRelationship);
3336 if ($oldFinancialAccount != $newFinancialAccount) {
3337 $params['total_amount'] = 0;
3338 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3339 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
3340 $params['prevContribution']->financial_type_id
, $accountRelationship);
3343 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3344 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3345 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3348 self
::updateFinancialAccounts($params, 'changeFinancialType');
3349 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3350 $params['financial_account_id'] = $newFinancialAccount;
3351 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3352 self
::updateFinancialAccounts($params);
3353 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3355 $params['deferred_financial_account_id'] = $newFinancialAccount;
3359 //Update contribution status
3360 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3361 if (!isset($params['refund_trxn_id'])) {
3362 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3363 // gets preference over another so I am only 'protecting' a very specific tested flow
3364 // and letting natural justice take care of the rest.
3365 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3367 if (!empty($params['contribution_status_id']) &&
3368 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3370 //Update Financial Records
3371 self
::updateFinancialAccounts($params, 'changedStatus');
3375 // change Payment Instrument for a Completed contribution
3376 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3377 // instrument is null and now new payment instrument is added along with the payment
3378 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3379 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3380 if (array_key_exists('payment_instrument_id', $params)) {
3381 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3382 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3383 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3385 //check if status is changed from Pending to Completed
3386 // do not update payment instrument changes for Pending to Completed
3387 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3388 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3390 // for all other statuses create new financial records
3391 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3392 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3393 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3397 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3398 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3399 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3401 // for any other payment instrument changes create new financial records
3402 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3403 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3404 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3407 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3408 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3410 // another special case when check number is changed, create new financial records
3411 // create financial trxn with negative amount
3412 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3413 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3414 // create financial trxn with positive amount
3415 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3416 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3417 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3422 //if Change contribution amount
3423 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3424 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3425 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3426 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3427 if (isset($totalAmount) &&
3428 $totalAmount != $params['prevContribution']->total_amount
3430 //Update Financial Records
3431 $params['trxnParams']['from_financial_account_id'] = NULL;
3432 self
::updateFinancialAccounts($params, 'changedAmount');
3437 // Looks like we might have a data correction update.
3438 // This would be a case where a transaction id has been entered but it is incorrect &
3439 // the person goes back in & fixes it, as opposed to a new transaction.
3440 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3441 // the data fix scenario.
3443 if (isset($params['refund_trxn_id'])) {
3444 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3445 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3446 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3449 $cardType = CRM_Utils_Array
::value('card_type_id', $params);
3450 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3451 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3456 // records finanical trxn and entity financial trxn
3457 // also make it available as return value
3458 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3459 $trxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3460 $trxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3461 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3462 $params['entity_id'] = $financialTxn->id
;
3463 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3464 self
::$_trxnIDs[] = $financialTxn->id
;
3468 // record line items and financial items
3469 if (empty($params['skipLineItem'])) {
3470 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3473 // create batch entry if batch_id is passed and
3474 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3475 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3476 $entityParams = array(
3477 'batch_id' => $params['batch_id'],
3478 'entity_table' => 'civicrm_financial_trxn',
3479 'entity_id' => $financialTxn->id
,
3481 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3484 // when a fee is charged
3485 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3486 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3489 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3490 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3492 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3493 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3494 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3496 unset($params['line_item']);
3497 self
::$_trxnIDs = NULL;
3502 * Update all financial accounts entry.
3504 * @param array $params
3505 * Contribution object, line item array and params for trxn.
3507 * @param string $context
3511 public static function updateFinancialAccounts(&$params, $context = NULL) {
3513 $inputParams = $params;
3515 $currentContributionStatus = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
3516 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3518 if (($previousContributionStatus == 'Pending'
3519 ||
$previousContributionStatus == 'In Progress')
3520 && $currentContributionStatus == 'Completed'
3521 && $context == 'changePaymentInstrument'
3525 if ((($previousContributionStatus == 'Partially paid'
3526 && $currentContributionStatus == 'Completed')
3527 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3528 && $currentContributionStatus == 'Partially paid'))
3529 && $context == 'changedStatus'
3533 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3534 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3536 if ($context == 'changedStatus') {
3537 if ($previousContributionStatus == 'Completed'
3538 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3541 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3542 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3543 $creditNoteId = self
::createCreditNoteId();
3544 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3547 elseif (($previousContributionStatus == 'Pending'
3548 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3550 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3551 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
3553 if ($currentContributionStatus == 'Cancelled') {
3554 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3555 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3556 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3557 $creditNoteId = self
::createCreditNoteId();
3558 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3562 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3566 elseif ($context == 'changePaymentInstrument') {
3567 $params['trxnParams']['net_amount'] = $params['trxnParams']['total_amount'];
3568 $deferredFinancialAccount = CRM_Utils_Array
::value('deferred_financial_account_id', $params);
3569 if (empty($deferredFinancialAccount)) {
3570 $deferredFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['prevContribution']->financial_type_id
, 'Deferred Revenue Account is');
3572 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC', FALSE, NULL, $deferredFinancialAccount);
3573 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3574 if ($params['total_amount'] != $params['trxnParams']['total_amount']) {
3575 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3576 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3579 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3580 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3585 if ($context == 'changedStatus') {
3586 if (($previousContributionStatus == 'Pending'
3587 ||
$previousContributionStatus == 'In Progress')
3588 && ($currentContributionStatus == 'Completed')
3590 if (empty($params['line_item'])) {
3592 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3593 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3594 // & this can be removed
3597 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
3598 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3599 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
3600 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3601 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3603 $entityParams = array(
3604 'entity_table' => 'civicrm_financial_item',
3606 foreach ($params['line_item'] as $fieldId => $fields) {
3607 foreach ($fields as $fieldValueId => $lineItemDetails) {
3609 1 => array(CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'), 'Integer'),
3610 2 => array($lineItemDetails['id'], 'Integer'),
3612 CRM_Core_DAO
::executeQuery($query, $fparams);
3614 1 => array($lineItemDetails['id'], 'Integer'),
3616 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3617 while ($financialItem->fetch()) {
3618 $entityParams['entity_id'] = $financialItem->id
;
3619 $entityParams['amount'] = $financialItem->amount
;
3620 foreach (self
::$_trxnIDs as $tID) {
3621 $entityParams['financial_trxn_id'] = $tID;
3622 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3631 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3632 $params['entity_id'] = $trxn->id
;
3633 if ($context != 'changePaymentInstrument') {
3634 $itemParams['entity_table'] = 'civicrm_line_item';
3635 $trxnIds['id'] = $params['entity_id'];
3636 foreach ($params['line_item'] as $fieldId => $fields) {
3637 foreach ($fields as $fieldValueId => $lineItemDetails) {
3638 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
3639 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3640 if ($params['contribution']->receive_date
) {
3641 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3644 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem['financial_account_id']);
3646 $currency = $params['prevContribution']->currency
;
3647 if ($params['contribution']->currency
) {
3648 $currency = $params['contribution']->currency
;
3651 $itemParams = array(
3652 'transaction_date' => $receiveDate,
3653 'contact_id' => $params['prevContribution']->contact_id
,
3654 'currency' => $currency,
3655 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund),
3656 'description' => $prevFinancialItem['description'],
3657 'status_id' => $prevFinancialItem['status_id'],
3658 'financial_account_id' => $financialAccount,
3659 'entity_table' => 'civicrm_line_item',
3660 'entity_id' => $lineItemDetails['id'],
3662 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3663 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
3664 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3666 if ($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') {
3667 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3668 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3669 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $lineItemDetails['tax_amount'];
3670 $itemParams['description'] = $taxTerm;
3671 if ($lineItemDetails['financial_type_id']) {
3672 $itemParams['financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
3673 $lineItemDetails['financial_type_id'],
3674 'Sales Tax Account is'
3677 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3682 if ($context == 'changeFinancialType') {
3683 $params['skipLineItem'] = FALSE;
3684 foreach ($params['line_item'] as &$lineItems) {
3685 foreach ($lineItems as &$line) {
3686 $line['financial_type_id'] = $params['financial_type_id'];
3690 if ($context == 'changePaymentInstrument') {
3691 // store financial item Proportionaly.
3692 $trxnParams = array(
3693 'total_amount' => $trxn->total_amount
,
3694 'contribution_id' => $params['contribution']->id
,
3696 self
::assignProportionalLineItems($trxnParams, $trxn->id
, $params['prevContribution']->total_amount
);
3698 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3702 * Is this contribution status a reversal.
3704 * If so we would expect to record a negative value in the financial_trxn table.
3706 * @param int $status_id
3710 public static function isContributionStatusNegative($status_id) {
3711 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3712 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3716 * Check status validation on update of a contribution.
3718 * @param array $values
3719 * Previous form values before submit.
3721 * @param array $fields
3722 * The input form values.
3724 * @param array $errors
3729 public static function checkStatusValidation($values, &$fields, &$errors) {
3730 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3731 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3732 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3736 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3737 $checkStatus = array(
3738 'Cancelled' => array('Completed', 'Refunded'),
3739 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3740 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3741 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3742 'Refunded' => array('Cancelled', 'Completed'),
3743 'Partially paid' => array('Completed'),
3746 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3747 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3749 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3750 1 => $contributionStatuses[$values['contribution_status_id']],
3751 2 => $contributionStatuses[$fields['contribution_status_id']],
3757 * Delete contribution of contact.
3761 * @param int $contactId
3765 public static function deleteContactContribution($contactId) {
3766 $contribution = new CRM_Contribute_DAO_Contribution();
3767 $contribution->contact_id
= $contactId;
3768 $contribution->find();
3769 while ($contribution->fetch()) {
3770 self
::deleteContribution($contribution->id
);
3775 * Get options for a given contribution field.
3776 * @see CRM_Core_DAO::buildOptions
3778 * @param string $fieldName
3779 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3780 * @param array $props whatever is known about this dao object.
3782 * @return array|bool
3784 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3785 $className = __CLASS__
;
3787 if (isset($props['orderColumn'])) {
3788 $params['orderColumn'] = $props['orderColumn'];
3790 switch ($fieldName) {
3791 // This field is not part of this object but the api supports it
3792 case 'payment_processor':
3793 $className = 'CRM_Contribute_BAO_ContributionPage';
3794 // Filter results by contribution page
3795 if (!empty($props['contribution_page_id'])) {
3796 $page = civicrm_api('contribution_page', 'getsingle', array(
3798 'id' => ($props['contribution_page_id']),
3800 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3801 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3805 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3806 case 'honor_type_id':
3807 $className = 'CRM_Contribute_BAO_ContributionSoft';
3808 $fieldName = 'soft_credit_type_id';
3809 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3812 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3816 * Validate financial type.
3820 * @param int $financialTypeId
3821 * Financial Type id.
3823 * @param string $relationName
3825 * @return array|bool
3827 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3828 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3830 if (!$financialAccount) {
3831 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3838 * Function to record additional payment for partial and refund contributions.
3840 * @param int $contributionId
3841 * is the invoice contribution id (got created after processing participant payment).
3842 * @param array $trxnsData
3843 * to take user provided input of transaction details.
3844 * @param string $paymentType
3845 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3846 * @param int $participantId
3847 * @param bool $updateStatus
3849 * @return null|object
3851 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3852 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3853 $getInfoOf['id'] = $contributionId;
3854 $defaults = array();
3855 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3856 if (!$participantId) {
3857 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id', 'contribution_id');
3860 // build params for recording financial trxn entry
3861 $params['contribution'] = $contributionDAO;
3862 $params = array_merge($defaults, $params);
3863 $params['skipLineItem'] = TRUE;
3864 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3865 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contributionDAO->financial_type_id
, 'Accounts Receivable Account is');
3867 // get the paid status id
3868 $paidStatus = CRM_Core_PseudoConstant
::getKey('CRM_Financial_DAO_FinancialItem', 'status_id', 'Paid');
3870 if ($paymentType == 'owed') {
3871 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3872 $params['partial_amount_to_pay'] = $trxnsData['total_amount'];
3873 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3874 $params['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $trxnsData);
3875 $params['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $trxnsData);
3878 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3879 $toFinancialAccount = $arAccountId;
3880 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3881 if (!empty($trxnId)) {
3882 $trxnId = $trxnId['trxn_id'];
3884 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3885 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3888 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3889 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3890 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3894 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3895 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3896 FROM civicrm_financial_trxn ft
3897 LEFT JOIN civicrm_entity_financial_trxn eft
3898 ON (ft.id = eft.financial_trxn_id)
3899 WHERE eft.entity_table = 'civicrm_contribution'
3900 AND eft.entity_id = {$contributionId}
3901 AND ft.to_financial_account_id != {$toFinancialAccount}
3902 AND ft.status_id = {$statusId}
3904 $query = CRM_Core_DAO
::executeQuery($sql);
3906 $sumOfPayments = $query->sum_of_payments
;
3909 if ($contributionDAO->total_amount
== $sumOfPayments) {
3910 // update contribution status and
3911 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3912 $contributionDAO->contribution_status_id
= $statusId;
3913 $contributionDAO->cancel_date
= 'null';
3914 $contributionDAO->cancel_reason
= NULL;
3915 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3916 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3917 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3918 $contributionDAO->save();
3920 //Change status of financial record too
3921 $financialTrxn->status_id
= $statusId;
3922 $financialTrxn->save();
3924 // note : not using the self::add method,
3925 // the reason because it performs 'status change' related code execution for financial records
3926 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3927 // are coded below i.e. just updating financial_item status to 'Paid'
3929 if ($participantId) {
3930 // update participant status
3931 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3932 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3933 foreach ($ids as $val) {
3934 $participantUpdate['id'] = $val;
3935 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3936 CRM_Event_BAO_Participant
::add($participantUpdate);
3940 // update financial item statuses
3941 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3942 $sqlFinancialItemUpdate = "
3943 UPDATE civicrm_financial_item fi
3944 LEFT JOIN civicrm_entity_financial_trxn eft
3945 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3946 SET status_id = {$paidStatus}
3947 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3949 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3952 elseif ($paymentType == 'refund') {
3953 $trxnsData['total_amount'] = $trxnsData['net_amount'] = -$trxnsData['total_amount'];
3954 $trxnsData['from_financial_account_id'] = $arAccountId;
3955 $trxnsData['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
3957 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3959 // note : not using the self::add method,
3960 // the reason because it performs 'status change' related code execution for financial records
3961 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3962 // are coded below i.e. just updating financial_item status to 'Paid'
3963 if ($updateStatus) {
3964 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3966 // add financial item entry
3967 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionDAO->id
);
3968 if (!empty($lineItems)) {
3969 foreach ($lineItems as $lineItemId => $lineItemValue) {
3970 // don't record financial item for cancelled line-item
3971 if ($lineItemValue['qty'] == 0) {
3974 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount
/ $contributionDAO->total_amount
);
3975 $addFinancialEntry = array(
3976 'transaction_date' => $financialTrxn->trxn_date
,
3977 'contact_id' => $contributionDAO->contact_id
,
3978 'amount' => round($paid, 2),
3979 'currency' => $contributionDAO->currency
,
3980 'status_id' => $paidStatus,
3981 'entity_id' => $lineItemId,
3982 'entity_table' => 'civicrm_line_item',
3984 $trxnIds['id'] = $financialTrxn->id
;
3985 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3988 if ($participantId) {
3989 // update participant status
3990 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3991 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3992 foreach ($ids as $val) {
3993 $participantUpdate['id'] = $val;
3994 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3995 CRM_Event_BAO_Participant
::add($participantUpdate);
4000 // activity creation
4001 if (!empty($financialTrxn)) {
4002 if ($participantId) {
4003 $inputParams['id'] = $participantId;
4006 $component = 'event';
4007 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
4008 $entityObj = $entityObj[$participantId];
4011 $entityObj = $contributionDAO;
4012 $component = 'contribution';
4014 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
4016 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
4017 return $financialTrxn;
4025 * @param $activityType
4027 * @param int $contributionId
4029 * @throws CRM_Core_Exception
4031 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
4032 if ($component == 'event') {
4033 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
4036 $title = ts('Contribution');
4038 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
4039 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
4040 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
4041 $targetCid = $entityObj->contact_id
;
4042 // source record id would be the contribution id
4043 $srcRecId = $contributionId;
4046 $activityParams = array(
4047 'source_contact_id' => $targetCid,
4048 'source_record_id' => $srcRecId,
4049 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
4050 'subject' => $subject,
4051 'activity_date_time' => $date,
4052 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
4053 'skipRecentView' => TRUE,
4056 // create activity with target contacts
4057 $session = CRM_Core_Session
::singleton();
4058 $id = $session->get('userID');
4060 $activityParams['source_contact_id'] = $id;
4061 $activityParams['target_contact_id'][] = $targetCid;
4064 CRM_Activity_BAO_Activity
::create($activityParams);
4068 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4072 * @param bool $getTrxnInfo
4073 * @param bool $usingLineTotal
4077 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
4078 if ($component == 'event') {
4079 $entity = 'participant';
4080 $entityTable = 'civicrm_participant';
4081 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4083 if (!$contributionId) {
4084 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4085 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4086 $id = $primaryParticipantId;
4088 if (!$contributionId) {
4093 elseif ($component == 'membership') {
4094 $entity = $component;
4095 $entityTable = 'civicrm_membership';
4096 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4099 $contributionId = $id;
4100 $entity = 'contribution';
4101 $entityTable = 'civicrm_contribution';
4104 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4105 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4107 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4108 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4110 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
4111 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4114 $baseTrxnId = $total['trxn_id'];
4115 $total = $total['total_amount'];
4118 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
4119 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
4121 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4122 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
4124 if ($paymentBalance == 0 && $contributionIsPayLater) {
4125 $paymentBalance = $total;
4128 $info['total'] = $total;
4129 $info['paid'] = $total - $paymentBalance;
4130 $info['balance'] = $paymentBalance;
4132 $info['component'] = $component;
4133 $info['payLater'] = $contributionIsPayLater;
4135 if ($getTrxnInfo && $baseTrxnId) {
4136 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4138 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4140 ft.payment_instrument_id,
4141 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
4143 FROM civicrm_contribution con
4144 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4145 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4146 AND ft.to_financial_account_id != %2
4147 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4148 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4149 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4151 WHERE con.id = %1 AND ft.is_payment = 1
4153 $queryParams = array(
4154 1 => array($contributionId, 'Integer'),
4155 2 => array($feeFinancialAccount, 'Integer'),
4157 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4158 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4160 while ($resultDAO->fetch()) {
4161 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4162 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4163 if ($resultDAO->card_type_id
) {
4164 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
4165 $pantruncation = '';
4166 if ($resultDAO->pan_truncation
) {
4167 $pantruncation = ": {$resultDAO->pan_truncation}";
4169 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4172 // show payment edit link only for payments done via backoffice form
4173 $paymentEditLink = '';
4174 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
4176 CRM_Core_Action
::UPDATE
=> array(
4177 'name' => "<i class='crm-i fa-pencil'></i>",
4178 'url' => 'civicrm/payment/edit',
4179 'class' => 'medium-popup',
4180 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4181 'title' => ts('Edit Payment'),
4184 $paymentEditLink = CRM_Core_Action
::formLink(
4186 CRM_Core_Action
::mask(array(CRM_Core_Permission
::EDIT
)),
4188 'id' => $resultDAO->id
,
4189 'contribution_id' => $contributionId,
4195 'id' => $resultDAO->id
,
4196 'total_amount' => $resultDAO->total_amount
,
4197 'financial_type' => $resultDAO->financial_account
,
4198 'payment_instrument' => $paidByLabel,
4199 'receive_date' => $resultDAO->trxn_date
,
4200 'trxn_id' => $resultDAO->trxn_id
,
4201 'status' => $statuses[$resultDAO->status_id
],
4202 'currency' => $resultDAO->currency
,
4203 'action' => $paymentEditLink,
4205 if ($paidByName == 'Check') {
4206 $val['check_number'] = $resultDAO->check_number
;
4210 $info['transaction'] = $rows;
4216 * Get the tax amount (misnamed function).
4218 * @param array $params
4219 * @param bool $isLineItem
4223 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4224 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4226 // Update contribution.
4227 if (!empty($params['id'])) {
4228 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4229 // there are no tax implications - early return.
4230 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4233 if (empty($params['prevContribution'])) {
4234 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4237 foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) {
4238 if (!isset($params[$field])) {
4239 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4240 // Tax amount gets added back on later....
4241 $params['total_amount'] = $params['prevContribution']->total_amount
-
4242 $params['prevContribution']->tax_amount
;
4245 $params[$field] = $params['prevContribution']->$field;
4246 if ($params[$field] != $params['prevContribution']->$field) {
4252 self
::calculateMissingAmountParams($params, $params['id']);
4253 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4254 // Assign tax Amount on update of contribution
4255 if (!empty($params['prevContribution']->tax_amount
)) {
4256 $params['tax_amount'] = 'null';
4257 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4258 foreach ($params['line_item'] as $setID => $priceField) {
4259 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4260 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4267 // New Contribution and update of contribution with tax rate financial type
4268 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4269 empty($params['skipLineItem']) && !$isLineItem
4271 $taxRateParams = $taxRates[$params['financial_type_id']];
4272 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4273 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4275 // Get Line Item on update of contribution
4276 if (isset($params['id'])) {
4277 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4280 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4282 foreach ($params['line_item'] as $setID => $priceField) {
4283 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4284 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4287 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4289 elseif (isset($params['api.line_item.create'])) {
4290 // Update total amount of contribution using lineItem
4291 $taxAmountArray = array();
4292 foreach ($params['api.line_item.create'] as $key => $value) {
4293 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4294 $taxRate = $taxRates[$value['financial_type_id']];
4295 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4296 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4299 $params['tax_amount'] = array_sum($taxAmountArray);
4300 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4303 // update line item of contrbution
4304 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4305 $taxRate = $taxRates[$params['financial_type_id']];
4306 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
4307 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4314 * Check financial type validation on update of a contribution.
4316 * @param Integer $financialTypeId
4317 * Value of latest Financial Type.
4319 * @param Integer $contributionId
4322 * @param array $errors
4327 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4328 if (!empty($financialTypeId)) {
4329 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4330 if ($oldFinancialTypeId == $financialTypeId) {
4334 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4336 '1' => array($contributionId, 'Integer'),
4338 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4339 if ($result->N
> 1) {
4340 $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.');
4345 * Update related pledge payment payments.
4347 * This function has been refactored out of the back office contribution form and may
4348 * still overlap with other functions.
4350 * @param string $action
4351 * @param int $pledgePaymentID
4352 * @param int $contributionID
4353 * @param bool $adjustTotalAmount
4354 * @param float $total_amount
4355 * @param float $original_total_amount
4356 * @param int $contribution_status_id
4357 * @param int $original_contribution_status_id
4359 public static function updateRelatedPledge(
4365 $original_total_amount,
4366 $contribution_status_id,
4367 $original_contribution_status_id
4369 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4373 if ($pledgePaymentID) {
4374 //store contribution id in payment record.
4375 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4378 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4385 if (!$pledgePaymentID) {
4388 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4394 $updatePledgePaymentStatus = FALSE;
4396 // If either the status or the amount has changed we update the pledge status.
4397 if ($action & CRM_Core_Action
::ADD
) {
4398 $updatePledgePaymentStatus = TRUE;
4400 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4401 ($original_total_amount != $total_amount))
4403 $updatePledgePaymentStatus = TRUE;
4406 if ($updatePledgePaymentStatus) {
4407 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4408 array($pledgePaymentID),
4409 $contribution_status_id,
4418 * Compute the stats values
4420 * @param string $stat either 'mode' or 'median'
4421 * @param string $sql
4422 * @param string $alias of civicrm_contribution
4424 * @return array|null
4426 public static function computeStats($stat, $sql, $alias = NULL) {
4427 $mode = $median = array();
4430 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4431 while ($modeDAO->fetch()) {
4432 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4433 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4442 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4443 foreach ($currencies as $currency => $val) {
4445 $where = "AND {$alias}.currency = '{$currency}'";
4446 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4450 $medianRow = floor($rowCount / 2);
4451 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4457 $medianValue = "SELECT {$alias}.total_amount as median
4459 ORDER BY median LIMIT {$medianRow},{$offset}";
4460 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4461 while ($medianValDAO->fetch()) {
4463 $midValue = $midValue +
$medianValDAO->median
;
4466 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4470 $midValue = $midValue / 2;
4471 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4482 * Is there only one line item attached to the contribution.
4488 * @throws \CiviCRM_API3_Exception
4490 public static function isSingleLineItem($id) {
4491 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4492 return ($lineItemCount == 1);
4496 * Complete an order.
4498 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4500 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4502 * Moving it out of the BaseIPN class is just the first step.
4504 * @param array $input
4506 * @param array $objects
4507 * @param CRM_Core_Transaction $transaction
4509 * @param CRM_Contribute_BAO_Contribution $contribution
4513 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution) {
4514 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4515 // The previous details are used when calculating line items so keep it before any code that 'does something'
4516 if (!empty($contribution->id
)) {
4517 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4518 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4520 $inputContributionWhiteList = array(
4525 'payment_instrument_id',
4530 'contribution_status_id',
4534 if (self
::isSingleLineItem($primaryContributionID)) {
4535 $inputContributionWhiteList[] = 'financial_type_id';
4538 $participant = CRM_Utils_Array
::value('participant', $objects);
4539 $memberships = CRM_Utils_Array
::value('membership', $objects);
4540 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4541 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4542 $event = CRM_Utils_Array
::value('event', $objects);
4544 $paymentProcessorId = '';
4545 if (isset($objects['paymentProcessor'])) {
4546 if (is_array($objects['paymentProcessor'])) {
4547 $paymentProcessorId = $objects['paymentProcessor']['id'];
4550 $paymentProcessorId = $objects['paymentProcessor']->id
;
4554 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4556 $contributionParams = array_merge(array(
4557 'contribution_status_id' => $completedContributionStatusID,
4558 'source' => self
::getRecurringContributionDescription($contribution, $event),
4559 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4562 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4563 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4564 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4567 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4569 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4570 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4571 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4572 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4575 if ($recurringContributionID) {
4576 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4578 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4580 if (empty($contributionParams['receive_date']) && $changeDate) {
4581 $contributionParams['receive_date'] = $changeDate;
4584 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4585 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4587 if (is_numeric($memberships)) {
4588 $memberships = array($objects['membership']);
4592 if (isset($input['is_email_receipt'])) {
4593 $values['is_email_receipt'] = $input['is_email_receipt'];
4596 if ($input['component'] == 'contribute') {
4597 if ($contribution->contribution_page_id
) {
4598 // Figure out what we gain from this.
4599 // Note that we may have overwritten the is_email_receipt input, fix that below.
4600 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4602 elseif ($recurContrib && $recurringContributionID) {
4603 $values['amount'] = $recurContrib->amount
;
4604 $values['financial_type_id'] = $objects['contributionType']->id
;
4605 $values['title'] = $source = ts('Offline Recurring Contribution');
4608 if (isset($input['is_email_receipt'])) {
4609 // CRM-19601 - we may have overwritten this above.
4610 $values['is_email_receipt'] = $input['is_email_receipt'];
4612 elseif ($recurContrib && $recurringContributionID) {
4613 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4614 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4615 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4618 if (!empty($memberships)) {
4619 foreach ($memberships as $membershipTypeIdKey => $membership) {
4621 $membershipParams = array(
4622 'id' => $membership->id
,
4623 'contact_id' => $membership->contact_id
,
4624 'is_test' => $membership->is_test
,
4625 'membership_type_id' => $membership->membership_type_id
,
4626 'membership_activity_status' => 'Completed',
4629 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4630 $membershipParams['membership_type_id'],
4631 $membershipParams['is_test'],
4632 $membershipParams['id']
4635 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4636 // this picks up membership type changes during renewals
4637 // @todo this is almost certainly an obsolete sql call, the pre-change
4638 // membership is accessible via $this->_relatedObjects
4640 SELECT membership_type_id
4641 FROM civicrm_membership_log
4642 WHERE membership_id={$membershipParams['id']}
4645 $dao = CRM_Core_DAO
::executeQuery($sql);
4646 if ($dao->fetch()) {
4647 if (!empty($dao->membership_type_id
)) {
4648 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4653 if (CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $input)) === 'Pending') {
4654 $membershipParams['num_terms'] = 0;
4657 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4658 $membershipParams['membership_type_id'],
4659 $primaryContributionID
4661 // @todo remove all this stuff in favour of letting the api call further down handle in
4662 // (it is a duplication of what the api does).
4663 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4664 if ($currentMembership) {
4666 * Fixed FOR CRM-4433
4667 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4668 * when Contribution mode is notify and membership is for renewal )
4670 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4672 // @todo - we should pass membership_type_id instead of null here but not
4673 // adding as not sure of testing
4674 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4675 $changeDate, NULL, $membershipParams['num_terms']
4678 $dates['join_date'] = $currentMembership['join_date'];
4681 //get the status for membership.
4682 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4684 $dates['join_date'],
4687 $membershipParams['membership_type_id'],
4691 unset($dates['end_date']);
4692 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4693 //we might be renewing membership,
4694 //so make status override false.
4695 $membershipParams['is_override'] = FALSE;
4697 //CRM-17723 - reset static $relatedContactIds array()
4698 // @todo move it to Civi Statics.
4700 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
4701 civicrm_api3('Membership', 'create', $membershipParams);
4707 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4708 if ($event->is_email_confirm
) {
4709 // @todo this should be set by the function that sends the mail after sending.
4710 $contributionParams['receipt_date'] = $changeDate;
4712 $participantParams['id'] = $participant->id
;
4713 $participantParams['status_id'] = 'Registered';
4714 civicrm_api3('Participant', 'create', $participantParams);
4718 $contributionParams['id'] = $contribution->id
;
4720 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4721 // unsetting it here does NOT cause any other contribution test to fail!
4722 unset($contributionParams['financial_type_id']);
4723 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4725 // Add new soft credit against current $contribution.
4726 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4727 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4730 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4731 'labelColumn' => 'name',
4734 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4735 $input['payment_processor'] = $paymentProcessorId;
4738 if (!empty($contribution->_relatedObjects
['participant'])) {
4739 $input['contribution_mode'] = 'participant';
4740 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4742 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4743 $input['contribution_mode'] = 'membership';
4744 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4745 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4746 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4749 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4750 $transaction->commit();
4752 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4753 $contributionParams['contribution_status_id'], $input['amount']);
4755 // create an activity record
4756 if ($input['component'] == 'contribute') {
4758 $targetContactID = NULL;
4759 if (!empty($ids['related_contact'])) {
4760 $targetContactID = $contribution->contact_id
;
4761 $contribution->contact_id
= $ids['related_contact'];
4763 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4766 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4767 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4768 if (!array_key_exists('is_email_receipt', $values) ||
4769 $values['is_email_receipt'] == 1
4771 civicrm_api3('Contribution', 'sendconfirmation', array(
4772 'id' => $contribution->id
,
4773 'payment_processor_id' => $paymentProcessorId,
4775 CRM_Core_Error
::debug_log_message("Receipt sent");
4778 CRM_Core_Error
::debug_log_message("Success: Database updated");
4779 return $contributionResult;
4783 * Send receipt from contribution.
4785 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4787 * Note that the compose message part has been moved to contribution
4788 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4790 * @param array $input
4791 * Incoming data from Payment processor.
4793 * Related object IDs.
4794 * @param int $contributionID
4795 * @param array $values
4796 * Values related to objects that have already been loaded.
4797 * @param bool $returnMessageText
4798 * Should text be returned instead of sent. This.
4799 * is because the function is also used to generate pdfs
4802 * @throws \CRM_Core_Exception
4803 * @throws \CiviCRM_API3_Exception
4805 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4806 $returnMessageText = FALSE) {
4808 $contribution = new CRM_Contribute_BAO_Contribution();
4809 $contribution->id
= $contributionID;
4810 if (!$contribution->find(TRUE)) {
4811 throw new CRM_Core_Exception('Contribution does not exist');
4813 $contribution->loadRelatedObjects($input, $ids, TRUE);
4814 // set receipt from e-mail and name in value
4815 if (!$returnMessageText) {
4816 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4818 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4819 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4820 // Contribution ID should really always be set. But ?
4821 if (!$returnMessageText && (!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4822 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4828 * Generate From email and from name in an array values
4830 public static function generateFromEmailAndName($input, $contribution) {
4831 // Use input valuse if supplied.
4832 if (!empty($input['receipt_from_email'])) {
4833 return array(CRM_Utils_array
::value('receipt_from_name', $input, ''), $input['receipt_from_email']);
4835 // if we are still empty see if we can use anything from a contribution page.
4836 $pageValues = array();
4837 if (!empty($contribution->contribution_page_id
)) {
4838 $pageValues = civicrm_api3('ContributionPage', 'getsingle', array('id' => $contribution->contribution_page_id
));
4840 // if we are still empty see if we can use anything from a contribution page.
4841 if (!empty($pageValues['receipt_from_email'])) {
4842 return array($pageValues['receipt_from_name'], $pageValues['receipt_from_email']);
4844 // If we are still empty fall back to the domain or logged in user information.
4845 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4849 * Generate credit note id with next avaible number
4854 public static function createCreditNoteId() {
4855 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4857 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4858 $creditNoteId = NULL;
4862 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4863 $result = civicrm_api3('Contribution', 'getcount', array(
4865 'creditnote_id' => $creditNoteId,
4867 } while ($result > 0);
4869 return $creditNoteId;
4873 * Load related memberships.
4875 * Note that in theory it should be possible to retrieve these from the line_item table
4876 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4877 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4878 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4879 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4881 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4887 public function loadRelatedMembershipObjects(&$ids) {
4889 SELECT membership_id
4890 FROM civicrm_membership_payment
4891 WHERE contribution_id = %1 ";
4892 $params = array(1 => array($this->id
, 'Integer'));
4893 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, array());
4895 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4896 while ($dao->fetch()) {
4897 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4898 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4902 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4903 foreach ($ids['membership'] as $id) {
4905 $membership = new CRM_Member_BAO_Membership();
4906 $membership->id
= $id;
4907 if (!$membership->find(TRUE)) {
4908 throw new Exception("Could not find membership record: $id");
4910 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4911 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4912 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4913 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4914 $membership->free();
4921 * This function is used to record partial payments for contribution
4923 * @param array $contribution
4925 * @param array $params
4929 public static function recordPartialPayment($contribution, $params) {
4930 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4931 $pendingStatus = array(
4932 array_search('Pending', $contributionStatuses),
4933 array_search('In Progress', $contributionStatuses),
4935 $statusId = array_search('Completed', $contributionStatuses);
4936 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4937 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is');
4939 elseif (!empty($params['payment_processor'])) {
4940 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['payment_processor'], NULL, 'civicrm_payment_processor');
4942 elseif (!empty($params['payment_instrument_id'])) {
4943 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4946 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4947 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4948 $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);
4950 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is');
4951 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4952 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4953 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4954 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4955 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4956 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4957 $balanceTrxnParams['currency'] = $contribution['currency'];
4958 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4959 $balanceTrxnParams['status_id'] = $statusId;
4960 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4961 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4962 if ($fromFinancialAccountId != NULL &&
4963 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4965 $balanceTrxnParams['is_payment'] = 1;
4967 if (!empty($params['payment_processor'])) {
4968 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4970 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4974 * Get the description (source field) for the recurring contribution.
4976 * @param CRM_Contribute_BAO_Contribution $contribution
4977 * @param CRM_Event_DAO_Event|null $event
4980 * @throws \CiviCRM_API3_Exception
4982 protected static function getRecurringContributionDescription($contribution, $event) {
4983 if (!empty($contribution->source
)) {
4984 return $contribution->source
;
4986 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4987 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4988 'id' => $contribution->contribution_page_id
,
4989 'return' => 'title',
4991 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4994 return ts('Online Event Registration') . ': ' . $event->title
;
4996 elseif (!empty($contribution->contribution_recur_id
)) {
4997 return 'recurring contribution';
5003 * Function to add payments for contribution
5004 * for Partially Paid status
5006 * @param array $contributions
5007 * @param array $contributionStatusId
5010 public static function addPayments($contributions, $contributionStatusId = NULL) {
5011 // get financial trxn which is a payment
5012 $ftSql = "SELECT ft.id, ft.total_amount
5013 FROM civicrm_financial_trxn ft
5014 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
5015 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
5016 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
5017 'labelColumn' => 'name',
5019 foreach ($contributions as $k => $contribution) {
5020 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
5021 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
5025 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
5028 // store financial item Proportionaly.
5029 $trxnParams = array(
5030 'total_amount' => $ftDao->total_amount
,
5031 'contribution_id' => $contribution->id
,
5033 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
5038 * Function use to store line item proportionaly in
5039 * in entity financial trxn table
5041 * @param array $trxnParams
5043 * @param Integer $trxnId
5045 * @param float $contributionTotalAmount
5048 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
5049 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
5050 if (!empty($lineItems)) {
5051 // get financial item
5052 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
5053 $entityParams = array(
5054 'contribution_total_amount' => $contributionTotalAmount,
5055 'trxn_total_amount' => $trxnParams['total_amount'],
5056 'trxn_id' => $trxnId,
5058 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
5063 * Function to check line items.
5065 * @param array $params
5066 * array of order params.
5068 * @throws \API_Exception
5070 public static function checkLineItems(&$params) {
5071 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
5072 $lineItemAmount = 0;
5073 foreach ($params['line_items'] as &$lineItems) {
5074 foreach ($lineItems['line_item'] as &$item) {
5075 if (empty($item['financial_type_id'])) {
5076 $item['financial_type_id'] = $params['financial_type_id'];
5078 $lineItemAmount +
= $item['line_total'];
5081 if (!isset($totalAmount)) {
5082 $params['total_amount'] = $lineItemAmount;
5084 elseif ($totalAmount != $lineItemAmount) {
5085 throw new API_Exception("Line item total doesn't match with total amount.");
5090 * Get the financial account for the item associated with the new transaction.
5092 * @param array $params
5093 * @param int $default
5097 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
5099 if (!empty($params['financial_account_id'])) {
5100 return $params['financial_account_id'];
5102 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
5103 $preferredAccountsRelationships = array(
5104 'Refunded' => 'Credit/Contra Revenue Account is',
5105 'Chargeback' => 'Chargeback Account is',
5107 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
5108 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
5109 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
5111 $preferredAccountsRelationships[$contributionStatus]
5118 * ContributionPage values were being imposed onto values.
5120 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
5121 * REALLY didn't want superimposed. The rest are left there in their overkill out
5124 * The rationale for making this explicit is that it was a case of carefully set values being
5125 * seemingly randonly overwritten without much care. In general I think array randomly setting
5126 * variables en mass is risky.
5128 * @param array $values
5132 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
5133 $contributionPageValues = array();
5134 CRM_Contribute_BAO_ContributionPage
::setValues(
5135 $this->contribution_page_id
,
5136 $contributionPageValues
5138 $valuesToCopy = array(
5139 // These are the values that I believe to be useful.
5142 'pay_later_receipt',
5144 'receipt_from_email',
5145 'receipt_from_name',
5149 'honoree_profile_id',
5150 'onbehalf_profile_id',
5151 'honor_block_is_active',
5152 // Kinda might be - but would be on the contribution...
5155 // Included for 'fear of regression' but can't justify any use for these....
5157 'payment_processor',
5158 'financial_type_id',
5159 'amount_block_is_active',
5164 'default_amount_id',
5168 'initial_amount_help_text',
5169 'initial_amount_label',
5171 'is_allow_other_amount',
5172 'is_billing_required',
5173 'is_confirm_enabled',
5174 'is_credit_card_only',
5176 'is_partial_payment',
5177 'is_recur_installments',
5178 'is_recur_interval',
5182 'min_initial_amount',
5183 'recur_frequency_unit',
5190 foreach ($valuesToCopy as $valueToCopy) {
5191 if (isset($contributionPageValues[$valueToCopy])) {
5192 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5199 * Get values of CiviContribute Settings
5200 * and check if its enabled or not.
5201 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5202 * in serialized form. Usually this should be stored as flat settings for each form fields
5203 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5204 * settings we will live with an inconsistency because it's too hard to change for now.
5205 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5208 * @param string $name
5212 public static function checkContributeSettings($name = NULL) {
5213 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5216 return CRM_Utils_Array
::value($name, $contributeSettings);
5218 return $contributeSettings;
5222 * This function process contribution related objects.
5224 * @param int $contributionId
5225 * @param int $statusId
5226 * @param int|null $previousStatusId
5228 * @param string $receiveDate
5230 * @return null|string
5232 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5234 if (!$contributionId ||
!$statusId) {
5239 'contribution_id' => $contributionId,
5240 'contribution_status_id' => $statusId,
5241 'previous_contribution_status_id' => $previousStatusId,
5242 'receive_date' => $receiveDate,
5245 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5247 if (!is_array($updateResult) ||
5248 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5249 !is_array($updatedComponents) ||
5250 empty($updatedComponents)
5255 // get the user display name.
5257 SELECT display_name as displayName
5258 FROM civicrm_contact
5259 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5260 WHERE civicrm_contribution.id = {$contributionId}";
5261 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5263 // get the status message for user.
5264 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5266 if ($componentName == 'CiviMember') {
5267 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5268 CRM_Member_PseudoConstant
::membershipStatus()
5270 if ($updatedStatusName == 'Cancelled') {
5271 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
5273 elseif ($updatedStatusName == 'Expired') {
5274 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
5277 $endDate = CRM_Utils_Array
::value('membership_end_date', $updateResult);
5279 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
5281 1 => $userDisplayName,
5289 if ($componentName == 'CiviEvent') {
5290 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5291 CRM_Event_PseudoConstant
::participantStatus()
5293 if ($updatedStatusName == 'Cancelled') {
5294 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
5296 elseif ($updatedStatusName == 'Registered') {
5297 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
5301 if ($componentName == 'CiviPledge') {
5302 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5303 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5305 if ($updatedStatusName == 'Cancelled') {
5306 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
5308 elseif ($updatedStatusName == 'Failed') {
5309 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
5311 elseif ($updatedStatusName == 'Completed') {
5312 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
5321 * Get the contribution as it is in the database before being updated.
5323 * @param int $contributionID
5327 private static function getOriginalContribution($contributionID) {
5328 return self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
5332 * Get the amount for the financial item row.
5334 * Helper function to start to break down recordFinancialTransactions for readability.
5336 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5338 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5339 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5342 * @todo move recordFinancialAccounts & helper functions to their own class?
5344 * @param array $params
5345 * Params as passed to contribution.create
5347 * @param string $context
5348 * changeFinancialType| changedAmount
5349 * @param array $lineItemDetails
5351 * @param bool $isARefund
5352 * Is this a refund / negative transaction.
5356 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund) {
5357 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
5358 return $params['total_amount'] - $params['prevContribution']->total_amount
;
5360 elseif ($context == 'changedStatus') {
5361 $cancelledTaxAmount = 0;
5363 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5365 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5367 elseif ($context === NULL) {
5368 // erm, yes because? but, hey, it's tested.
5369 return $params['total_amount'];
5371 elseif (empty($lineItemDetails['line_total'])) {
5372 // follow legacy code path
5374 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', array('civi.tag' => 'deprecated'));
5375 return $params['total_amount'];
5378 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5383 * Get the multiplier for adjusting rows.
5385 * If we are dealing with a refund or cancellation then it will be a negative
5386 * amount to reflect the negative transaction.
5388 * If we are changing Financial Type it will be a negative amount to
5389 * adjust down the old type.
5391 * @param int $contribution_status_id
5392 * @param string $context
5396 protected static function getMultiplier($contribution_status_id, $context) {
5397 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5404 * Assign Test Value.
5406 * @param string $fieldName
5407 * @param array $fieldDef
5408 * @param int $counter
5410 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5411 if ($fieldName == 'tax_amount') {
5412 $this->{$fieldName} = "0.00";
5414 elseif ($fieldName == 'net_amount') {
5415 $this->{$fieldName} = "2.00";
5417 elseif ($fieldName == 'total_amount') {
5418 $this->{$fieldName} = "3.00";
5420 elseif ($fieldName == 'fee_amount') {
5421 $this->{$fieldName} = "1.00";
5424 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5429 * Check if contribution has participant/membership payment.
5431 * @param int $contributionId
5436 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5437 // get line item for contribution
5438 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5439 // check if line item is for membership or participant
5440 foreach ($lineItems as $items) {
5441 if ($items['entity_table'] == 'civicrm_participant') {
5445 elseif ($items['entity_table'] == 'civicrm_membership') {
5457 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5459 * @param array $trxnParams
5460 * Financial trxn params
5461 * @param string $contributionParams
5462 * Contribution Params
5466 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5467 if (!self
::checkContributeSettings('always_post_to_accounts_receivable')) {
5470 $statusId = $contributionParams['contribution']->contribution_status_id
;
5471 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5472 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5473 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5474 // Return if contribution status is not completed.
5475 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5476 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5477 && $contributionParams['prevContribution']->is_pay_later
== 0
5483 $params = $trxnParams;
5484 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5485 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5486 $params['to_financial_account_id'] = $arAccountId;
5487 $params['status_id'] = array_search('Pending', $contributionStatuses);
5488 $params['is_payment'] = FALSE;
5489 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5490 self
::$_trxnIDs[] = $trxn->id
;
5491 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5495 * Calculate financial item amount when contribution is updated.
5497 * @param array $params
5498 * contribution params
5499 * @param array $amountParams
5501 * @param string $context
5505 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5506 if (!empty($params['is_quick_config'])) {
5507 $amount = $amountParams['item_amount'];
5509 $amount = $params['total_amount'];
5510 if ($context === NULL) {
5511 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5516 $amount = $amountParams['line_total'];
5517 if ($context == 'changedAmount') {
5518 $amount -= $amountParams['previous_line_total'];
5520 $amount *= $amountParams['diff'];
5526 * Retrieve Sales Tax Financial Accounts.
5532 public static function getSalesTaxFinancialAccounts() {
5533 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5534 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5535 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5536 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5537 $queryParams = array(1 => array($accountRel, 'Integer'));
5538 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5539 $financialAccount = array();
5540 while ($dao->fetch()) {
5541 $financialAccount[$dao->id
] = $dao->id
;
5543 return $financialAccount;
5547 * Create tax entry in civicrm_entity_financial_trxn table.
5549 * @param array $entityParams
5551 * @param array $eftParams
5554 public static function createProportionalEntry($entityParams, $eftParams) {
5555 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5556 // Record Entity Financial Trxn; CRM-20145
5557 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5558 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5562 * Create array of last financial item id's.
5564 * @param int $contributionId
5568 public static function getLastFinancialItemIds($contributionId) {
5569 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5570 FROM civicrm_financial_item fi
5571 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5572 WHERE li.contribution_id = %1";
5573 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contributionId, 'Integer')));
5574 $ftIds = $taxItems = array();
5575 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5576 while ($dao->fetch()) {
5577 /* if sales tax item*/
5578 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5579 $taxItems[$dao->price_field_value_id
] = array(
5580 'financial_item_id' => $dao->id
,
5581 'amount' => $dao->tax_amount
,
5585 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5588 return array($ftIds, $taxItems);
5592 * Create proportional entries in civicrm_entity_financial_trxn.
5594 * @param array $entityParams
5596 * @param array $lineItems
5598 * @param array $ftIds
5600 * @param array $taxItems
5603 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5605 'entity_table' => 'civicrm_financial_item',
5606 'financial_trxn_id' => $entityParams['trxn_id'],
5608 foreach ($lineItems as $key => $value) {
5609 if ($value['qty'] == 0) {
5612 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5613 $entityParams['line_item_amount'] = $value['line_total'];
5614 self
::createProportionalEntry($entityParams, $eftParams);
5615 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5616 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5617 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5618 self
::createProportionalEntry($entityParams, $eftParams);
5624 * Load entities related to the contribution into $this->_relatedObjects.
5628 * @throws \CRM_Core_Exception
5630 protected function loadRelatedEntitiesByID($ids) {
5632 'contact' => 'CRM_Contact_BAO_Contact',
5633 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5634 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5635 'financialType' => 'CRM_Financial_BAO_FinancialType',
5636 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5638 foreach ($entities as $entity => $bao) {
5639 if (!empty($ids[$entity])) {
5640 $this->_relatedObjects
[$entity] = new $bao();
5641 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5642 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5643 throw new CRM_Core_Exception($entity . ' could not be loaded');
5650 * Should an email receipt be sent for this contribution when complete.
5652 * @param array $input
5656 protected function isEmailReceipt($input) {
5657 if (isset($input['is_email_receipt'])) {
5658 return $input['is_email_receipt'];
5660 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5661 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5667 * Function to replace contribution tokens.
5669 * @param array $contributionIds
5671 * @param string $subject
5673 * @param array $subjectToken
5675 * @param string $text
5677 * @param string $html
5679 * @param array $messageToken
5681 * @param bool $escapeSmarty
5685 public static function replaceContributionTokens(
5694 if (empty($contributionIds)) {
5697 $contributionDetails = array();
5698 foreach ($contributionIds as $id) {
5699 $result = civicrm_api3('Contribution', 'get', array('id' => $id));
5700 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5701 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5702 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5704 return $contributionDetails;