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
::getOriginalContribution($contributionID);
190 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($params, $contributionID);
192 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
193 isset($params['financial_type_id']))) {
194 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
197 if ($contributionID) {
198 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
201 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
203 $contribution = new CRM_Contribute_BAO_Contribution();
204 $contribution->copyValues($params);
206 $contribution->id
= $contributionID;
208 if (empty($contribution->id
)) {
209 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
210 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
211 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
215 $result = $contribution->save();
217 // Add financial_trxn details as part of fix for CRM-4724
218 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
219 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
221 //add Account details
222 $params['contribution'] = $contribution;
223 self
::recordFinancialAccounts($params);
225 if (self
::isUpdateToRecurringContribution($params)) {
226 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
227 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
228 $contributionStatus[$params['contribution_status_id']]
232 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
234 if ($contributionID) {
235 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
238 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
245 * Is this contribution updating an existing recurring contribution.
247 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
248 * pending payment is being confirmed (or failing).
250 * @param array $params
254 public static function isUpdateToRecurringContribution($params) {
255 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
258 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
261 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
264 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
265 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
272 * Get defaults for new entity.
275 public static function getDefaults() {
277 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
278 FALSE, FALSE, FALSE, 'AND is_default = 1')
280 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
285 * Fetch the object and store the values in the values array.
287 * @param array $params
288 * Input parameters to find object.
289 * @param array $values
290 * Output values of the object.
292 * The array that holds all the db ids.
294 * @return CRM_Contribute_BAO_Contribution|null
295 * The found object or null
297 public static function getValues($params, &$values, &$ids) {
298 if (empty($params)) {
301 $contribution = new CRM_Contribute_BAO_Contribution();
303 $contribution->copyValues($params);
305 if ($contribution->find(TRUE)) {
306 $ids['contribution'] = $contribution->id
;
308 CRM_Core_DAO
::storeValues($contribution, $values);
310 return $contribution;
312 $null = NULL; // return by reference
317 * Get the values and resolve the most common mappings.
319 * Since contribution status is resolved in almost every function that calls getValues it makes
320 * sense to have an extra function to resolve it rather than repeat the code.
322 * Think carefully before adding more mappings to be resolved as there could be performance implications
323 * if this function starts to be called from more iterative functions.
325 * @param array $params
326 * Input parameters to find object.
329 * Array of the found contribution.
330 * @throws CRM_Core_Exception
332 public static function getValuesWithMappings($params) {
333 $values = $ids = array();
334 $contribution = self
::getValues($params, $values, $ids);
335 if (is_null($contribution)) {
336 throw new CRM_Core_Exception('No contribution found');
338 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
343 * Calculate net_amount & fee_amount if they are not set.
345 * Net amount should be total - fee.
346 * This should only be called for new contributions.
348 * @param array $params
349 * Params for a new contribution before they are saved.
350 * @param int|null $contributionID
351 * Contribution ID if we are dealing with an update.
353 * @throws \CiviCRM_API3_Exception
355 public static function calculateMissingAmountParams(&$params, $contributionID) {
356 if (!$contributionID && !isset($params['fee_amount'])) {
357 if (isset($params['total_amount']) && isset($params['net_amount'])) {
358 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
361 $params['fee_amount'] = 0;
364 if (!isset($params['net_amount'])) {
365 if (!$contributionID) {
366 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
369 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
370 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
371 // net_amount may need adjusting.
372 $contribution = civicrm_api3('Contribution', 'getsingle', array(
373 'id' => $contributionID,
374 'return' => array('total_amount', 'net_amount'),
376 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
377 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
378 $params['net_amount'] = $totalAmount - $feeAmount;
386 * @param $billingLocationTypeID
390 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
391 $hasBillingField = FALSE;
392 $billingFields = array(
400 //build address array
401 $addressParams = array();
402 $addressParams['location_type_id'] = $billingLocationTypeID;
403 $addressParams['is_billing'] = 1;
405 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
406 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
407 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
408 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
410 foreach ($billingFields as $value) {
411 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
412 if (!empty($addressParams[$value])) {
413 $hasBillingField = TRUE;
416 return array($hasBillingField, $addressParams);
420 * Get address params ready to be passed to the payment processor.
422 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
423 * To create an address we need state_province_id.
425 * @param array $params
426 * @param int $billingLocationTypeID
430 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
431 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
432 foreach ($addressParams as $name => $field) {
433 if (substr($name, 0, 8) == 'billing_') {
434 $addressParams[substr($name, 9)] = $addressParams[$field];
437 return array($hasBillingField, $addressParams);
441 * Get the number of terms for this contribution for a given membership type
442 * based on querying the line item table and relevant price field values
443 * Note that any one contribution should only be able to have one line item relating to a particular membership
446 * @param int $membershipTypeID
448 * @param int $contributionID
452 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
453 $numTerms = CRM_Core_DAO
::singleValueQuery("
454 SELECT membership_num_terms FROM civicrm_line_item li
455 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
456 WHERE contribution_id = %1 AND membership_type_id = %2",
457 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
459 // default of 1 is precautionary
460 return empty($numTerms) ?
1 : $numTerms;
464 * Takes an associative array and creates a contribution object.
466 * @param array $params
467 * (reference ) an assoc array of name/value pairs.
469 * The array that holds all the db ids.
471 * @return CRM_Contribute_BAO_Contribution
473 public static function create(&$params, $ids = array()) {
474 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date', 'revenue_recognition_date');
475 foreach ($dateFields as $df) {
476 if (isset($params[$df])) {
477 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
481 //if contribution is created with cancelled or refunded status, add credit note id
482 if (!empty($params['contribution_status_id'])) {
483 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
485 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
486 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
488 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
489 $params['creditnote_id'] = self
::createCreditNoteId();
494 $transaction = new CRM_Core_Transaction();
496 $contribution = self
::add($params, $ids);
498 if (is_a($contribution, 'CRM_Core_Error')) {
499 $transaction->rollback();
500 return $contribution;
503 $params['contribution_id'] = $contribution->id
;
505 if (!empty($params['custom']) &&
506 is_array($params['custom'])
508 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
511 $session = CRM_Core_Session
::singleton();
513 if (!empty($params['note'])) {
515 'entity_table' => 'civicrm_contribution',
516 'note' => $params['note'],
517 'entity_id' => $contribution->id
,
518 'contact_id' => $session->get('userID'),
519 'modified_date' => date('Ymd'),
521 if (!$noteParams['contact_id']) {
522 $noteParams['contact_id'] = $params['contact_id'];
524 CRM_Core_BAO_Note
::add($noteParams);
527 // make entry in batch entity batch table
528 if (!empty($params['batch_id'])) {
529 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
530 $titleFields = array(
536 $retrieveRequired = 0;
537 foreach ($titleFields as $titleField) {
538 if (!isset($contribution->$titleField)) {
539 $retrieveRequired = 1;
543 if ($retrieveRequired == 1) {
544 $contribution->find(TRUE);
548 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
550 $transaction->commit();
552 // check if activity record exist for this contribution, if
554 $activity = new CRM_Activity_DAO_Activity();
555 $activity->source_record_id
= $contribution->id
;
556 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
561 //CRM-18406: Update activity when edit contribution.
562 if ($activity->find(TRUE)) {
563 // CRM-13237 : if activity record found, update it with campaign id of contribution
564 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
565 $contribution->activity_id
= $activity->id
;
567 if (empty($contribution->contact_id
)) {
568 $contribution->find(TRUE);
570 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
572 // do not add to recent items for import, CRM-4399
573 if (empty($params['skipRecentView'])) {
574 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
575 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
577 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
578 $titleFields = array(
584 $retrieveRequired = 0;
585 foreach ($titleFields as $titleField) {
586 if (!isset($contribution->$titleField)) {
587 $retrieveRequired = 1;
591 if ($retrieveRequired == 1) {
592 $contribution->find(TRUE);
594 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
595 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
597 $recentOther = array();
598 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
599 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
600 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
604 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
605 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
606 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
610 // add the recently created Contribution
611 CRM_Utils_Recent
::add($title,
615 $contribution->contact_id
,
621 return $contribution;
625 * Get the values for pseudoconstants for name->value and reverse.
627 * @param array $defaults
628 * (reference) the default values, some of which need to be resolved.
629 * @param bool $reverse
630 * True if we want to resolve the values in the reverse direction (value -> name).
632 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
633 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
634 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
635 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
636 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
640 * Convert associative array names to values and vice-versa.
642 * This function is used by both the web form layer and the api. Note that
643 * the api needs the name => value conversion, also the view layer typically
644 * requires value => name conversion
646 * @param array $defaults
647 * @param string $property
648 * @param array $lookup
649 * @param bool $reverse
653 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
654 $id = $property . '_id';
656 $src = $reverse ?
$property : $id;
657 $dst = $reverse ?
$id : $property;
659 if (!array_key_exists($src, $defaults)) {
663 $look = $reverse ?
array_flip($lookup) : $lookup;
665 if (is_array($look)) {
666 if (!array_key_exists($defaults[$src], $look)) {
670 $defaults[$dst] = $look[$defaults[$src]];
675 * Retrieve DB object based on input parameters.
677 * It also stores all the retrieved values in the default array.
679 * @param array $params
680 * (reference ) an assoc array of name/value pairs.
681 * @param array $defaults
682 * (reference ) an assoc array to hold the name / value pairs.
683 * in a hierarchical manner
685 * (reference) the array that holds all the db ids.
687 * @return CRM_Contribute_BAO_Contribution
689 public static function retrieve(&$params, &$defaults, &$ids) {
690 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
691 return $contribution;
695 * Combine all the importable fields from the lower levels object.
697 * The ordering is important, since currently we do not have a weight
698 * scheme. Adding weight is super important and should be done in the
699 * next week or so, before this can be called complete.
701 * @param string $contactType
702 * @param bool $status
705 * array of importable Fields
707 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
708 if (!self
::$_importableFields) {
709 if (!self
::$_importableFields) {
710 self
::$_importableFields = array();
714 $fields = array('' => array('title' => ts('- do not import -')));
717 $fields = array('' => array('title' => ts('- Contribution Fields -')));
720 $note = CRM_Core_DAO_Note
::import();
721 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
722 unset($tmpFields['option_value']);
723 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
724 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
726 // Using new Dedupe rule.
728 'contact_type' => $contactType,
729 'used' => 'Unsupervised',
731 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
732 $tmpContactField = array();
733 if (is_array($fieldsArray)) {
734 foreach ($fieldsArray as $value) {
735 //skip if there is no dupe rule
736 if ($value == 'none') {
739 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
744 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
745 $tmpContactField[trim($value)] = $contactFields[trim($value)];
747 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
750 $title = $tmpContactField[trim($value)]['title'];
752 $tmpContactField[trim($value)]['title'] = $title;
756 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
757 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
758 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
759 $fields = array_merge($fields, $tmpContactField);
760 $fields = array_merge($fields, $tmpFields);
761 $fields = array_merge($fields, $note);
762 $fields = array_merge($fields, $optionFields);
763 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
764 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
765 self
::$_importableFields = $fields;
767 return self
::$_importableFields;
771 * Combine all the exportable fields from the lower level objects.
773 * @param bool $checkPermission
776 * array of exportable Fields
778 public static function &exportableFields($checkPermission = TRUE) {
779 if (!self
::$_exportableFields) {
780 if (!self
::$_exportableFields) {
781 self
::$_exportableFields = array();
784 $impFields = CRM_Contribute_DAO_Contribution
::export();
785 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
786 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
787 $typeField = CRM_Financial_DAO_FinancialType
::export();
788 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
789 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
790 $contributionStatus = array(
791 'contribution_status' => array(
792 'title' => ts('Contribution Status'),
793 'name' => 'contribution_status',
794 'data_type' => CRM_Utils_Type
::T_STRING
,
798 $contributionPage = array(
799 'contribution_page' => array(
800 'title' => ts('Contribution Page'),
801 'name' => 'contribution_page',
802 'where' => 'civicrm_contribution_page.title',
803 'data_type' => CRM_Utils_Type
::T_STRING
,
807 $contributionNote = array(
808 'contribution_note' => array(
809 'title' => ts('Contribution Note'),
810 'name' => 'contribution_note',
811 'data_type' => CRM_Utils_Type
::T_TEXT
,
815 $contributionRecurId = array(
816 'contribution_recur_id' => array(
817 'title' => ts('Recurring Contributions ID'),
818 'name' => 'contribution_recur_id',
819 'where' => 'civicrm_contribution.contribution_recur_id',
820 'data_type' => CRM_Utils_Type
::T_INT
,
824 $extraFields = array(
825 'contribution_batch' => array(
826 'title' => ts('Batch Name'),
831 $campaignTitle = array(
832 'contribution_campaign_title' => array(
833 'title' => ts('Campaign Title'),
834 'name' => 'campaign_title',
835 'where' => 'civicrm_campaign.title',
836 'data_type' => CRM_Utils_Type
::T_STRING
,
839 $softCreditFields = array(
840 'contribution_soft_credit_name' => array(
841 'name' => 'contribution_soft_credit_name',
842 'title' => 'Soft Credit For',
843 'where' => 'civicrm_contact_d.display_name',
844 'data_type' => CRM_Utils_Type
::T_STRING
,
846 'contribution_soft_credit_amount' => array(
847 'name' => 'contribution_soft_credit_amount',
848 'title' => 'Soft Credit Amount',
849 'where' => 'civicrm_contribution_soft.amount',
850 'data_type' => CRM_Utils_Type
::T_MONEY
,
852 'contribution_soft_credit_type' => array(
853 'name' => 'contribution_soft_credit_type',
854 'title' => 'Soft Credit Type',
855 'where' => 'contribution_softcredit_type.label',
856 'data_type' => CRM_Utils_Type
::T_STRING
,
858 'contribution_soft_credit_contribution_id' => array(
859 'name' => 'contribution_soft_credit_contribution_id',
860 'title' => 'Soft Credit For Contribution ID',
861 'where' => 'civicrm_contribution_soft.contribution_id',
862 'data_type' => CRM_Utils_Type
::T_INT
,
864 'contribution_soft_credit_contact_id' => array(
865 'name' => 'contribution_soft_credit_contact_id',
866 'title' => 'Soft Credit For Contact ID',
867 'where' => 'civicrm_contact_d.id',
868 'data_type' => CRM_Utils_Type
::T_INT
,
872 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
874 'contribution_product_id' => array(
875 'title' => ts('Premium'),
876 'name' => 'contribution_product_id',
877 'where' => 'civicrm_product.id',
878 'data_type' => CRM_Utils_Type
::T_INT
,
882 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
883 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
884 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
887 self
::$_exportableFields = $fields;
890 return self
::$_exportableFields;
894 * @param null $status
895 * @param null $startDate
896 * @param null $endDate
900 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
904 $where[] = 'contribution_status_id = 1';
908 $where[] = 'contribution_status_id = 3';
913 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
916 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
918 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
919 if ($financialTypes) {
920 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
921 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
924 $where[] = "c.financial_type_id IN (0)";
927 $whereCond = implode(' AND ', $where);
930 SELECT sum( total_amount ) as total_amount,
931 count( c.id ) as total_count,
933 FROM civicrm_contribution c
934 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
935 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
937 AND ( is_test = 0 OR is_test IS NULL )
938 AND contact.is_deleted = 0
942 $dao = CRM_Core_DAO
::executeQuery($query);
945 while ($dao->fetch()) {
946 $count +
= $dao->total_count
;
947 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
951 'amount' => implode(', ', $amount),
959 * Delete the indirect records associated with this contribution first.
964 * $results no of deleted Contribution on success, false otherwise
966 public static function deleteContribution($id) {
967 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
969 $transaction = new CRM_Core_Transaction();
972 //delete activity record
974 'source_record_id' => $id,
975 // activity type id for contribution
976 'activity_type_id' => 6,
979 CRM_Activity_BAO_Activity
::deleteActivity($params);
981 //delete billing address if exists for this contribution.
982 self
::deleteAddress($id);
984 //update pledge and pledge payment, CRM-3961
985 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
987 // remove entry from civicrm_price_set_entity, CRM-5095
988 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
989 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
991 // cleanup line items.
992 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
994 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
995 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
997 if ($participantId) {
998 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1001 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1005 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1006 $noteId = key($note);
1008 CRM_Core_BAO_Note
::del($noteId, FALSE);
1011 $dao = new CRM_Contribute_DAO_Contribution();
1014 $results = $dao->delete();
1016 $transaction->commit();
1018 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1020 // delete the recently created Contribution
1021 $contributionRecent = array(
1023 'type' => 'Contribution',
1025 CRM_Utils_Recent
::del($contributionRecent);
1031 * React to a financial transaction (payment) failure.
1033 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1034 * payments is important for forensic and outreach reasons.
1036 * @param int $contributionID
1037 * @param int $contactID
1038 * @param string $message
1040 * @throws \CiviCRM_API3_Exception
1042 public static function failPayment($contributionID, $contactID, $message) {
1043 civicrm_api3('activity', 'create', array(
1044 'activity_type_id' => 'Failed Payment',
1045 'details' => $message,
1046 'subject' => ts('Payment failed at payment processor'),
1047 'source_record_id' => $contributionID,
1048 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1054 * Check if there is a contribution with the same trxn_id or invoice_id.
1056 * @param array $input
1057 * An assoc array of name/value pairs.
1058 * @param array $duplicates
1059 * (reference) store ids of duplicate contribs.
1063 * true if duplicate, false otherwise
1065 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1067 $id = CRM_Utils_Array
::value('id', $input);
1069 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1070 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1076 $clause[] = "trxn_id = %1";
1077 $input[1] = array($trxn_id, 'String');
1081 $clause[] = "invoice_id = %2";
1082 $input[2] = array($invoice_id, 'String');
1085 if (empty($clause)) {
1089 $clause = implode(' OR ', $clause);
1091 $clause = "( $clause ) AND id != %3";
1092 $input[3] = array($id, 'Integer');
1095 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1096 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1098 while ($dao->fetch()) {
1099 $duplicates[] = $dao->id
;
1106 * Takes an associative array and creates a contribution_product object.
1108 * the function extract all the params it needs to initialize the create a
1109 * contribution_product object. the params array could contain additional unused name/value
1112 * @param array $params
1113 * (reference) an assoc array of name/value pairs.
1115 * @return CRM_Contribute_DAO_ContributionProduct
1117 public static function addPremium(&$params) {
1118 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1119 $contributionProduct->copyValues($params);
1120 return $contributionProduct->save();
1124 * Get list of contribution fields for profile.
1125 * For now we only allow custom contribution fields to be in
1128 * @param bool $addExtraFields
1129 * True if special fields needs to be added.
1132 * the list of contribution fields
1134 public static function getContributionFields($addExtraFields = TRUE) {
1135 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1136 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1138 if ($addExtraFields) {
1139 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1142 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1144 foreach ($contributionFields as $key => $var) {
1145 if ($key == 'contribution_contact_id') {
1148 elseif ($key == 'contribution_campaign_id') {
1149 $var['title'] = ts('Campaign');
1151 $fields[$key] = $var;
1154 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1159 * Add extra fields specific to contribution.
1161 public static function getSpecialContributionFields() {
1162 $extraFields = array(
1163 'contribution_soft_credit_name' => array(
1164 'name' => 'contribution_soft_credit_name',
1165 'title' => 'Soft Credit Name',
1166 'headerPattern' => '/^soft_credit_name$/i',
1167 'where' => 'civicrm_contact_d.display_name',
1169 'contribution_soft_credit_email' => array(
1170 'name' => 'contribution_soft_credit_email',
1171 'title' => 'Soft Credit Email',
1172 'headerPattern' => '/^soft_credit_email$/i',
1173 'where' => 'soft_email.email',
1175 'contribution_soft_credit_phone' => array(
1176 'name' => 'contribution_soft_credit_phone',
1177 'title' => 'Soft Credit Phone',
1178 'headerPattern' => '/^soft_credit_phone$/i',
1179 'where' => 'soft_phone.phone',
1181 'contribution_soft_credit_contact_id' => array(
1182 'name' => 'contribution_soft_credit_contact_id',
1183 'title' => 'Soft Credit Contact ID',
1184 'headerPattern' => '/^soft_credit_contact_id$/i',
1185 'where' => 'civicrm_contribution_soft.contact_id',
1187 'contribution_pcp_title' => array(
1188 'name' => 'contribution_pcp_title',
1189 'title' => 'Personal Campaign Page Title',
1190 'headerPattern' => '/^contribution_pcp_title$/i',
1191 'where' => 'contribution_pcp.title',
1195 return $extraFields;
1199 * @param int $pageID
1203 public static function getCurrentandGoalAmount($pageID) {
1205 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1206 FROM civicrm_contribution_page p,
1207 civicrm_contribution c
1208 WHERE p.id = c.contribution_page_id
1210 AND c.cancel_date is null
1214 $config = CRM_Core_Config
::singleton();
1215 $params = array(1 => array($pageID, 'Integer'));
1216 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1218 if ($dao->fetch()) {
1219 return array($dao->goal
, $dao->total
);
1222 return array(NULL, NULL);
1227 * Get list of contributions which credit the passed in contact ID.
1229 * The returned array provides details about the original contribution & donor.
1231 * @todo - this is a confusing function called from one place. It has a test. It would be
1232 * nice to deprecate it.
1234 * @param int $honorId
1235 * In Honor of Contact ID.
1238 * list of contribution fields
1240 public static function getHonorContacts($honorId) {
1242 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1243 $honorDAO->contact_id
= $honorId;
1246 $type = CRM_Contribute_PseudoConstant
::financialType();
1248 while ($honorDAO->fetch()) {
1249 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1250 $contributionDAO->id
= $honorDAO->contribution_id
;
1252 if ($contributionDAO->find(TRUE)) {
1253 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1254 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1255 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1256 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1257 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1258 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1259 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1260 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1261 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1269 * Get the sort name of a contact for a particular contribution.
1272 * Id of the contribution.
1274 * @return null|string
1275 * sort name of the contact if found
1277 public static function sortName($id) {
1278 $id = CRM_Utils_Type
::escape($id, 'Integer');
1281 SELECT civicrm_contact.sort_name
1282 FROM civicrm_contribution, civicrm_contact
1283 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1284 AND civicrm_contribution.id = {$id}
1286 return CRM_Core_DAO
::singleValueQuery($query);
1290 * @param int $contactID
1294 public static function annual($contactID) {
1295 if (is_array($contactID)) {
1296 $contactIDs = implode(',', $contactID);
1299 $contactIDs = $contactID;
1302 $config = CRM_Core_Config
::singleton();
1303 $startDate = $endDate = NULL;
1305 $currentMonth = date('m');
1306 $currentDay = date('d');
1307 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1308 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1309 (int ) $config->fiscalYearStart
['d'] > $currentDay
1312 $year = date('Y') - 1;
1317 $nextYear = $year +
1;
1319 if ($config->fiscalYearStart
) {
1320 $newFiscalYearStart = $config->fiscalYearStart
;
1321 if ($newFiscalYearStart['M'] < 10) {
1322 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1324 if ($newFiscalYearStart['d'] < 10) {
1325 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1327 $config->fiscalYearStart
= $newFiscalYearStart;
1328 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1333 $startDate = "$year$monthDay";
1334 $endDate = "$nextYear$monthDay";
1335 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1336 $additionalWhere = " AND b.financial_type_id IN (0)";
1337 $liWhere = " AND i.financial_type_id IN (0)";
1338 if (!empty($financialTypes)) {
1339 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1340 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1343 SELECT count(*) as count,
1344 sum(total_amount) as amount,
1345 avg(total_amount) as average,
1347 FROM civicrm_contribution b
1348 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1349 WHERE b.contact_id IN ( $contactIDs )
1350 AND b.contribution_status_id = 1
1352 AND b.receive_date >= $startDate
1353 AND b.receive_date < $endDate
1357 $dao = CRM_Core_DAO
::executeQuery($query);
1359 $amount = $average = array();
1360 while ($dao->fetch()) {
1361 if ($dao->count
> 0 && $dao->amount
> 0) {
1362 $count +
= $dao->count
;
1363 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1364 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1370 implode(', ', $amount),
1371 implode(', ', $average),
1374 return array(0, 0, 0);
1378 * Check if there is a contribution with the params passed in.
1380 * Used for trxn_id,invoice_id and contribution_id
1382 * @param array $params
1383 * An assoc array of name/value pairs.
1386 * contribution id if success else NULL
1388 public static function checkDuplicateIds($params) {
1389 $dao = new CRM_Contribute_DAO_Contribution();
1393 foreach ($params as $k => $v) {
1395 $clause[] = "$k = '$v'";
1398 $clause = implode(' AND ', $clause);
1399 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1400 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1402 while ($dao->fetch()) {
1410 * Get the contribution details for component export.
1412 * @param int $exportMode
1414 * @param string $componentIds
1420 public static function getContributionDetails($exportMode, $componentIds) {
1421 $paymentDetails = array();
1422 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1424 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1425 $componentSelect = " civicrm_participant_payment.participant_id id";
1426 $additionalClause = "
1427 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1428 AND civicrm_participant_payment.participant_id {$componentClause} )
1431 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1432 $componentSelect = " civicrm_membership_payment.membership_id id";
1433 $additionalClause = "
1434 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1435 AND civicrm_membership_payment.membership_id {$componentClause} )
1438 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1439 $componentSelect = " civicrm_pledge_payment.id id";
1440 $additionalClause = "
1441 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1442 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1446 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1447 trxn_id, {$componentSelect}
1448 FROM civicrm_contribution
1449 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1450 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1451 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1452 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1453 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1454 AND option_group_contribution_status.id = contribution_status.option_group_id )
1458 $dao = CRM_Core_DAO
::executeQuery($query);
1460 while ($dao->fetch()) {
1461 $paymentDetails[$dao->id
] = array(
1462 'total_amount' => $dao->total_amount
,
1463 'contribution_status' => $dao->status
,
1464 'receive_date' => $dao->receive_date
,
1465 'pay_instru' => $dao->payment_instrument
,
1466 'trxn_id' => $dao->trxn_id
,
1470 return $paymentDetails;
1474 * Create address associated with contribution record.
1476 * As long as there is one or more billing field in the parameters we will create the address.
1478 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1481 * @param array $params
1482 * @param int $billingLocationTypeID
1487 public static function createAddress($params, $billingLocationTypeID) {
1488 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1489 if ($hasBillingField) {
1490 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1491 return $address->id
;
1498 * Delete billing address record related contribution.
1500 * @param int $contributionId
1501 * @param int $contactId
1503 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1505 $contactJoin = NULL;
1507 if ($contributionId) {
1508 $clauses[] = "cc.id = {$contributionId}";
1512 $clauses[] = "cco.id = {$contactId}";
1513 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1516 if (empty($clauses)) {
1517 CRM_Core_Error
::fatal();
1520 $condition = implode(' OR ', $clauses);
1524 FROM civicrm_address ca
1525 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1529 $dao = CRM_Core_DAO
::executeQuery($query);
1531 while ($dao->fetch()) {
1532 $params = array('id' => $dao->id
);
1533 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1538 * This function check online pending contribution associated w/
1539 * Online Event Registration or Online Membership signup.
1541 * @param int $componentId
1542 * Participant/membership id.
1543 * @param string $componentName
1547 * pending contribution id.
1549 public static function checkOnlinePendingContribution($componentId, $componentName) {
1550 $contributionId = NULL;
1551 if (!$componentId ||
1552 !in_array($componentName, array('Event', 'Membership'))
1554 return $contributionId;
1557 if ($componentName == 'Event') {
1558 $idName = 'participant_id';
1559 $componentTable = 'civicrm_participant';
1560 $paymentTable = 'civicrm_participant_payment';
1561 $source = ts('Online Event Registration');
1564 if ($componentName == 'Membership') {
1565 $idName = 'membership_id';
1566 $componentTable = 'civicrm_membership';
1567 $paymentTable = 'civicrm_membership_payment';
1568 $source = ts('Online Contribution');
1571 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1574 SELECT component.id as {$idName},
1575 componentPayment.contribution_id as contribution_id,
1576 contribution.source source,
1577 contribution.contribution_status_id as contribution_status_id,
1578 contribution.is_pay_later as is_pay_later
1579 FROM $componentTable component
1580 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1581 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1582 WHERE component.id = {$componentId}";
1584 $dao = CRM_Core_DAO
::executeQuery($query);
1586 while ($dao->fetch()) {
1587 if ($dao->contribution_id
&&
1588 $dao->is_pay_later
&&
1589 $dao->contribution_status_id
== $pendingStatusId &&
1590 strpos($dao->source
, $source) !== FALSE
1592 $contributionId = $dao->contribution_id
;
1597 return $contributionId;
1601 * Update contribution as well as related objects.
1603 * This function by-passes hooks - to address this - don't use this function.
1607 * Use api contribute.completetransaction
1608 * For failures use failPayment (preferably exposing by api in the process).
1610 * @param array $params
1611 * @param bool $processContributionObject
1614 * @throws \Exception
1616 public static function transitionComponents($params, $processContributionObject = FALSE) {
1617 // get minimum required values.
1618 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1619 $componentId = CRM_Utils_Array
::value('component_id', $params);
1620 $componentName = CRM_Utils_Array
::value('componentName', $params);
1621 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1622 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1624 // if we already processed contribution object pass previous status id.
1625 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1627 $updateResult = array();
1629 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1631 // we process only ( Completed, Cancelled, or Failed ) contributions.
1632 if (!$contributionId ||
1633 !in_array($contributionStatusId, array(
1634 array_search('Completed', $contributionStatuses),
1635 array_search('Cancelled', $contributionStatuses),
1636 array_search('Failed', $contributionStatuses),
1639 return $updateResult;
1642 if (!$componentName ||
!$componentId) {
1643 // get the related component details.
1644 $componentDetails = self
::getComponentDetails($contributionId);
1647 $componentDetails['contact_id'] = $contactId;
1648 $componentDetails['component'] = $componentName;
1650 if ($componentName == 'event') {
1651 $componentDetails['participant'] = $componentId;
1654 $componentDetails['membership'] = $componentId;
1658 if (!empty($componentDetails['contact_id'])) {
1659 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1665 // do check for required ids.
1666 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1667 return $updateResult;
1670 //now we are ready w/ required ids, start processing.
1672 $baseIPN = new CRM_Core_Payment_BaseIPN();
1674 $input = $ids = $objects = array();
1676 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1677 $ids['contribution'] = $contributionId;
1678 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1679 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1680 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1681 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1682 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1683 $ids['contributionRecur'] = NULL;
1684 $ids['contributionPage'] = NULL;
1686 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1687 CRM_Core_Error
::fatal();
1690 $memberships = &$objects['membership'];
1691 $participant = &$objects['participant'];
1692 $pledgePayment = &$objects['pledge_payment'];
1693 $contribution = &$objects['contribution'];
1695 if ($pledgePayment) {
1696 $pledgePaymentIDs = array();
1697 foreach ($pledgePayment as $key => $object) {
1698 $pledgePaymentIDs[] = $object->id
;
1700 $pledgeID = $pledgePayment[0]->pledge_id
;
1703 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1706 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1707 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1712 // we might want to process contribution object.
1713 $processContribution = FALSE;
1714 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1715 if (is_array($memberships)) {
1716 foreach ($memberships as $membership) {
1718 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1719 $membership->save();
1721 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1722 if ($processContributionObject) {
1723 $processContribution = TRUE;
1730 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1731 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1733 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1734 if ($processContributionObject) {
1735 $processContribution = TRUE;
1739 if ($pledgePayment) {
1740 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1742 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1743 if ($processContributionObject) {
1744 $processContribution = TRUE;
1748 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1749 if (is_array($memberships)) {
1750 foreach ($memberships as $membership) {
1752 $membership->status_id
= array_search('Expired', $membershipStatuses);
1753 $membership->save();
1755 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1756 if ($processContributionObject) {
1757 $processContribution = TRUE;
1763 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1764 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1766 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1767 if ($processContributionObject) {
1768 $processContribution = TRUE;
1772 if ($pledgePayment) {
1773 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1775 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1776 if ($processContributionObject) {
1777 $processContribution = TRUE;
1781 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1783 // only pending contribution related object processed.
1784 if ($previousContriStatusId &&
1785 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1787 // this is case when we already processed contribution object.
1788 return $updateResult;
1790 elseif (!$previousContriStatusId &&
1791 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1793 // this is case when we are going to process contribution object later.
1794 return $updateResult;
1797 if (is_array($memberships)) {
1798 foreach ($memberships as $membership) {
1803 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1804 $membership->membership_type_id
,
1805 $membership->is_test
, $membership->id
1808 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1809 // this picks up membership type changes during renewals
1811 SELECT membership_type_id
1812 FROM civicrm_membership_log
1813 WHERE membership_id=$membership->id
1816 $dao = new CRM_Core_DAO();
1818 if ($dao->fetch()) {
1819 if (!empty($dao->membership_type_id
)) {
1820 $membership->membership_type_id
= $dao->membership_type_id
;
1821 $membership->save();
1824 // else fall back to using current membership type
1827 // Figure out number of terms
1829 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1830 foreach ($lineitems as $lineitem) {
1831 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1832 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1834 // in case membership_num_terms comes through as null or zero
1835 $numterms = $numterms >= 1 ?
$numterms : 1;
1840 // CRM-15735-to update the membership status as per the contribution receive date
1842 if (!empty($params['receive_date'])) {
1843 $joinDate = $params['receive_date'];
1844 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1845 $membership->end_date
,
1846 $membership->join_date
,
1847 $params['receive_date'],
1849 $membership->membership_type_id
,
1852 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1853 $membership->save();
1856 if ($currentMembership) {
1857 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1858 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1859 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1862 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1865 //get the status for membership.
1866 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1868 $dates['join_date'],
1871 $membership->membership_type_id
,
1875 $formattedParams = array(
1876 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1877 array_search('Current', $membershipStatuses)
1879 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1880 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1881 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1884 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1886 $membership->copyValues($formattedParams);
1887 $membership->save();
1889 //updating the membership log
1890 $membershipLog = array();
1891 $membershipLog = $formattedParams;
1892 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1893 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1895 $membershipLog['start_date'] = $logStartDate;
1896 $membershipLog['membership_id'] = $membership->id
;
1897 $membershipLog['modified_id'] = $membership->contact_id
;
1898 $membershipLog['modified_date'] = date('Ymd');
1899 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1901 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1903 //update related Memberships.
1904 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1906 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1909 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1910 if ($processContributionObject) {
1911 $processContribution = TRUE;
1914 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1920 $updatedStatusId = array_search('Registered', $participantStatuses);
1921 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1923 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1924 if ($processContributionObject) {
1925 $processContribution = TRUE;
1929 if ($pledgePayment) {
1930 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1932 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1933 if ($processContributionObject) {
1934 $processContribution = TRUE;
1939 // process contribution object.
1940 if ($processContribution) {
1941 $contributionParams = array();
1948 'payment_instrument_id',
1951 'financial_type_id',
1952 'contribution_status_id',
1953 'non_deductible_amount',
1957 foreach ($fields as $field) {
1958 if (empty($params[$field])) {
1961 $contributionParams[$field] = $params[$field];
1964 $ids = array('contribution' => $contributionId);
1965 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1968 return $updateResult;
1972 * Returns all contribution related object ids.
1974 * @param $contributionId
1978 public static function getComponentDetails($contributionId) {
1979 $componentDetails = $pledgePayment = array();
1980 if (!$contributionId) {
1981 return $componentDetails;
1985 SELECT c.id as contribution_id,
1986 c.contact_id as contact_id,
1987 c.contribution_recur_id,
1988 mp.membership_id as membership_id,
1989 m.membership_type_id as membership_type_id,
1990 pp.participant_id as participant_id,
1991 p.event_id as event_id,
1992 pgp.id as pledge_payment_id
1993 FROM civicrm_contribution c
1994 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1995 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1996 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1997 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1998 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1999 WHERE c.id = $contributionId";
2001 $dao = CRM_Core_DAO
::executeQuery($query);
2002 $componentDetails = array();
2004 while ($dao->fetch()) {
2005 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2006 $componentDetails['contact_id'] = $dao->contact_id
;
2007 if ($dao->event_id
) {
2008 $componentDetails['event'] = $dao->event_id
;
2010 if ($dao->participant_id
) {
2011 $componentDetails['participant'] = $dao->participant_id
;
2013 if ($dao->membership_id
) {
2014 if (!isset($componentDetails['membership'])) {
2015 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2017 $componentDetails['membership'][] = $dao->membership_id
;
2018 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2020 if ($dao->pledge_payment_id
) {
2021 $pledgePayment[] = $dao->pledge_payment_id
;
2023 if ($dao->contribution_recur_id
) {
2024 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2028 if ($pledgePayment) {
2029 $componentDetails['pledge_payment'] = $pledgePayment;
2032 return $componentDetails;
2036 * @param int $contactId
2037 * @param bool $includeSoftCredit
2039 * @return null|string
2041 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2045 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
2046 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2047 $liWhere = " AND i.financial_type_id IN (0)";
2048 if (!empty($financialTypes)) {
2049 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2050 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2052 $contactContributionsSQL = "
2053 SELECT contribution.id AS id
2054 FROM civicrm_contribution contribution
2055 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2056 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2060 $contactSoftCreditContributionsSQL = "
2061 SELECT contribution.id
2062 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2063 ON ( contribution.id = softContribution.contribution_id )
2064 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2065 $query = "SELECT count( x.id ) count FROM ( ";
2066 $query .= $contactContributionsSQL;
2068 if ($includeSoftCredit) {
2069 $query .= " UNION ";
2070 $query .= $contactSoftCreditContributionsSQL;
2075 return CRM_Core_DAO
::singleValueQuery($query);
2079 * Repeat a transaction as part of a recurring series.
2081 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2082 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2083 * subsequent call to the contribution.completetransaction api.
2085 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2087 * @param CRM_Contribute_BAO_Contribution $contribution
2088 * @param array $input
2089 * @param array $contributionParams
2090 * @param int $paymentProcessorID
2093 * @throws CiviCRM_API3_Exception
2095 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2096 if (!empty($contribution->id
)) {
2099 if (empty($contribution->id
)) {
2100 // Unclear why this would only be set for repeats.
2101 if (!empty($input['amount'])) {
2102 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2105 if (!empty($contributionParams['contribution_recur_id'])) {
2106 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2107 'id' => $contributionParams['contribution_recur_id'],
2109 if (!empty($recurringContribution['campaign_id'])) {
2110 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2111 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2113 if (!empty($recurringContribution['financial_type_id'])) {
2114 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2115 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2118 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2119 $contributionParams['contribution_recur_id'],
2120 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2122 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2124 $contributionParams['status_id'] = 'Pending';
2125 if (isset($contributionParams['financial_type_id'])) {
2126 // Give precedence to passed in type.
2127 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2130 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2132 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2133 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2135 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2136 //do not create CC or BCC emails or profile notifications.
2137 //The if is just to be safe. Not sure if we can ever arrive with this unset
2138 if (isset($contribution->contribution_page_id
)) {
2139 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2142 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2143 $contribution->id
= $createContribution['id'];
2144 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2150 * Get individual id for onbehalf contribution.
2152 * @param int $contributionId
2154 * @param int $contributorId
2158 * containing organization id and individual id
2160 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2164 if (!$contributionId) {
2168 // fetch contributor id if null
2169 if (!$contributorId) {
2170 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2171 $contributionId, 'contact_id'
2175 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2176 $activityTypeId = array_search('Contribution', $activityTypeIds);
2178 if ($activityTypeId && $contributorId) {
2180 SELECT civicrm_activity_contact.contact_id
2181 FROM civicrm_activity_contact
2182 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2183 WHERE civicrm_activity.activity_type_id = %1
2184 AND civicrm_activity.source_record_id = %2
2185 AND civicrm_activity_contact.record_type_id = %3
2188 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2189 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2192 1 => array($activityTypeId, 'Integer'),
2193 2 => array($contributionId, 'Integer'),
2194 3 => array($sourceID, 'Integer'),
2197 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2199 // for on behalf contribution source is individual and contributor is organization
2200 if ($sourceContactId && $sourceContactId != $contributorId) {
2201 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2202 // get rel type id for employee of relation
2203 foreach ($relationshipTypeIds as $id => $typeVals) {
2204 if ($typeVals['name_a_b'] == 'Employee of') {
2205 $relationshipTypeId = $id;
2210 $rel = new CRM_Contact_DAO_Relationship();
2211 $rel->relationship_type_id
= $relationshipTypeId;
2212 $rel->contact_id_a
= $sourceContactId;
2213 $rel->contact_id_b
= $contributorId;
2214 if ($rel->find(TRUE)) {
2215 $ids['individual_id'] = $rel->contact_id_a
;
2216 $ids['organization_id'] = $rel->contact_id_b
;
2227 public static function getContributionDates() {
2228 $config = CRM_Core_Config
::singleton();
2229 $currentMonth = date('m');
2230 $currentDay = date('d');
2231 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2232 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2233 (int ) $config->fiscalYearStart
['d'] > $currentDay
2236 $year = date('Y') - 1;
2241 $year = array('Y' => $year);
2242 $yearDate = $config->fiscalYearStart
;
2243 $yearDate = array_merge($year, $yearDate);
2244 $yearDate = CRM_Utils_Date
::format($yearDate);
2246 $monthDate = date('Ym') . '01';
2252 'yearDate' => $yearDate,
2253 'monthDate' => $monthDate,
2258 * Load objects relations to contribution object.
2259 * Objects are stored in the $_relatedObjects property
2260 * In the first instance we are just moving functionality from BASEIpn -
2261 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2263 * Note that the unit test for the BaseIPN class tests this function
2265 * @param array $input
2266 * Input as delivered from Payment Processor.
2268 * Ids as Loaded by Payment Processor.
2269 * @param bool $loadAll
2270 * Load all related objects - even where id not passed in? (allows API to call this).
2275 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2277 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2278 if (empty($ids['contact']) && isset($this->contact_id
)) {
2279 $ids['contact'] = $this->contact_id
;
2282 if (empty($this->_component
)) {
2283 if (!empty($ids['event'])) {
2284 $this->_component
= 'event';
2287 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2291 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2292 // refactoring than anything else, and has unit test coverage.
2293 if (empty($this->financial_type_id
)) {
2297 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2302 if (!$paymentProcessorID && $this->contribution_page_id
) {
2303 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2304 $this->contribution_page_id
,
2307 if ($paymentProcessorID) {
2308 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2312 $ids['contributionType'] = $this->financial_type_id
;
2313 $ids['financialType'] = $this->financial_type_id
;
2316 'contact' => 'CRM_Contact_BAO_Contact',
2317 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2318 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2319 'financialType' => 'CRM_Financial_BAO_FinancialType',
2321 foreach ($entities as $entity => $bao) {
2322 if (!empty($ids[$entity])) {
2323 $this->_relatedObjects
[$entity] = new $bao();
2324 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2325 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2326 throw new CRM_Core_Exception($entity . ' could not be loaded');
2331 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2332 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2335 if (!empty($ids['pledge_payment'])) {
2336 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2337 if (empty($paymentID)) {
2340 $payment = new CRM_Pledge_BAO_PledgePayment();
2341 $payment->id
= $paymentID;
2342 if (!$payment->find(TRUE)) {
2343 throw new Exception("Could not find pledge payment record: " . $paymentID);
2345 $this->_relatedObjects
['pledge_payment'][] = $payment;
2349 $this->loadRelatedMembershipObjects($ids);
2351 if ($this->_component
!= 'contribute') {
2352 // we are in event mode
2353 // make sure event exists and is valid
2354 $event = new CRM_Event_BAO_Event();
2355 $event->id
= $ids['event'];
2356 if ($ids['event'] &&
2359 throw new Exception("Could not find event: " . $ids['event']);
2362 $this->_relatedObjects
['event'] = &$event;
2364 $participant = new CRM_Event_BAO_Participant();
2365 $participant->id
= $ids['participant'];
2366 if ($ids['participant'] &&
2367 !$participant->find(TRUE)
2369 throw new Exception("Could not find participant: " . $ids['participant']);
2371 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2373 $this->_relatedObjects
['participant'] = &$participant;
2375 // get the payment processor id from event - this is inaccurate see CRM-16923
2376 // in future we should look at throwing an exception here rather than an dubious guess.
2377 if (!$paymentProcessorID) {
2378 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2379 if ($paymentProcessorID) {
2380 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2385 if ($paymentProcessorID) {
2386 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2387 $this->is_test ?
'test' : 'live'
2389 $ids['paymentProcessor'] = $paymentProcessorID;
2390 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2396 * Create array of message information - ie. return html version, txt version, to field
2398 * @param array $input
2399 * Incoming information.
2400 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2401 * just check presence of recur object but maintaining legacy approach
2404 * IDs of related objects.
2405 * @param array $values
2406 * Any values that may have already been compiled by calling process.
2407 * This is augmented by values 'gathered' by gatherMessageValues
2408 * @param bool $recur
2409 * @param bool $returnMessageText
2410 * Distinguishes between whether to send message or return.
2411 * message text. We are working towards this function ALWAYS returning message text & calling
2412 * function doing emails / pdfs with it
2418 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2419 $this->loadRelatedObjects($input, $ids);
2421 if (empty($this->_component
)) {
2422 $this->_component
= CRM_Utils_Array
::value('component', $input);
2425 //not really sure what params might be passed in but lets merge em into values
2426 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2427 if (!empty($input['receipt_date'])) {
2428 $values['receipt_date'] = $input['receipt_date'];
2431 $template = CRM_Core_Smarty
::singleton();
2432 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2433 //what does recur 'mean here - to do with payment processor return functionality but
2434 // what is the importance
2435 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2436 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2438 $entityID = $entity = NULL;
2439 if (isset($ids['contribution'])) {
2440 $entity = 'contribution';
2441 $entityID = $ids['contribution'];
2443 if (!empty($ids['membership'])) {
2444 //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
2445 // 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
2446 // line having loaded an array
2447 $ids['membership'] = (array) $ids['membership'];
2448 $entity = 'membership';
2449 $entityID = $ids['membership'][0];
2452 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2453 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2454 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2456 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2457 //direct mode showing billing block, so use directIPN for temporary
2458 $template->assign('contributeMode', 'directIPN');
2461 // todo remove strtolower - check consistency
2462 if (strtolower($this->_component
) == 'event') {
2463 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2464 $values['event'] = array();
2466 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2468 //get location details
2469 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2470 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2472 $ufJoinParams = array(
2473 'entity_table' => 'civicrm_event',
2474 'entity_id' => $ids['event'],
2475 'module' => 'CiviEvent',
2478 list($custom_pre_id,
2480 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2482 $values['custom_pre_id'] = $custom_pre_id;
2483 $values['custom_post_id'] = $custom_post_ids;
2484 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2485 //and cases involving status updation through ipn
2486 // whatever that means!
2487 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2488 // perhaps we should throw an e-notice if amount is set & force total_amount?
2489 if (!empty($input['amount'])) {
2490 $values['totalAmount'] = $input['amount'];
2493 if ($values['event']['is_email_confirm']) {
2494 $values['is_email_receipt'] = 1;
2497 if (!empty($ids['contribution'])) {
2498 $values['contributionId'] = $ids['contribution'];
2501 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2502 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2506 $values['contribution_id'] = $this->id
;
2507 if (!empty($ids['related_contact'])) {
2508 $values['related_contact'] = $ids['related_contact'];
2509 if (isset($ids['onbehalf_dupe_alert'])) {
2510 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2512 $entityBlock = array(
2513 'contact_id' => $ids['contact'],
2514 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2515 'Home', 'id', 'name'
2518 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2519 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2522 if ($this->is_test
) {
2525 if (!empty($this->_relatedObjects
['membership'])) {
2526 foreach ($this->_relatedObjects
['membership'] as $membership) {
2527 if ($membership->id
) {
2528 $values['isMembership'] = TRUE;
2529 $values['membership_assign'] = TRUE;
2531 // need to set the membership values here
2532 $template->assign('membership_name',
2533 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2535 $template->assign('mem_start_date', $membership->start_date
);
2536 $template->assign('mem_join_date', $membership->join_date
);
2537 $template->assign('mem_end_date', $membership->end_date
);
2538 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2539 $template->assign('mem_status', $membership_status);
2540 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2541 $values['is_pay_later'] = 1;
2544 // if separate payment there are two contributions recorded and the
2545 // admin will need to send a receipt for each of them separately.
2546 // we dont link the two in the db (but can potentially infer it if needed)
2547 $template->assign('is_separate_payment', 0);
2549 if ($recur && $paymentObject) {
2550 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2551 $template->assign('cancelSubscriptionUrl', $url);
2552 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2553 $template->assign('updateSubscriptionBillingUrl', $url);
2554 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2555 $template->assign('updateSubscriptionUrl', $url);
2558 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2561 // otherwise if its about sending emails, continue sending without return, as we
2562 // don't want to exit the loop.
2567 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2573 * Gather values for contribution mail - this function has been created
2574 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2575 * Values related to the contribution in question are gathered
2577 * @param array $input
2578 * Input into function (probably from payment processor).
2579 * @param array $values
2581 * The set of ids related to the input.
2585 public function _gatherMessageValues($input, &$values, $ids = array()) {
2586 // set display address of contributor
2587 if ($this->address_id
) {
2588 $addressParams = array('id' => $this->address_id
);
2589 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2590 $addressDetails = array_values($addressDetails);
2592 // Else we assign the billing address of the contribution contact.
2594 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2595 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2596 $addressDetails = array_values($addressDetails);
2599 if (!empty($addressDetails[0]['display'])) {
2600 $values['address'] = $addressDetails[0]['display'];
2603 if ($this->_component
== 'contribute') {
2604 //get soft contributions
2605 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2606 if (!empty($softContributions)) {
2607 $values['softContributions'] = $softContributions['soft_credit'];
2609 if (isset($this->contribution_page_id
)) {
2610 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2611 if ($this->contribution_page_id
) {
2612 // CRM-8254 - override default currency if applicable
2613 $config = CRM_Core_Config
::singleton();
2614 $config->defaultCurrency
= CRM_Utils_Array
::value(
2617 $config->defaultCurrency
2621 // no contribution page -probably back office
2623 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2624 $values['is_email_receipt'] = 1;
2625 $values['title'] = 'Contribution';
2627 // set lineItem for contribution
2629 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2630 if (!empty($lineItem)) {
2631 $itemId = key($lineItem);
2632 foreach ($lineItem as &$eachItem) {
2633 if (isset($this->_relatedObjects
['membership'])
2634 && is_array($this->_relatedObjects
['membership'])
2635 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2636 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2637 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2638 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2641 $values['lineItem'][0] = $lineItem;
2642 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2646 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2650 // if this is onbehalf of contribution then set related contact
2651 if (!empty($relatedContact['individual_id'])) {
2652 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2657 $eventParams = array(
2658 'id' => $this->_relatedObjects
['event']->id
,
2660 $values['event'] = array();
2662 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2663 // add custom fields for event
2664 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2666 $eventCustomGroup = array();
2667 foreach ($eventGroupTree as $key => $group) {
2668 if ($key === 'info') {
2672 foreach ($group['fields'] as $k => $customField) {
2673 $groupLabel = $group['title'];
2674 if (!empty($customField['customValue'])) {
2675 foreach ($customField['customValue'] as $customFieldValues) {
2676 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2681 $values['event']['customGroup'] = $eventCustomGroup;
2683 //get participant details
2684 $participantParams = array(
2685 'id' => $this->_relatedObjects
['participant']->id
,
2688 $values['participant'] = array();
2690 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2691 // add custom fields for event
2692 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2693 $participantCustomGroup = array();
2694 foreach ($participantGroupTree as $key => $group) {
2695 if ($key === 'info') {
2699 foreach ($group['fields'] as $k => $customField) {
2700 $groupLabel = $group['title'];
2701 if (!empty($customField['customValue'])) {
2702 foreach ($customField['customValue'] as $customFieldValues) {
2703 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2708 $values['participant']['customGroup'] = $participantCustomGroup;
2710 //get location details
2711 $locationParams = array(
2712 'entity_id' => $this->_relatedObjects
['event']->id
,
2713 'entity_table' => 'civicrm_event',
2715 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2717 $ufJoinParams = array(
2718 'entity_table' => 'civicrm_event',
2719 'entity_id' => $ids['event'],
2720 'module' => 'CiviEvent',
2723 list($custom_pre_id,
2725 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2727 $values['custom_pre_id'] = $custom_pre_id;
2728 $values['custom_post_id'] = $custom_post_ids;
2730 // set lineItem for event contribution
2732 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2733 if (!empty($participantIds)) {
2734 foreach ($participantIds as $pIDs) {
2735 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2736 if (!CRM_Utils_System
::isNull($lineItem)) {
2737 $values['lineItem'][] = $lineItem;
2744 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2746 $customGroup = array();
2747 foreach ($groupTree as $key => $group) {
2748 if ($key === 'info') {
2752 foreach ($group['fields'] as $k => $customField) {
2753 $groupLabel = $group['title'];
2754 if (!empty($customField['customValue'])) {
2755 foreach ($customField['customValue'] as $customFieldValues) {
2756 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2761 $values['customGroup'] = $customGroup;
2767 * Assign message variables to template but try to break the habit.
2769 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2770 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2771 * multiple recurring payments for processors like IATS that use tokens.
2773 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2774 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2775 * Note we send directly from this function in some cases because it is only partly refactored.
2777 * Don't call this function directly as the signature will change.
2781 * @param CRM_Core_SMARTY $template
2782 * @param bool $recur
2783 * @param bool $returnMessageText
2787 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2788 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2789 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2790 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2791 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2792 $values['useForMember'] = TRUE;
2794 //assign honor information to receipt message
2795 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2797 if (isset($softRecord['soft_credit'])) {
2798 //if id of contribution page is present
2799 if (!empty($values['id'])) {
2800 $values['honor'] = array(
2801 'honor_profile_values' => array(),
2802 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2803 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2805 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2807 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2808 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2811 //offline contribution
2812 $softCreditTypes = $softCredits = array();
2813 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2814 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2815 $softCredits[$key] = array(
2816 'Name' => $softCredit['contact_name'],
2817 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2820 $template->assign('softCreditTypes', $softCreditTypes);
2821 $template->assign('softCredits', $softCredits);
2825 $dao = new CRM_Contribute_DAO_ContributionProduct();
2826 $dao->contribution_id
= $this->id
;
2827 if ($dao->find(TRUE)) {
2828 $premiumId = $dao->product_id
;
2829 $template->assign('option', $dao->product_option
);
2831 $productDAO = new CRM_Contribute_DAO_Product();
2832 $productDAO->id
= $premiumId;
2833 $productDAO->find(TRUE);
2834 $template->assign('selectPremium', TRUE);
2835 $template->assign('product_name', $productDAO->name
);
2836 $template->assign('price', $productDAO->price
);
2837 $template->assign('sku', $productDAO->sku
);
2839 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2840 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2841 if (!$values['amount'] && isset($this->total_amount
)) {
2842 $values['amount'] = $this->total_amount
;
2845 // add the new contribution values
2846 if (strtolower($this->_component
) == 'contribute') {
2848 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2849 $softDAO->contribution_id
= $this->id
;
2850 if ($softDAO->find(TRUE)) {
2851 $template->assign('pcpBlock', TRUE);
2852 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2853 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2854 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2856 //assign the pcp page title for email subject
2857 $pcpDAO = new CRM_PCP_DAO_PCP();
2858 $pcpDAO->id
= $softDAO->pcp_id
;
2859 if ($pcpDAO->find(TRUE)) {
2860 $template->assign('title', $pcpDAO->title
);
2865 if ($this->financial_type_id
) {
2866 $values['financial_type_id'] = $this->financial_type_id
;
2869 $template->assign('trxn_id', $this->trxn_id
);
2870 $template->assign('receive_date',
2871 CRM_Utils_Date
::processDate($this->receive_date
)
2873 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
2874 $template->assign('contributeMode', 'notify');
2875 $template->assign('action', $this->is_test ?
1024 : 1);
2876 $template->assign('receipt_text',
2877 CRM_Utils_Array
::value('receipt_text',
2881 $template->assign('is_monetary', 1);
2882 $template->assign('is_recur', (bool) $recur);
2883 $template->assign('currency', $this->currency
);
2884 $template->assign('address', CRM_Utils_Address
::format($input));
2885 if (!empty($values['customGroup'])) {
2886 $template->assign('customGroup', $values['customGroup']);
2888 if (!empty($values['softContributions'])) {
2889 $template->assign('softContributions', $values['softContributions']);
2891 if ($this->_component
== 'event') {
2892 $template->assign('title', $values['event']['title']);
2893 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2894 $viewRoles = array();
2895 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2896 $viewRoles[] = $participantRoles[$v];
2898 $values['event']['participant_role'] = implode(', ', $viewRoles);
2899 $template->assign('event', $values['event']);
2900 $template->assign('participant', $values['participant']);
2901 $template->assign('location', $values['location']);
2902 $template->assign('customPre', $values['custom_pre_id']);
2903 $template->assign('customPost', $values['custom_post_id']);
2906 if ($this->_relatedObjects
['participant']->is_test
) {
2910 $values['params'] = array();
2911 //to get email of primary participant.
2912 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2913 $primaryAmount[] = array(
2914 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2915 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2917 //build an array of cId/pId of participants
2918 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2919 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2920 //send receipt to additional participant if exists
2921 if (count($additionalIDs)) {
2922 $template->assign('isPrimary', 0);
2923 $template->assign('customProfile', NULL);
2924 //set additionalParticipant true
2925 $values['params']['additionalParticipant'] = TRUE;
2926 foreach ($additionalIDs as $pId => $cId) {
2928 //to change the status pending to completed
2929 $additional = new CRM_Event_DAO_Participant();
2930 $additional->id
= $pId;
2931 $additional->contact_id
= $cId;
2932 $additional->find(TRUE);
2933 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2934 $additional->status_id
= 1;
2935 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2936 //if additional participant dont have email
2938 if (!$additionalParticipantInfo) {
2939 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2941 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2942 $primaryAmount[] = array(
2943 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2944 'amount' => $additional->fee_amount
,
2946 $additional->save();
2947 $additional->free();
2948 $template->assign('amount', $amount);
2949 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2953 //build an array of custom profile and assigning it to template
2954 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2956 if (count($customProfile)) {
2957 $template->assign('customProfile', $customProfile);
2960 // for primary contact
2961 $values['params']['additionalParticipant'] = FALSE;
2962 $template->assign('isPrimary', 1);
2963 $template->assign('amount', $primaryAmount);
2964 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2965 if ($this->payment_instrument_id
) {
2966 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2967 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2969 // carry paylater, since we did not created billing,
2970 // so need to pull email from primary location, CRM-4395
2971 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2977 * Check whether payment processor supports
2978 * cancellation of contribution subscription
2980 * @param int $contributionId
2983 * @param bool $isNotCancelled
2987 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2988 $cacheKeyString = "$contributionId";
2989 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2991 static $supportsCancel = array();
2993 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2994 $supportsCancel[$cacheKeyString] = FALSE;
2995 $isCancelled = FALSE;
2997 if ($isNotCancelled) {
2998 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3001 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3002 if (!empty($paymentObject)) {
3003 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3006 return $supportsCancel[$cacheKeyString];
3010 * Check whether subscription is already cancelled.
3012 * @param int $contributionId
3016 * contribution status
3018 public static function isSubscriptionCancelled($contributionId) {
3020 SELECT cr.contribution_status_id
3021 FROM civicrm_contribution_recur cr
3022 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3023 WHERE con.id = %1 LIMIT 1";
3024 $params = array(1 => array($contributionId, 'Integer'));
3025 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3026 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3027 if ($status == 'Cancelled') {
3034 * Create all financial accounts entry.
3036 * @param array $params
3037 * Contribution object, line item array and params for trxn.
3040 * @param array $financialTrxnValues
3042 * @return null|object
3044 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3045 $skipRecords = $update = $return = $isRelatedId = FALSE;
3047 $additionalParticipantId = array();
3048 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3049 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3051 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3052 $entityId = $params['participant_id'];
3053 $entityTable = 'civicrm_participant';
3054 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3056 elseif (!empty($params['membership_id'])) {
3057 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3058 // are created off one contribution should be handled elsewhere
3059 $entityId = $params['membership_id'];
3060 $entityTable = 'civicrm_membership';
3063 $entityId = $params['contribution']->id
;
3064 $entityTable = 'civicrm_contribution';
3067 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3068 $isRelatedId = TRUE;
3071 $entityID[] = $entityId;
3072 if (!empty($additionalParticipantId)) {
3073 $entityID +
= $additionalParticipantId;
3075 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3076 if (empty($params['prevContribution'])) {
3083 $statusId = $params['contribution']->contribution_status_id
;
3084 // CRM-13964 partial payment
3085 if ($contributionStatus == 'Partially paid'
3086 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3088 $partialAmtPay = $params['partial_amount_pay'];
3089 $partialAmtTotal = $params['partial_payment_total'];
3091 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3092 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3093 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3094 $params['total_amount'] = $partialAmtPay;
3096 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3097 if (empty($balanceTrxnInfo['trxn_id'])) {
3098 // create new balance transaction record
3099 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3100 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3102 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3103 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3104 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3105 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3106 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3107 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3108 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3109 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3110 $balanceTrxnParams['status_id'] = $statusId;
3111 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3112 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3113 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3114 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3116 $balanceTrxnParams['is_payment'] = 1;
3118 if (!empty($params['payment_processor'])) {
3119 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3121 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3125 // build line item array if its not set in $params
3126 if (empty($params['line_item']) ||
$additionalParticipantId) {
3127 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3130 if ($contributionStatus != 'Failed' &&
3131 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3133 $skipRecords = TRUE;
3134 $pendingStatus = array(
3138 if (in_array($contributionStatus, $pendingStatus)) {
3139 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3140 $params['financial_type_id'],
3141 'Accounts Receivable Account is'
3144 elseif (!empty($params['payment_processor'])) {
3145 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3146 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array(
3147 'id' => $params['payment_processor'],
3148 'return' => 'payment_instrument_id',
3151 elseif (!empty($params['payment_instrument_id'])) {
3152 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3155 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3156 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3157 $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);
3160 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3161 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3162 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3165 //build financial transaction params
3166 $trxnParams = array(
3167 'contribution_id' => $params['contribution']->id
,
3168 'to_financial_account_id' => $params['to_financial_account_id'],
3169 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3170 'total_amount' => $totalAmount,
3171 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3172 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3173 'currency' => $params['contribution']->currency
,
3174 'trxn_id' => $params['contribution']->trxn_id
,
3175 'status_id' => $statusId,
3176 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3177 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3179 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback') {
3180 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3181 if (isset($params['refund_trxn_id'])) {
3182 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3183 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3186 //CRM-16259, set is_payment flag for non pending status
3187 if (!in_array($contributionStatus, $pendingStatus)) {
3188 $trxnParams['is_payment'] = 1;
3190 if (!empty($params['payment_processor'])) {
3191 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3194 if (isset($fromFinancialAccountId)) {
3195 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3198 // consider external values passed for recording transaction entry
3199 if (!empty($financialTrxnValues)) {
3200 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3203 $params['trxnParams'] = $trxnParams;
3205 if (!empty($params['prevContribution'])) {
3207 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3208 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3209 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3210 if (!isset($params['trxnParams']['trxn_id'])) {
3211 // Actually I have no idea why we are overwriting any values from the previous contribution.
3212 // (filling makes sense to me). However, only protecting this value as I really really know we
3213 // don't want this one overwritten.
3215 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3217 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3219 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3220 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3221 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3223 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3224 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3227 //if financial type is changed
3228 if (!empty($params['financial_type_id']) &&
3229 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3231 $accountRelationship = 'Income Account is';
3232 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3233 $accountRelationship = 'Deferred Revenue Account is';
3235 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '$accountRelationship' "));
3236 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $relationTypeId);
3237 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3238 if ($oldFinancialAccount != $newFinancialAccount) {
3239 $params['total_amount'] = 0;
3240 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3241 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3242 $params['prevContribution']->financial_type_id
, $relationTypeId);
3245 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3246 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3247 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3250 self
::updateFinancialAccounts($params, 'changeFinancialType');
3251 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3252 $params['financial_account_id'] = $newFinancialAccount;
3253 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3254 self
::updateFinancialAccounts($params);
3255 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3257 $params['deferred_financial_account_id'] = $newFinancialAccount;
3261 //Update contribution status
3262 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3263 if (!isset($params['refund_trxn_id'])) {
3264 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3265 // gets preference over another so I am only 'protecting' a very specific tested flow
3266 // and letting natural justice take care of the rest.
3267 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3269 if (!empty($params['contribution_status_id']) &&
3270 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3272 //Update Financial Records
3273 self
::updateFinancialAccounts($params, 'changedStatus');
3277 // change Payment Instrument for a Completed contribution
3278 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3279 // instrument is null and now new payment instrument is added along with the payment
3280 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3281 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3282 if (array_key_exists('payment_instrument_id', $params)) {
3283 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3284 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3285 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3287 //check if status is changed from Pending to Completed
3288 // do not update payment instrument changes for Pending to Completed
3289 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3290 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3292 // for all other statuses create new financial records
3293 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3294 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3295 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3299 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3300 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3301 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3303 // for any other payment instrument changes create new financial records
3304 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3305 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3306 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3309 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3310 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3312 // another special case when check number is changed, create new financial records
3313 // create financial trxn with negative amount
3314 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3315 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3316 // create financial trxn with positive amount
3317 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3318 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3319 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3324 //if Change contribution amount
3325 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3326 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3327 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3328 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3329 if (isset($totalAmount) &&
3330 $totalAmount != $params['prevContribution']->total_amount
3332 //Update Financial Records
3333 $params['trxnParams']['from_financial_account_id'] = NULL;
3334 self
::updateFinancialAccounts($params, 'changedAmount');
3339 // Looks like we might have a data correction update.
3340 // This would be a case where a transaction id has been entered but it is incorrect &
3341 // the person goes back in & fixes it, as opposed to a new transaction.
3342 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3343 // the data fix scenario.
3345 if (isset($params['refund_trxn_id'])) {
3346 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3347 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3348 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3355 // records finanical trxn and entity financial trxn
3356 // also make it available as return value
3357 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3358 $params['entity_id'] = $financialTxn->id
;
3361 // record line items and financial items
3362 if (empty($params['skipLineItem'])) {
3363 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3366 // create batch entry if batch_id is passed and
3367 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3368 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3369 $entityParams = array(
3370 'batch_id' => $params['batch_id'],
3371 'entity_table' => 'civicrm_financial_trxn',
3372 'entity_id' => $financialTxn->id
,
3374 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3377 // when a fee is charged
3378 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3379 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3382 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3383 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3385 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3386 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3387 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3389 unset($params['line_item']);
3395 * Update all financial accounts entry.
3397 * @param array $params
3398 * Contribution object, line item array and params for trxn.
3400 * @param string $context
3403 * @param null $skipTrxn
3406 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3407 $itemAmount = $trxnID = NULL;
3408 //get all the statuses
3409 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3410 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3411 if (($previousContributionStatus == 'Pending'
3412 ||
$previousContributionStatus == 'In Progress')
3413 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3414 && $context == 'changePaymentInstrument'
3418 if ((($previousContributionStatus == 'Partially paid'
3419 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3420 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3421 && $params['contribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus)))
3422 && $context == 'changedStatus'
3426 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3427 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3429 if ($context == 'changedStatus') {
3430 //get all the statuses
3431 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3432 $cancelledTaxAmount = 0;
3433 if ($previousContributionStatus == 'Completed'
3434 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3436 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3437 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $params, '0.00');
3438 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3439 $creditNoteId = self
::createCreditNoteId();
3440 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3443 elseif (($previousContributionStatus == 'Pending'
3444 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3446 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3447 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3448 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3450 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3451 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3452 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3453 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3454 $creditNoteId = self
::createCreditNoteId();
3455 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3459 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3462 $itemAmount = $params['trxnParams']['total_amount'] +
$cancelledTaxAmount;
3464 elseif ($context == 'changePaymentInstrument') {
3465 $params['trxnParams']['net_amount'] = $params['trxnParams']['total_amount'];
3466 $deferredFinancialAccount = CRM_Utils_Array
::value('deferred_financial_account_id', $params);
3467 if (empty($deferredFinancialAccount)) {
3468 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
3469 $deferredFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $relationTypeId);
3471 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC', FALSE, NULL, $deferredFinancialAccount);
3472 if ($params['trxnParams']['total_amount'] < 0) {
3473 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3474 if ($params['total_amount'] > 0) {
3475 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3476 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3479 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3480 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3485 if ($params['total_amount'] < 0) {
3486 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3487 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3490 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3491 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3496 if ($context == 'changedStatus') {
3497 if (($previousContributionStatus == 'Pending'
3498 ||
$previousContributionStatus == 'In Progress')
3499 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3501 if (empty($params['line_item'])) {
3503 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3504 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3505 // & this can be removed
3508 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3509 $params['entity_id'] = $trxn->id
;
3510 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3511 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3513 $entityParams = array(
3514 'entity_table' => 'civicrm_financial_item',
3515 'financial_trxn_id' => $trxn->id
,
3517 foreach ($params['line_item'] as $fieldId => $fields) {
3518 foreach ($fields as $fieldValueId => $fieldValues) {
3520 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3521 2 => array($fieldValues['id'], 'Integer'),
3523 CRM_Core_DAO
::executeQuery($query, $fparams);
3525 1 => array($fieldValues['id'], 'Integer'),
3527 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3528 while ($financialItem->fetch()) {
3529 $entityParams['entity_id'] = $financialItem->id
;
3530 $entityParams['amount'] = $financialItem->amount
;
3531 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3538 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3539 $params['entity_id'] = $trxn->id
;
3540 if ($context != 'changePaymentInstrument') {
3541 $itemParams['entity_table'] = 'civicrm_line_item';
3542 $trxnIds['id'] = $params['entity_id'];
3543 foreach ($params['line_item'] as $fieldId => $fields) {
3544 foreach ($fields as $fieldValueId => $fieldValues) {
3545 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($fieldValues['id']);
3546 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3547 if ($params['contribution']->receive_date
) {
3548 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3551 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem);
3553 $currency = $params['prevContribution']->currency
;
3554 if ($params['contribution']->currency
) {
3555 $currency = $params['contribution']->currency
;
3558 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($params['contribution']->contribution_status_id
)) {
3561 if (!empty($params['is_quick_config'])) {
3562 $amount = $itemAmount;
3564 $amount = $params['total_amount'];
3568 $amount = $diff * $fieldValues['line_total'];
3571 $itemParams = array(
3572 'transaction_date' => $receiveDate,
3573 'contact_id' => $params['prevContribution']->contact_id
,
3574 'currency' => $currency,
3575 'amount' => $amount,
3576 'description' => $prevFinancialItem->description
,
3577 'status_id' => $prevFinancialItem->status_id
,
3578 'financial_account_id' => $financialAccount,
3579 'entity_table' => 'civicrm_line_item',
3580 'entity_id' => $fieldValues['id'],
3582 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3583 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $amount;
3584 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3586 if ($fieldValues['tax_amount']) {
3587 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3588 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3589 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3590 $itemParams['description'] = $taxTerm;
3591 if ($fieldValues['financial_type_id']) {
3592 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3594 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3599 if ($context == 'changeFinancialType') {
3600 $params['skipLineItem'] = FALSE;
3601 foreach ($params['line_item'] as &$lineItems) {
3602 foreach ($lineItems as &$line) {
3603 $line['financial_type_id'] = $params['financial_type_id'];
3607 if ($context == 'changePaymentInstrument') {
3608 foreach ($params['line_item'] as $lineitems) {
3609 foreach ($lineitems as $fieldValueId => $fieldValues) {
3610 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($fieldValues['id']);
3611 if (!CRM_Utils_Rule
::currencyCode($trxn->currency
)) {
3612 $trxn->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
3615 // save to entity_financial_trxn table
3616 $entityFinancialTrxnParams = array(
3617 'entity_table' => "civicrm_financial_item",
3618 'entity_id' => $prevFinancialItem->id
,
3619 'financial_trxn_id' => $trxn->id
,
3620 'amount' => $trxn->total_amount
,
3621 'currency' => $trxn->currency
,
3623 $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
3624 $entityTrxn->copyValues($entityFinancialTrxnParams);
3625 $entityTrxn->save();
3629 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3633 * Is this contribution status a reversal.
3635 * If so we would expect to record a negative value in the financial_trxn table.
3637 * @param int $status_id
3641 public static function isContributionStatusNegative($status_id) {
3642 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3643 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3647 * Check status validation on update of a contribution.
3649 * @param array $values
3650 * Previous form values before submit.
3652 * @param array $fields
3653 * The input form values.
3655 * @param array $errors
3660 public static function checkStatusValidation($values, &$fields, &$errors) {
3661 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3662 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3663 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3667 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3668 $checkStatus = array(
3669 'Cancelled' => array('Completed', 'Refunded'),
3670 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3671 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3672 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3673 'Refunded' => array('Cancelled', 'Completed'),
3674 'Partially paid' => array('Completed'),
3677 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3678 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3680 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3681 1 => $contributionStatuses[$values['contribution_status_id']],
3682 2 => $contributionStatuses[$fields['contribution_status_id']],
3688 * Delete contribution of contact.
3692 * @param int $contactId
3696 public static function deleteContactContribution($contactId) {
3697 $contribution = new CRM_Contribute_DAO_Contribution();
3698 $contribution->contact_id
= $contactId;
3699 $contribution->find();
3700 while ($contribution->fetch()) {
3701 self
::deleteContribution($contribution->id
);
3706 * Get options for a given contribution field.
3707 * @see CRM_Core_DAO::buildOptions
3709 * @param string $fieldName
3710 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3711 * @param array $props whatever is known about this dao object.
3713 * @return array|bool
3715 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3716 $className = __CLASS__
;
3718 switch ($fieldName) {
3719 // This field is not part of this object but the api supports it
3720 case 'payment_processor':
3721 $className = 'CRM_Contribute_BAO_ContributionPage';
3722 // Filter results by contribution page
3723 if (!empty($props['contribution_page_id'])) {
3724 $page = civicrm_api('contribution_page', 'getsingle', array(
3726 'id' => ($props['contribution_page_id']),
3728 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3729 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3733 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3734 case 'honor_type_id':
3735 $className = 'CRM_Contribute_BAO_ContributionSoft';
3736 $fieldName = 'soft_credit_type_id';
3737 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3740 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3744 * Validate financial type.
3748 * @param int $financialTypeId
3749 * Financial Type id.
3751 * @param string $relationName
3753 * @return array|bool
3755 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3756 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3757 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3759 if (!$financialAccount) {
3760 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3767 * Function to record additional payment for partial and refund contributions.
3769 * @param int $contributionId
3770 * is the invoice contribution id (got created after processing participant payment).
3771 * @param array $trxnsData
3772 * to take user provided input of transaction details.
3773 * @param string $paymentType
3774 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3775 * @param int $participantId
3777 * @return null|object
3779 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3780 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3781 $getInfoOf['id'] = $contributionId;
3782 $defaults = array();
3783 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3784 if (!$participantId) {
3785 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id');
3788 if ($paymentType == 'owed') {
3789 // build params for recording financial trxn entry
3790 $params['contribution'] = $contributionDAO;
3791 $params = array_merge($defaults, $params);
3792 $params['skipLineItem'] = TRUE;
3793 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3794 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3795 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3796 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3799 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3800 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3801 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3803 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3804 if (!empty($trxnId)) {
3805 $trxnId = $trxnId['trxn_id'];
3807 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3808 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3811 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3812 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3813 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3817 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3818 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3819 FROM civicrm_financial_trxn ft
3820 LEFT JOIN civicrm_entity_financial_trxn eft
3821 ON (ft.id = eft.financial_trxn_id)
3822 WHERE eft.entity_table = 'civicrm_contribution'
3823 AND eft.entity_id = {$contributionId}
3824 AND ft.to_financial_account_id != {$toFinancialAccount}
3825 AND ft.status_id = {$statusId}
3827 $query = CRM_Core_DAO
::executeQuery($sql);
3829 $sumOfPayments = $query->sum_of_payments
;
3832 if ($contributionDAO->total_amount
== $sumOfPayments) {
3833 // update contribution status and
3834 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3835 $contributionDAO->contribution_status_id
= $statusId;
3836 $contributionDAO->cancel_date
= 'null';
3837 $contributionDAO->cancel_reason
= NULL;
3838 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3839 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3840 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3841 $contributionDAO->save();
3843 //Change status of financial record too
3844 $financialTrxn->status_id
= $statusId;
3845 $financialTrxn->save();
3847 // note : not using the self::add method,
3848 // the reason because it performs 'status change' related code execution for financial records
3849 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3850 // are coded below i.e. just updating financial_item status to 'Paid'
3852 if ($participantId) {
3853 // update participant status
3854 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3855 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3856 foreach ($ids as $val) {
3857 $participantUpdate['id'] = $val;
3858 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3859 CRM_Event_BAO_Participant
::add($participantUpdate);
3863 // update financial item statuses
3864 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3865 $paidStatus = array_search('Paid', $financialItemStatus);
3867 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3868 $sqlFinancialItemUpdate = "
3869 UPDATE civicrm_financial_item fi
3870 LEFT JOIN civicrm_entity_financial_trxn eft
3871 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3872 SET status_id = {$paidStatus}
3873 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3875 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3878 elseif ($paymentType == 'refund') {
3879 // build params for recording financial trxn entry
3880 $params['contribution'] = $contributionDAO;
3881 $params = array_merge($defaults, $params);
3882 $params['skipLineItem'] = TRUE;
3883 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3884 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3886 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3887 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3888 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3890 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3892 // note : not using the self::add method,
3893 // the reason because it performs 'status change' related code execution for financial records
3894 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3895 // are coded below i.e. just updating financial_item status to 'Paid'
3896 if ($updateStatus) {
3897 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3899 // add financial item entry
3900 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3901 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionDAO->id
);
3902 if (!empty($lineItems)) {
3903 foreach ($lineItems as $lineItemId => $lineItemValue) {
3904 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount
/ $contributionDAO->total_amount
);
3905 $addFinancialEntry = array(
3906 'transaction_date' => $financialTrxn->trxn_date
,
3907 'contact_id' => $contributionDAO->contact_id
,
3908 'amount' => round($paid, 2),
3909 'status_id' => array_search('Paid', $financialItemStatus),
3910 'entity_id' => $lineItemId,
3911 'entity_table' => 'civicrm_line_item',
3913 $trxnIds['id'] = $financialTrxn->id
;
3914 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3917 if ($participantId) {
3918 // update participant status
3919 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3920 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3921 foreach ($ids as $val) {
3922 $participantUpdate['id'] = $val;
3923 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3924 CRM_Event_BAO_Participant
::add($participantUpdate);
3929 // activity creation
3930 if (!empty($financialTrxn)) {
3931 if ($participantId) {
3932 $inputParams['id'] = $participantId;
3935 $component = 'event';
3936 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3937 $entityObj = $entityObj[$participantId];
3939 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3941 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3943 return $financialTrxn;
3949 * @param $activityType
3951 * @param int $contributionId
3953 * @throws CRM_Core_Exception
3955 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3956 if ($component == 'event') {
3957 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3958 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3959 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3960 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3961 $targetCid = $entityObj->contact_id
;
3962 // source record id would be the contribution id
3963 $srcRecId = $contributionId;
3967 $activityParams = array(
3968 'source_contact_id' => $targetCid,
3969 'source_record_id' => $srcRecId,
3970 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3974 'subject' => $subject,
3975 'activity_date_time' => $date,
3976 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3980 'skipRecentView' => TRUE,
3983 // create activity with target contacts
3984 $session = CRM_Core_Session
::singleton();
3985 $id = $session->get('userID');
3987 $activityParams['source_contact_id'] = $id;
3988 $activityParams['target_contact_id'][] = $targetCid;
3990 CRM_Activity_BAO_Activity
::create($activityParams);
3994 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3998 * @param bool $getTrxnInfo
3999 * @param bool $usingLineTotal
4003 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
4004 if ($component == 'event') {
4005 $entity = 'participant';
4006 $entityTable = 'civicrm_participant';
4007 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4009 if (!$contributionId) {
4010 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4011 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4012 $id = $primaryParticipantId;
4014 if (!$contributionId) {
4020 $contributionId = $id;
4021 $entity = 'contribution';
4022 $entityTable = 'civicrm_contribution';
4025 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4026 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4028 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4029 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4031 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
4032 // for additional participants
4033 if ($entityTable == 'civicrm_participant') {
4034 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
4036 foreach ($ids as $val) {
4037 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
4041 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
4045 $baseTrxnId = $total['trxn_id'];
4046 $total = $total['total_amount'];
4049 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
4050 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
4052 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
4053 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4054 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
4056 if ($paymentBalance == 0 && $contributionIsPayLater) {
4057 $paymentBalance = $total;
4060 $info['total'] = $total;
4061 $info['paid'] = $total - $paymentBalance;
4062 $info['balance'] = $paymentBalance;
4064 $info['component'] = $component;
4065 $info['payLater'] = $contributionIsPayLater;
4067 if ($getTrxnInfo && $baseTrxnId) {
4068 $arRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4069 $arAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $arRelationTypeId);
4071 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4073 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4075 ft.payment_instrument_id,
4076 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, con.currency
4078 FROM civicrm_contribution con
4079 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4080 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4081 AND ft.to_financial_account_id != %2
4082 INNER JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4083 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4084 INNER JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4086 WHERE con.id = %1 AND ft.to_financial_account_id <> %3
4088 $queryParams = array(
4089 1 => array($contributionId, 'Integer'),
4090 2 => array($feeFinancialAccount, 'Integer'),
4091 3 => array($arAccount, 'Integer'),
4093 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4094 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4096 while ($resultDAO->fetch()) {
4097 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4098 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4100 'total_amount' => $resultDAO->total_amount
,
4101 'financial_type' => $resultDAO->financial_account
,
4102 'payment_instrument' => $paidByLabel,
4103 'receive_date' => $resultDAO->trxn_date
,
4104 'trxn_id' => $resultDAO->trxn_id
,
4105 'status' => $statuses[$resultDAO->status_id
],
4106 'currency' => $resultDAO->currency
,
4108 if ($paidByName == 'Check') {
4109 $val['check_number'] = $resultDAO->check_number
;
4113 $info['transaction'] = $rows;
4119 * Get financial account id has 'Sales Tax Account is' account relationship with financial type.
4121 * @param int $financialTypeId
4124 * Financial Account Id
4126 public static function getFinancialAccountId($financialTypeId) {
4127 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4128 $searchParams = array(
4129 'entity_table' => 'civicrm_financial_type',
4130 'entity_id' => $financialTypeId,
4131 'account_relationship' => $accountRel,
4134 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
4136 return CRM_Utils_Array
::value('financial_account_id', $result);
4140 * Get the tax amount (misnamed function).
4142 * @param array $params
4143 * @param bool $isLineItem
4147 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4148 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4150 // Update contribution.
4151 if (!empty($params['id'])) {
4152 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4153 // there are no tax implications - early return.
4154 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4157 if (empty($params['prevContribution'])) {
4158 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4161 foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) {
4162 if (!isset($params[$field])) {
4163 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4164 // Tax amount gets added back on later....
4165 $params['total_amount'] = $params['prevContribution']->total_amount
-
4166 $params['prevContribution']->tax_amount
;
4169 $params[$field] = $params['prevContribution']->$field;
4170 if ($params[$field] != $params['prevContribution']->$field) {
4176 self
::calculateMissingAmountParams($params, $params['id']);
4177 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4178 // Assign tax Amount on update of contribution
4179 if (!empty($params['prevContribution']->tax_amount
)) {
4180 $params['tax_amount'] = 'null';
4181 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4182 foreach ($params['line_item'] as $setID => $priceField) {
4183 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4184 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4191 // New Contribution and update of contribution with tax rate financial type
4192 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4193 empty($params['skipLineItem']) && !$isLineItem
4195 $taxRateParams = $taxRates[$params['financial_type_id']];
4196 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4197 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4199 // Get Line Item on update of contribution
4200 if (isset($params['id'])) {
4201 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4204 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4206 foreach ($params['line_item'] as $setID => $priceField) {
4207 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4208 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4211 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4213 elseif (isset($params['api.line_item.create'])) {
4214 // Update total amount of contribution using lineItem
4215 $taxAmountArray = array();
4216 foreach ($params['api.line_item.create'] as $key => $value) {
4217 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4218 $taxRate = $taxRates[$value['financial_type_id']];
4219 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4220 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4223 $params['tax_amount'] = array_sum($taxAmountArray);
4224 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4227 // update line item of contrbution
4228 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4229 $taxRate = $taxRates[$params['financial_type_id']];
4230 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
4231 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4238 * Check financial type validation on update of a contribution.
4240 * @param Integer $financialTypeId
4241 * Value of latest Financial Type.
4243 * @param Integer $contributionId
4246 * @param array $errors
4251 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4252 if (!empty($financialTypeId)) {
4253 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4254 if ($oldFinancialTypeId == $financialTypeId) {
4258 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4260 '1' => array($contributionId, 'Integer'),
4262 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4263 if ($result->N
> 1) {
4264 $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.');
4269 * Update related pledge payment payments.
4271 * This function has been refactored out of the back office contribution form and may
4272 * still overlap with other functions.
4274 * @param string $action
4275 * @param int $pledgePaymentID
4276 * @param int $contributionID
4277 * @param bool $adjustTotalAmount
4278 * @param float $total_amount
4279 * @param float $original_total_amount
4280 * @param int $contribution_status_id
4281 * @param int $original_contribution_status_id
4283 public static function updateRelatedPledge(
4289 $original_total_amount,
4290 $contribution_status_id,
4291 $original_contribution_status_id
4293 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4297 if ($pledgePaymentID) {
4298 //store contribution id in payment record.
4299 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4302 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4309 if (!$pledgePaymentID) {
4312 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4318 $updatePledgePaymentStatus = FALSE;
4320 // If either the status or the amount has changed we update the pledge status.
4321 if ($action & CRM_Core_Action
::ADD
) {
4322 $updatePledgePaymentStatus = TRUE;
4324 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4325 ($original_total_amount != $total_amount))
4327 $updatePledgePaymentStatus = TRUE;
4330 if ($updatePledgePaymentStatus) {
4331 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4332 array($pledgePaymentID),
4333 $contribution_status_id,
4342 * Compute the stats values
4344 * @param $stat either 'mode' or 'median'
4346 * @param $alias of civicrm_contribution
4348 public static function computeStats($stat, $sql, $alias = NULL) {
4349 $mode = $median = array();
4352 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4353 while ($modeDAO->fetch()) {
4354 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4355 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4364 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4365 foreach ($currencies as $currency => $val) {
4367 $where = "AND {$alias}.currency = '{$currency}'";
4368 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4372 $medianRow = floor($rowCount / 2);
4373 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4379 $medianValue = "SELECT {$alias}.total_amount as median
4381 ORDER BY median LIMIT {$medianRow},{$offset}";
4382 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4383 while ($medianValDAO->fetch()) {
4385 $midValue = $midValue +
$medianValDAO->median
;
4388 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4392 $midValue = $midValue / 2;
4393 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4404 * Is there only one line item attached to the contribution.
4410 * @throws \CiviCRM_API3_Exception
4412 public static function isSingleLineItem($id) {
4413 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4414 return ($lineItemCount == 1);
4418 * Complete an order.
4420 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4422 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4424 * Moving it out of the BaseIPN class is just the first step.
4426 * @param array $input
4428 * @param array $objects
4429 * @param CRM_Core_Transaction $transaction
4431 * @param CRM_Contribute_BAO_Contribution $contribution
4432 * @param bool $isRecurring
4433 * Duplication of param needs review. Only used by AuthorizeNetIPN
4434 * @param int $isFirstOrLastRecurringPayment
4435 * Deprecated param only used by AuthorizeNetIPN.
4437 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4438 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4439 // The previous details are used when calculating line items so keep it before any code that 'does something'
4440 if (!empty($contribution->id
)) {
4441 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4442 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4444 $inputContributionWhiteList = array(
4449 'payment_instrument_id',
4454 'contribution_status_id',
4456 if (self
::isSingleLineItem($primaryContributionID)) {
4457 $inputContributionWhiteList[] = 'financial_type_id';
4460 $participant = CRM_Utils_Array
::value('participant', $objects);
4461 $memberships = CRM_Utils_Array
::value('membership', $objects);
4462 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4463 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4464 $event = CRM_Utils_Array
::value('event', $objects);
4466 $paymentProcessorId = '';
4467 if (isset($objects['paymentProcessor'])) {
4468 if (is_array($objects['paymentProcessor'])) {
4469 $paymentProcessorId = $objects['paymentProcessor']['id'];
4472 $paymentProcessorId = $objects['paymentProcessor']->id
;
4476 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4478 $contributionParams = array_merge(array(
4479 'contribution_status_id' => $completedContributionStatusID,
4480 'source' => self
::getRecurringContributionDescription($contribution, $event),
4481 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4483 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4485 if ($recurringContributionID) {
4486 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4488 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4490 if (empty($contributionParams['receive_date']) && $changeDate) {
4491 $contributionParams['receive_date'] = $changeDate;
4494 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4495 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4497 if (is_numeric($memberships)) {
4498 $memberships = array($objects['membership']);
4502 if (isset($input['is_email_receipt'])) {
4503 $values['is_email_receipt'] = $input['is_email_receipt'];
4506 if ($input['component'] == 'contribute') {
4507 if ($contribution->contribution_page_id
) {
4508 // Figure out what we gain from this.
4509 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4511 elseif ($recurContrib && $recurringContributionID) {
4512 $values['amount'] = $recurContrib->amount
;
4513 $values['financial_type_id'] = $objects['contributionType']->id
;
4514 $values['title'] = $source = ts('Offline Recurring Contribution');
4517 if ($recurContrib && $recurringContributionID && !isset($input['is_email_receipt'])) {
4518 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4519 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4520 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4523 if (!empty($memberships)) {
4524 foreach ($memberships as $membershipTypeIdKey => $membership) {
4526 $membershipParams = array(
4527 'id' => $membership->id
,
4528 'contact_id' => $membership->contact_id
,
4529 'is_test' => $membership->is_test
,
4530 'membership_type_id' => $membership->membership_type_id
,
4533 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4534 $membershipParams['membership_type_id'],
4535 $membershipParams['is_test'],
4536 $membershipParams['id']
4539 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4540 // this picks up membership type changes during renewals
4542 SELECT membership_type_id
4543 FROM civicrm_membership_log
4544 WHERE membership_id={$membershipParams['id']}
4547 $dao = CRM_Core_DAO
::executeQuery($sql);
4548 if ($dao->fetch()) {
4549 if (!empty($dao->membership_type_id
)) {
4550 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4555 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4556 $membershipParams['membership_type_id'],
4557 $primaryContributionID
4559 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4560 if ($currentMembership) {
4562 * Fixed FOR CRM-4433
4563 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4564 * when Contribution mode is notify and membership is for renewal )
4566 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4568 // @todo - we should pass membership_type_id instead of null here but not
4569 // adding as not sure of testing
4570 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4571 $changeDate, NULL, $membershipParams['num_terms']
4574 $dates['join_date'] = $currentMembership['join_date'];
4577 //get the status for membership.
4578 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4580 $dates['join_date'],
4583 $membershipParams['membership_type_id'],
4587 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4588 //we might be renewing membership,
4589 //so make status override false.
4590 $membershipParams['is_override'] = FALSE;
4591 //CRM-17723 - reset static $relatedContactIds array()
4593 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
4594 civicrm_api3('Membership', 'create', $membershipParams);
4600 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4601 if ($event->is_email_confirm
) {
4602 // @todo this should be set by the function that sends the mail after sending.
4603 $contributionParams['receipt_date'] = $changeDate;
4605 $participantParams['id'] = $participant->id
;
4606 $participantParams['status_id'] = 'Registered';
4607 civicrm_api3('Participant', 'create', $participantParams);
4611 $contributionParams['id'] = $contribution->id
;
4613 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4615 // Add new soft credit against current $contribution.
4616 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4617 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4620 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4621 'labelColumn' => 'name',
4624 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4625 $input['payment_processor'] = $paymentProcessorId;
4628 if (!empty($contribution->_relatedObjects
['participant'])) {
4629 $input['contribution_mode'] = 'participant';
4630 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4632 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4633 $input['contribution_mode'] = 'membership';
4634 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4635 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4636 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4639 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4640 $transaction->commit();
4642 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4643 $contributionParams['contribution_status_id'], $input['amount']);
4645 // create an activity record
4646 if ($input['component'] == 'contribute') {
4648 $targetContactID = NULL;
4649 if (!empty($ids['related_contact'])) {
4650 $targetContactID = $contribution->contact_id
;
4651 $contribution->contact_id
= $ids['related_contact'];
4653 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4657 CRM_Activity_BAO_Activity
::addActivity($participant);
4660 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4661 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4662 if (!array_key_exists('is_email_receipt', $values) ||
4663 $values['is_email_receipt'] == 1
4665 civicrm_api3('Contribution', 'sendconfirmation', array(
4666 'id' => $contribution->id
,
4667 'payment_processor_id' => $paymentProcessorId,
4669 CRM_Core_Error
::debug_log_message("Receipt sent");
4672 CRM_Core_Error
::debug_log_message("Success: Database updated");
4674 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4675 $isFirstOrLastRecurringPayment);
4677 return $contributionResult;
4681 * Send receipt from contribution.
4683 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4685 * Note that the compose message part has been moved to contribution
4686 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4688 * @param array $input
4689 * Incoming data from Payment processor.
4691 * Related object IDs.
4692 * @param int $contributionID
4693 * @param array $values
4694 * Values related to objects that have already been loaded.
4695 * @param bool $recur
4696 * Is it part of a recurring contribution.
4697 * @param bool $returnMessageText
4698 * Should text be returned instead of sent. This.
4699 * is because the function is also used to generate pdfs
4702 * @throws \CRM_Core_Exception
4703 * @throws \CiviCRM_API3_Exception
4705 public static function sendMail(&$input, &$ids, $contributionID, &$values, $recur = FALSE,
4706 $returnMessageText = FALSE) {
4707 $input['is_recur'] = $recur;
4709 $contribution = new CRM_Contribute_BAO_Contribution();
4710 $contribution->id
= $contributionID;
4711 if (!$contribution->find(TRUE)) {
4712 throw new CRM_Core_Exception('Contribution does not exist');
4714 $contribution->loadRelatedObjects($input, $ids, TRUE);
4715 // set receipt from e-mail and name in value
4716 if (!$returnMessageText) {
4717 $session = CRM_Core_Session
::singleton();
4718 $userID = $session->get('userID');
4719 if (!empty($userID)) {
4720 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4721 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4722 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4726 $return = $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4727 // Contribution ID should really always be set. But ?
4728 if (!$returnMessageText && (!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4729 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4735 * Generate credit note id with next avaible number
4740 public static function createCreditNoteId() {
4741 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4743 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4744 $creditNoteId = NULL;
4748 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4749 $result = civicrm_api3('Contribution', 'getcount', array(
4751 'creditnote_id' => $creditNoteId,
4753 } while ($result > 0);
4755 return $creditNoteId;
4759 * Load related memberships.
4761 * Note that in theory it should be possible to retrieve these from the line_item table
4762 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4763 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4764 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4765 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4767 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4773 public function loadRelatedMembershipObjects(&$ids) {
4775 SELECT membership_id
4776 FROM civicrm_membership_payment
4777 WHERE contribution_id = %1 ";
4778 $params = array(1 => array($this->id
, 'Integer'));
4780 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4781 while ($dao->fetch()) {
4782 if ($dao->membership_id
) {
4783 if (!is_array($ids['membership'])) {
4784 $ids['membership'] = array();
4786 $ids['membership'][] = $dao->membership_id
;
4790 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4791 foreach ($ids['membership'] as $id) {
4793 $membership = new CRM_Member_BAO_Membership();
4794 $membership->id
= $id;
4795 if (!$membership->find(TRUE)) {
4796 throw new Exception("Could not find membership record: $id");
4798 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4799 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4800 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4801 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4802 $membership->free();
4809 * This function is used to record partial payments for contribution
4811 * @param array $contribution
4813 * @param array $params
4817 public static function recordPartialPayment($contribution, $params) {
4818 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4819 $pendingStatus = array(
4820 array_search('Pending', $contributionStatuses),
4821 array_search('In Progress', $contributionStatuses),
4823 $statusId = array_search('Completed', $contributionStatuses);
4824 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4825 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4826 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4828 elseif (!empty($params['payment_processor'])) {
4829 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4831 elseif (!empty($params['payment_instrument_id'])) {
4832 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4835 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4836 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4837 $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);
4839 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4840 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4841 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4842 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4843 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4844 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4845 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4846 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4847 $balanceTrxnParams['currency'] = $contribution['currency'];
4848 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4849 $balanceTrxnParams['status_id'] = $statusId;
4850 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4851 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4852 if ($fromFinancialAccountId != NULL &&
4853 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4855 $balanceTrxnParams['is_payment'] = 1;
4857 if (!empty($params['payment_processor'])) {
4858 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4860 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4864 * Get the description (source field) for the recurring contribution.
4866 * @param CRM_Contribute_BAO_Contribution $contribution
4867 * @param CRM_Event_DAO_Event|null $event
4870 * @throws \CiviCRM_API3_Exception
4872 protected static function getRecurringContributionDescription($contribution, $event) {
4873 if (!empty($contribution->source
)) {
4874 return $contribution->source
;
4876 elseif (!empty($contribution->contribution_page_id
)) {
4877 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4878 'id' => $contribution->contribution_page_id
,
4879 'return' => 'title',
4881 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4884 return ts('Online Event Registration') . ': ' . $event->title
;
4886 elseif (!empty($contribution->contribution_recur_id
)) {
4887 return 'recurring contribution';
4893 * Function to add payments for contribution
4894 * for Partially Paid status
4896 * @param array $lineItems
4897 * @param array $contributions
4898 * @param array $contributionStatusId
4901 public static function addPayments($lineItems, $contributions, $contributionStatusId = NULL) {
4902 // get financial trxn which is a payment
4903 $ftSql = "SELECT ft.id, ft.total_amount
4904 FROM civicrm_financial_trxn ft
4905 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4906 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4907 $sql = "SELECT fi.id, li.price_field_value_id
4908 FROM civicrm_financial_item fi
4909 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id
4910 WHERE li.contribution_id = %1";
4911 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4912 'labelColumn' => 'name',
4914 foreach ($contributions as $k => $contribution) {
4915 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4916 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4920 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4922 $trxnAmount = $ftDao->total_amount
;
4925 // get financial item
4926 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contribution->id
, 'Integer')));
4927 while ($dao->fetch()) {
4928 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4932 'entity_table' => 'civicrm_financial_item',
4933 'financial_trxn_id' => $ftId,
4935 foreach ($lineItems as $key => $value) {
4936 if ($value['qty'] == 0) {
4939 $paid = $value['line_total'] * ($trxnAmount / $contribution->total_amount
);
4940 // Record Entity Financial Trxn
4941 $params['amount'] = round($paid, 2);
4942 $params['entity_id'] = $ftIds[$value['price_field_value_id']];
4944 civicrm_api3('EntityFinancialTrxn', 'create', $params);
4950 * Function use to store line item proportionaly in
4951 * in entity financial trxn table
4953 * @param array $params
4954 * array of contribution params.
4955 * @param object $trxn
4956 * CRM_Financial_DAO_FinancialTrxn object
4957 * @param array $contribution
4960 public static function assignProportionalLineItems($params, $trxn, $contribution) {
4961 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution_id']);
4962 if (!empty($lineItems)) {
4963 // get financial item
4964 $sql = "SELECT fi.id, li.price_field_value_id
4965 FROM civicrm_financial_item fi
4966 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
4967 WHERE li.contribution_id = %1";
4968 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($params['contribution_id'], 'Integer')));
4969 while ($dao->fetch()) {
4970 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4973 'entity_table' => 'civicrm_financial_item',
4974 'financial_trxn_id' => $trxn->id
,
4976 foreach ($lineItems as $key => $value) {
4977 $paid = $value['line_total'] * ($params['total_amount'] / $contribution['total_amount']);
4978 // Record Entity Financial Trxn
4979 $eftParams['amount'] = round($paid, 2);
4980 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
4982 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
4988 * Function to check line items
4990 * @param array $params
4991 * array of order params.
4994 public static function checkLineItems(&$params) {
4995 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4996 $lineItemAmount = 0;
4997 foreach ($params['line_items'] as &$lineItems) {
4998 foreach ($lineItems['line_item'] as &$item) {
4999 if (empty($item['financial_type_id'])) {
5000 $item['financial_type_id'] = $params['financial_type_id'];
5002 $lineItemAmount +
= $item['line_total'];
5005 if (!isset($totalAmount)) {
5006 $params['total_amount'] = $lineItemAmount;
5008 elseif ($totalAmount != $lineItemAmount) {
5009 throw new API_Exception("Line item total doesn't match with total amount.");
5014 * Get the financial account for the item associated with the new transaction.
5016 * @param array $params
5017 * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem
5021 public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) {
5023 if (!empty($params['financial_account_id'])) {
5024 return $params['financial_account_id'];
5026 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
5027 $preferredAccountsRelationships = array(
5028 'Refunded' => 'Credit/Contra Revenue Account is',
5029 'Chargeback' => 'Chargeback Account is',
5031 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
5032 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
5033 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
5035 $preferredAccountsRelationships[$contributionStatus]
5038 return $prevFinancialItem->financial_account_id
;
5042 * ContributionPage values were being imposed onto values.
5044 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
5045 * REALLY didn't want superimposed. The rest are left there in their overkill out
5048 * The rationale for making this explicit is that it was a case of carefully set values being
5049 * seemingly randonly overwritten without much care. In general I think array randomly setting
5050 * variables en mass is risky.
5052 * @param array $values
5056 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
5057 $contributionPageValues = array();
5058 CRM_Contribute_BAO_ContributionPage
::setValues(
5059 $this->contribution_page_id
,
5060 $contributionPageValues
5062 $valuesToCopy = array(
5063 // These are the values that I believe to be useful.
5067 'pay_later_receipt',
5069 'receipt_from_email',
5070 'receipt_from_name',
5074 'honoree_profile_id',
5075 'onbehalf_profile_id',
5076 'honor_block_is_active',
5077 // Kinda might be - but would be on the contribution...
5080 // Included for 'fear of regression' but can't justify any use for these....
5082 'payment_processor',
5083 'financial_type_id',
5084 'amount_block_is_active',
5089 'default_amount_id',
5093 'initial_amount_help_text',
5094 'initial_amount_label',
5096 'is_allow_other_amount',
5097 'is_billing_required',
5098 'is_confirm_enabled',
5099 'is_credit_card_only',
5101 'is_partial_payment',
5102 'is_recur_installments',
5103 'is_recur_interval',
5107 'min_initial_amount',
5108 'recur_frequency_unit',
5115 foreach ($valuesToCopy as $valueToCopy) {
5116 if (isset($contributionPageValues[$valueToCopy])) {
5117 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5124 * Get values of CiviContribute Settings
5125 * and check if its enabled or not.
5126 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5127 * in serialized form. Usually this should be stored as flat settings for each form fields
5128 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5129 * settings we will live with an inconsistency because it's too hard to change for now.
5130 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5133 * @param string $name
5137 public static function checkContributeSettings($name = NULL) {
5138 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5141 return CRM_Utils_Array
::value($name, $contributeSettings);
5143 return $contributeSettings;
5147 * This function process contribution related objects.
5149 * @param int $contributionId
5150 * @param int $statusId
5151 * @param int|null $previousStatusId
5153 * @param string $receiveDate
5155 * @return null|string
5157 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5159 if (!$contributionId ||
!$statusId) {
5164 'contribution_id' => $contributionId,
5165 'contribution_status_id' => $statusId,
5166 'previous_contribution_status_id' => $previousStatusId,
5167 'receive_date' => $receiveDate,
5170 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5172 if (!is_array($updateResult) ||
5173 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5174 !is_array($updatedComponents) ||
5175 empty($updatedComponents)
5180 // get the user display name.
5182 SELECT display_name as displayName
5183 FROM civicrm_contact
5184 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5185 WHERE civicrm_contribution.id = {$contributionId}";
5186 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5188 // get the status message for user.
5189 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5191 if ($componentName == 'CiviMember') {
5192 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5193 CRM_Member_PseudoConstant
::membershipStatus()
5195 if ($updatedStatusName == 'Cancelled') {
5196 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
5198 elseif ($updatedStatusName == 'Expired') {
5199 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
5202 $endDate = CRM_Utils_Array
::value('membership_end_date', $updateResult);
5204 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
5206 1 => $userDisplayName,
5214 if ($componentName == 'CiviEvent') {
5215 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5216 CRM_Event_PseudoConstant
::participantStatus()
5218 if ($updatedStatusName == 'Cancelled') {
5219 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
5221 elseif ($updatedStatusName == 'Registered') {
5222 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
5226 if ($componentName == 'CiviPledge') {
5227 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5228 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5230 if ($updatedStatusName == 'Cancelled') {
5231 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
5233 elseif ($updatedStatusName == 'Failed') {
5234 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
5236 elseif ($updatedStatusName == 'Completed') {
5237 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
5246 * Get the contribution as it is in the database before being updated.
5248 * @param int $contributionID
5252 private static function getOriginalContribution($contributionID) {
5253 return self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
5257 * Assign Test Value.
5259 * @param string $fieldName
5260 * @param array $fieldDef
5261 * @param int $counter
5263 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5264 if ($fieldName == 'tax_amount') {
5265 $this->{$fieldName} = "0.00";
5267 elseif ($fieldName == 'net_amount') {
5268 $this->{$fieldName} = "2.00";
5270 elseif ($fieldName == 'total_amount') {
5271 $this->{$fieldName} = "3.00";
5273 elseif ($fieldName == 'fee_amount') {
5274 $this->{$fieldName} = "1.00";
5277 parent
::assignTestValues($fieldName, $fieldDef, $counter);