3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
33 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
36 * Static field for all the contribution information that we can potentially import
40 static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 static $_exportableFields = NULL;
50 * Field for all the objects related to this contribution
51 * @var array of objects (e.g membership object, participant object)
53 public $_relatedObjects = array();
56 * Field for the component - either 'event' (participant) or 'contribute'
57 * (any item related to a contribution page e.g. membership, pledge, contribution)
58 * This is used for composing messages because they have dependency on the
59 * contribution_page or event page - although over time we may eliminate that
61 * @var string component or event
63 public $_component = NULL;
66 * Possibly obsolete variable.
68 * If you use it please explain why it is set in the create function here.
72 public $trxn_result_code;
77 public function __construct() {
78 parent
::__construct();
82 * Takes an associative array and creates a contribution object.
84 * the function extract all the params it needs to initialize the create a
85 * contribution object. the params array could contain additional unused name/value
88 * @param array $params
89 * (reference ) an assoc array of name/value pairs.
91 * The array that holds all the db ids.
93 * @return CRM_Contribute_BAO_Contribution|void
95 public static function add(&$params, $ids = array()) {
99 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
100 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
101 $duplicates = array();
102 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
103 $error = CRM_Core_Error
::singleton();
104 $d = implode(', ', $duplicates);
105 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
108 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
113 // first clean up all the money fields
114 $moneyFields = array(
118 'non_deductible_amount',
121 //if priceset is used, no need to cleanup money
122 if (!empty($params['skipCleanMoney'])) {
123 unset($moneyFields[0]);
126 foreach ($moneyFields as $field) {
127 if (isset($params[$field])) {
128 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
132 //set defaults in create mode
133 if (!$contributionID) {
134 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
137 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
138 //if contribution is created with cancelled or refunded status, add credit note id
139 if (!empty($params['contribution_status_id'])) {
140 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
141 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
142 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
144 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
145 $params['creditnote_id'] = self
::createCreditNoteId();
150 // Since the fee amount is expecting this (later on) ensure it is always set.
151 // It would only not be set for an update where it is unchanged.
152 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id'));
156 && CRM_Utils_Array
::value('membership_id', $params)
157 && self
::checkContributeSettings('deferred_revenue_enabled')
159 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
160 if ($memberStartDate) {
161 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
164 self
::calculateMissingAmountParams($params, $contributionID);
166 if (!empty($params['payment_instrument_id'])) {
167 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
168 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
169 $params['check_number'] = 'null';
173 $setPrevContribution = TRUE;
174 // CRM-13964 partial payment
175 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
176 $partialAmtTotal = $params['partial_payment_total'];
177 $partialAmtPay = $params['partial_amount_pay'];
178 $params['total_amount'] = $partialAmtTotal;
179 if ($partialAmtPay < $partialAmtTotal) {
180 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
181 $params['is_pay_later'] = 0;
182 $setPrevContribution = FALSE;
185 if ($contributionID && $setPrevContribution) {
186 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
189 if ($contributionID) {
190 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
193 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
195 $contribution = new CRM_Contribute_BAO_Contribution();
196 $contribution->copyValues($params);
198 $contribution->id
= $contributionID;
200 if (empty($contribution->id
)) {
201 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
202 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
203 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
207 $result = $contribution->save();
209 // Add financial_trxn details as part of fix for CRM-4724
210 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
211 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
213 //add Account details
214 $params['contribution'] = $contribution;
215 self
::recordFinancialAccounts($params);
217 if (self
::isUpdateToRecurringContribution($params)) {
218 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
219 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
220 $contributionStatus[$params['contribution_status_id']]
224 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
226 if ($contributionID) {
227 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
230 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
237 * Is this contribution updating an existing recurring contribution.
239 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
240 * pending payment is being confirmed (or failing).
242 * @param array $params
246 public static function isUpdateToRecurringContribution($params) {
247 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
250 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
253 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
256 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
257 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
264 * Get defaults for new entity.
267 public static function getDefaults() {
269 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
270 FALSE, FALSE, FALSE, 'AND is_default = 1')
272 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
277 * Fetch the object and store the values in the values array.
279 * @param array $params
280 * Input parameters to find object.
281 * @param array $values
282 * Output values of the object.
284 * The array that holds all the db ids.
286 * @return CRM_Contribute_BAO_Contribution|null
287 * The found object or null
289 public static function getValues($params, &$values, &$ids) {
290 if (empty($params)) {
293 $contribution = new CRM_Contribute_BAO_Contribution();
295 $contribution->copyValues($params);
297 if ($contribution->find(TRUE)) {
298 $ids['contribution'] = $contribution->id
;
300 CRM_Core_DAO
::storeValues($contribution, $values);
302 return $contribution;
304 $null = NULL; // return by reference
309 * Get the values and resolve the most common mappings.
311 * Since contribution status is resolved in almost every function that calls getValues it makes
312 * sense to have an extra function to resolve it rather than repeat the code.
314 * Think carefully before adding more mappings to be resolved as there could be performance implications
315 * if this function starts to be called from more iterative functions.
317 * @param array $params
318 * Input parameters to find object.
321 * Array of the found contribution.
322 * @throws CRM_Core_Exception
324 public static function getValuesWithMappings($params) {
325 $values = $ids = array();
326 $contribution = self
::getValues($params, $values, $ids);
327 if (is_null($contribution)) {
328 throw new CRM_Core_Exception('No contribution found');
330 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
335 * Calculate net_amount & fee_amount if they are not set.
337 * Net amount should be total - fee.
338 * This should only be called for new contributions.
340 * @param array $params
341 * Params for a new contribution before they are saved.
342 * @param int|null $contributionID
343 * Contribution ID if we are dealing with an update.
345 * @throws \CiviCRM_API3_Exception
347 public static function calculateMissingAmountParams(&$params, $contributionID) {
348 if (!$contributionID && !isset($params['fee_amount'])) {
349 if (isset($params['total_amount']) && isset($params['net_amount'])) {
350 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
353 $params['fee_amount'] = 0;
356 if (!isset($params['net_amount'])) {
357 if (!$contributionID) {
358 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
361 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
362 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
363 // net_amount may need adjusting.
364 $contribution = civicrm_api3('Contribution', 'getsingle', array(
365 'id' => $contributionID,
366 'return' => array('total_amount', 'net_amount'),
368 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
369 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
370 $params['net_amount'] = $totalAmount - $feeAmount;
378 * @param $billingLocationTypeID
382 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
383 $hasBillingField = FALSE;
384 $billingFields = array(
392 //build address array
393 $addressParams = array();
394 $addressParams['location_type_id'] = $billingLocationTypeID;
395 $addressParams['is_billing'] = 1;
397 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
398 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
399 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
400 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
402 foreach ($billingFields as $value) {
403 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
404 if (!empty($addressParams[$value])) {
405 $hasBillingField = TRUE;
408 return array($hasBillingField, $addressParams);
412 * Get address params ready to be passed to the payment processor.
414 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
415 * To create an address we need state_province_id.
417 * @param array $params
418 * @param int $billingLocationTypeID
422 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
423 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
424 foreach ($addressParams as $name => $field) {
425 if (substr($name, 0, 8) == 'billing_') {
426 $addressParams[substr($name, 9)] = $addressParams[$field];
429 return array($hasBillingField, $addressParams);
433 * Get the number of terms for this contribution for a given membership type
434 * based on querying the line item table and relevant price field values
435 * Note that any one contribution should only be able to have one line item relating to a particular membership
438 * @param int $membershipTypeID
440 * @param int $contributionID
444 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
445 $numTerms = CRM_Core_DAO
::singleValueQuery("
446 SELECT membership_num_terms FROM civicrm_line_item li
447 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
448 WHERE contribution_id = %1 AND membership_type_id = %2",
449 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
451 // default of 1 is precautionary
452 return empty($numTerms) ?
1 : $numTerms;
456 * Takes an associative array and creates a contribution object.
458 * @param array $params
459 * (reference ) an assoc array of name/value pairs.
461 * The array that holds all the db ids.
463 * @return CRM_Contribute_BAO_Contribution
465 public static function create(&$params, $ids = array()) {
466 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date', 'revenue_recognition_date');
467 foreach ($dateFields as $df) {
468 if (isset($params[$df])) {
469 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
473 //if contribution is created with cancelled or refunded status, add credit note id
474 if (!empty($params['contribution_status_id'])) {
475 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
477 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
478 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
480 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
481 $params['creditnote_id'] = self
::createCreditNoteId();
486 $transaction = new CRM_Core_Transaction();
488 $contribution = self
::add($params, $ids);
490 if (is_a($contribution, 'CRM_Core_Error')) {
491 $transaction->rollback();
492 return $contribution;
495 $params['contribution_id'] = $contribution->id
;
497 if (!empty($params['custom']) &&
498 is_array($params['custom'])
500 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
503 $session = CRM_Core_Session
::singleton();
505 if (!empty($params['note'])) {
507 'entity_table' => 'civicrm_contribution',
508 'note' => $params['note'],
509 'entity_id' => $contribution->id
,
510 'contact_id' => $session->get('userID'),
511 'modified_date' => date('Ymd'),
513 if (!$noteParams['contact_id']) {
514 $noteParams['contact_id'] = $params['contact_id'];
516 CRM_Core_BAO_Note
::add($noteParams);
519 // make entry in batch entity batch table
520 if (!empty($params['batch_id'])) {
521 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
522 $titleFields = array(
528 $retrieveRequired = 0;
529 foreach ($titleFields as $titleField) {
530 if (!isset($contribution->$titleField)) {
531 $retrieveRequired = 1;
535 if ($retrieveRequired == 1) {
536 $contribution->find(TRUE);
540 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
542 $transaction->commit();
544 // check if activity record exist for this contribution, if
546 $activity = new CRM_Activity_DAO_Activity();
547 $activity->source_record_id
= $contribution->id
;
548 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
553 //CRM-18406: Update activity when edit contribution.
554 if ($activity->find(TRUE)) {
555 // CRM-13237 : if activity record found, update it with campaign id of contribution
556 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
557 $contribution->activity_id
= $activity->id
;
559 if (empty($contribution->contact_id
)) {
560 $contribution->find(TRUE);
562 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
564 // do not add to recent items for import, CRM-4399
565 if (empty($params['skipRecentView'])) {
566 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
567 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
569 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
570 $titleFields = array(
576 $retrieveRequired = 0;
577 foreach ($titleFields as $titleField) {
578 if (!isset($contribution->$titleField)) {
579 $retrieveRequired = 1;
583 if ($retrieveRequired == 1) {
584 $contribution->find(TRUE);
586 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
587 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
589 $recentOther = array();
590 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
591 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
592 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
596 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
597 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
598 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
602 // add the recently created Contribution
603 CRM_Utils_Recent
::add($title,
607 $contribution->contact_id
,
613 return $contribution;
617 * Get the values for pseudoconstants for name->value and reverse.
619 * @param array $defaults
620 * (reference) the default values, some of which need to be resolved.
621 * @param bool $reverse
622 * True if we want to resolve the values in the reverse direction (value -> name).
624 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
625 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
626 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
627 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
628 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
632 * Convert associative array names to values and vice-versa.
634 * This function is used by both the web form layer and the api. Note that
635 * the api needs the name => value conversion, also the view layer typically
636 * requires value => name conversion
638 * @param array $defaults
639 * @param string $property
640 * @param array $lookup
641 * @param bool $reverse
645 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
646 $id = $property . '_id';
648 $src = $reverse ?
$property : $id;
649 $dst = $reverse ?
$id : $property;
651 if (!array_key_exists($src, $defaults)) {
655 $look = $reverse ?
array_flip($lookup) : $lookup;
657 if (is_array($look)) {
658 if (!array_key_exists($defaults[$src], $look)) {
662 $defaults[$dst] = $look[$defaults[$src]];
667 * Retrieve DB object based on input parameters.
669 * It also stores all the retrieved values in the default array.
671 * @param array $params
672 * (reference ) an assoc array of name/value pairs.
673 * @param array $defaults
674 * (reference ) an assoc array to hold the name / value pairs.
675 * in a hierarchical manner
677 * (reference) the array that holds all the db ids.
679 * @return CRM_Contribute_BAO_Contribution
681 public static function retrieve(&$params, &$defaults, &$ids) {
682 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
683 return $contribution;
687 * Combine all the importable fields from the lower levels object.
689 * The ordering is important, since currently we do not have a weight
690 * scheme. Adding weight is super important and should be done in the
691 * next week or so, before this can be called complete.
693 * @param string $contactType
694 * @param bool $status
697 * array of importable Fields
699 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
700 if (!self
::$_importableFields) {
701 if (!self
::$_importableFields) {
702 self
::$_importableFields = array();
706 $fields = array('' => array('title' => ts('- do not import -')));
709 $fields = array('' => array('title' => ts('- Contribution Fields -')));
712 $note = CRM_Core_DAO_Note
::import();
713 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
714 unset($tmpFields['option_value']);
715 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
716 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
718 // Using new Dedupe rule.
720 'contact_type' => $contactType,
721 'used' => 'Unsupervised',
723 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
724 $tmpContactField = array();
725 if (is_array($fieldsArray)) {
726 foreach ($fieldsArray as $value) {
727 //skip if there is no dupe rule
728 if ($value == 'none') {
731 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
736 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
737 $tmpContactField[trim($value)] = $contactFields[trim($value)];
739 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
742 $title = $tmpContactField[trim($value)]['title'];
744 $tmpContactField[trim($value)]['title'] = $title;
748 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
749 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
750 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
751 $fields = array_merge($fields, $tmpContactField);
752 $fields = array_merge($fields, $tmpFields);
753 $fields = array_merge($fields, $note);
754 $fields = array_merge($fields, $optionFields);
755 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
756 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
757 self
::$_importableFields = $fields;
759 return self
::$_importableFields;
763 * Combine all the exportable fields from the lower level objects.
765 * @param bool $checkPermission
768 * array of exportable Fields
770 public static function &exportableFields($checkPermission = TRUE) {
771 if (!self
::$_exportableFields) {
772 if (!self
::$_exportableFields) {
773 self
::$_exportableFields = array();
776 $impFields = CRM_Contribute_DAO_Contribution
::export();
777 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
778 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
779 $typeField = CRM_Financial_DAO_FinancialType
::export();
780 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
781 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
782 $contributionStatus = array(
783 'contribution_status' => array(
784 'title' => ts('Contribution Status'),
785 'name' => 'contribution_status',
786 'data_type' => CRM_Utils_Type
::T_STRING
,
790 $contributionPage = array(
791 'contribution_page' => array(
792 'title' => ts('Contribution Page'),
793 'name' => 'contribution_page',
794 'where' => 'civicrm_contribution_page.title',
795 'data_type' => CRM_Utils_Type
::T_STRING
,
799 $contributionNote = array(
800 'contribution_note' => array(
801 'title' => ts('Contribution Note'),
802 'name' => 'contribution_note',
803 'data_type' => CRM_Utils_Type
::T_TEXT
,
807 $contributionRecurId = array(
808 'contribution_recur_id' => array(
809 'title' => ts('Recurring Contributions ID'),
810 'name' => 'contribution_recur_id',
811 'where' => 'civicrm_contribution.contribution_recur_id',
812 'data_type' => CRM_Utils_Type
::T_INT
,
816 $extraFields = array(
817 'contribution_batch' => array(
818 'title' => ts('Batch Name'),
823 $campaignTitle = array(
824 'contribution_campaign_title' => array(
825 'title' => ts('Campaign Title'),
826 'name' => 'campaign_title',
827 'where' => 'civicrm_campaign.title',
828 'data_type' => CRM_Utils_Type
::T_STRING
,
831 $softCreditFields = array(
832 'contribution_soft_credit_name' => array(
833 'name' => 'contribution_soft_credit_name',
834 'title' => 'Soft Credit For',
835 'where' => 'civicrm_contact_d.display_name',
836 'data_type' => CRM_Utils_Type
::T_STRING
,
838 'contribution_soft_credit_amount' => array(
839 'name' => 'contribution_soft_credit_amount',
840 'title' => 'Soft Credit Amount',
841 'where' => 'civicrm_contribution_soft.amount',
842 'data_type' => CRM_Utils_Type
::T_MONEY
,
844 'contribution_soft_credit_type' => array(
845 'name' => 'contribution_soft_credit_type',
846 'title' => 'Soft Credit Type',
847 'where' => 'contribution_softcredit_type.label',
848 'data_type' => CRM_Utils_Type
::T_STRING
,
850 'contribution_soft_credit_contribution_id' => array(
851 'name' => 'contribution_soft_credit_contribution_id',
852 'title' => 'Soft Credit For Contribution ID',
853 'where' => 'civicrm_contribution_soft.contribution_id',
854 'data_type' => CRM_Utils_Type
::T_INT
,
856 'contribution_soft_credit_contact_id' => array(
857 'name' => 'contribution_soft_credit_contact_id',
858 'title' => 'Soft Credit For Contact ID',
859 'where' => 'civicrm_contact_d.id',
860 'data_type' => CRM_Utils_Type
::T_INT
,
864 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
866 'contribution_product_id' => array(
867 'title' => ts('Premium'),
868 'name' => 'contribution_product_id',
869 'where' => 'civicrm_product.id',
870 'data_type' => CRM_Utils_Type
::T_INT
,
874 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
875 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
876 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
879 self
::$_exportableFields = $fields;
882 return self
::$_exportableFields;
886 * @param null $status
887 * @param null $startDate
888 * @param null $endDate
892 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
896 $where[] = 'contribution_status_id = 1';
900 $where[] = 'contribution_status_id = 3';
905 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
908 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
910 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
911 if ($financialTypes) {
912 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
913 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
916 $where[] = "c.financial_type_id IN (0)";
919 $whereCond = implode(' AND ', $where);
922 SELECT sum( total_amount ) as total_amount,
923 count( c.id ) as total_count,
925 FROM civicrm_contribution c
926 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
927 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
929 AND ( is_test = 0 OR is_test IS NULL )
930 AND contact.is_deleted = 0
934 $dao = CRM_Core_DAO
::executeQuery($query);
937 while ($dao->fetch()) {
938 $count +
= $dao->total_count
;
939 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
943 'amount' => implode(', ', $amount),
951 * Delete the indirect records associated with this contribution first.
956 * $results no of deleted Contribution on success, false otherwise
958 public static function deleteContribution($id) {
959 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
961 $transaction = new CRM_Core_Transaction();
964 //delete activity record
966 'source_record_id' => $id,
967 // activity type id for contribution
968 'activity_type_id' => 6,
971 CRM_Activity_BAO_Activity
::deleteActivity($params);
973 //delete billing address if exists for this contribution.
974 self
::deleteAddress($id);
976 //update pledge and pledge payment, CRM-3961
977 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
979 // remove entry from civicrm_price_set_entity, CRM-5095
980 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
981 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
983 // cleanup line items.
984 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
986 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
987 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
989 if ($participantId) {
990 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
993 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
997 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
998 $noteId = key($note);
1000 CRM_Core_BAO_Note
::del($noteId, FALSE);
1003 $dao = new CRM_Contribute_DAO_Contribution();
1006 $results = $dao->delete();
1008 $transaction->commit();
1010 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1012 // delete the recently created Contribution
1013 $contributionRecent = array(
1015 'type' => 'Contribution',
1017 CRM_Utils_Recent
::del($contributionRecent);
1023 * React to a financial transaction (payment) failure.
1025 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1026 * payments is important for forensic and outreach reasons.
1028 * @param int $contributionID
1029 * @param int $contactID
1030 * @param string $message
1032 * @throws \CiviCRM_API3_Exception
1034 public static function failPayment($contributionID, $contactID, $message) {
1035 civicrm_api3('activity', 'create', array(
1036 'activity_type_id' => 'Failed Payment',
1037 'details' => $message,
1038 'subject' => ts('Payment failed at payment processor'),
1039 'source_record_id' => $contributionID,
1040 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1046 * Check if there is a contribution with the same trxn_id or invoice_id.
1048 * @param array $input
1049 * An assoc array of name/value pairs.
1050 * @param array $duplicates
1051 * (reference) store ids of duplicate contribs.
1055 * true if duplicate, false otherwise
1057 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1059 $id = CRM_Utils_Array
::value('id', $input);
1061 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1062 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1068 $clause[] = "trxn_id = %1";
1069 $input[1] = array($trxn_id, 'String');
1073 $clause[] = "invoice_id = %2";
1074 $input[2] = array($invoice_id, 'String');
1077 if (empty($clause)) {
1081 $clause = implode(' OR ', $clause);
1083 $clause = "( $clause ) AND id != %3";
1084 $input[3] = array($id, 'Integer');
1087 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1088 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1090 while ($dao->fetch()) {
1091 $duplicates[] = $dao->id
;
1098 * Takes an associative array and creates a contribution_product object.
1100 * the function extract all the params it needs to initialize the create a
1101 * contribution_product object. the params array could contain additional unused name/value
1104 * @param array $params
1105 * (reference) an assoc array of name/value pairs.
1107 * @return CRM_Contribute_DAO_ContributionProduct
1109 public static function addPremium(&$params) {
1110 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1111 $contributionProduct->copyValues($params);
1112 return $contributionProduct->save();
1116 * Get list of contribution fields for profile.
1117 * For now we only allow custom contribution fields to be in
1120 * @param bool $addExtraFields
1121 * True if special fields needs to be added.
1124 * the list of contribution fields
1126 public static function getContributionFields($addExtraFields = TRUE) {
1127 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1128 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1130 if ($addExtraFields) {
1131 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1134 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1136 foreach ($contributionFields as $key => $var) {
1137 if ($key == 'contribution_contact_id') {
1140 elseif ($key == 'contribution_campaign_id') {
1141 $var['title'] = ts('Campaign');
1143 $fields[$key] = $var;
1146 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1151 * Add extra fields specific to contribution.
1153 public static function getSpecialContributionFields() {
1154 $extraFields = array(
1155 'contribution_soft_credit_name' => array(
1156 'name' => 'contribution_soft_credit_name',
1157 'title' => 'Soft Credit Name',
1158 'headerPattern' => '/^soft_credit_name$/i',
1159 'where' => 'civicrm_contact_d.display_name',
1161 'contribution_soft_credit_email' => array(
1162 'name' => 'contribution_soft_credit_email',
1163 'title' => 'Soft Credit Email',
1164 'headerPattern' => '/^soft_credit_email$/i',
1165 'where' => 'soft_email.email',
1167 'contribution_soft_credit_phone' => array(
1168 'name' => 'contribution_soft_credit_phone',
1169 'title' => 'Soft Credit Phone',
1170 'headerPattern' => '/^soft_credit_phone$/i',
1171 'where' => 'soft_phone.phone',
1173 'contribution_soft_credit_contact_id' => array(
1174 'name' => 'contribution_soft_credit_contact_id',
1175 'title' => 'Soft Credit Contact ID',
1176 'headerPattern' => '/^soft_credit_contact_id$/i',
1177 'where' => 'civicrm_contribution_soft.contact_id',
1179 'contribution_pcp_title' => array(
1180 'name' => 'contribution_pcp_title',
1181 'title' => 'Personal Campaign Page Title',
1182 'headerPattern' => '/^contribution_pcp_title$/i',
1183 'where' => 'contribution_pcp.title',
1187 return $extraFields;
1191 * @param int $pageID
1195 public static function getCurrentandGoalAmount($pageID) {
1197 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1198 FROM civicrm_contribution_page p,
1199 civicrm_contribution c
1200 WHERE p.id = c.contribution_page_id
1202 AND c.cancel_date is null
1206 $config = CRM_Core_Config
::singleton();
1207 $params = array(1 => array($pageID, 'Integer'));
1208 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1210 if ($dao->fetch()) {
1211 return array($dao->goal
, $dao->total
);
1214 return array(NULL, NULL);
1219 * Get list of contributions which credit the passed in contact ID.
1221 * The returned array provides details about the original contribution & donor.
1223 * @todo - this is a confusing function called from one place. It has a test. It would be
1224 * nice to deprecate it.
1226 * @param int $honorId
1227 * In Honor of Contact ID.
1230 * list of contribution fields
1232 public static function getHonorContacts($honorId) {
1234 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1235 $honorDAO->contact_id
= $honorId;
1238 $type = CRM_Contribute_PseudoConstant
::financialType();
1240 while ($honorDAO->fetch()) {
1241 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1242 $contributionDAO->id
= $honorDAO->contribution_id
;
1244 if ($contributionDAO->find(TRUE)) {
1245 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1246 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1247 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1248 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1249 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1250 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1251 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1252 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1253 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1261 * Get the sort name of a contact for a particular contribution.
1264 * Id of the contribution.
1266 * @return null|string
1267 * sort name of the contact if found
1269 public static function sortName($id) {
1270 $id = CRM_Utils_Type
::escape($id, 'Integer');
1273 SELECT civicrm_contact.sort_name
1274 FROM civicrm_contribution, civicrm_contact
1275 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1276 AND civicrm_contribution.id = {$id}
1278 return CRM_Core_DAO
::singleValueQuery($query);
1282 * @param int $contactID
1286 public static function annual($contactID) {
1287 if (is_array($contactID)) {
1288 $contactIDs = implode(',', $contactID);
1291 $contactIDs = $contactID;
1294 $config = CRM_Core_Config
::singleton();
1295 $startDate = $endDate = NULL;
1297 $currentMonth = date('m');
1298 $currentDay = date('d');
1299 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1300 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1301 (int ) $config->fiscalYearStart
['d'] > $currentDay
1304 $year = date('Y') - 1;
1309 $nextYear = $year +
1;
1311 if ($config->fiscalYearStart
) {
1312 $newFiscalYearStart = $config->fiscalYearStart
;
1313 if ($newFiscalYearStart['M'] < 10) {
1314 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1316 if ($newFiscalYearStart['d'] < 10) {
1317 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1319 $config->fiscalYearStart
= $newFiscalYearStart;
1320 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1325 $startDate = "$year$monthDay";
1326 $endDate = "$nextYear$monthDay";
1327 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1328 $additionalWhere = " AND b.financial_type_id IN (0)";
1329 $liWhere = " AND i.financial_type_id IN (0)";
1330 if (!empty($financialTypes)) {
1331 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1332 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1335 SELECT count(*) as count,
1336 sum(total_amount) as amount,
1337 avg(total_amount) as average,
1339 FROM civicrm_contribution b
1340 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1341 WHERE b.contact_id IN ( $contactIDs )
1342 AND b.contribution_status_id = 1
1344 AND b.receive_date >= $startDate
1345 AND b.receive_date < $endDate
1349 $dao = CRM_Core_DAO
::executeQuery($query);
1351 $amount = $average = array();
1352 while ($dao->fetch()) {
1353 if ($dao->count
> 0 && $dao->amount
> 0) {
1354 $count +
= $dao->count
;
1355 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1356 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1362 implode(', ', $amount),
1363 implode(', ', $average),
1366 return array(0, 0, 0);
1370 * Check if there is a contribution with the params passed in.
1372 * Used for trxn_id,invoice_id and contribution_id
1374 * @param array $params
1375 * An assoc array of name/value pairs.
1378 * contribution id if success else NULL
1380 public static function checkDuplicateIds($params) {
1381 $dao = new CRM_Contribute_DAO_Contribution();
1385 foreach ($params as $k => $v) {
1387 $clause[] = "$k = '$v'";
1390 $clause = implode(' AND ', $clause);
1391 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1392 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1394 while ($dao->fetch()) {
1402 * Get the contribution details for component export.
1404 * @param int $exportMode
1406 * @param string $componentIds
1412 public static function getContributionDetails($exportMode, $componentIds) {
1413 $paymentDetails = array();
1414 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1416 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1417 $componentSelect = " civicrm_participant_payment.participant_id id";
1418 $additionalClause = "
1419 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1420 AND civicrm_participant_payment.participant_id {$componentClause} )
1423 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1424 $componentSelect = " civicrm_membership_payment.membership_id id";
1425 $additionalClause = "
1426 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1427 AND civicrm_membership_payment.membership_id {$componentClause} )
1430 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1431 $componentSelect = " civicrm_pledge_payment.id id";
1432 $additionalClause = "
1433 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1434 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1438 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1439 trxn_id, {$componentSelect}
1440 FROM civicrm_contribution
1441 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1442 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1443 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1444 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1445 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1446 AND option_group_contribution_status.id = contribution_status.option_group_id )
1450 $dao = CRM_Core_DAO
::executeQuery($query);
1452 while ($dao->fetch()) {
1453 $paymentDetails[$dao->id
] = array(
1454 'total_amount' => $dao->total_amount
,
1455 'contribution_status' => $dao->status
,
1456 'receive_date' => $dao->receive_date
,
1457 'pay_instru' => $dao->payment_instrument
,
1458 'trxn_id' => $dao->trxn_id
,
1462 return $paymentDetails;
1466 * Create address associated with contribution record.
1468 * As long as there is one or more billing field in the parameters we will create the address.
1470 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1473 * @param array $params
1474 * @param int $billingLocationTypeID
1479 public static function createAddress($params, $billingLocationTypeID) {
1480 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1481 if ($hasBillingField) {
1482 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1483 return $address->id
;
1490 * Delete billing address record related contribution.
1492 * @param int $contributionId
1493 * @param int $contactId
1495 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1497 $contactJoin = NULL;
1499 if ($contributionId) {
1500 $clauses[] = "cc.id = {$contributionId}";
1504 $clauses[] = "cco.id = {$contactId}";
1505 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1508 if (empty($clauses)) {
1509 CRM_Core_Error
::fatal();
1512 $condition = implode(' OR ', $clauses);
1516 FROM civicrm_address ca
1517 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1521 $dao = CRM_Core_DAO
::executeQuery($query);
1523 while ($dao->fetch()) {
1524 $params = array('id' => $dao->id
);
1525 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1530 * This function check online pending contribution associated w/
1531 * Online Event Registration or Online Membership signup.
1533 * @param int $componentId
1534 * Participant/membership id.
1535 * @param string $componentName
1539 * pending contribution id.
1541 public static function checkOnlinePendingContribution($componentId, $componentName) {
1542 $contributionId = NULL;
1543 if (!$componentId ||
1544 !in_array($componentName, array('Event', 'Membership'))
1546 return $contributionId;
1549 if ($componentName == 'Event') {
1550 $idName = 'participant_id';
1551 $componentTable = 'civicrm_participant';
1552 $paymentTable = 'civicrm_participant_payment';
1553 $source = ts('Online Event Registration');
1556 if ($componentName == 'Membership') {
1557 $idName = 'membership_id';
1558 $componentTable = 'civicrm_membership';
1559 $paymentTable = 'civicrm_membership_payment';
1560 $source = ts('Online Contribution');
1563 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1566 SELECT component.id as {$idName},
1567 componentPayment.contribution_id as contribution_id,
1568 contribution.source source,
1569 contribution.contribution_status_id as contribution_status_id,
1570 contribution.is_pay_later as is_pay_later
1571 FROM $componentTable component
1572 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1573 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1574 WHERE component.id = {$componentId}";
1576 $dao = CRM_Core_DAO
::executeQuery($query);
1578 while ($dao->fetch()) {
1579 if ($dao->contribution_id
&&
1580 $dao->is_pay_later
&&
1581 $dao->contribution_status_id
== $pendingStatusId &&
1582 strpos($dao->source
, $source) !== FALSE
1584 $contributionId = $dao->contribution_id
;
1589 return $contributionId;
1593 * Update contribution as well as related objects.
1595 * This function by-passes hooks - to address this - don't use this function.
1599 * Use api contribute.completetransaction
1600 * For failures use failPayment (preferably exposing by api in the process).
1602 * @param array $params
1603 * @param bool $processContributionObject
1606 * @throws \Exception
1608 public static function transitionComponents($params, $processContributionObject = FALSE) {
1609 // get minimum required values.
1610 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1611 $componentId = CRM_Utils_Array
::value('component_id', $params);
1612 $componentName = CRM_Utils_Array
::value('componentName', $params);
1613 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1614 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1616 // if we already processed contribution object pass previous status id.
1617 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1619 $updateResult = array();
1621 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1623 // we process only ( Completed, Cancelled, or Failed ) contributions.
1624 if (!$contributionId ||
1625 !in_array($contributionStatusId, array(
1626 array_search('Completed', $contributionStatuses),
1627 array_search('Cancelled', $contributionStatuses),
1628 array_search('Failed', $contributionStatuses),
1631 return $updateResult;
1634 if (!$componentName ||
!$componentId) {
1635 // get the related component details.
1636 $componentDetails = self
::getComponentDetails($contributionId);
1639 $componentDetails['contact_id'] = $contactId;
1640 $componentDetails['component'] = $componentName;
1642 if ($componentName == 'event') {
1643 $componentDetails['participant'] = $componentId;
1646 $componentDetails['membership'] = $componentId;
1650 if (!empty($componentDetails['contact_id'])) {
1651 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1657 // do check for required ids.
1658 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1659 return $updateResult;
1662 //now we are ready w/ required ids, start processing.
1664 $baseIPN = new CRM_Core_Payment_BaseIPN();
1666 $input = $ids = $objects = array();
1668 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1669 $ids['contribution'] = $contributionId;
1670 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1671 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1672 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1673 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1674 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1675 $ids['contributionRecur'] = NULL;
1676 $ids['contributionPage'] = NULL;
1678 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1679 CRM_Core_Error
::fatal();
1682 $memberships = &$objects['membership'];
1683 $participant = &$objects['participant'];
1684 $pledgePayment = &$objects['pledge_payment'];
1685 $contribution = &$objects['contribution'];
1687 if ($pledgePayment) {
1688 $pledgePaymentIDs = array();
1689 foreach ($pledgePayment as $key => $object) {
1690 $pledgePaymentIDs[] = $object->id
;
1692 $pledgeID = $pledgePayment[0]->pledge_id
;
1695 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1698 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1699 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1704 // we might want to process contribution object.
1705 $processContribution = FALSE;
1706 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1707 if (is_array($memberships)) {
1708 foreach ($memberships as $membership) {
1710 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1711 $membership->save();
1713 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1714 if ($processContributionObject) {
1715 $processContribution = TRUE;
1722 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1723 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1725 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1726 if ($processContributionObject) {
1727 $processContribution = TRUE;
1731 if ($pledgePayment) {
1732 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1734 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1735 if ($processContributionObject) {
1736 $processContribution = TRUE;
1740 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1741 if (is_array($memberships)) {
1742 foreach ($memberships as $membership) {
1744 $membership->status_id
= array_search('Expired', $membershipStatuses);
1745 $membership->save();
1747 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1748 if ($processContributionObject) {
1749 $processContribution = TRUE;
1755 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1756 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1758 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1759 if ($processContributionObject) {
1760 $processContribution = TRUE;
1764 if ($pledgePayment) {
1765 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1767 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1768 if ($processContributionObject) {
1769 $processContribution = TRUE;
1773 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1775 // only pending contribution related object processed.
1776 if ($previousContriStatusId &&
1777 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1779 // this is case when we already processed contribution object.
1780 return $updateResult;
1782 elseif (!$previousContriStatusId &&
1783 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1785 // this is case when we are going to process contribution object later.
1786 return $updateResult;
1789 if (is_array($memberships)) {
1790 foreach ($memberships as $membership) {
1795 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1796 $membership->membership_type_id
,
1797 $membership->is_test
, $membership->id
1800 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1801 // this picks up membership type changes during renewals
1803 SELECT membership_type_id
1804 FROM civicrm_membership_log
1805 WHERE membership_id=$membership->id
1808 $dao = new CRM_Core_DAO();
1810 if ($dao->fetch()) {
1811 if (!empty($dao->membership_type_id
)) {
1812 $membership->membership_type_id
= $dao->membership_type_id
;
1813 $membership->save();
1816 // else fall back to using current membership type
1819 // Figure out number of terms
1821 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1822 foreach ($lineitems as $lineitem) {
1823 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1824 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1826 // in case membership_num_terms comes through as null or zero
1827 $numterms = $numterms >= 1 ?
$numterms : 1;
1832 // CRM-15735-to update the membership status as per the contribution receive date
1834 if (!empty($params['receive_date'])) {
1835 $joinDate = $params['receive_date'];
1836 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1837 $membership->end_date
,
1838 $membership->join_date
,
1839 $params['receive_date'],
1841 $membership->membership_type_id
,
1844 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1845 $membership->save();
1848 if ($currentMembership) {
1849 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1850 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1851 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1854 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1857 //get the status for membership.
1858 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1860 $dates['join_date'],
1863 $membership->membership_type_id
,
1867 $formattedParams = array(
1868 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1869 array_search('Current', $membershipStatuses)
1871 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1872 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1873 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1876 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1878 $membership->copyValues($formattedParams);
1879 $membership->save();
1881 //updating the membership log
1882 $membershipLog = array();
1883 $membershipLog = $formattedParams;
1884 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1885 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1887 $membershipLog['start_date'] = $logStartDate;
1888 $membershipLog['membership_id'] = $membership->id
;
1889 $membershipLog['modified_id'] = $membership->contact_id
;
1890 $membershipLog['modified_date'] = date('Ymd');
1891 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1893 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1895 //update related Memberships.
1896 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1898 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1901 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1902 if ($processContributionObject) {
1903 $processContribution = TRUE;
1906 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1912 $updatedStatusId = array_search('Registered', $participantStatuses);
1913 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1915 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1916 if ($processContributionObject) {
1917 $processContribution = TRUE;
1921 if ($pledgePayment) {
1922 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1924 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1925 if ($processContributionObject) {
1926 $processContribution = TRUE;
1931 // process contribution object.
1932 if ($processContribution) {
1933 $contributionParams = array();
1940 'payment_instrument_id',
1943 'financial_type_id',
1944 'contribution_status_id',
1945 'non_deductible_amount',
1949 foreach ($fields as $field) {
1950 if (empty($params[$field])) {
1953 $contributionParams[$field] = $params[$field];
1956 $ids = array('contribution' => $contributionId);
1957 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1960 return $updateResult;
1964 * Returns all contribution related object ids.
1966 * @param $contributionId
1970 public static function getComponentDetails($contributionId) {
1971 $componentDetails = $pledgePayment = array();
1972 if (!$contributionId) {
1973 return $componentDetails;
1977 SELECT c.id as contribution_id,
1978 c.contact_id as contact_id,
1979 c.contribution_recur_id,
1980 mp.membership_id as membership_id,
1981 m.membership_type_id as membership_type_id,
1982 pp.participant_id as participant_id,
1983 p.event_id as event_id,
1984 pgp.id as pledge_payment_id
1985 FROM civicrm_contribution c
1986 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1987 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1988 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1989 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1990 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1991 WHERE c.id = $contributionId";
1993 $dao = CRM_Core_DAO
::executeQuery($query);
1994 $componentDetails = array();
1996 while ($dao->fetch()) {
1997 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1998 $componentDetails['contact_id'] = $dao->contact_id
;
1999 if ($dao->event_id
) {
2000 $componentDetails['event'] = $dao->event_id
;
2002 if ($dao->participant_id
) {
2003 $componentDetails['participant'] = $dao->participant_id
;
2005 if ($dao->membership_id
) {
2006 if (!isset($componentDetails['membership'])) {
2007 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2009 $componentDetails['membership'][] = $dao->membership_id
;
2010 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2012 if ($dao->pledge_payment_id
) {
2013 $pledgePayment[] = $dao->pledge_payment_id
;
2015 if ($dao->contribution_recur_id
) {
2016 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2020 if ($pledgePayment) {
2021 $componentDetails['pledge_payment'] = $pledgePayment;
2024 return $componentDetails;
2028 * @param int $contactId
2029 * @param bool $includeSoftCredit
2031 * @return null|string
2033 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2037 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
2038 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2039 $liWhere = " AND i.financial_type_id IN (0)";
2040 if (!empty($financialTypes)) {
2041 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2042 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2044 $contactContributionsSQL = "
2045 SELECT contribution.id AS id
2046 FROM civicrm_contribution contribution
2047 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2048 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2052 $contactSoftCreditContributionsSQL = "
2053 SELECT contribution.id
2054 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2055 ON ( contribution.id = softContribution.contribution_id )
2056 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2057 $query = "SELECT count( x.id ) count FROM ( ";
2058 $query .= $contactContributionsSQL;
2060 if ($includeSoftCredit) {
2061 $query .= " UNION ";
2062 $query .= $contactSoftCreditContributionsSQL;
2067 return CRM_Core_DAO
::singleValueQuery($query);
2071 * Repeat a transaction as part of a recurring series.
2073 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2074 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2075 * subsequent call to the contribution.completetransaction api.
2077 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2079 * @param CRM_Contribute_BAO_Contribution $contribution
2080 * @param array $input
2081 * @param array $contributionParams
2082 * @param int $paymentProcessorID
2085 * @throws CiviCRM_API3_Exception
2087 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2088 if (!empty($contribution->id
)) {
2091 if (empty($contribution->id
)) {
2092 // Unclear why this would only be set for repeats.
2093 if (!empty($input['amount'])) {
2094 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2097 if (!empty($contributionParams['contribution_recur_id'])) {
2098 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2099 'id' => $contributionParams['contribution_recur_id'],
2101 if (!empty($recurringContribution['campaign_id'])) {
2102 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2103 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2105 if (!empty($recurringContribution['financial_type_id'])) {
2106 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2107 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2110 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2111 $contributionParams['contribution_recur_id'],
2112 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2114 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2116 $contributionParams['status_id'] = 'Pending';
2117 if (isset($contributionParams['financial_type_id'])) {
2118 // Give precedence to passed in type.
2119 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2122 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2124 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2125 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2127 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2128 //do not create CC or BCC emails or profile notifications.
2129 //The if is just to be safe. Not sure if we can ever arrive with this unset
2130 if (isset($contribution->contribution_page_id
)) {
2131 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2134 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2135 $contribution->id
= $createContribution['id'];
2136 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2142 * Get individual id for onbehalf contribution.
2144 * @param int $contributionId
2146 * @param int $contributorId
2150 * containing organization id and individual id
2152 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2156 if (!$contributionId) {
2160 // fetch contributor id if null
2161 if (!$contributorId) {
2162 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2163 $contributionId, 'contact_id'
2167 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2168 $activityTypeId = array_search('Contribution', $activityTypeIds);
2170 if ($activityTypeId && $contributorId) {
2172 SELECT civicrm_activity_contact.contact_id
2173 FROM civicrm_activity_contact
2174 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2175 WHERE civicrm_activity.activity_type_id = %1
2176 AND civicrm_activity.source_record_id = %2
2177 AND civicrm_activity_contact.record_type_id = %3
2180 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2181 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2184 1 => array($activityTypeId, 'Integer'),
2185 2 => array($contributionId, 'Integer'),
2186 3 => array($sourceID, 'Integer'),
2189 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2191 // for on behalf contribution source is individual and contributor is organization
2192 if ($sourceContactId && $sourceContactId != $contributorId) {
2193 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2194 // get rel type id for employee of relation
2195 foreach ($relationshipTypeIds as $id => $typeVals) {
2196 if ($typeVals['name_a_b'] == 'Employee of') {
2197 $relationshipTypeId = $id;
2202 $rel = new CRM_Contact_DAO_Relationship();
2203 $rel->relationship_type_id
= $relationshipTypeId;
2204 $rel->contact_id_a
= $sourceContactId;
2205 $rel->contact_id_b
= $contributorId;
2206 if ($rel->find(TRUE)) {
2207 $ids['individual_id'] = $rel->contact_id_a
;
2208 $ids['organization_id'] = $rel->contact_id_b
;
2219 public static function getContributionDates() {
2220 $config = CRM_Core_Config
::singleton();
2221 $currentMonth = date('m');
2222 $currentDay = date('d');
2223 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2224 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2225 (int ) $config->fiscalYearStart
['d'] > $currentDay
2228 $year = date('Y') - 1;
2233 $year = array('Y' => $year);
2234 $yearDate = $config->fiscalYearStart
;
2235 $yearDate = array_merge($year, $yearDate);
2236 $yearDate = CRM_Utils_Date
::format($yearDate);
2238 $monthDate = date('Ym') . '01';
2244 'yearDate' => $yearDate,
2245 'monthDate' => $monthDate,
2250 * Load objects relations to contribution object.
2251 * Objects are stored in the $_relatedObjects property
2252 * In the first instance we are just moving functionality from BASEIpn -
2253 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2255 * Note that the unit test for the BaseIPN class tests this function
2257 * @param array $input
2258 * Input as delivered from Payment Processor.
2260 * Ids as Loaded by Payment Processor.
2261 * @param bool $loadAll
2262 * Load all related objects - even where id not passed in? (allows API to call this).
2267 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2269 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2270 if (empty($ids['contact']) && isset($this->contact_id
)) {
2271 $ids['contact'] = $this->contact_id
;
2274 if (empty($this->_component
)) {
2275 if (!empty($ids['event'])) {
2276 $this->_component
= 'event';
2279 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2283 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2284 // refactoring than anything else, and has unit test coverage.
2285 if (empty($this->financial_type_id
)) {
2289 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2294 if (!$paymentProcessorID && $this->contribution_page_id
) {
2295 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2296 $this->contribution_page_id
,
2299 if ($paymentProcessorID) {
2300 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2304 $ids['contributionType'] = $this->financial_type_id
;
2305 $ids['financialType'] = $this->financial_type_id
;
2308 'contact' => 'CRM_Contact_BAO_Contact',
2309 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2310 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2311 'financialType' => 'CRM_Financial_BAO_FinancialType',
2313 foreach ($entities as $entity => $bao) {
2314 if (!empty($ids[$entity])) {
2315 $this->_relatedObjects
[$entity] = new $bao();
2316 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2317 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2318 throw new CRM_Core_Exception($entity . ' could not be loaded');
2323 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2324 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2327 if (!empty($ids['pledge_payment'])) {
2328 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2329 if (empty($paymentID)) {
2332 $payment = new CRM_Pledge_BAO_PledgePayment();
2333 $payment->id
= $paymentID;
2334 if (!$payment->find(TRUE)) {
2335 throw new Exception("Could not find pledge payment record: " . $paymentID);
2337 $this->_relatedObjects
['pledge_payment'][] = $payment;
2341 $this->loadRelatedMembershipObjects($ids);
2343 if ($this->_component
!= 'contribute') {
2344 // we are in event mode
2345 // make sure event exists and is valid
2346 $event = new CRM_Event_BAO_Event();
2347 $event->id
= $ids['event'];
2348 if ($ids['event'] &&
2351 throw new Exception("Could not find event: " . $ids['event']);
2354 $this->_relatedObjects
['event'] = &$event;
2356 $participant = new CRM_Event_BAO_Participant();
2357 $participant->id
= $ids['participant'];
2358 if ($ids['participant'] &&
2359 !$participant->find(TRUE)
2361 throw new Exception("Could not find participant: " . $ids['participant']);
2363 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2365 $this->_relatedObjects
['participant'] = &$participant;
2367 // get the payment processor id from event - this is inaccurate see CRM-16923
2368 // in future we should look at throwing an exception here rather than an dubious guess.
2369 if (!$paymentProcessorID) {
2370 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2371 if ($paymentProcessorID) {
2372 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2377 if ($paymentProcessorID) {
2378 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2379 $this->is_test ?
'test' : 'live'
2381 $ids['paymentProcessor'] = $paymentProcessorID;
2382 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2388 * Create array of message information - ie. return html version, txt version, to field
2390 * @param array $input
2391 * Incoming information.
2392 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2393 * just check presence of recur object but maintaining legacy approach
2396 * IDs of related objects.
2397 * @param array $values
2398 * Any values that may have already been compiled by calling process.
2399 * This is augmented by values 'gathered' by gatherMessageValues
2400 * @param bool $recur
2401 * @param bool $returnMessageText
2402 * Distinguishes between whether to send message or return.
2403 * message text. We are working towards this function ALWAYS returning message text & calling
2404 * function doing emails / pdfs with it
2410 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2411 $this->loadRelatedObjects($input, $ids);
2413 if (empty($this->_component
)) {
2414 $this->_component
= CRM_Utils_Array
::value('component', $input);
2417 //not really sure what params might be passed in but lets merge em into values
2418 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2419 if (!empty($input['receipt_date'])) {
2420 $values['receipt_date'] = $input['receipt_date'];
2423 $template = CRM_Core_Smarty
::singleton();
2424 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2425 //what does recur 'mean here - to do with payment processor return functionality but
2426 // what is the importance
2427 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2428 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2430 $entityID = $entity = NULL;
2431 if (isset($ids['contribution'])) {
2432 $entity = 'contribution';
2433 $entityID = $ids['contribution'];
2435 if (!empty($ids['membership'])) {
2436 //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
2437 // 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
2438 // line having loaded an array
2439 $ids['membership'] = (array) $ids['membership'];
2440 $entity = 'membership';
2441 $entityID = $ids['membership'][0];
2444 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2445 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2446 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2448 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2449 //direct mode showing billing block, so use directIPN for temporary
2450 $template->assign('contributeMode', 'directIPN');
2453 // todo remove strtolower - check consistency
2454 if (strtolower($this->_component
) == 'event') {
2455 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2456 $values['event'] = array();
2458 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2460 //get location details
2461 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2462 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2464 $ufJoinParams = array(
2465 'entity_table' => 'civicrm_event',
2466 'entity_id' => $ids['event'],
2467 'module' => 'CiviEvent',
2470 list($custom_pre_id,
2472 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2474 $values['custom_pre_id'] = $custom_pre_id;
2475 $values['custom_post_id'] = $custom_post_ids;
2476 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2477 //and cases involving status updation through ipn
2478 // whatever that means!
2479 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2480 // perhaps we should throw an e-notice if amount is set & force total_amount?
2481 if (!empty($input['amount'])) {
2482 $values['totalAmount'] = $input['amount'];
2485 if ($values['event']['is_email_confirm']) {
2486 $values['is_email_receipt'] = 1;
2489 if (!empty($ids['contribution'])) {
2490 $values['contributionId'] = $ids['contribution'];
2493 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2494 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2498 $values['contribution_id'] = $this->id
;
2499 if (!empty($ids['related_contact'])) {
2500 $values['related_contact'] = $ids['related_contact'];
2501 if (isset($ids['onbehalf_dupe_alert'])) {
2502 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2504 $entityBlock = array(
2505 'contact_id' => $ids['contact'],
2506 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2507 'Home', 'id', 'name'
2510 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2511 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2514 if ($this->is_test
) {
2517 if (!empty($this->_relatedObjects
['membership'])) {
2518 foreach ($this->_relatedObjects
['membership'] as $membership) {
2519 if ($membership->id
) {
2520 $values['isMembership'] = TRUE;
2521 $values['membership_assign'] = TRUE;
2523 // need to set the membership values here
2524 $template->assign('membership_name',
2525 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2527 $template->assign('mem_start_date', $membership->start_date
);
2528 $template->assign('mem_join_date', $membership->join_date
);
2529 $template->assign('mem_end_date', $membership->end_date
);
2530 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2531 $template->assign('mem_status', $membership_status);
2532 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2533 $values['is_pay_later'] = 1;
2536 // if separate payment there are two contributions recorded and the
2537 // admin will need to send a receipt for each of them separately.
2538 // we dont link the two in the db (but can potentially infer it if needed)
2539 $template->assign('is_separate_payment', 0);
2541 if ($recur && $paymentObject) {
2542 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2543 $template->assign('cancelSubscriptionUrl', $url);
2544 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2545 $template->assign('updateSubscriptionBillingUrl', $url);
2546 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2547 $template->assign('updateSubscriptionUrl', $url);
2550 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2553 // otherwise if its about sending emails, continue sending without return, as we
2554 // don't want to exit the loop.
2559 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2565 * Gather values for contribution mail - this function has been created
2566 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2567 * Values related to the contribution in question are gathered
2569 * @param array $input
2570 * Input into function (probably from payment processor).
2571 * @param array $values
2573 * The set of ids related to the input.
2577 public function _gatherMessageValues($input, &$values, $ids = array()) {
2578 // set display address of contributor
2579 if ($this->address_id
) {
2580 $addressParams = array('id' => $this->address_id
);
2581 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2582 $addressDetails = array_values($addressDetails);
2584 // Else we assign the billing address of the contribution contact.
2586 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2587 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2588 $addressDetails = array_values($addressDetails);
2591 if (!empty($addressDetails[0]['display'])) {
2592 $values['address'] = $addressDetails[0]['display'];
2595 if ($this->_component
== 'contribute') {
2596 //get soft contributions
2597 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2598 if (!empty($softContributions)) {
2599 $values['softContributions'] = $softContributions['soft_credit'];
2601 if (isset($this->contribution_page_id
)) {
2602 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2603 if ($this->contribution_page_id
) {
2604 // CRM-8254 - override default currency if applicable
2605 $config = CRM_Core_Config
::singleton();
2606 $config->defaultCurrency
= CRM_Utils_Array
::value(
2609 $config->defaultCurrency
2613 // no contribution page -probably back office
2615 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2616 $values['is_email_receipt'] = 1;
2617 $values['title'] = 'Contribution';
2619 // set lineItem for contribution
2621 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2622 if (!empty($lineItem)) {
2623 $itemId = key($lineItem);
2624 foreach ($lineItem as &$eachItem) {
2625 if (isset($this->_relatedObjects
['membership'])
2626 && is_array($this->_relatedObjects
['membership'])
2627 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2628 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2629 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2630 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2633 $values['lineItem'][0] = $lineItem;
2634 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2638 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2642 // if this is onbehalf of contribution then set related contact
2643 if (!empty($relatedContact['individual_id'])) {
2644 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2649 $eventParams = array(
2650 'id' => $this->_relatedObjects
['event']->id
,
2652 $values['event'] = array();
2654 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2655 // add custom fields for event
2656 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2658 $eventCustomGroup = array();
2659 foreach ($eventGroupTree as $key => $group) {
2660 if ($key === 'info') {
2664 foreach ($group['fields'] as $k => $customField) {
2665 $groupLabel = $group['title'];
2666 if (!empty($customField['customValue'])) {
2667 foreach ($customField['customValue'] as $customFieldValues) {
2668 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2673 $values['event']['customGroup'] = $eventCustomGroup;
2675 //get participant details
2676 $participantParams = array(
2677 'id' => $this->_relatedObjects
['participant']->id
,
2680 $values['participant'] = array();
2682 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2683 // add custom fields for event
2684 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2685 $participantCustomGroup = array();
2686 foreach ($participantGroupTree as $key => $group) {
2687 if ($key === 'info') {
2691 foreach ($group['fields'] as $k => $customField) {
2692 $groupLabel = $group['title'];
2693 if (!empty($customField['customValue'])) {
2694 foreach ($customField['customValue'] as $customFieldValues) {
2695 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2700 $values['participant']['customGroup'] = $participantCustomGroup;
2702 //get location details
2703 $locationParams = array(
2704 'entity_id' => $this->_relatedObjects
['event']->id
,
2705 'entity_table' => 'civicrm_event',
2707 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2709 $ufJoinParams = array(
2710 'entity_table' => 'civicrm_event',
2711 'entity_id' => $ids['event'],
2712 'module' => 'CiviEvent',
2715 list($custom_pre_id,
2717 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2719 $values['custom_pre_id'] = $custom_pre_id;
2720 $values['custom_post_id'] = $custom_post_ids;
2722 // set lineItem for event contribution
2724 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2725 if (!empty($participantIds)) {
2726 foreach ($participantIds as $pIDs) {
2727 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2728 if (!CRM_Utils_System
::isNull($lineItem)) {
2729 $values['lineItem'][] = $lineItem;
2736 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2738 $customGroup = array();
2739 foreach ($groupTree as $key => $group) {
2740 if ($key === 'info') {
2744 foreach ($group['fields'] as $k => $customField) {
2745 $groupLabel = $group['title'];
2746 if (!empty($customField['customValue'])) {
2747 foreach ($customField['customValue'] as $customFieldValues) {
2748 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2753 $values['customGroup'] = $customGroup;
2759 * Assign message variables to template but try to break the habit.
2761 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2762 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2763 * multiple recurring payments for processors like IATS that use tokens.
2765 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2766 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2767 * Note we send directly from this function in some cases because it is only partly refactored.
2769 * Don't call this function directly as the signature will change.
2773 * @param CRM_Core_SMARTY $template
2774 * @param bool $recur
2775 * @param bool $returnMessageText
2779 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2780 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2781 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2782 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2783 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2784 $values['useForMember'] = TRUE;
2786 //assign honor information to receipt message
2787 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2789 if (isset($softRecord['soft_credit'])) {
2790 //if id of contribution page is present
2791 if (!empty($values['id'])) {
2792 $values['honor'] = array(
2793 'honor_profile_values' => array(),
2794 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2795 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2797 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2799 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2800 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2803 //offline contribution
2804 $softCreditTypes = $softCredits = array();
2805 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2806 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2807 $softCredits[$key] = array(
2808 'Name' => $softCredit['contact_name'],
2809 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2812 $template->assign('softCreditTypes', $softCreditTypes);
2813 $template->assign('softCredits', $softCredits);
2817 $dao = new CRM_Contribute_DAO_ContributionProduct();
2818 $dao->contribution_id
= $this->id
;
2819 if ($dao->find(TRUE)) {
2820 $premiumId = $dao->product_id
;
2821 $template->assign('option', $dao->product_option
);
2823 $productDAO = new CRM_Contribute_DAO_Product();
2824 $productDAO->id
= $premiumId;
2825 $productDAO->find(TRUE);
2826 $template->assign('selectPremium', TRUE);
2827 $template->assign('product_name', $productDAO->name
);
2828 $template->assign('price', $productDAO->price
);
2829 $template->assign('sku', $productDAO->sku
);
2831 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2832 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2833 if (!$values['amount'] && isset($this->total_amount
)) {
2834 $values['amount'] = $this->total_amount
;
2837 // add the new contribution values
2838 if (strtolower($this->_component
) == 'contribute') {
2840 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2841 $softDAO->contribution_id
= $this->id
;
2842 if ($softDAO->find(TRUE)) {
2843 $template->assign('pcpBlock', TRUE);
2844 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2845 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2846 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2848 //assign the pcp page title for email subject
2849 $pcpDAO = new CRM_PCP_DAO_PCP();
2850 $pcpDAO->id
= $softDAO->pcp_id
;
2851 if ($pcpDAO->find(TRUE)) {
2852 $template->assign('title', $pcpDAO->title
);
2857 if ($this->financial_type_id
) {
2858 $values['financial_type_id'] = $this->financial_type_id
;
2861 $template->assign('trxn_id', $this->trxn_id
);
2862 $template->assign('receive_date',
2863 CRM_Utils_Date
::processDate($this->receive_date
)
2865 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
2866 $template->assign('contributeMode', 'notify');
2867 $template->assign('action', $this->is_test ?
1024 : 1);
2868 $template->assign('receipt_text',
2869 CRM_Utils_Array
::value('receipt_text',
2873 $template->assign('is_monetary', 1);
2874 $template->assign('is_recur', (bool) $recur);
2875 $template->assign('currency', $this->currency
);
2876 $template->assign('address', CRM_Utils_Address
::format($input));
2877 if (!empty($values['customGroup'])) {
2878 $template->assign('customGroup', $values['customGroup']);
2880 if (!empty($values['softContributions'])) {
2881 $template->assign('softContributions', $values['softContributions']);
2883 if ($this->_component
== 'event') {
2884 $template->assign('title', $values['event']['title']);
2885 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2886 $viewRoles = array();
2887 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2888 $viewRoles[] = $participantRoles[$v];
2890 $values['event']['participant_role'] = implode(', ', $viewRoles);
2891 $template->assign('event', $values['event']);
2892 $template->assign('participant', $values['participant']);
2893 $template->assign('location', $values['location']);
2894 $template->assign('customPre', $values['custom_pre_id']);
2895 $template->assign('customPost', $values['custom_post_id']);
2898 if ($this->_relatedObjects
['participant']->is_test
) {
2902 $values['params'] = array();
2903 //to get email of primary participant.
2904 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2905 $primaryAmount[] = array(
2906 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2907 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2909 //build an array of cId/pId of participants
2910 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2911 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2912 //send receipt to additional participant if exists
2913 if (count($additionalIDs)) {
2914 $template->assign('isPrimary', 0);
2915 $template->assign('customProfile', NULL);
2916 //set additionalParticipant true
2917 $values['params']['additionalParticipant'] = TRUE;
2918 foreach ($additionalIDs as $pId => $cId) {
2920 //to change the status pending to completed
2921 $additional = new CRM_Event_DAO_Participant();
2922 $additional->id
= $pId;
2923 $additional->contact_id
= $cId;
2924 $additional->find(TRUE);
2925 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2926 $additional->status_id
= 1;
2927 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2928 //if additional participant dont have email
2930 if (!$additionalParticipantInfo) {
2931 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2933 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2934 $primaryAmount[] = array(
2935 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2936 'amount' => $additional->fee_amount
,
2938 $additional->save();
2939 $additional->free();
2940 $template->assign('amount', $amount);
2941 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2945 //build an array of custom profile and assigning it to template
2946 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2948 if (count($customProfile)) {
2949 $template->assign('customProfile', $customProfile);
2952 // for primary contact
2953 $values['params']['additionalParticipant'] = FALSE;
2954 $template->assign('isPrimary', 1);
2955 $template->assign('amount', $primaryAmount);
2956 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2957 if ($this->payment_instrument_id
) {
2958 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2959 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2961 // carry paylater, since we did not created billing,
2962 // so need to pull email from primary location, CRM-4395
2963 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2969 * Check whether payment processor supports
2970 * cancellation of contribution subscription
2972 * @param int $contributionId
2975 * @param bool $isNotCancelled
2979 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2980 $cacheKeyString = "$contributionId";
2981 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2983 static $supportsCancel = array();
2985 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2986 $supportsCancel[$cacheKeyString] = FALSE;
2987 $isCancelled = FALSE;
2989 if ($isNotCancelled) {
2990 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2993 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2994 if (!empty($paymentObject)) {
2995 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
2998 return $supportsCancel[$cacheKeyString];
3002 * Check whether subscription is already cancelled.
3004 * @param int $contributionId
3008 * contribution status
3010 public static function isSubscriptionCancelled($contributionId) {
3012 SELECT cr.contribution_status_id
3013 FROM civicrm_contribution_recur cr
3014 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3015 WHERE con.id = %1 LIMIT 1";
3016 $params = array(1 => array($contributionId, 'Integer'));
3017 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3018 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3019 if ($status == 'Cancelled') {
3026 * Create all financial accounts entry.
3028 * @param array $params
3029 * Contribution object, line item array and params for trxn.
3032 * @param array $financialTrxnValues
3034 * @return null|object
3036 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3037 $skipRecords = $update = $return = $isRelatedId = FALSE;
3039 $additionalParticipantId = array();
3040 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3041 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3043 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3044 $entityId = $params['participant_id'];
3045 $entityTable = 'civicrm_participant';
3046 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3048 elseif (!empty($params['membership_id'])) {
3049 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3050 // are created off one contribution should be handled elsewhere
3051 $entityId = $params['membership_id'];
3052 $entityTable = 'civicrm_membership';
3055 $entityId = $params['contribution']->id
;
3056 $entityTable = 'civicrm_contribution';
3059 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3060 $isRelatedId = TRUE;
3063 $entityID[] = $entityId;
3064 if (!empty($additionalParticipantId)) {
3065 $entityID +
= $additionalParticipantId;
3067 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3068 if (empty($params['prevContribution'])) {
3075 $statusId = $params['contribution']->contribution_status_id
;
3076 // CRM-13964 partial payment
3077 if ($contributionStatus == 'Partially paid'
3078 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3080 $partialAmtPay = $params['partial_amount_pay'];
3081 $partialAmtTotal = $params['partial_payment_total'];
3083 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3084 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3085 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3086 $params['total_amount'] = $partialAmtPay;
3088 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3089 if (empty($balanceTrxnInfo['trxn_id'])) {
3090 // create new balance transaction record
3091 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3092 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3094 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3095 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3096 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3097 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3098 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3099 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3100 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3101 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3102 $balanceTrxnParams['status_id'] = $statusId;
3103 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3104 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3105 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3106 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3108 $balanceTrxnParams['is_payment'] = 1;
3110 if (!empty($params['payment_processor'])) {
3111 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3113 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3117 // build line item array if its not set in $params
3118 if (empty($params['line_item']) ||
$additionalParticipantId) {
3119 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3122 if ($contributionStatus != 'Failed' &&
3123 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3125 $skipRecords = TRUE;
3126 $pendingStatus = array(
3130 if (in_array($contributionStatus, $pendingStatus)) {
3131 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3132 $params['financial_type_id'],
3133 'Accounts Receivable Account is'
3136 elseif (!empty($params['payment_processor'])) {
3137 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3138 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array(
3139 'id' => $params['payment_processor'],
3140 'return' => 'payment_instrument_id',
3143 elseif (!empty($params['payment_instrument_id'])) {
3144 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3147 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3148 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3149 $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);
3152 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3153 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3154 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3157 //build financial transaction params
3158 $trxnParams = array(
3159 'contribution_id' => $params['contribution']->id
,
3160 'to_financial_account_id' => $params['to_financial_account_id'],
3161 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3162 'total_amount' => $totalAmount,
3163 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3164 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3165 'currency' => $params['contribution']->currency
,
3166 'trxn_id' => $params['contribution']->trxn_id
,
3167 'status_id' => $statusId,
3168 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3169 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3171 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback') {
3172 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3173 if (isset($params['refund_trxn_id'])) {
3174 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3175 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3178 //CRM-16259, set is_payment flag for non pending status
3179 if (!in_array($contributionStatus, $pendingStatus)) {
3180 $trxnParams['is_payment'] = 1;
3182 if (!empty($params['payment_processor'])) {
3183 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3186 if (isset($fromFinancialAccountId)) {
3187 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3190 // consider external values passed for recording transaction entry
3191 if (!empty($financialTrxnValues)) {
3192 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3195 $params['trxnParams'] = $trxnParams;
3197 if (!empty($params['prevContribution'])) {
3199 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3200 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3201 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3202 if (!isset($params['trxnParams']['trxn_id'])) {
3203 // Actually I have no idea why we are overwriting any values from the previous contribution.
3204 // (filling makes sense to me). However, only protecting this value as I really really know we
3205 // don't want this one overwritten.
3207 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3209 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3211 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3212 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3213 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3215 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3216 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3219 //if financial type is changed
3220 if (!empty($params['financial_type_id']) &&
3221 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3223 $accountRelationship = 'Income Account is';
3224 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3225 $accountRelationship = 'Deferred Revenue Account is';
3227 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '$accountRelationship' "));
3228 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $relationTypeId);
3229 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3230 if ($oldFinancialAccount != $newFinancialAccount) {
3231 $params['total_amount'] = 0;
3232 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3233 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3234 $params['prevContribution']->financial_type_id
, $relationTypeId);
3237 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3238 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3239 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3242 self
::updateFinancialAccounts($params, 'changeFinancialType');
3243 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3244 $params['financial_account_id'] = $newFinancialAccount;
3245 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3246 self
::updateFinancialAccounts($params);
3247 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3249 $params['deferred_financial_account_id'] = $newFinancialAccount;
3253 //Update contribution status
3254 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3255 if (!isset($params['refund_trxn_id'])) {
3256 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3257 // gets preference over another so I am only 'protecting' a very specific tested flow
3258 // and letting natural justice take care of the rest.
3259 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3261 if (!empty($params['contribution_status_id']) &&
3262 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3264 //Update Financial Records
3265 self
::updateFinancialAccounts($params, 'changedStatus');
3269 // change Payment Instrument for a Completed contribution
3270 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3271 // instrument is null and now new payment instrument is added along with the payment
3272 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3273 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3274 if (array_key_exists('payment_instrument_id', $params)) {
3275 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3276 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3277 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3279 //check if status is changed from Pending to Completed
3280 // do not update payment instrument changes for Pending to Completed
3281 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3282 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3284 // for all other statuses create new financial records
3285 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3286 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3287 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3291 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3292 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3293 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3295 // for any other payment instrument changes create new financial records
3296 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3297 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3298 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3301 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3302 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3304 // another special case when check number is changed, create new financial records
3305 // create financial trxn with negative amount
3306 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3307 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3308 // create financial trxn with positive amount
3309 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3310 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3311 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3316 //if Change contribution amount
3317 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3318 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3319 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3320 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3321 if (isset($totalAmount) &&
3322 $totalAmount != $params['prevContribution']->total_amount
3324 //Update Financial Records
3325 $params['trxnParams']['from_financial_account_id'] = NULL;
3326 self
::updateFinancialAccounts($params, 'changedAmount');
3331 // Looks like we might have a data correction update.
3332 // This would be a case where a transaction id has been entered but it is incorrect &
3333 // the person goes back in & fixes it, as opposed to a new transaction.
3334 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3335 // the data fix scenario.
3337 if (isset($params['refund_trxn_id'])) {
3338 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3339 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3340 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3347 // records finanical trxn and entity financial trxn
3348 // also make it available as return value
3349 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3350 $params['entity_id'] = $financialTxn->id
;
3353 // record line items and financial items
3354 if (empty($params['skipLineItem'])) {
3355 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3358 // create batch entry if batch_id is passed and
3359 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3360 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3361 $entityParams = array(
3362 'batch_id' => $params['batch_id'],
3363 'entity_table' => 'civicrm_financial_trxn',
3364 'entity_id' => $financialTxn->id
,
3366 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3369 // when a fee is charged
3370 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3371 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3374 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3375 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3377 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3378 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3379 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3381 unset($params['line_item']);
3387 * Update all financial accounts entry.
3389 * @param array $params
3390 * Contribution object, line item array and params for trxn.
3392 * @param string $context
3395 * @param null $skipTrxn
3398 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3399 $itemAmount = $trxnID = NULL;
3400 //get all the statuses
3401 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3402 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3403 if (($previousContributionStatus == 'Pending'
3404 ||
$previousContributionStatus == 'In Progress')
3405 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3406 && $context == 'changePaymentInstrument'
3410 if ((($previousContributionStatus == 'Partially paid'
3411 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3412 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3413 && $params['contribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus)))
3414 && $context == 'changedStatus'
3418 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3419 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3421 if ($context == 'changedStatus') {
3422 //get all the statuses
3423 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3424 $cancelledTaxAmount = 0;
3425 if ($previousContributionStatus == 'Completed'
3426 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3428 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3429 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $params, '0.00');
3430 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3431 $creditNoteId = self
::createCreditNoteId();
3432 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3435 elseif (($previousContributionStatus == 'Pending'
3436 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3438 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3439 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3440 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3442 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3443 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3444 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3445 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3446 $creditNoteId = self
::createCreditNoteId();
3447 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3451 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3454 $itemAmount = $params['trxnParams']['total_amount'] +
$cancelledTaxAmount;
3456 elseif ($context == 'changePaymentInstrument') {
3457 if ($params['trxnParams']['total_amount'] < 0) {
3458 $deferredFinancialAccount = CRM_Utils_Array
::value('deferred_financial_account_id', $params);
3459 if (empty($deferredFinancialAccount)) {
3460 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
3461 $deferredFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $relationTypeId);
3463 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC', FALSE, NULL, $deferredFinancialAccount);
3464 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3465 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3466 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3470 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3471 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3475 if ($context == 'changedStatus') {
3476 if (($previousContributionStatus == 'Pending'
3477 ||
$previousContributionStatus == 'In Progress')
3478 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3480 if (empty($params['line_item'])) {
3482 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3483 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3484 // & this can be removed
3487 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3488 $params['entity_id'] = $trxn->id
;
3489 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3490 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3492 $entityParams = array(
3493 'entity_table' => 'civicrm_financial_item',
3494 'financial_trxn_id' => $trxn->id
,
3496 foreach ($params['line_item'] as $fieldId => $fields) {
3497 foreach ($fields as $fieldValueId => $fieldValues) {
3499 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3500 2 => array($fieldValues['id'], 'Integer'),
3502 CRM_Core_DAO
::executeQuery($query, $fparams);
3504 1 => array($fieldValues['id'], 'Integer'),
3506 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3507 while ($financialItem->fetch()) {
3508 $entityParams['entity_id'] = $financialItem->id
;
3509 $entityParams['amount'] = $financialItem->amount
;
3510 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3518 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3519 $params['entity_id'] = $trxn->id
;
3520 if ($context != 'changePaymentInstrument') {
3521 $itemParams['entity_table'] = 'civicrm_line_item';
3522 $trxnIds['id'] = $params['entity_id'];
3523 foreach ($params['line_item'] as $fieldId => $fields) {
3524 foreach ($fields as $fieldValueId => $fieldValues) {
3525 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($fieldValues['id']);
3526 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3527 if ($params['contribution']->receive_date
) {
3528 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3531 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem);
3533 $currency = $params['prevContribution']->currency
;
3534 if ($params['contribution']->currency
) {
3535 $currency = $params['contribution']->currency
;
3538 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($params['contribution']->contribution_status_id
)) {
3541 if (!empty($params['is_quick_config'])) {
3542 $amount = $itemAmount;
3544 $amount = $params['total_amount'];
3548 $amount = $diff * $fieldValues['line_total'];
3551 $itemParams = array(
3552 'transaction_date' => $receiveDate,
3553 'contact_id' => $params['prevContribution']->contact_id
,
3554 'currency' => $currency,
3555 'amount' => $amount,
3556 'description' => $prevFinancialItem->description
,
3557 'status_id' => $prevFinancialItem->status_id
,
3558 'financial_account_id' => $financialAccount,
3559 'entity_table' => 'civicrm_line_item',
3560 'entity_id' => $fieldValues['id'],
3562 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3563 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $amount;
3564 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3566 if ($fieldValues['tax_amount']) {
3567 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3568 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3569 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3570 $itemParams['description'] = $taxTerm;
3571 if ($fieldValues['financial_type_id']) {
3572 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3574 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3579 if ($context == 'changeFinancialType') {
3580 $params['skipLineItem'] = FALSE;
3581 foreach ($params['line_item'] as &$lineItems) {
3582 foreach ($lineItems as &$line) {
3583 $line['financial_type_id'] = $params['financial_type_id'];
3587 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3591 * Is this contribution status a reversal.
3593 * If so we would expect to record a negative value in the financial_trxn table.
3595 * @param int $status_id
3599 public static function isContributionStatusNegative($status_id) {
3600 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3601 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3605 * Check status validation on update of a contribution.
3607 * @param array $values
3608 * Previous form values before submit.
3610 * @param array $fields
3611 * The input form values.
3613 * @param array $errors
3618 public static function checkStatusValidation($values, &$fields, &$errors) {
3619 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3620 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3621 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3625 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3626 $checkStatus = array(
3627 'Cancelled' => array('Completed', 'Refunded'),
3628 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3629 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3630 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3631 'Refunded' => array('Cancelled', 'Completed'),
3632 'Partially paid' => array('Completed'),
3635 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3636 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3638 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3639 1 => $contributionStatuses[$values['contribution_status_id']],
3640 2 => $contributionStatuses[$fields['contribution_status_id']],
3646 * Delete contribution of contact.
3650 * @param int $contactId
3654 public static function deleteContactContribution($contactId) {
3655 $contribution = new CRM_Contribute_DAO_Contribution();
3656 $contribution->contact_id
= $contactId;
3657 $contribution->find();
3658 while ($contribution->fetch()) {
3659 self
::deleteContribution($contribution->id
);
3664 * Get options for a given contribution field.
3665 * @see CRM_Core_DAO::buildOptions
3667 * @param string $fieldName
3668 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3669 * @param array $props whatever is known about this dao object.
3671 * @return array|bool
3673 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3674 $className = __CLASS__
;
3676 switch ($fieldName) {
3677 // This field is not part of this object but the api supports it
3678 case 'payment_processor':
3679 $className = 'CRM_Contribute_BAO_ContributionPage';
3680 // Filter results by contribution page
3681 if (!empty($props['contribution_page_id'])) {
3682 $page = civicrm_api('contribution_page', 'getsingle', array(
3684 'id' => ($props['contribution_page_id']),
3686 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3687 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3691 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3692 case 'honor_type_id':
3693 $className = 'CRM_Contribute_BAO_ContributionSoft';
3694 $fieldName = 'soft_credit_type_id';
3695 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3698 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3702 * Validate financial type.
3706 * @param int $financialTypeId
3707 * Financial Type id.
3709 * @param string $relationName
3711 * @return array|bool
3713 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3714 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3715 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3717 if (!$financialAccount) {
3718 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3725 * Function to record additional payment for partial and refund contributions.
3727 * @param int $contributionId
3728 * is the invoice contribution id (got created after processing participant payment).
3729 * @param array $trxnsData
3730 * to take user provided input of transaction details.
3731 * @param string $paymentType
3732 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3733 * @param int $participantId
3735 * @return null|object
3737 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3738 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3739 $getInfoOf['id'] = $contributionId;
3740 $defaults = array();
3741 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3742 if (!$participantId) {
3743 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id');
3746 if ($paymentType == 'owed') {
3747 // build params for recording financial trxn entry
3748 $params['contribution'] = $contributionDAO;
3749 $params = array_merge($defaults, $params);
3750 $params['skipLineItem'] = TRUE;
3751 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3752 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3753 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3754 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3757 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3758 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3759 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3761 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3762 if (!empty($trxnId)) {
3763 $trxnId = $trxnId['trxn_id'];
3765 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3766 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3769 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3770 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3771 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3775 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3776 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3777 FROM civicrm_financial_trxn ft
3778 LEFT JOIN civicrm_entity_financial_trxn eft
3779 ON (ft.id = eft.financial_trxn_id)
3780 WHERE eft.entity_table = 'civicrm_contribution'
3781 AND eft.entity_id = {$contributionId}
3782 AND ft.to_financial_account_id != {$toFinancialAccount}
3783 AND ft.status_id = {$statusId}
3785 $query = CRM_Core_DAO
::executeQuery($sql);
3787 $sumOfPayments = $query->sum_of_payments
;
3790 if ($contributionDAO->total_amount
== $sumOfPayments) {
3791 // update contribution status and
3792 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3793 $contributionDAO->contribution_status_id
= $statusId;
3794 $contributionDAO->cancel_date
= 'null';
3795 $contributionDAO->cancel_reason
= NULL;
3796 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3797 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3798 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3799 $contributionDAO->save();
3801 //Change status of financial record too
3802 $financialTrxn->status_id
= $statusId;
3803 $financialTrxn->save();
3805 // note : not using the self::add method,
3806 // the reason because it performs 'status change' related code execution for financial records
3807 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3808 // are coded below i.e. just updating financial_item status to 'Paid'
3810 if ($participantId) {
3811 // update participant status
3812 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3813 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3814 foreach ($ids as $val) {
3815 $participantUpdate['id'] = $val;
3816 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3817 CRM_Event_BAO_Participant
::add($participantUpdate);
3821 // update financial item statuses
3822 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3823 $paidStatus = array_search('Paid', $financialItemStatus);
3825 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3826 $sqlFinancialItemUpdate = "
3827 UPDATE civicrm_financial_item fi
3828 LEFT JOIN civicrm_entity_financial_trxn eft
3829 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3830 SET status_id = {$paidStatus}
3831 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3833 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3836 elseif ($paymentType == 'refund') {
3837 // build params for recording financial trxn entry
3838 $params['contribution'] = $contributionDAO;
3839 $params = array_merge($defaults, $params);
3840 $params['skipLineItem'] = TRUE;
3841 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3842 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3844 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3845 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3846 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3848 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3850 // note : not using the self::add method,
3851 // the reason because it performs 'status change' related code execution for financial records
3852 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3853 // are coded below i.e. just updating financial_item status to 'Paid'
3854 if ($updateStatus) {
3855 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3857 // add financial item entry
3858 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3859 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionDAO->id
);
3860 if (!empty($lineItems)) {
3861 foreach ($lineItems as $lineItemId => $lineItemValue) {
3862 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount
/ $contributionDAO->total_amount
);
3863 $addFinancialEntry = array(
3864 'transaction_date' => $financialTrxn->trxn_date
,
3865 'contact_id' => $contributionDAO->contact_id
,
3866 'amount' => round($paid, 2),
3867 'status_id' => array_search('Paid', $financialItemStatus),
3868 'entity_id' => $lineItemId,
3869 'entity_table' => 'civicrm_line_item',
3871 $trxnIds['id'] = $financialTrxn->id
;
3872 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3875 if ($participantId) {
3876 // update participant status
3877 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3878 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3879 foreach ($ids as $val) {
3880 $participantUpdate['id'] = $val;
3881 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3882 CRM_Event_BAO_Participant
::add($participantUpdate);
3887 // activity creation
3888 if (!empty($financialTrxn)) {
3889 if ($participantId) {
3890 $inputParams['id'] = $participantId;
3893 $component = 'event';
3894 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3895 $entityObj = $entityObj[$participantId];
3897 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3899 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3901 return $financialTrxn;
3907 * @param $activityType
3909 * @param int $contributionId
3911 * @throws CRM_Core_Exception
3913 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3914 if ($component == 'event') {
3915 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3916 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3917 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3918 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3919 $targetCid = $entityObj->contact_id
;
3920 // source record id would be the contribution id
3921 $srcRecId = $contributionId;
3925 $activityParams = array(
3926 'source_contact_id' => $targetCid,
3927 'source_record_id' => $srcRecId,
3928 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3932 'subject' => $subject,
3933 'activity_date_time' => $date,
3934 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3938 'skipRecentView' => TRUE,
3941 // create activity with target contacts
3942 $session = CRM_Core_Session
::singleton();
3943 $id = $session->get('userID');
3945 $activityParams['source_contact_id'] = $id;
3946 $activityParams['target_contact_id'][] = $targetCid;
3948 CRM_Activity_BAO_Activity
::create($activityParams);
3952 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3956 * @param bool $getTrxnInfo
3957 * @param bool $usingLineTotal
3961 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3962 if ($component == 'event') {
3963 $entity = 'participant';
3964 $entityTable = 'civicrm_participant';
3965 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3967 if (!$contributionId) {
3968 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3969 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3970 $id = $primaryParticipantId;
3972 if (!$contributionId) {
3978 $contributionId = $id;
3979 $entity = 'contribution';
3980 $entityTable = 'civicrm_contribution';
3983 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3984 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3986 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3987 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3989 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3990 // for additional participants
3991 if ($entityTable == 'civicrm_participant') {
3992 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3994 foreach ($ids as $val) {
3995 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3999 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
4003 $baseTrxnId = $total['trxn_id'];
4004 $total = $total['total_amount'];
4007 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
4008 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
4010 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
4011 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4012 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
4014 if ($paymentBalance == 0 && $contributionIsPayLater) {
4015 $paymentBalance = $total;
4018 $info['total'] = $total;
4019 $info['paid'] = $total - $paymentBalance;
4020 $info['balance'] = $paymentBalance;
4022 $info['component'] = $component;
4023 $info['payLater'] = $contributionIsPayLater;
4025 if ($getTrxnInfo && $baseTrxnId) {
4026 $arRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4027 $arAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $arRelationTypeId);
4029 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4031 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4033 ft.payment_instrument_id,
4034 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, con.currency
4036 FROM civicrm_contribution con
4037 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4038 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4039 AND ft.to_financial_account_id != %2
4040 INNER JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4041 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4042 INNER JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4044 WHERE con.id = %1 AND ft.to_financial_account_id <> %3
4047 $queryParams = array(
4048 1 => array($contributionId, 'Integer'),
4049 2 => array($feeFinancialAccount, 'Integer'),
4050 3 => array($arAccount, 'Integer'),
4052 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4054 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4056 while ($resultDAO->fetch()) {
4057 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4058 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4060 'total_amount' => $resultDAO->total_amount
,
4061 'financial_type' => $resultDAO->financial_account
,
4062 'payment_instrument' => $paidByLabel,
4063 'receive_date' => $resultDAO->trxn_date
,
4064 'trxn_id' => $resultDAO->trxn_id
,
4065 'status' => $statuses[$resultDAO->status_id
],
4066 'currency' => $resultDAO->currency
,
4068 if ($paidByName == 'Check') {
4069 $val['check_number'] = $resultDAO->check_number
;
4073 $info['transaction'] = $rows;
4079 * Get financial account id has 'Sales Tax Account is'
4080 * account relationship with financial type
4082 * @param int $financialTypeId
4084 * @return FinancialAccountId
4086 public static function getFinancialAccountId($financialTypeId) {
4087 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4088 $searchParams = array(
4089 'entity_table' => 'civicrm_financial_type',
4090 'entity_id' => $financialTypeId,
4091 'account_relationship' => $accountRel,
4094 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
4096 return CRM_Utils_Array
::value('financial_account_id', $result);
4102 * @param array $params
4103 * @param bool $isLineItem
4107 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4108 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4110 // Update contribution.
4111 if (!empty($params['id'])) {
4112 $id = $params['id'];
4113 $values = $ids = array();
4114 $contrbutionParams = array('id' => $id);
4115 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
4117 // To assign pervious finantial type on update of contribution
4118 if (!isset($params['financial_type_id'])) {
4119 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
4121 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
4122 // Assisn tax Amount on update of contrbution
4123 if (!empty($prevContributionValue->tax_amount
)) {
4124 $params['tax_amount'] = 'null';
4125 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4126 foreach ($params['line_item'] as $setID => $priceField) {
4127 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4128 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4135 // New Contrbution and update of contribution with tax rate financial type
4136 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4137 empty($params['skipLineItem']) && !$isLineItem
4139 $taxRateParams = $taxRates[$params['financial_type_id']];
4140 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4141 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4143 // Get Line Item on update of contribution
4144 if (isset($params['id'])) {
4145 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4148 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4150 foreach ($params['line_item'] as $setID => $priceField) {
4151 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4152 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4155 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4157 elseif (isset($params['api.line_item.create'])) {
4158 // Update total amount of contribution using lineItem
4159 $taxAmountArray = array();
4160 foreach ($params['api.line_item.create'] as $key => $value) {
4161 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4162 $taxRate = $taxRates[$value['financial_type_id']];
4163 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4164 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4167 $params['tax_amount'] = array_sum($taxAmountArray);
4168 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4171 // update line item of contrbution
4172 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4173 $taxRate = $taxRates[$params['financial_type_id']];
4174 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
4175 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4182 * Check financial type validation on update of a contribution.
4184 * @param Integer $financialTypeId
4185 * Value of latest Financial Type.
4187 * @param Integer $contributionId
4190 * @param array $errors
4195 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4196 if (!empty($financialTypeId)) {
4197 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4198 if ($oldFinancialTypeId == $financialTypeId) {
4202 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4204 '1' => array($contributionId, 'Integer'),
4206 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4207 if ($result->N
> 1) {
4208 $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.');
4213 * Update related pledge payment payments.
4215 * This function has been refactored out of the back office contribution form and may
4216 * still overlap with other functions.
4218 * @param string $action
4219 * @param int $pledgePaymentID
4220 * @param int $contributionID
4221 * @param bool $adjustTotalAmount
4222 * @param float $total_amount
4223 * @param float $original_total_amount
4224 * @param int $contribution_status_id
4225 * @param int $original_contribution_status_id
4227 public static function updateRelatedPledge(
4233 $original_total_amount,
4234 $contribution_status_id,
4235 $original_contribution_status_id
4237 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4241 if ($pledgePaymentID) {
4242 //store contribution id in payment record.
4243 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4246 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4253 if (!$pledgePaymentID) {
4256 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4262 $updatePledgePaymentStatus = FALSE;
4264 // If either the status or the amount has changed we update the pledge status.
4265 if ($action & CRM_Core_Action
::ADD
) {
4266 $updatePledgePaymentStatus = TRUE;
4268 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4269 ($original_total_amount != $total_amount))
4271 $updatePledgePaymentStatus = TRUE;
4274 if ($updatePledgePaymentStatus) {
4275 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4276 array($pledgePaymentID),
4277 $contribution_status_id,
4286 * Compute the stats values
4288 * @param $stat either 'mode' or 'median'
4290 * @param $alias of civicrm_contribution
4292 public static function computeStats($stat, $sql, $alias = NULL) {
4293 $mode = $median = array();
4296 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4297 while ($modeDAO->fetch()) {
4298 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4299 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4308 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4309 foreach ($currencies as $currency => $val) {
4311 $where = "AND {$alias}.currency = '{$currency}'";
4312 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4316 $medianRow = floor($rowCount / 2);
4317 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4323 $medianValue = "SELECT {$alias}.total_amount as median
4325 ORDER BY median LIMIT {$medianRow},{$offset}";
4326 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4327 while ($medianValDAO->fetch()) {
4329 $midValue = $midValue +
$medianValDAO->median
;
4332 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4336 $midValue = $midValue / 2;
4337 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4348 * Is there only one line item attached to the contribution.
4354 * @throws \CiviCRM_API3_Exception
4356 public static function isSingleLineItem($id) {
4357 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4358 return ($lineItemCount == 1);
4362 * Complete an order.
4364 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4366 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4368 * Moving it out of the BaseIPN class is just the first step.
4370 * @param array $input
4372 * @param array $objects
4373 * @param CRM_Core_Transaction $transaction
4375 * @param CRM_Contribute_BAO_Contribution $contribution
4376 * @param bool $isRecurring
4377 * Duplication of param needs review. Only used by AuthorizeNetIPN
4378 * @param int $isFirstOrLastRecurringPayment
4379 * Deprecated param only used by AuthorizeNetIPN.
4381 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4382 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4383 // The previous details are used when calculating line items so keep it before any code that 'does something'
4384 if (!empty($contribution->id
)) {
4385 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4386 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4388 $inputContributionWhiteList = array(
4393 'payment_instrument_id',
4398 'contribution_status_id',
4400 if (self
::isSingleLineItem($primaryContributionID)) {
4401 $inputContributionWhiteList[] = 'financial_type_id';
4404 $participant = CRM_Utils_Array
::value('participant', $objects);
4405 $memberships = CRM_Utils_Array
::value('membership', $objects);
4406 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4407 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4408 $event = CRM_Utils_Array
::value('event', $objects);
4410 $paymentProcessorId = '';
4411 if (isset($objects['paymentProcessor'])) {
4412 if (is_array($objects['paymentProcessor'])) {
4413 $paymentProcessorId = $objects['paymentProcessor']['id'];
4416 $paymentProcessorId = $objects['paymentProcessor']->id
;
4420 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4422 $contributionParams = array_merge(array(
4423 'contribution_status_id' => $completedContributionStatusID,
4424 'source' => self
::getRecurringContributionDescription($contribution, $event),
4425 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4427 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4429 if ($recurringContributionID) {
4430 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4432 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4434 if (empty($contributionParams['receive_date']) && $changeDate) {
4435 $contributionParams['receive_date'] = $changeDate;
4438 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4439 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4441 if (is_numeric($memberships)) {
4442 $memberships = array($objects['membership']);
4446 if (isset($input['is_email_receipt'])) {
4447 $values['is_email_receipt'] = $input['is_email_receipt'];
4450 if ($input['component'] == 'contribute') {
4451 if ($contribution->contribution_page_id
) {
4452 // Figure out what we gain from this.
4453 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4455 elseif ($recurContrib && $recurringContributionID) {
4456 $values['amount'] = $recurContrib->amount
;
4457 $values['financial_type_id'] = $objects['contributionType']->id
;
4458 $values['title'] = $source = ts('Offline Recurring Contribution');
4461 if ($recurContrib && $recurringContributionID && !isset($input['is_email_receipt'])) {
4462 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4463 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4464 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4467 if (!empty($memberships)) {
4468 foreach ($memberships as $membershipTypeIdKey => $membership) {
4470 $membershipParams = array(
4471 'id' => $membership->id
,
4472 'contact_id' => $membership->contact_id
,
4473 'is_test' => $membership->is_test
,
4474 'membership_type_id' => $membership->membership_type_id
,
4477 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4478 $membershipParams['membership_type_id'],
4479 $membershipParams['is_test'],
4480 $membershipParams['id']
4483 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4484 // this picks up membership type changes during renewals
4486 SELECT membership_type_id
4487 FROM civicrm_membership_log
4488 WHERE membership_id={$membershipParams['id']}
4491 $dao = CRM_Core_DAO
::executeQuery($sql);
4492 if ($dao->fetch()) {
4493 if (!empty($dao->membership_type_id
)) {
4494 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4499 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4500 $membershipParams['membership_type_id'],
4501 $primaryContributionID
4503 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4504 if ($currentMembership) {
4506 * Fixed FOR CRM-4433
4507 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4508 * when Contribution mode is notify and membership is for renewal )
4510 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4512 // @todo - we should pass membership_type_id instead of null here but not
4513 // adding as not sure of testing
4514 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4515 $changeDate, NULL, $membershipParams['num_terms']
4518 $dates['join_date'] = $currentMembership['join_date'];
4521 //get the status for membership.
4522 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4524 $dates['join_date'],
4527 $membershipParams['membership_type_id'],
4531 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4532 //we might be renewing membership,
4533 //so make status override false.
4534 $membershipParams['is_override'] = FALSE;
4535 //CRM-17723 - reset static $relatedContactIds array()
4537 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
4538 civicrm_api3('Membership', 'create', $membershipParams);
4544 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4545 if ($event->is_email_confirm
) {
4546 // @todo this should be set by the function that sends the mail after sending.
4547 $contributionParams['receipt_date'] = $changeDate;
4549 $participantParams['id'] = $participant->id
;
4550 $participantParams['status_id'] = 'Registered';
4551 civicrm_api3('Participant', 'create', $participantParams);
4555 $contributionParams['id'] = $contribution->id
;
4557 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4559 // Add new soft credit against current $contribution.
4560 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4561 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4564 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4565 'labelColumn' => 'name',
4568 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4569 $input['payment_processor'] = $paymentProcessorId;
4572 if (!empty($contribution->_relatedObjects
['participant'])) {
4573 $input['contribution_mode'] = 'participant';
4574 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4576 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4577 $input['contribution_mode'] = 'membership';
4578 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4579 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4580 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4583 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4584 $transaction->commit();
4586 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4587 $contributionParams['contribution_status_id'], $input['amount']);
4589 // create an activity record
4590 if ($input['component'] == 'contribute') {
4592 $targetContactID = NULL;
4593 if (!empty($ids['related_contact'])) {
4594 $targetContactID = $contribution->contact_id
;
4595 $contribution->contact_id
= $ids['related_contact'];
4597 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4601 CRM_Activity_BAO_Activity
::addActivity($participant);
4604 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4605 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4606 if (!array_key_exists('is_email_receipt', $values) ||
4607 $values['is_email_receipt'] == 1
4609 civicrm_api3('Contribution', 'sendconfirmation', array(
4610 'id' => $contribution->id
,
4611 'payment_processor_id' => $paymentProcessorId,
4613 CRM_Core_Error
::debug_log_message("Receipt sent");
4616 CRM_Core_Error
::debug_log_message("Success: Database updated");
4618 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4619 $isFirstOrLastRecurringPayment);
4621 return $contributionResult;
4625 * Send receipt from contribution.
4627 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4629 * Note that the compose message part has been moved to contribution
4630 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4632 * @param array $input
4633 * Incoming data from Payment processor.
4635 * Related object IDs.
4636 * @param int $contributionID
4637 * @param array $values
4638 * Values related to objects that have already been loaded.
4639 * @param bool $recur
4640 * Is it part of a recurring contribution.
4641 * @param bool $returnMessageText
4642 * Should text be returned instead of sent. This.
4643 * is because the function is also used to generate pdfs
4646 * @throws \CRM_Core_Exception
4647 * @throws \CiviCRM_API3_Exception
4649 public static function sendMail(&$input, &$ids, $contributionID, &$values, $recur = FALSE,
4650 $returnMessageText = FALSE) {
4651 $input['is_recur'] = $recur;
4653 $contribution = new CRM_Contribute_BAO_Contribution();
4654 $contribution->id
= $contributionID;
4655 if (!$contribution->find(TRUE)) {
4656 throw new CRM_Core_Exception('Contribution does not exist');
4658 $contribution->loadRelatedObjects($input, $ids, TRUE);
4659 // set receipt from e-mail and name in value
4660 if (!$returnMessageText) {
4661 $session = CRM_Core_Session
::singleton();
4662 $userID = $session->get('userID');
4663 if (!empty($userID)) {
4664 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4665 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4666 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4670 $return = $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4671 // Contribution ID should really always be set. But ?
4672 if (!$returnMessageText && (!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4673 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4679 * Generate credit note id with next avaible number
4684 public static function createCreditNoteId() {
4685 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4687 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4688 $creditNoteId = NULL;
4692 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4693 $result = civicrm_api3('Contribution', 'getcount', array(
4695 'creditnote_id' => $creditNoteId,
4697 } while ($result > 0);
4699 return $creditNoteId;
4703 * Load related memberships.
4705 * Note that in theory it should be possible to retrieve these from the line_item table
4706 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4707 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4708 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4709 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4711 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4717 public function loadRelatedMembershipObjects(&$ids) {
4719 SELECT membership_id
4720 FROM civicrm_membership_payment
4721 WHERE contribution_id = %1 ";
4722 $params = array(1 => array($this->id
, 'Integer'));
4724 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4725 while ($dao->fetch()) {
4726 if ($dao->membership_id
) {
4727 if (!is_array($ids['membership'])) {
4728 $ids['membership'] = array();
4730 $ids['membership'][] = $dao->membership_id
;
4734 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4735 foreach ($ids['membership'] as $id) {
4737 $membership = new CRM_Member_BAO_Membership();
4738 $membership->id
= $id;
4739 if (!$membership->find(TRUE)) {
4740 throw new Exception("Could not find membership record: $id");
4742 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4743 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4744 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4745 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4746 $membership->free();
4753 * This function is used to record partial payments for contribution
4755 * @param array $contribution
4757 * @param array $params
4761 public static function recordPartialPayment($contribution, $params) {
4762 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4763 $pendingStatus = array(
4764 array_search('Pending', $contributionStatuses),
4765 array_search('In Progress', $contributionStatuses),
4767 $statusId = array_search('Completed', $contributionStatuses);
4768 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4769 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4770 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4772 elseif (!empty($params['payment_processor'])) {
4773 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4775 elseif (!empty($params['payment_instrument_id'])) {
4776 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4779 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4780 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4781 $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);
4783 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4784 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4785 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4786 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4787 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4788 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4789 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4790 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4791 $balanceTrxnParams['currency'] = $contribution['currency'];
4792 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4793 $balanceTrxnParams['status_id'] = $statusId;
4794 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4795 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4796 if ($fromFinancialAccountId != NULL &&
4797 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4799 $balanceTrxnParams['is_payment'] = 1;
4801 if (!empty($params['payment_processor'])) {
4802 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4804 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4808 * Get the description (source field) for the recurring contribution.
4810 * @param CRM_Contribute_BAO_Contribution $contribution
4811 * @param CRM_Event_DAO_Event|null $event
4814 * @throws \CiviCRM_API3_Exception
4816 protected static function getRecurringContributionDescription($contribution, $event) {
4817 if (!empty($contribution->source
)) {
4818 return $contribution->source
;
4820 elseif (!empty($contribution->contribution_page_id
)) {
4821 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4822 'id' => $contribution->contribution_page_id
,
4823 'return' => 'title',
4825 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4828 return ts('Online Event Registration') . ': ' . $event->title
;
4830 elseif (!empty($contribution->contribution_recur_id
)) {
4831 return 'recurring contribution';
4837 * Function to add payments for contribution
4838 * for Partially Paid status
4840 * @param array $lineItems
4841 * @param array $contributions
4842 * @param array $contributionStatusId
4845 public static function addPayments($lineItems, $contributions, $contributionStatusId = NULL) {
4846 // get financial trxn which is a payment
4847 $ftSql = "SELECT ft.id, ft.total_amount
4848 FROM civicrm_financial_trxn ft
4849 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4850 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4851 $sql = "SELECT fi.id, li.price_field_value_id
4852 FROM civicrm_financial_item fi
4853 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id
4854 WHERE li.contribution_id = %1";
4855 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4856 'labelColumn' => 'name',
4858 foreach ($contributions as $k => $contribution) {
4859 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4860 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4864 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4866 $trxnAmount = $ftDao->total_amount
;
4869 // get financial item
4870 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contribution->id
, 'Integer')));
4871 while ($dao->fetch()) {
4872 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4876 'entity_table' => 'civicrm_financial_item',
4877 'financial_trxn_id' => $ftId,
4879 foreach ($lineItems as $key => $value) {
4880 if ($value['qty'] == 0) {
4883 $paid = $value['line_total'] * ($trxnAmount / $contribution->total_amount
);
4884 // Record Entity Financial Trxn
4885 $params['amount'] = round($paid, 2);
4886 $params['entity_id'] = $ftIds[$value['price_field_value_id']];
4888 civicrm_api3('EntityFinancialTrxn', 'create', $params);
4894 * Function use to store line item proportionaly in
4895 * in entity financial trxn table
4897 * @param array $params
4898 * array of contribution params.
4899 * @param object $trxn
4900 * CRM_Financial_DAO_FinancialTrxn object
4901 * @param array $contribution
4904 public static function assignProportionalLineItems($params, $trxn, $contribution) {
4905 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution_id']);
4906 if (!empty($lineItems)) {
4907 // get financial item
4908 $sql = "SELECT fi.id, li.price_field_value_id
4909 FROM civicrm_financial_item fi
4910 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
4911 WHERE li.contribution_id = %1";
4912 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($params['contribution_id'], 'Integer')));
4913 while ($dao->fetch()) {
4914 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4917 'entity_table' => 'civicrm_financial_item',
4918 'financial_trxn_id' => $trxn->id
,
4920 foreach ($lineItems as $key => $value) {
4921 $paid = $value['line_total'] * ($params['total_amount'] / $contribution['total_amount']);
4922 // Record Entity Financial Trxn
4923 $eftParams['amount'] = round($paid, 2);
4924 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
4926 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
4932 * Function to check line items
4934 * @param array $params
4935 * array of order params.
4938 public static function checkLineItems(&$params) {
4939 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4940 $lineItemAmount = 0;
4941 foreach ($params['line_items'] as &$lineItems) {
4942 foreach ($lineItems['line_item'] as &$item) {
4943 if (empty($item['financial_type_id'])) {
4944 $item['financial_type_id'] = $params['financial_type_id'];
4946 $lineItemAmount +
= $item['line_total'];
4949 if (!isset($totalAmount)) {
4950 $params['total_amount'] = $lineItemAmount;
4952 elseif ($totalAmount != $lineItemAmount) {
4953 throw new API_Exception("Line item total doesn't match with total amount.");
4958 * Get the financial account for the item associated with the new transaction.
4960 * @param array $params
4961 * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem
4965 public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) {
4967 if (!empty($params['financial_account_id'])) {
4968 return $params['financial_account_id'];
4970 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4971 $preferredAccountsRelationships = array(
4972 'Refunded' => 'Credit/Contra Revenue Account is',
4973 'Chargeback' => 'Chargeback Account is',
4975 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4976 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4977 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4979 $preferredAccountsRelationships[$contributionStatus]
4982 return $prevFinancialItem->financial_account_id
;
4986 * ContributionPage values were being imposed onto values.
4988 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4989 * REALLY didn't want superimposed. The rest are left there in their overkill out
4992 * The rationale for making this explicit is that it was a case of carefully set values being
4993 * seemingly randonly overwritten without much care. In general I think array randomly setting
4994 * variables en mass is risky.
4996 * @param array $values
5000 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
5001 $contributionPageValues = array();
5002 CRM_Contribute_BAO_ContributionPage
::setValues(
5003 $this->contribution_page_id
,
5004 $contributionPageValues
5006 $valuesToCopy = array(
5007 // These are the values that I believe to be useful.
5010 'pay_later_receipt',
5012 'receipt_from_email',
5013 'receipt_from_name',
5017 'honoree_profile_id',
5018 'onbehalf_profile_id',
5019 'honor_block_is_active',
5020 // Kinda might be - but would be on the contribution...
5023 // Included for 'fear of regression' but can't justify any use for these....
5025 'payment_processor',
5026 'financial_type_id',
5027 'amount_block_is_active',
5032 'default_amount_id',
5036 'initial_amount_help_text',
5037 'initial_amount_label',
5039 'is_allow_other_amount',
5040 'is_billing_required',
5041 'is_confirm_enabled',
5042 'is_credit_card_only',
5044 'is_partial_payment',
5045 'is_recur_installments',
5046 'is_recur_interval',
5050 'min_initial_amount',
5051 'recur_frequency_unit',
5058 foreach ($valuesToCopy as $valueToCopy) {
5059 if (isset($contributionPageValues[$valueToCopy])) {
5060 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5067 * Get values of CiviContribute Settings
5068 * and check if its enabled or not.
5069 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5070 * in serialized form. Usually this should be stored as flat settings for each form fields
5071 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5072 * settings we will live with an inconsistency because it's too hard to change for now.
5073 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5076 * @param string $name
5080 public static function checkContributeSettings($name = NULL) {
5081 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5084 return CRM_Utils_Array
::value($name, $contributeSettings);
5086 return $contributeSettings;
5090 * This function process contribution related objects.
5092 * @param int $contributionId
5093 * @param int $statusId
5094 * @param int|null $previousStatusId
5096 * @param string $receiveDate
5098 * @return null|string
5100 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5102 if (!$contributionId ||
!$statusId) {
5107 'contribution_id' => $contributionId,
5108 'contribution_status_id' => $statusId,
5109 'previous_contribution_status_id' => $previousStatusId,
5110 'receive_date' => $receiveDate,
5113 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5115 if (!is_array($updateResult) ||
5116 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5117 !is_array($updatedComponents) ||
5118 empty($updatedComponents)
5123 // get the user display name.
5125 SELECT display_name as displayName
5126 FROM civicrm_contact
5127 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5128 WHERE civicrm_contribution.id = {$contributionId}";
5129 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5131 // get the status message for user.
5132 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5134 if ($componentName == 'CiviMember') {
5135 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5136 CRM_Member_PseudoConstant
::membershipStatus()
5138 if ($updatedStatusName == 'Cancelled') {
5139 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
5141 elseif ($updatedStatusName == 'Expired') {
5142 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
5145 $endDate = CRM_Utils_Array
::value('membership_end_date', $updateResult);
5147 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
5149 1 => $userDisplayName,
5157 if ($componentName == 'CiviEvent') {
5158 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5159 CRM_Event_PseudoConstant
::participantStatus()
5161 if ($updatedStatusName == 'Cancelled') {
5162 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
5164 elseif ($updatedStatusName == 'Registered') {
5165 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
5169 if ($componentName == 'CiviPledge') {
5170 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5171 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5173 if ($updatedStatusName == 'Cancelled') {
5174 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
5176 elseif ($updatedStatusName == 'Failed') {
5177 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
5179 elseif ($updatedStatusName == 'Completed') {
5180 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));