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'));
155 self
::calculateMissingAmountParams($params, $contributionID);
157 if (!empty($params['payment_instrument_id'])) {
158 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
159 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
160 $params['check_number'] = 'null';
164 $setPrevContribution = TRUE;
165 // CRM-13964 partial payment
166 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
167 $partialAmtTotal = $params['partial_payment_total'];
168 $partialAmtPay = $params['partial_amount_pay'];
169 $params['total_amount'] = $partialAmtTotal;
170 if ($partialAmtPay < $partialAmtTotal) {
171 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
172 $params['is_pay_later'] = 0;
173 $setPrevContribution = FALSE;
176 if ($contributionID && $setPrevContribution) {
177 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
180 if ($contributionID) {
181 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
184 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
186 $contribution = new CRM_Contribute_BAO_Contribution();
187 $contribution->copyValues($params);
189 $contribution->id
= $contributionID;
191 if (empty($contribution->id
)) {
192 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
193 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
194 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
198 $result = $contribution->save();
200 // Add financial_trxn details as part of fix for CRM-4724
201 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
202 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
204 //add Account details
205 $params['contribution'] = $contribution;
206 self
::recordFinancialAccounts($params);
208 if (self
::isUpdateToRecurringContribution($params)) {
209 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
210 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
211 $contributionStatus[$params['contribution_status_id']]
215 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
217 if ($contributionID) {
218 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
221 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
228 * Is this contribution updating an existing recurring contribution.
230 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
231 * pending payment is being confirmed (or failing).
233 * @param array $params
237 public static function isUpdateToRecurringContribution($params) {
238 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
241 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
244 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
247 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
248 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
255 * Get defaults for new entity.
258 public static function getDefaults() {
260 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
261 FALSE, FALSE, FALSE, 'AND is_default = 1')
263 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
268 * Fetch the object and store the values in the values array.
270 * @param array $params
271 * Input parameters to find object.
272 * @param array $values
273 * Output values of the object.
275 * The array that holds all the db ids.
277 * @return CRM_Contribute_BAO_Contribution|null
278 * The found object or null
280 public static function getValues($params, &$values, &$ids) {
281 if (empty($params)) {
284 $contribution = new CRM_Contribute_BAO_Contribution();
286 $contribution->copyValues($params);
288 if ($contribution->find(TRUE)) {
289 $ids['contribution'] = $contribution->id
;
291 CRM_Core_DAO
::storeValues($contribution, $values);
293 return $contribution;
295 $null = NULL; // return by reference
300 * Get the values and resolve the most common mappings.
302 * Since contribution status is resolved in almost every function that calls getValues it makes
303 * sense to have an extra function to resolve it rather than repeat the code.
305 * Think carefully before adding more mappings to be resolved as there could be performance implications
306 * if this function starts to be called from more iterative functions.
308 * @param array $params
309 * Input parameters to find object.
312 * Array of the found contribution.
313 * @throws CRM_Core_Exception
315 public static function getValuesWithMappings($params) {
316 $values = $ids = array();
317 $contribution = self
::getValues($params, $values, $ids);
318 if (is_null($contribution)) {
319 throw new CRM_Core_Exception('No contribution found');
321 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
326 * Calculate net_amount & fee_amount if they are not set.
328 * Net amount should be total - fee.
329 * This should only be called for new contributions.
331 * @param array $params
332 * Params for a new contribution before they are saved.
333 * @param int|null $contributionID
334 * Contribution ID if we are dealing with an update.
336 * @throws \CiviCRM_API3_Exception
338 public static function calculateMissingAmountParams(&$params, $contributionID) {
339 if (!$contributionID && !isset($params['fee_amount'])) {
340 if (isset($params['total_amount']) && isset($params['net_amount'])) {
341 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
344 $params['fee_amount'] = 0;
347 if (!isset($params['net_amount'])) {
348 if (!$contributionID) {
349 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
352 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
353 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
354 // net_amount may need adjusting.
355 $contribution = civicrm_api3('Contribution', 'getsingle', array(
356 'id' => $contributionID,
357 'return' => array('total_amount', 'net_amount'),
359 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
360 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
361 $params['net_amount'] = $totalAmount - $feeAmount;
369 * @param $billingLocationTypeID
373 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
374 $hasBillingField = FALSE;
375 $billingFields = array(
383 //build address array
384 $addressParams = array();
385 $addressParams['location_type_id'] = $billingLocationTypeID;
386 $addressParams['is_billing'] = 1;
388 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
389 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
390 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
391 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
393 foreach ($billingFields as $value) {
394 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
395 if (!empty($addressParams[$value])) {
396 $hasBillingField = TRUE;
399 return array($hasBillingField, $addressParams);
403 * Get address params ready to be passed to the payment processor.
405 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
406 * To create an address we need state_province_id.
408 * @param array $params
409 * @param int $billingLocationTypeID
413 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
414 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
415 foreach ($addressParams as $name => $field) {
416 if (substr($name, 0, 8) == 'billing_') {
417 $addressParams[substr($name, 9)] = $addressParams[$field];
420 return array($hasBillingField, $addressParams);
424 * Get the number of terms for this contribution for a given membership type
425 * based on querying the line item table and relevant price field values
426 * Note that any one contribution should only be able to have one line item relating to a particular membership
429 * @param int $membershipTypeID
431 * @param int $contributionID
435 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
436 $numTerms = CRM_Core_DAO
::singleValueQuery("
437 SELECT membership_num_terms FROM civicrm_line_item li
438 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
439 WHERE contribution_id = %1 AND membership_type_id = %2",
440 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
442 // default of 1 is precautionary
443 return empty($numTerms) ?
1 : $numTerms;
447 * Takes an associative array and creates a contribution object.
449 * @param array $params
450 * (reference ) an assoc array of name/value pairs.
452 * The array that holds all the db ids.
454 * @return CRM_Contribute_BAO_Contribution
456 public static function create(&$params, $ids = array()) {
457 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
458 foreach ($dateFields as $df) {
459 if (isset($params[$df])) {
460 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
464 //if contribution is created with cancelled or refunded status, add credit note id
465 if (!empty($params['contribution_status_id'])) {
466 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
468 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
469 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
471 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
472 $params['creditnote_id'] = self
::createCreditNoteId();
477 $transaction = new CRM_Core_Transaction();
479 $contribution = self
::add($params, $ids);
481 if (is_a($contribution, 'CRM_Core_Error')) {
482 $transaction->rollback();
483 return $contribution;
486 $params['contribution_id'] = $contribution->id
;
488 if (!empty($params['custom']) &&
489 is_array($params['custom'])
491 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
494 $session = CRM_Core_Session
::singleton();
496 if (!empty($params['note'])) {
498 'entity_table' => 'civicrm_contribution',
499 'note' => $params['note'],
500 'entity_id' => $contribution->id
,
501 'contact_id' => $session->get('userID'),
502 'modified_date' => date('Ymd'),
504 if (!$noteParams['contact_id']) {
505 $noteParams['contact_id'] = $params['contact_id'];
507 CRM_Core_BAO_Note
::add($noteParams);
510 // make entry in batch entity batch table
511 if (!empty($params['batch_id'])) {
512 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
513 $titleFields = array(
519 $retrieveRequired = 0;
520 foreach ($titleFields as $titleField) {
521 if (!isset($contribution->$titleField)) {
522 $retrieveRequired = 1;
526 if ($retrieveRequired == 1) {
527 $contribution->find(TRUE);
531 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
533 $transaction->commit();
535 // check if activity record exist for this contribution, if
537 $activity = new CRM_Activity_DAO_Activity();
538 $activity->source_record_id
= $contribution->id
;
539 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
544 //CRM-18406: Update activity when edit contribution.
545 if ($activity->find(TRUE)) {
546 // CRM-13237 : if activity record found, update it with campaign id of contribution
547 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
548 $contribution->activity_id
= $activity->id
;
550 if (empty($contribution->contact_id
)) {
551 $contribution->find(TRUE);
553 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
555 // do not add to recent items for import, CRM-4399
556 if (empty($params['skipRecentView'])) {
557 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
558 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
560 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
561 $titleFields = array(
567 $retrieveRequired = 0;
568 foreach ($titleFields as $titleField) {
569 if (!isset($contribution->$titleField)) {
570 $retrieveRequired = 1;
574 if ($retrieveRequired == 1) {
575 $contribution->find(TRUE);
577 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
578 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
580 $recentOther = array();
581 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
582 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
583 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
587 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
588 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
589 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
593 // add the recently created Contribution
594 CRM_Utils_Recent
::add($title,
598 $contribution->contact_id
,
604 return $contribution;
608 * Get the values for pseudoconstants for name->value and reverse.
610 * @param array $defaults
611 * (reference) the default values, some of which need to be resolved.
612 * @param bool $reverse
613 * True if we want to resolve the values in the reverse direction (value -> name).
615 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
616 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
617 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
618 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
619 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
623 * Convert associative array names to values and vice-versa.
625 * This function is used by both the web form layer and the api. Note that
626 * the api needs the name => value conversion, also the view layer typically
627 * requires value => name conversion
629 * @param array $defaults
630 * @param string $property
631 * @param array $lookup
632 * @param bool $reverse
636 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
637 $id = $property . '_id';
639 $src = $reverse ?
$property : $id;
640 $dst = $reverse ?
$id : $property;
642 if (!array_key_exists($src, $defaults)) {
646 $look = $reverse ?
array_flip($lookup) : $lookup;
648 if (is_array($look)) {
649 if (!array_key_exists($defaults[$src], $look)) {
653 $defaults[$dst] = $look[$defaults[$src]];
658 * Retrieve DB object based on input parameters.
660 * It also stores all the retrieved values in the default array.
662 * @param array $params
663 * (reference ) an assoc array of name/value pairs.
664 * @param array $defaults
665 * (reference ) an assoc array to hold the name / value pairs.
666 * in a hierarchical manner
668 * (reference) the array that holds all the db ids.
670 * @return CRM_Contribute_BAO_Contribution
672 public static function retrieve(&$params, &$defaults, &$ids) {
673 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
674 return $contribution;
678 * Combine all the importable fields from the lower levels object.
680 * The ordering is important, since currently we do not have a weight
681 * scheme. Adding weight is super important and should be done in the
682 * next week or so, before this can be called complete.
684 * @param string $contactType
685 * @param bool $status
688 * array of importable Fields
690 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
691 if (!self
::$_importableFields) {
692 if (!self
::$_importableFields) {
693 self
::$_importableFields = array();
697 $fields = array('' => array('title' => ts('- do not import -')));
700 $fields = array('' => array('title' => ts('- Contribution Fields -')));
703 $note = CRM_Core_DAO_Note
::import();
704 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
705 unset($tmpFields['option_value']);
706 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
707 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
709 // Using new Dedupe rule.
711 'contact_type' => $contactType,
712 'used' => 'Unsupervised',
714 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
715 $tmpContactField = array();
716 if (is_array($fieldsArray)) {
717 foreach ($fieldsArray as $value) {
718 //skip if there is no dupe rule
719 if ($value == 'none') {
722 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
727 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
728 $tmpContactField[trim($value)] = $contactFields[trim($value)];
730 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
733 $title = $tmpContactField[trim($value)]['title'];
735 $tmpContactField[trim($value)]['title'] = $title;
739 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
740 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
741 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
742 $fields = array_merge($fields, $tmpContactField);
743 $fields = array_merge($fields, $tmpFields);
744 $fields = array_merge($fields, $note);
745 $fields = array_merge($fields, $optionFields);
746 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
747 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
748 self
::$_importableFields = $fields;
750 return self
::$_importableFields;
754 * Combine all the exportable fields from the lower level objects.
756 * @param bool $checkPermission
759 * array of exportable Fields
761 public static function &exportableFields($checkPermission = TRUE) {
762 if (!self
::$_exportableFields) {
763 if (!self
::$_exportableFields) {
764 self
::$_exportableFields = array();
767 $impFields = CRM_Contribute_DAO_Contribution
::export();
768 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
769 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
770 $typeField = CRM_Financial_DAO_FinancialType
::export();
771 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
772 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
773 $contributionStatus = array(
774 'contribution_status' => array(
775 'title' => ts('Contribution Status'),
776 'name' => 'contribution_status',
777 'data_type' => CRM_Utils_Type
::T_STRING
,
781 $contributionPage = array(
782 'contribution_page' => array(
783 'title' => ts('Contribution Page'),
784 'name' => 'contribution_page',
785 'where' => 'civicrm_contribution_page.title',
786 'data_type' => CRM_Utils_Type
::T_STRING
,
790 $contributionNote = array(
791 'contribution_note' => array(
792 'title' => ts('Contribution Note'),
793 'name' => 'contribution_note',
794 'data_type' => CRM_Utils_Type
::T_TEXT
,
798 $contributionRecurId = array(
799 'contribution_recur_id' => array(
800 'title' => ts('Recurring Contributions ID'),
801 'name' => 'contribution_recur_id',
802 'where' => 'civicrm_contribution.contribution_recur_id',
803 'data_type' => CRM_Utils_Type
::T_INT
,
807 $extraFields = array(
808 'contribution_batch' => array(
809 'title' => ts('Batch Name'),
814 $campaignTitle = array(
815 'contribution_campaign_title' => array(
816 'title' => ts('Campaign Title'),
817 'name' => 'campaign_title',
818 'where' => 'civicrm_campaign.title',
819 'data_type' => CRM_Utils_Type
::T_STRING
,
822 $softCreditFields = array(
823 'contribution_soft_credit_name' => array(
824 'name' => 'contribution_soft_credit_name',
825 'title' => 'Soft Credit For',
826 'where' => 'civicrm_contact_d.display_name',
827 'data_type' => CRM_Utils_Type
::T_STRING
,
829 'contribution_soft_credit_amount' => array(
830 'name' => 'contribution_soft_credit_amount',
831 'title' => 'Soft Credit Amount',
832 'where' => 'civicrm_contribution_soft.amount',
833 'data_type' => CRM_Utils_Type
::T_MONEY
,
835 'contribution_soft_credit_type' => array(
836 'name' => 'contribution_soft_credit_type',
837 'title' => 'Soft Credit Type',
838 'where' => 'contribution_softcredit_type.label',
839 'data_type' => CRM_Utils_Type
::T_STRING
,
841 'contribution_soft_credit_contribution_id' => array(
842 'name' => 'contribution_soft_credit_contribution_id',
843 'title' => 'Soft Credit For Contribution ID',
844 'where' => 'civicrm_contribution_soft.contribution_id',
845 'data_type' => CRM_Utils_Type
::T_INT
,
847 'contribution_soft_credit_contact_id' => array(
848 'name' => 'contribution_soft_credit_contact_id',
849 'title' => 'Soft Credit For Contact ID',
850 'where' => 'civicrm_contact_d.id',
851 'data_type' => CRM_Utils_Type
::T_INT
,
855 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
857 'contribution_product_id' => array(
858 'title' => ts('Premium'),
859 'name' => 'contribution_product_id',
860 'where' => 'civicrm_product.id',
861 'data_type' => CRM_Utils_Type
::T_INT
,
865 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
866 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
867 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
870 self
::$_exportableFields = $fields;
873 return self
::$_exportableFields;
877 * @param null $status
878 * @param null $startDate
879 * @param null $endDate
883 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
887 $where[] = 'contribution_status_id = 1';
891 $where[] = 'contribution_status_id = 3';
896 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
899 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
901 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
902 if ($financialTypes) {
903 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
904 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
907 $where[] = "c.financial_type_id IN (0)";
910 $whereCond = implode(' AND ', $where);
913 SELECT sum( total_amount ) as total_amount,
914 count( c.id ) as total_count,
916 FROM civicrm_contribution c
917 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
918 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
920 AND ( is_test = 0 OR is_test IS NULL )
921 AND contact.is_deleted = 0
925 $dao = CRM_Core_DAO
::executeQuery($query);
928 while ($dao->fetch()) {
929 $count +
= $dao->total_count
;
930 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
934 'amount' => implode(', ', $amount),
942 * Delete the indirect records associated with this contribution first.
947 * $results no of deleted Contribution on success, false otherwise
949 public static function deleteContribution($id) {
950 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
952 $transaction = new CRM_Core_Transaction();
955 //delete activity record
957 'source_record_id' => $id,
958 // activity type id for contribution
959 'activity_type_id' => 6,
962 CRM_Activity_BAO_Activity
::deleteActivity($params);
964 //delete billing address if exists for this contribution.
965 self
::deleteAddress($id);
967 //update pledge and pledge payment, CRM-3961
968 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
970 // remove entry from civicrm_price_set_entity, CRM-5095
971 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
972 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
974 // cleanup line items.
975 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
977 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
978 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
980 if ($participantId) {
981 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
984 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
988 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
989 $noteId = key($note);
991 CRM_Core_BAO_Note
::del($noteId, FALSE);
994 $dao = new CRM_Contribute_DAO_Contribution();
997 $results = $dao->delete();
999 $transaction->commit();
1001 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1003 // delete the recently created Contribution
1004 $contributionRecent = array(
1006 'type' => 'Contribution',
1008 CRM_Utils_Recent
::del($contributionRecent);
1014 * React to a financial transaction (payment) failure.
1016 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1017 * payments is important for forensic and outreach reasons.
1019 * @param int $contributionID
1020 * @param int $contactID
1021 * @param string $message
1023 * @throws \CiviCRM_API3_Exception
1025 public static function failPayment($contributionID, $contactID, $message) {
1026 civicrm_api3('activity', 'create', array(
1027 'activity_type_id' => 'Failed Payment',
1028 'details' => $message,
1029 'subject' => ts('Payment failed at payment processor'),
1030 'source_record_id' => $contributionID,
1031 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1037 * Check if there is a contribution with the same trxn_id or invoice_id.
1039 * @param array $input
1040 * An assoc array of name/value pairs.
1041 * @param array $duplicates
1042 * (reference) store ids of duplicate contribs.
1046 * true if duplicate, false otherwise
1048 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1050 $id = CRM_Utils_Array
::value('id', $input);
1052 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1053 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1059 $clause[] = "trxn_id = %1";
1060 $input[1] = array($trxn_id, 'String');
1064 $clause[] = "invoice_id = %2";
1065 $input[2] = array($invoice_id, 'String');
1068 if (empty($clause)) {
1072 $clause = implode(' OR ', $clause);
1074 $clause = "( $clause ) AND id != %3";
1075 $input[3] = array($id, 'Integer');
1078 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1079 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1081 while ($dao->fetch()) {
1082 $duplicates[] = $dao->id
;
1089 * Takes an associative array and creates a contribution_product object.
1091 * the function extract all the params it needs to initialize the create a
1092 * contribution_product object. the params array could contain additional unused name/value
1095 * @param array $params
1096 * (reference) an assoc array of name/value pairs.
1098 * @return CRM_Contribute_DAO_ContributionProduct
1100 public static function addPremium(&$params) {
1101 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1102 $contributionProduct->copyValues($params);
1103 return $contributionProduct->save();
1107 * Get list of contribution fields for profile.
1108 * For now we only allow custom contribution fields to be in
1111 * @param bool $addExtraFields
1112 * True if special fields needs to be added.
1115 * the list of contribution fields
1117 public static function getContributionFields($addExtraFields = TRUE) {
1118 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1119 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1121 if ($addExtraFields) {
1122 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1125 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1127 foreach ($contributionFields as $key => $var) {
1128 if ($key == 'contribution_contact_id') {
1131 elseif ($key == 'contribution_campaign_id') {
1132 $var['title'] = ts('Campaign');
1134 $fields[$key] = $var;
1137 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1142 * Add extra fields specific to contribution.
1144 public static function getSpecialContributionFields() {
1145 $extraFields = array(
1146 'contribution_soft_credit_name' => array(
1147 'name' => 'contribution_soft_credit_name',
1148 'title' => 'Soft Credit Name',
1149 'headerPattern' => '/^soft_credit_name$/i',
1150 'where' => 'civicrm_contact_d.display_name',
1152 'contribution_soft_credit_email' => array(
1153 'name' => 'contribution_soft_credit_email',
1154 'title' => 'Soft Credit Email',
1155 'headerPattern' => '/^soft_credit_email$/i',
1156 'where' => 'soft_email.email',
1158 'contribution_soft_credit_phone' => array(
1159 'name' => 'contribution_soft_credit_phone',
1160 'title' => 'Soft Credit Phone',
1161 'headerPattern' => '/^soft_credit_phone$/i',
1162 'where' => 'soft_phone.phone',
1164 'contribution_soft_credit_contact_id' => array(
1165 'name' => 'contribution_soft_credit_contact_id',
1166 'title' => 'Soft Credit Contact ID',
1167 'headerPattern' => '/^soft_credit_contact_id$/i',
1168 'where' => 'civicrm_contribution_soft.contact_id',
1170 'contribution_pcp_title' => array(
1171 'name' => 'contribution_pcp_title',
1172 'title' => 'Personal Campaign Page Title',
1173 'headerPattern' => '/^contribution_pcp_title$/i',
1174 'where' => 'contribution_pcp.title',
1178 return $extraFields;
1182 * @param int $pageID
1186 public static function getCurrentandGoalAmount($pageID) {
1188 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1189 FROM civicrm_contribution_page p,
1190 civicrm_contribution c
1191 WHERE p.id = c.contribution_page_id
1193 AND c.cancel_date is null
1197 $config = CRM_Core_Config
::singleton();
1198 $params = array(1 => array($pageID, 'Integer'));
1199 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1201 if ($dao->fetch()) {
1202 return array($dao->goal
, $dao->total
);
1205 return array(NULL, NULL);
1210 * Get list of contributions which credit the passed in contact ID.
1212 * The returned array provides details about the original contribution & donor.
1214 * @todo - this is a confusing function called from one place. It has a test. It would be
1215 * nice to deprecate it.
1217 * @param int $honorId
1218 * In Honor of Contact ID.
1221 * list of contribution fields
1223 public static function getHonorContacts($honorId) {
1225 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1226 $honorDAO->contact_id
= $honorId;
1229 $type = CRM_Contribute_PseudoConstant
::financialType();
1231 while ($honorDAO->fetch()) {
1232 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1233 $contributionDAO->id
= $honorDAO->contribution_id
;
1235 if ($contributionDAO->find(TRUE)) {
1236 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1237 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1238 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1239 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1240 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1241 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1242 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1243 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1244 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1252 * Get the sort name of a contact for a particular contribution.
1255 * Id of the contribution.
1257 * @return null|string
1258 * sort name of the contact if found
1260 public static function sortName($id) {
1261 $id = CRM_Utils_Type
::escape($id, 'Integer');
1264 SELECT civicrm_contact.sort_name
1265 FROM civicrm_contribution, civicrm_contact
1266 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1267 AND civicrm_contribution.id = {$id}
1269 return CRM_Core_DAO
::singleValueQuery($query);
1273 * @param int $contactID
1277 public static function annual($contactID) {
1278 if (is_array($contactID)) {
1279 $contactIDs = implode(',', $contactID);
1282 $contactIDs = $contactID;
1285 $config = CRM_Core_Config
::singleton();
1286 $startDate = $endDate = NULL;
1288 $currentMonth = date('m');
1289 $currentDay = date('d');
1290 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1291 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1292 (int ) $config->fiscalYearStart
['d'] > $currentDay
1295 $year = date('Y') - 1;
1300 $nextYear = $year +
1;
1302 if ($config->fiscalYearStart
) {
1303 $newFiscalYearStart = $config->fiscalYearStart
;
1304 if ($newFiscalYearStart['M'] < 10) {
1305 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1307 if ($newFiscalYearStart['d'] < 10) {
1308 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1310 $config->fiscalYearStart
= $newFiscalYearStart;
1311 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1316 $startDate = "$year$monthDay";
1317 $endDate = "$nextYear$monthDay";
1318 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1319 $additionalWhere = " AND b.financial_type_id IN (0)";
1320 $liWhere = " AND i.financial_type_id IN (0)";
1321 if (!empty($financialTypes)) {
1322 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1323 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1326 SELECT count(*) as count,
1327 sum(total_amount) as amount,
1328 avg(total_amount) as average,
1330 FROM civicrm_contribution b
1331 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1332 WHERE b.contact_id IN ( $contactIDs )
1333 AND b.contribution_status_id = 1
1335 AND b.receive_date >= $startDate
1336 AND b.receive_date < $endDate
1340 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1342 $amount = $average = array();
1343 while ($dao->fetch()) {
1344 if ($dao->count
> 0 && $dao->amount
> 0) {
1345 $count +
= $dao->count
;
1346 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1347 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1353 implode(', ', $amount),
1354 implode(', ', $average),
1357 return array(0, 0, 0);
1361 * Check if there is a contribution with the params passed in.
1363 * Used for trxn_id,invoice_id and contribution_id
1365 * @param array $params
1366 * An assoc array of name/value pairs.
1369 * contribution id if success else NULL
1371 public static function checkDuplicateIds($params) {
1372 $dao = new CRM_Contribute_DAO_Contribution();
1376 foreach ($params as $k => $v) {
1378 $clause[] = "$k = '$v'";
1381 $clause = implode(' AND ', $clause);
1382 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1383 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1385 while ($dao->fetch()) {
1393 * Get the contribution details for component export.
1395 * @param int $exportMode
1397 * @param string $componentIds
1403 public static function getContributionDetails($exportMode, $componentIds) {
1404 $paymentDetails = array();
1405 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1407 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1408 $componentSelect = " civicrm_participant_payment.participant_id id";
1409 $additionalClause = "
1410 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1411 AND civicrm_participant_payment.participant_id {$componentClause} )
1414 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1415 $componentSelect = " civicrm_membership_payment.membership_id id";
1416 $additionalClause = "
1417 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1418 AND civicrm_membership_payment.membership_id {$componentClause} )
1421 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1422 $componentSelect = " civicrm_pledge_payment.id id";
1423 $additionalClause = "
1424 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1425 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1429 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1430 trxn_id, {$componentSelect}
1431 FROM civicrm_contribution
1432 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1433 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1434 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1435 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1436 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1437 AND option_group_contribution_status.id = contribution_status.option_group_id )
1441 $dao = CRM_Core_DAO
::executeQuery($query);
1443 while ($dao->fetch()) {
1444 $paymentDetails[$dao->id
] = array(
1445 'total_amount' => $dao->total_amount
,
1446 'contribution_status' => $dao->status
,
1447 'receive_date' => $dao->receive_date
,
1448 'pay_instru' => $dao->payment_instrument
,
1449 'trxn_id' => $dao->trxn_id
,
1453 return $paymentDetails;
1457 * Create address associated with contribution record.
1459 * As long as there is one or more billing field in the parameters we will create the address.
1461 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1464 * @param array $params
1465 * @param int $billingLocationTypeID
1470 public static function createAddress($params, $billingLocationTypeID) {
1471 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1472 if ($hasBillingField) {
1473 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1474 return $address->id
;
1481 * Delete billing address record related contribution.
1483 * @param int $contributionId
1484 * @param int $contactId
1486 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1488 $contactJoin = NULL;
1490 if ($contributionId) {
1491 $clauses[] = "cc.id = {$contributionId}";
1495 $clauses[] = "cco.id = {$contactId}";
1496 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1499 if (empty($clauses)) {
1500 CRM_Core_Error
::fatal();
1503 $condition = implode(' OR ', $clauses);
1507 FROM civicrm_address ca
1508 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1512 $dao = CRM_Core_DAO
::executeQuery($query);
1514 while ($dao->fetch()) {
1515 $params = array('id' => $dao->id
);
1516 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1521 * This function check online pending contribution associated w/
1522 * Online Event Registration or Online Membership signup.
1524 * @param int $componentId
1525 * Participant/membership id.
1526 * @param string $componentName
1530 * pending contribution id.
1532 public static function checkOnlinePendingContribution($componentId, $componentName) {
1533 $contributionId = NULL;
1534 if (!$componentId ||
1535 !in_array($componentName, array('Event', 'Membership'))
1537 return $contributionId;
1540 if ($componentName == 'Event') {
1541 $idName = 'participant_id';
1542 $componentTable = 'civicrm_participant';
1543 $paymentTable = 'civicrm_participant_payment';
1544 $source = ts('Online Event Registration');
1547 if ($componentName == 'Membership') {
1548 $idName = 'membership_id';
1549 $componentTable = 'civicrm_membership';
1550 $paymentTable = 'civicrm_membership_payment';
1551 $source = ts('Online Contribution');
1554 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1557 SELECT component.id as {$idName},
1558 componentPayment.contribution_id as contribution_id,
1559 contribution.source source,
1560 contribution.contribution_status_id as contribution_status_id,
1561 contribution.is_pay_later as is_pay_later
1562 FROM $componentTable component
1563 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1564 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1565 WHERE component.id = {$componentId}";
1567 $dao = CRM_Core_DAO
::executeQuery($query);
1569 while ($dao->fetch()) {
1570 if ($dao->contribution_id
&&
1571 $dao->is_pay_later
&&
1572 $dao->contribution_status_id
== $pendingStatusId &&
1573 strpos($dao->source
, $source) !== FALSE
1575 $contributionId = $dao->contribution_id
;
1580 return $contributionId;
1584 * Update contribution as well as related objects.
1586 * This function by-passes hooks - to address this - don't use this function.
1590 * Use api contribute.completetransaction
1591 * For failures use failPayment (preferably exposing by api in the process).
1593 * @param array $params
1594 * @param bool $processContributionObject
1597 * @throws \Exception
1599 public static function transitionComponents($params, $processContributionObject = FALSE) {
1600 // get minimum required values.
1601 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1602 $componentId = CRM_Utils_Array
::value('component_id', $params);
1603 $componentName = CRM_Utils_Array
::value('componentName', $params);
1604 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1605 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1607 // if we already processed contribution object pass previous status id.
1608 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1610 $updateResult = array();
1612 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1614 // we process only ( Completed, Cancelled, or Failed ) contributions.
1615 if (!$contributionId ||
1616 !in_array($contributionStatusId, array(
1617 array_search('Completed', $contributionStatuses),
1618 array_search('Cancelled', $contributionStatuses),
1619 array_search('Failed', $contributionStatuses),
1622 return $updateResult;
1625 if (!$componentName ||
!$componentId) {
1626 // get the related component details.
1627 $componentDetails = self
::getComponentDetails($contributionId);
1630 $componentDetails['contact_id'] = $contactId;
1631 $componentDetails['component'] = $componentName;
1633 if ($componentName == 'event') {
1634 $componentDetails['participant'] = $componentId;
1637 $componentDetails['membership'] = $componentId;
1641 if (!empty($componentDetails['contact_id'])) {
1642 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1648 // do check for required ids.
1649 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1650 return $updateResult;
1653 //now we are ready w/ required ids, start processing.
1655 $baseIPN = new CRM_Core_Payment_BaseIPN();
1657 $input = $ids = $objects = array();
1659 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1660 $ids['contribution'] = $contributionId;
1661 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1662 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1663 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1664 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1665 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1666 $ids['contributionRecur'] = NULL;
1667 $ids['contributionPage'] = NULL;
1669 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1670 CRM_Core_Error
::fatal();
1673 $memberships = &$objects['membership'];
1674 $participant = &$objects['participant'];
1675 $pledgePayment = &$objects['pledge_payment'];
1676 $contribution = &$objects['contribution'];
1678 if ($pledgePayment) {
1679 $pledgePaymentIDs = array();
1680 foreach ($pledgePayment as $key => $object) {
1681 $pledgePaymentIDs[] = $object->id
;
1683 $pledgeID = $pledgePayment[0]->pledge_id
;
1686 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1689 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1690 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1695 // we might want to process contribution object.
1696 $processContribution = FALSE;
1697 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1698 if (is_array($memberships)) {
1699 foreach ($memberships as $membership) {
1701 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1702 $membership->save();
1704 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1705 if ($processContributionObject) {
1706 $processContribution = TRUE;
1713 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1714 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1716 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1717 if ($processContributionObject) {
1718 $processContribution = TRUE;
1722 if ($pledgePayment) {
1723 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1725 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1726 if ($processContributionObject) {
1727 $processContribution = TRUE;
1731 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1732 if (is_array($memberships)) {
1733 foreach ($memberships as $membership) {
1735 $membership->status_id
= array_search('Expired', $membershipStatuses);
1736 $membership->save();
1738 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1739 if ($processContributionObject) {
1740 $processContribution = TRUE;
1746 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1747 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1749 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1750 if ($processContributionObject) {
1751 $processContribution = TRUE;
1755 if ($pledgePayment) {
1756 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1758 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1759 if ($processContributionObject) {
1760 $processContribution = TRUE;
1764 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1766 // only pending contribution related object processed.
1767 if ($previousContriStatusId &&
1768 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1770 // this is case when we already processed contribution object.
1771 return $updateResult;
1773 elseif (!$previousContriStatusId &&
1774 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1776 // this is case when we are going to process contribution object later.
1777 return $updateResult;
1780 if (is_array($memberships)) {
1781 foreach ($memberships as $membership) {
1786 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1787 $membership->membership_type_id
,
1788 $membership->is_test
, $membership->id
1791 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1792 // this picks up membership type changes during renewals
1794 SELECT membership_type_id
1795 FROM civicrm_membership_log
1796 WHERE membership_id=$membership->id
1799 $dao = new CRM_Core_DAO();
1801 if ($dao->fetch()) {
1802 if (!empty($dao->membership_type_id
)) {
1803 $membership->membership_type_id
= $dao->membership_type_id
;
1804 $membership->save();
1807 // else fall back to using current membership type
1810 // Figure out number of terms
1812 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1813 foreach ($lineitems as $lineitem) {
1814 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1815 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1817 // in case membership_num_terms comes through as null or zero
1818 $numterms = $numterms >= 1 ?
$numterms : 1;
1823 // CRM-15735-to update the membership status as per the contribution receive date
1825 if (!empty($params['receive_date'])) {
1826 $joinDate = $params['receive_date'];
1827 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1828 $membership->end_date
,
1829 $membership->join_date
,
1830 $params['receive_date'],
1832 $membership->membership_type_id
,
1835 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1836 $membership->save();
1839 if ($currentMembership) {
1840 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1841 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1842 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1845 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1848 //get the status for membership.
1849 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1851 $dates['join_date'],
1854 $membership->membership_type_id
,
1858 $formattedParams = array(
1859 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1860 array_search('Current', $membershipStatuses)
1862 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1863 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1864 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1867 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1869 $membership->copyValues($formattedParams);
1870 $membership->save();
1872 //updating the membership log
1873 $membershipLog = array();
1874 $membershipLog = $formattedParams;
1875 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1876 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1878 $membershipLog['start_date'] = $logStartDate;
1879 $membershipLog['membership_id'] = $membership->id
;
1880 $membershipLog['modified_id'] = $membership->contact_id
;
1881 $membershipLog['modified_date'] = date('Ymd');
1882 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1884 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1886 //update related Memberships.
1887 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1889 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1892 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1893 if ($processContributionObject) {
1894 $processContribution = TRUE;
1897 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1903 $updatedStatusId = array_search('Registered', $participantStatuses);
1904 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1906 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1907 if ($processContributionObject) {
1908 $processContribution = TRUE;
1912 if ($pledgePayment) {
1913 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1915 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1916 if ($processContributionObject) {
1917 $processContribution = TRUE;
1922 // process contribution object.
1923 if ($processContribution) {
1924 $contributionParams = array();
1931 'payment_instrument_id',
1934 'financial_type_id',
1935 'contribution_status_id',
1936 'non_deductible_amount',
1940 foreach ($fields as $field) {
1941 if (empty($params[$field])) {
1944 $contributionParams[$field] = $params[$field];
1947 $ids = array('contribution' => $contributionId);
1948 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1951 return $updateResult;
1955 * Returns all contribution related object ids.
1957 * @param $contributionId
1961 public static function getComponentDetails($contributionId) {
1962 $componentDetails = $pledgePayment = array();
1963 if (!$contributionId) {
1964 return $componentDetails;
1968 SELECT c.id as contribution_id,
1969 c.contact_id as contact_id,
1970 c.contribution_recur_id,
1971 mp.membership_id as membership_id,
1972 m.membership_type_id as membership_type_id,
1973 pp.participant_id as participant_id,
1974 p.event_id as event_id,
1975 pgp.id as pledge_payment_id
1976 FROM civicrm_contribution c
1977 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1978 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1979 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1980 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1981 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1982 WHERE c.id = $contributionId";
1984 $dao = CRM_Core_DAO
::executeQuery($query);
1985 $componentDetails = array();
1987 while ($dao->fetch()) {
1988 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1989 $componentDetails['contact_id'] = $dao->contact_id
;
1990 if ($dao->event_id
) {
1991 $componentDetails['event'] = $dao->event_id
;
1993 if ($dao->participant_id
) {
1994 $componentDetails['participant'] = $dao->participant_id
;
1996 if ($dao->membership_id
) {
1997 if (!isset($componentDetails['membership'])) {
1998 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2000 $componentDetails['membership'][] = $dao->membership_id
;
2001 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2003 if ($dao->pledge_payment_id
) {
2004 $pledgePayment[] = $dao->pledge_payment_id
;
2006 if ($dao->contribution_recur_id
) {
2007 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2011 if ($pledgePayment) {
2012 $componentDetails['pledge_payment'] = $pledgePayment;
2015 return $componentDetails;
2019 * @param int $contactId
2020 * @param bool $includeSoftCredit
2022 * @return null|string
2024 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2028 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
2029 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2030 $liWhere = " AND i.financial_type_id IN (0)";
2031 if (!empty($financialTypes)) {
2032 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2033 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2035 $contactContributionsSQL = "
2036 SELECT contribution.id AS id
2037 FROM civicrm_contribution contribution
2038 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2039 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2043 $contactSoftCreditContributionsSQL = "
2044 SELECT contribution.id
2045 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2046 ON ( contribution.id = softContribution.contribution_id )
2047 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2048 $query = "SELECT count( x.id ) count FROM ( ";
2049 $query .= $contactContributionsSQL;
2051 if ($includeSoftCredit) {
2052 $query .= " UNION ";
2053 $query .= $contactSoftCreditContributionsSQL;
2058 return CRM_Core_DAO
::singleValueQuery($query);
2062 * Repeat a transaction as part of a recurring series.
2064 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2065 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2066 * subsequent call to the contribution.completetransaction api.
2068 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2070 * @param CRM_Contribute_BAO_Contribution $contribution
2071 * @param array $input
2072 * @param array $contributionParams
2073 * @param int $paymentProcessorID
2076 * @throws CiviCRM_API3_Exception
2078 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2079 if (!empty($contribution->id
)) {
2082 if (empty($contribution->id
)) {
2083 // Unclear why this would only be set for repeats.
2084 if (!empty($input['amount'])) {
2085 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2087 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorID;
2089 if (!empty($contributionParams['contribution_recur_id'])) {
2090 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2091 'id' => $contributionParams['contribution_recur_id'],
2093 if (!empty($recurringContribution['campaign_id'])) {
2094 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2095 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2097 if (!empty($recurringContribution['financial_type_id'])) {
2098 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2099 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2102 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2103 $contributionParams['contribution_recur_id'],
2104 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2106 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2108 $contributionParams['status_id'] = 'Pending';
2109 if (isset($contributionParams['financial_type_id'])) {
2110 // Give precedence to passed in type.
2111 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2114 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2116 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2117 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2119 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2120 $contribution->id
= $createContribution['id'];
2121 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2127 * Get individual id for onbehalf contribution.
2129 * @param int $contributionId
2131 * @param int $contributorId
2135 * containing organization id and individual id
2137 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2141 if (!$contributionId) {
2145 // fetch contributor id if null
2146 if (!$contributorId) {
2147 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2148 $contributionId, 'contact_id'
2152 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2153 $activityTypeId = array_search('Contribution', $activityTypeIds);
2155 if ($activityTypeId && $contributorId) {
2157 SELECT civicrm_activity_contact.contact_id
2158 FROM civicrm_activity_contact
2159 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2160 WHERE civicrm_activity.activity_type_id = %1
2161 AND civicrm_activity.source_record_id = %2
2162 AND civicrm_activity_contact.record_type_id = %3
2165 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2166 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2169 1 => array($activityTypeId, 'Integer'),
2170 2 => array($contributionId, 'Integer'),
2171 3 => array($sourceID, 'Integer'),
2174 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2176 // for on behalf contribution source is individual and contributor is organization
2177 if ($sourceContactId && $sourceContactId != $contributorId) {
2178 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2179 // get rel type id for employee of relation
2180 foreach ($relationshipTypeIds as $id => $typeVals) {
2181 if ($typeVals['name_a_b'] == 'Employee of') {
2182 $relationshipTypeId = $id;
2187 $rel = new CRM_Contact_DAO_Relationship();
2188 $rel->relationship_type_id
= $relationshipTypeId;
2189 $rel->contact_id_a
= $sourceContactId;
2190 $rel->contact_id_b
= $contributorId;
2191 if ($rel->find(TRUE)) {
2192 $ids['individual_id'] = $rel->contact_id_a
;
2193 $ids['organization_id'] = $rel->contact_id_b
;
2204 public static function getContributionDates() {
2205 $config = CRM_Core_Config
::singleton();
2206 $currentMonth = date('m');
2207 $currentDay = date('d');
2208 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2209 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2210 (int ) $config->fiscalYearStart
['d'] > $currentDay
2213 $year = date('Y') - 1;
2218 $year = array('Y' => $year);
2219 $yearDate = $config->fiscalYearStart
;
2220 $yearDate = array_merge($year, $yearDate);
2221 $yearDate = CRM_Utils_Date
::format($yearDate);
2223 $monthDate = date('Ym') . '01';
2229 'yearDate' => $yearDate,
2230 'monthDate' => $monthDate,
2235 * Load objects relations to contribution object.
2236 * Objects are stored in the $_relatedObjects property
2237 * In the first instance we are just moving functionality from BASEIpn -
2238 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2240 * Note that the unit test for the BaseIPN class tests this function
2242 * @param array $input
2243 * Input as delivered from Payment Processor.
2245 * Ids as Loaded by Payment Processor.
2246 * @param bool $loadAll
2247 * Load all related objects - even where id not passed in? (allows API to call this).
2252 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2254 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2255 if (empty($ids['contact']) && isset($this->contact_id
)) {
2256 $ids['contact'] = $this->contact_id
;
2259 if (empty($this->_component
)) {
2260 if (!empty($ids['event'])) {
2261 $this->_component
= 'event';
2264 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2268 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2269 // refactoring than anything else, and has unit test coverage.
2270 if (empty($this->financial_type_id
)) {
2274 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2279 if (!$paymentProcessorID && $this->contribution_page_id
) {
2280 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2281 $this->contribution_page_id
,
2284 if ($paymentProcessorID) {
2285 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2289 $ids['contributionType'] = $this->financial_type_id
;
2290 $ids['financialType'] = $this->financial_type_id
;
2293 'contact' => 'CRM_Contact_BAO_Contact',
2294 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2295 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2296 'financialType' => 'CRM_Financial_BAO_FinancialType',
2298 foreach ($entities as $entity => $bao) {
2299 if (!empty($ids[$entity])) {
2300 $this->_relatedObjects
[$entity] = new $bao();
2301 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2302 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2303 throw new CRM_Core_Exception($entity . ' could not be loaded');
2308 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2309 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2312 if (!empty($ids['pledge_payment'])) {
2313 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2314 if (empty($paymentID)) {
2317 $payment = new CRM_Pledge_BAO_PledgePayment();
2318 $payment->id
= $paymentID;
2319 if (!$payment->find(TRUE)) {
2320 throw new Exception("Could not find pledge payment record: " . $paymentID);
2322 $this->_relatedObjects
['pledge_payment'][] = $payment;
2326 $this->loadRelatedMembershipObjects($ids);
2328 if ($this->_component
!= 'contribute') {
2329 // we are in event mode
2330 // make sure event exists and is valid
2331 $event = new CRM_Event_BAO_Event();
2332 $event->id
= $ids['event'];
2333 if ($ids['event'] &&
2336 throw new Exception("Could not find event: " . $ids['event']);
2339 $this->_relatedObjects
['event'] = &$event;
2341 $participant = new CRM_Event_BAO_Participant();
2342 $participant->id
= $ids['participant'];
2343 if ($ids['participant'] &&
2344 !$participant->find(TRUE)
2346 throw new Exception("Could not find participant: " . $ids['participant']);
2348 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2350 $this->_relatedObjects
['participant'] = &$participant;
2352 // get the payment processor id from event - this is inaccurate see CRM-16923
2353 // in future we should look at throwing an exception here rather than an dubious guess.
2354 if (!$paymentProcessorID) {
2355 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2356 if ($paymentProcessorID) {
2357 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2362 if ($paymentProcessorID) {
2363 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2364 $this->is_test ?
'test' : 'live'
2366 $ids['paymentProcessor'] = $paymentProcessorID;
2367 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2373 * Create array of message information - ie. return html version, txt version, to field
2375 * @param array $input
2376 * Incoming information.
2377 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2378 * just check presence of recur object but maintaining legacy approach
2381 * IDs of related objects.
2382 * @param array $values
2383 * Any values that may have already been compiled by calling process.
2384 * This is augmented by values 'gathered' by gatherMessageValues
2385 * @param bool $recur
2386 * @param bool $returnMessageText
2387 * Distinguishes between whether to send message or return.
2388 * message text. We are working towards this function ALWAYS returning message text & calling
2389 * function doing emails / pdfs with it
2395 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2396 $this->loadRelatedObjects($input, $ids);
2398 if (empty($this->_component
)) {
2399 $this->_component
= CRM_Utils_Array
::value('component', $input);
2402 //not really sure what params might be passed in but lets merge em into values
2403 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2404 if (!empty($input['receipt_date'])) {
2405 $values['receipt_date'] = $input['receipt_date'];
2408 $template = CRM_Core_Smarty
::singleton();
2409 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2410 //what does recur 'mean here - to do with payment processor return functionality but
2411 // what is the importance
2412 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2413 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2415 $entityID = $entity = NULL;
2416 if (isset($ids['contribution'])) {
2417 $entity = 'contribution';
2418 $entityID = $ids['contribution'];
2420 if (!empty($ids['membership'])) {
2421 //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
2422 // 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
2423 // line having loaded an array
2424 $ids['membership'] = (array) $ids['membership'];
2425 $entity = 'membership';
2426 $entityID = $ids['membership'][0];
2429 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2430 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2431 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2433 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2434 //direct mode showing billing block, so use directIPN for temporary
2435 $template->assign('contributeMode', 'directIPN');
2438 // todo remove strtolower - check consistency
2439 if (strtolower($this->_component
) == 'event') {
2440 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2441 $values['event'] = array();
2443 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2445 //get location details
2446 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2447 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2449 $ufJoinParams = array(
2450 'entity_table' => 'civicrm_event',
2451 'entity_id' => $ids['event'],
2452 'module' => 'CiviEvent',
2455 list($custom_pre_id,
2457 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2459 $values['custom_pre_id'] = $custom_pre_id;
2460 $values['custom_post_id'] = $custom_post_ids;
2461 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2462 //and cases involving status updation through ipn
2463 // whatever that means!
2464 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2465 // perhaps we should throw an e-notice if amount is set & force total_amount?
2466 if (!empty($input['amount'])) {
2467 $values['totalAmount'] = $input['amount'];
2470 if ($values['event']['is_email_confirm']) {
2471 $values['is_email_receipt'] = 1;
2474 if (!empty($ids['contribution'])) {
2475 $values['contributionId'] = $ids['contribution'];
2478 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2479 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2483 $values['contribution_id'] = $this->id
;
2484 if (!empty($ids['related_contact'])) {
2485 $values['related_contact'] = $ids['related_contact'];
2486 if (isset($ids['onbehalf_dupe_alert'])) {
2487 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2489 $entityBlock = array(
2490 'contact_id' => $ids['contact'],
2491 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2492 'Home', 'id', 'name'
2495 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2496 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2499 if ($this->is_test
) {
2502 if (!empty($this->_relatedObjects
['membership'])) {
2503 foreach ($this->_relatedObjects
['membership'] as $membership) {
2504 if ($membership->id
) {
2505 $values['isMembership'] = TRUE;
2506 $values['membership_assign'] = TRUE;
2508 // need to set the membership values here
2509 $template->assign('membership_name',
2510 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2512 $template->assign('mem_start_date', $membership->start_date
);
2513 $template->assign('mem_join_date', $membership->join_date
);
2514 $template->assign('mem_end_date', $membership->end_date
);
2515 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2516 $template->assign('mem_status', $membership_status);
2517 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2518 $values['is_pay_later'] = 1;
2521 // if separate payment there are two contributions recorded and the
2522 // admin will need to send a receipt for each of them separately.
2523 // we dont link the two in the db (but can potentially infer it if needed)
2524 $template->assign('is_separate_payment', 0);
2526 if ($recur && $paymentObject) {
2527 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2528 $template->assign('cancelSubscriptionUrl', $url);
2529 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2530 $template->assign('updateSubscriptionBillingUrl', $url);
2531 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2532 $template->assign('updateSubscriptionUrl', $url);
2535 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2538 // otherwise if its about sending emails, continue sending without return, as we
2539 // don't want to exit the loop.
2544 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2550 * Gather values for contribution mail - this function has been created
2551 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2552 * Values related to the contribution in question are gathered
2554 * @param array $input
2555 * Input into function (probably from payment processor).
2556 * @param array $values
2558 * The set of ids related to the input.
2562 public function _gatherMessageValues($input, &$values, $ids = array()) {
2563 // set display address of contributor
2564 if ($this->address_id
) {
2565 $addressParams = array('id' => $this->address_id
);
2566 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2567 $addressDetails = array_values($addressDetails);
2569 // Else we assign the billing address of the contribution contact.
2571 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2572 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2573 $addressDetails = array_values($addressDetails);
2576 if (!empty($addressDetails[0]['display'])) {
2577 $values['address'] = $addressDetails[0]['display'];
2580 if ($this->_component
== 'contribute') {
2581 //get soft contributions
2582 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2583 if (!empty($softContributions)) {
2584 $values['softContributions'] = $softContributions['soft_credit'];
2586 if (isset($this->contribution_page_id
)) {
2587 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2588 if ($this->contribution_page_id
) {
2589 // CRM-8254 - override default currency if applicable
2590 $config = CRM_Core_Config
::singleton();
2591 $config->defaultCurrency
= CRM_Utils_Array
::value(
2594 $config->defaultCurrency
2598 // no contribution page -probably back office
2600 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2601 $values['is_email_receipt'] = 1;
2602 $values['title'] = 'Contribution';
2604 // set lineItem for contribution
2606 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2607 if (!empty($lineItem)) {
2608 $itemId = key($lineItem);
2609 foreach ($lineItem as &$eachItem) {
2610 if (isset($this->_relatedObjects
['membership'])
2611 && is_array($this->_relatedObjects
['membership'])
2612 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2613 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2614 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2615 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2618 $values['lineItem'][0] = $lineItem;
2619 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2623 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2627 // if this is onbehalf of contribution then set related contact
2628 if (!empty($relatedContact['individual_id'])) {
2629 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2634 $eventParams = array(
2635 'id' => $this->_relatedObjects
['event']->id
,
2637 $values['event'] = array();
2639 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2640 // add custom fields for event
2641 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2643 $eventCustomGroup = array();
2644 foreach ($eventGroupTree as $key => $group) {
2645 if ($key === 'info') {
2649 foreach ($group['fields'] as $k => $customField) {
2650 $groupLabel = $group['title'];
2651 if (!empty($customField['customValue'])) {
2652 foreach ($customField['customValue'] as $customFieldValues) {
2653 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2658 $values['event']['customGroup'] = $eventCustomGroup;
2660 //get participant details
2661 $participantParams = array(
2662 'id' => $this->_relatedObjects
['participant']->id
,
2665 $values['participant'] = array();
2667 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2668 // add custom fields for event
2669 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2670 $participantCustomGroup = array();
2671 foreach ($participantGroupTree as $key => $group) {
2672 if ($key === 'info') {
2676 foreach ($group['fields'] as $k => $customField) {
2677 $groupLabel = $group['title'];
2678 if (!empty($customField['customValue'])) {
2679 foreach ($customField['customValue'] as $customFieldValues) {
2680 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2685 $values['participant']['customGroup'] = $participantCustomGroup;
2687 //get location details
2688 $locationParams = array(
2689 'entity_id' => $this->_relatedObjects
['event']->id
,
2690 'entity_table' => 'civicrm_event',
2692 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2694 $ufJoinParams = array(
2695 'entity_table' => 'civicrm_event',
2696 'entity_id' => $ids['event'],
2697 'module' => 'CiviEvent',
2700 list($custom_pre_id,
2702 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2704 $values['custom_pre_id'] = $custom_pre_id;
2705 $values['custom_post_id'] = $custom_post_ids;
2707 // set lineItem for event contribution
2709 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2710 if (!empty($participantIds)) {
2711 foreach ($participantIds as $pIDs) {
2712 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2713 if (!CRM_Utils_System
::isNull($lineItem)) {
2714 $values['lineItem'][] = $lineItem;
2721 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2723 $customGroup = array();
2724 foreach ($groupTree as $key => $group) {
2725 if ($key === 'info') {
2729 foreach ($group['fields'] as $k => $customField) {
2730 $groupLabel = $group['title'];
2731 if (!empty($customField['customValue'])) {
2732 foreach ($customField['customValue'] as $customFieldValues) {
2733 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2738 $values['customGroup'] = $customGroup;
2744 * Assign message variables to template but try to break the habit.
2746 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2747 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2748 * multiple recurring payments for processors like IATS that use tokens.
2750 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2751 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2752 * Note we send directly from this function in some cases because it is only partly refactored.
2754 * Don't call this function directly as the signature will change.
2758 * @param CRM_Core_SMARTY $template
2759 * @param bool $recur
2760 * @param bool $returnMessageText
2764 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2765 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2766 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2767 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2768 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2769 $values['useForMember'] = TRUE;
2771 //assign honor information to receipt message
2772 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2774 if (isset($softRecord['soft_credit'])) {
2775 //if id of contribution page is present
2776 if (!empty($values['id'])) {
2777 $values['honor'] = array(
2778 'honor_profile_values' => array(),
2779 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2780 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2782 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2784 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2785 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2788 //offline contribution
2789 $softCreditTypes = $softCredits = array();
2790 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2791 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2792 $softCredits[$key] = array(
2793 'Name' => $softCredit['contact_name'],
2794 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2797 $template->assign('softCreditTypes', $softCreditTypes);
2798 $template->assign('softCredits', $softCredits);
2802 $dao = new CRM_Contribute_DAO_ContributionProduct();
2803 $dao->contribution_id
= $this->id
;
2804 if ($dao->find(TRUE)) {
2805 $premiumId = $dao->product_id
;
2806 $template->assign('option', $dao->product_option
);
2808 $productDAO = new CRM_Contribute_DAO_Product();
2809 $productDAO->id
= $premiumId;
2810 $productDAO->find(TRUE);
2811 $template->assign('selectPremium', TRUE);
2812 $template->assign('product_name', $productDAO->name
);
2813 $template->assign('price', $productDAO->price
);
2814 $template->assign('sku', $productDAO->sku
);
2816 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2817 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2818 if (!$values['amount'] && isset($this->total_amount
)) {
2819 $values['amount'] = $this->total_amount
;
2822 // add the new contribution values
2823 if (strtolower($this->_component
) == 'contribute') {
2825 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2826 $softDAO->contribution_id
= $this->id
;
2827 if ($softDAO->find(TRUE)) {
2828 $template->assign('pcpBlock', TRUE);
2829 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2830 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2831 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2833 //assign the pcp page title for email subject
2834 $pcpDAO = new CRM_PCP_DAO_PCP();
2835 $pcpDAO->id
= $softDAO->pcp_id
;
2836 if ($pcpDAO->find(TRUE)) {
2837 $template->assign('title', $pcpDAO->title
);
2842 if ($this->financial_type_id
) {
2843 $values['financial_type_id'] = $this->financial_type_id
;
2846 $template->assign('trxn_id', $this->trxn_id
);
2847 $template->assign('receive_date',
2848 CRM_Utils_Date
::processDate($this->receive_date
)
2850 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
2851 $template->assign('contributeMode', 'notify');
2852 $template->assign('action', $this->is_test ?
1024 : 1);
2853 $template->assign('receipt_text',
2854 CRM_Utils_Array
::value('receipt_text',
2858 $template->assign('is_monetary', 1);
2859 $template->assign('is_recur', (bool) $recur);
2860 $template->assign('currency', $this->currency
);
2861 $template->assign('address', CRM_Utils_Address
::format($input));
2862 if (!empty($values['customGroup'])) {
2863 $template->assign('customGroup', $values['customGroup']);
2865 if (!empty($values['softContributions'])) {
2866 $template->assign('softContributions', $values['softContributions']);
2868 if ($this->_component
== 'event') {
2869 $template->assign('title', $values['event']['title']);
2870 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2871 $viewRoles = array();
2872 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2873 $viewRoles[] = $participantRoles[$v];
2875 $values['event']['participant_role'] = implode(', ', $viewRoles);
2876 $template->assign('event', $values['event']);
2877 $template->assign('participant', $values['participant']);
2878 $template->assign('location', $values['location']);
2879 $template->assign('customPre', $values['custom_pre_id']);
2880 $template->assign('customPost', $values['custom_post_id']);
2883 if ($this->_relatedObjects
['participant']->is_test
) {
2887 $values['params'] = array();
2888 //to get email of primary participant.
2889 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2890 $primaryAmount[] = array(
2891 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2892 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2894 //build an array of cId/pId of participants
2895 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2896 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2897 //send receipt to additional participant if exists
2898 if (count($additionalIDs)) {
2899 $template->assign('isPrimary', 0);
2900 $template->assign('customProfile', NULL);
2901 //set additionalParticipant true
2902 $values['params']['additionalParticipant'] = TRUE;
2903 foreach ($additionalIDs as $pId => $cId) {
2905 //to change the status pending to completed
2906 $additional = new CRM_Event_DAO_Participant();
2907 $additional->id
= $pId;
2908 $additional->contact_id
= $cId;
2909 $additional->find(TRUE);
2910 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2911 $additional->status_id
= 1;
2912 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2913 //if additional participant dont have email
2915 if (!$additionalParticipantInfo) {
2916 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2918 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2919 $primaryAmount[] = array(
2920 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2921 'amount' => $additional->fee_amount
,
2923 $additional->save();
2924 $additional->free();
2925 $template->assign('amount', $amount);
2926 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2930 //build an array of custom profile and assigning it to template
2931 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2933 if (count($customProfile)) {
2934 $template->assign('customProfile', $customProfile);
2937 // for primary contact
2938 $values['params']['additionalParticipant'] = FALSE;
2939 $template->assign('isPrimary', 1);
2940 $template->assign('amount', $primaryAmount);
2941 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2942 if ($this->payment_instrument_id
) {
2943 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2944 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2946 // carry paylater, since we did not created billing,
2947 // so need to pull email from primary location, CRM-4395
2948 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2954 * Check whether payment processor supports
2955 * cancellation of contribution subscription
2957 * @param int $contributionId
2960 * @param bool $isNotCancelled
2964 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2965 $cacheKeyString = "$contributionId";
2966 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2968 static $supportsCancel = array();
2970 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2971 $supportsCancel[$cacheKeyString] = FALSE;
2972 $isCancelled = FALSE;
2974 if ($isNotCancelled) {
2975 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2978 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2979 if (!empty($paymentObject)) {
2980 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
2983 return $supportsCancel[$cacheKeyString];
2987 * Check whether subscription is already cancelled.
2989 * @param int $contributionId
2993 * contribution status
2995 public static function isSubscriptionCancelled($contributionId) {
2997 SELECT cr.contribution_status_id
2998 FROM civicrm_contribution_recur cr
2999 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3000 WHERE con.id = %1 LIMIT 1";
3001 $params = array(1 => array($contributionId, 'Integer'));
3002 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3003 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3004 if ($status == 'Cancelled') {
3011 * Create all financial accounts entry.
3013 * @param array $params
3014 * Contribution object, line item array and params for trxn.
3017 * @param array $financialTrxnValues
3019 * @return null|object
3021 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3022 $skipRecords = $update = $return = $isRelatedId = FALSE;
3024 $additionalParticipantId = array();
3025 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3026 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3028 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3029 $entityId = $params['participant_id'];
3030 $entityTable = 'civicrm_participant';
3031 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3033 elseif (!empty($params['membership_id'])) {
3034 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3035 // are created off one contribution should be handled elsewhere
3036 $entityId = $params['membership_id'];
3037 $entityTable = 'civicrm_membership';
3040 $entityId = $params['contribution']->id
;
3041 $entityTable = 'civicrm_contribution';
3044 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3045 $isRelatedId = TRUE;
3048 $entityID[] = $entityId;
3049 if (!empty($additionalParticipantId)) {
3050 $entityID +
= $additionalParticipantId;
3052 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3053 if (empty($params['prevContribution'])) {
3060 $statusId = $params['contribution']->contribution_status_id
;
3061 // CRM-13964 partial payment
3062 if ($contributionStatus == 'Partially paid'
3063 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3065 $partialAmtPay = $params['partial_amount_pay'];
3066 $partialAmtTotal = $params['partial_payment_total'];
3068 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3069 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3070 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3071 $params['total_amount'] = $partialAmtPay;
3073 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3074 if (empty($balanceTrxnInfo['trxn_id'])) {
3075 // create new balance transaction record
3076 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3077 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3079 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3080 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3081 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3082 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3083 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3084 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3085 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3086 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3087 $balanceTrxnParams['status_id'] = $statusId;
3088 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3089 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3090 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3091 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3093 $balanceTrxnParams['is_payment'] = 1;
3095 if (!empty($params['payment_processor'])) {
3096 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3098 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3102 // build line item array if its not set in $params
3103 if (empty($params['line_item']) ||
$additionalParticipantId) {
3104 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3107 if ($contributionStatus != 'Failed' &&
3108 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3110 $skipRecords = TRUE;
3111 $pendingStatus = array(
3115 if (in_array($contributionStatus, $pendingStatus)) {
3116 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3117 $params['financial_type_id'],
3118 'Accounts Receivable Account is'
3121 elseif (!empty($params['payment_processor'])) {
3122 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3124 elseif (!empty($params['payment_instrument_id'])) {
3125 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3128 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3129 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3130 $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);
3133 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3134 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3135 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3138 //build financial transaction params
3139 $trxnParams = array(
3140 'contribution_id' => $params['contribution']->id
,
3141 'to_financial_account_id' => $params['to_financial_account_id'],
3142 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3143 'total_amount' => $totalAmount,
3144 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3145 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3146 'currency' => $params['contribution']->currency
,
3147 'trxn_id' => $params['contribution']->trxn_id
,
3148 'status_id' => $statusId,
3149 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
3150 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3152 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback') {
3153 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3154 if (isset($params['refund_trxn_id'])) {
3155 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3156 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3159 //CRM-16259, set is_payment flag for non pending status
3160 if (!in_array($contributionStatus, $pendingStatus)) {
3161 $trxnParams['is_payment'] = 1;
3163 if (!empty($params['payment_processor'])) {
3164 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3167 if (isset($fromFinancialAccountId)) {
3168 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3171 // consider external values passed for recording transaction entry
3172 if (!empty($financialTrxnValues)) {
3173 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3176 $params['trxnParams'] = $trxnParams;
3178 if (!empty($params['prevContribution'])) {
3180 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3181 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3182 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3183 if (!isset($params['trxnParams']['trxn_id'])) {
3184 // Actually I have no idea why we are overwriting any values from the previous contribution.
3185 // (filling makes sense to me). However, only protecting this value as I really really know we
3186 // don't want this one overwritten.
3188 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3190 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3192 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3193 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3194 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3196 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3197 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3200 //if financial type is changed
3201 if (!empty($params['financial_type_id']) &&
3202 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3204 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3205 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3206 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3207 if ($oldFinancialAccount != $newFinancialAccount) {
3208 $params['total_amount'] = 0;
3209 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3210 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3211 $params['prevContribution']->financial_type_id
, $relationTypeId);
3214 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3215 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3216 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3219 self
::updateFinancialAccounts($params, 'changeFinancialType');
3220 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3221 $params['financial_account_id'] = $newFinancialAccount;
3222 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3223 self
::updateFinancialAccounts($params);
3224 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3229 //Update contribution status
3230 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3231 if (!isset($params['refund_trxn_id'])) {
3232 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3233 // gets preference over another so I am only 'protecting' a very specific tested flow
3234 // and letting natural justice take care of the rest.
3235 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3237 if (!empty($params['contribution_status_id']) &&
3238 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3240 //Update Financial Records
3241 self
::updateFinancialAccounts($params, 'changedStatus');
3245 // change Payment Instrument for a Completed contribution
3246 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3247 // instrument is null and now new payment instrument is added along with the payment
3248 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3249 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3250 if (array_key_exists('payment_instrument_id', $params)) {
3251 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3252 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3253 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3255 //check if status is changed from Pending to Completed
3256 // do not update payment instrument changes for Pending to Completed
3257 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3258 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3260 // for all other statuses create new financial records
3261 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3262 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3263 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3267 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3268 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3269 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3271 // for any other payment instrument changes create new financial records
3272 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3273 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3274 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3277 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3278 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3280 // another special case when check number is changed, create new financial records
3281 // create financial trxn with negative amount
3282 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3283 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3284 // create financial trxn with positive amount
3285 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3286 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3287 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3292 //if Change contribution amount
3293 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3294 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3295 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3296 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3297 if (isset($totalAmount) &&
3298 $totalAmount != $params['prevContribution']->total_amount
3300 //Update Financial Records
3301 $params['trxnParams']['from_financial_account_id'] = NULL;
3302 self
::updateFinancialAccounts($params, 'changedAmount');
3307 // Looks like we might have a data correction update.
3308 // This would be a case where a transaction id has been entered but it is incorrect &
3309 // the person goes back in & fixes it, as opposed to a new transaction.
3310 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3311 // the data fix scenario.
3313 if (isset($params['refund_trxn_id'])) {
3314 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3315 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3316 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3323 // records finanical trxn and entity financial trxn
3324 // also make it available as return value
3325 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3326 $params['entity_id'] = $financialTxn->id
;
3329 // record line items and financial items
3330 if (empty($params['skipLineItem'])) {
3331 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3334 // create batch entry if batch_id is passed and
3335 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3336 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3337 $entityParams = array(
3338 'batch_id' => $params['batch_id'],
3339 'entity_table' => 'civicrm_financial_trxn',
3340 'entity_id' => $financialTxn->id
,
3342 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3345 // when a fee is charged
3346 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3347 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3350 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3351 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3353 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3354 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3355 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3357 unset($params['line_item']);
3363 * Update all financial accounts entry.
3365 * @param array $params
3366 * Contribution object, line item array and params for trxn.
3368 * @param string $context
3371 * @param null $skipTrxn
3374 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3375 $itemAmount = $trxnID = NULL;
3376 //get all the statuses
3377 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3378 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3379 if (($previousContributionStatus == 'Pending'
3380 ||
$previousContributionStatus == 'In Progress')
3381 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3382 && $context == 'changePaymentInstrument'
3386 if ((($previousContributionStatus == 'Partially paid'
3387 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3388 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3389 && $params['contribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus)))
3390 && $context == 'changedStatus'
3394 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3395 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3397 if ($context == 'changedStatus') {
3398 //get all the statuses
3399 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3400 $cancelledTaxAmount = 0;
3401 if ($previousContributionStatus == 'Completed'
3402 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3404 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3405 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $params, '0.00');
3406 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3407 $creditNoteId = self
::createCreditNoteId();
3408 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3411 elseif (($previousContributionStatus == 'Pending'
3412 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3414 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3415 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3416 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3418 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3419 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3420 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3421 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3422 $creditNoteId = self
::createCreditNoteId();
3423 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3427 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3430 $itemAmount = $params['trxnParams']['total_amount'] +
$cancelledTaxAmount;
3432 elseif ($context == 'changePaymentInstrument') {
3433 if ($params['trxnParams']['total_amount'] < 0) {
3434 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3435 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3436 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3437 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3441 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3442 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3446 if ($context == 'changedStatus') {
3447 if (($previousContributionStatus == 'Pending'
3448 ||
$previousContributionStatus == 'In Progress')
3449 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3451 if (empty($params['line_item'])) {
3453 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3454 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3455 // & this can be removed
3458 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3459 $params['entity_id'] = $trxn->id
;
3460 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3461 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3463 $entityParams = array(
3464 'entity_table' => 'civicrm_financial_item',
3465 'financial_trxn_id' => $trxn->id
,
3467 foreach ($params['line_item'] as $fieldId => $fields) {
3468 foreach ($fields as $fieldValueId => $fieldValues) {
3470 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3471 2 => array($fieldValues['id'], 'Integer'),
3473 CRM_Core_DAO
::executeQuery($query, $fparams);
3475 1 => array($fieldValues['id'], 'Integer'),
3477 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3478 while ($financialItem->fetch()) {
3479 $entityParams['entity_id'] = $financialItem->id
;
3480 $entityParams['amount'] = $financialItem->amount
;
3481 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3489 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3490 $params['entity_id'] = $trxn->id
;
3491 if ($context != 'changePaymentInstrument') {
3492 $itemParams['entity_table'] = 'civicrm_line_item';
3493 $trxnIds['id'] = $params['entity_id'];
3494 foreach ($params['line_item'] as $fieldId => $fields) {
3495 foreach ($fields as $fieldValueId => $fieldValues) {
3496 $prevParams['entity_id'] = $fieldValues['id'];
3497 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3499 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3500 if ($params['contribution']->receive_date
) {
3501 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3504 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem);
3506 $currency = $params['prevContribution']->currency
;
3507 if ($params['contribution']->currency
) {
3508 $currency = $params['contribution']->currency
;
3511 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($params['contribution']->contribution_status_id
)) {
3514 if (!empty($params['is_quick_config'])) {
3515 $amount = $itemAmount;
3517 $amount = $params['total_amount'];
3521 $amount = $diff * $fieldValues['line_total'];
3524 $itemParams = array(
3525 'transaction_date' => $receiveDate,
3526 'contact_id' => $params['prevContribution']->contact_id
,
3527 'currency' => $currency,
3528 'amount' => $amount,
3529 'description' => $prevFinancialItem->description
,
3530 'status_id' => $prevFinancialItem->status_id
,
3531 'financial_account_id' => $financialAccount,
3532 'entity_table' => 'civicrm_line_item',
3533 'entity_id' => $fieldValues['id'],
3535 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3537 if ($fieldValues['tax_amount']) {
3538 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3539 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3540 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3541 $itemParams['description'] = $taxTerm;
3542 if ($fieldValues['financial_type_id']) {
3543 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3545 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3550 if ($context == 'changeFinancialType') {
3551 $params['skipLineItem'] = FALSE;
3552 foreach ($params['line_item'] as &$lineItems) {
3553 foreach ($lineItems as &$line) {
3554 $line['financial_type_id'] = $params['financial_type_id'];
3561 * Is this contribution status a reversal.
3563 * If so we would expect to record a negative value in the financial_trxn table.
3565 * @param int $status_id
3569 public static function isContributionStatusNegative($status_id) {
3570 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3571 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3575 * Check status validation on update of a contribution.
3577 * @param array $values
3578 * Previous form values before submit.
3580 * @param array $fields
3581 * The input form values.
3583 * @param array $errors
3588 public static function checkStatusValidation($values, &$fields, &$errors) {
3589 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3590 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3591 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3595 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3596 $checkStatus = array(
3597 'Cancelled' => array('Completed', 'Refunded'),
3598 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3599 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3600 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3601 'Refunded' => array('Cancelled', 'Completed'),
3602 'Partially paid' => array('Completed'),
3605 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3606 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3608 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3609 1 => $contributionStatuses[$values['contribution_status_id']],
3610 2 => $contributionStatuses[$fields['contribution_status_id']],
3616 * Delete contribution of contact.
3620 * @param int $contactId
3624 public static function deleteContactContribution($contactId) {
3625 $contribution = new CRM_Contribute_DAO_Contribution();
3626 $contribution->contact_id
= $contactId;
3627 $contribution->find();
3628 while ($contribution->fetch()) {
3629 self
::deleteContribution($contribution->id
);
3634 * Get options for a given contribution field.
3635 * @see CRM_Core_DAO::buildOptions
3637 * @param string $fieldName
3638 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3639 * @param array $props whatever is known about this dao object.
3641 * @return array|bool
3643 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3644 $className = __CLASS__
;
3646 switch ($fieldName) {
3647 // This field is not part of this object but the api supports it
3648 case 'payment_processor':
3649 $className = 'CRM_Contribute_BAO_ContributionPage';
3650 // Filter results by contribution page
3651 if (!empty($props['contribution_page_id'])) {
3652 $page = civicrm_api('contribution_page', 'getsingle', array(
3654 'id' => ($props['contribution_page_id']),
3656 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3657 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3661 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3662 case 'honor_type_id':
3663 $className = 'CRM_Contribute_BAO_ContributionSoft';
3664 $fieldName = 'soft_credit_type_id';
3665 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3668 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3672 * Validate financial type.
3676 * @param int $financialTypeId
3677 * Financial Type id.
3679 * @param string $relationName
3681 * @return array|bool
3683 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3684 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3685 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3687 if (!$financialAccount) {
3688 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3695 * Function to record additional payment for partial and refund contributions.
3697 * @param int $contributionId
3698 * is the invoice contribution id (got created after processing participant payment).
3699 * @param array $trxnsData
3700 * to take user provided input of transaction details.
3701 * @param string $paymentType
3702 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3703 * @param int $participantId
3705 * @return null|object
3707 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3708 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3709 $getInfoOf['id'] = $contributionId;
3710 $defaults = array();
3711 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3712 if (!$participantId) {
3713 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id');
3716 if ($paymentType == 'owed') {
3717 // build params for recording financial trxn entry
3718 $params['contribution'] = $contributionDAO;
3719 $params = array_merge($defaults, $params);
3720 $params['skipLineItem'] = TRUE;
3721 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3722 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3723 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3724 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3727 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3728 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3729 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3731 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3732 if (!empty($trxnId)) {
3733 $trxnId = $trxnId['trxn_id'];
3735 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3736 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3739 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3740 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3741 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3745 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3746 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3747 FROM civicrm_financial_trxn ft
3748 LEFT JOIN civicrm_entity_financial_trxn eft
3749 ON (ft.id = eft.financial_trxn_id)
3750 WHERE eft.entity_table = 'civicrm_contribution'
3751 AND eft.entity_id = {$contributionId}
3752 AND ft.to_financial_account_id != {$toFinancialAccount}
3753 AND ft.status_id = {$statusId}
3755 $query = CRM_Core_DAO
::executeQuery($sql);
3757 $sumOfPayments = $query->sum_of_payments
;
3760 if ($contributionDAO->total_amount
== $sumOfPayments) {
3761 // update contribution status and
3762 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3763 $contributionDAO->contribution_status_id
= $statusId;
3764 $contributionDAO->cancel_date
= 'null';
3765 $contributionDAO->cancel_reason
= NULL;
3766 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3767 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3768 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3769 $contributionDAO->save();
3771 //Change status of financial record too
3772 $financialTrxn->status_id
= $statusId;
3773 $financialTrxn->save();
3775 // note : not using the self::add method,
3776 // the reason because it performs 'status change' related code execution for financial records
3777 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3778 // are coded below i.e. just updating financial_item status to 'Paid'
3780 if ($participantId) {
3781 // update participant status
3782 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3783 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3784 foreach ($ids as $val) {
3785 $participantUpdate['id'] = $val;
3786 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3787 CRM_Event_BAO_Participant
::add($participantUpdate);
3791 // update financial item statuses
3792 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3793 $paidStatus = array_search('Paid', $financialItemStatus);
3795 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3796 $sqlFinancialItemUpdate = "
3797 UPDATE civicrm_financial_item fi
3798 LEFT JOIN civicrm_entity_financial_trxn eft
3799 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3800 SET status_id = {$paidStatus}
3801 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3803 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3806 elseif ($paymentType == 'refund') {
3807 // build params for recording financial trxn entry
3808 $params['contribution'] = $contributionDAO;
3809 $params = array_merge($defaults, $params);
3810 $params['skipLineItem'] = TRUE;
3811 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3812 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3814 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3815 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3816 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3818 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3820 // note : not using the self::add method,
3821 // the reason because it performs 'status change' related code execution for financial records
3822 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3823 // are coded below i.e. just updating financial_item status to 'Paid'
3824 if ($updateStatus) {
3825 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3827 // add financial item entry
3828 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3829 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionDAO->id
);
3830 if (!empty($lineItems)) {
3831 foreach ($lineItems as $lineItemId => $lineItemValue) {
3832 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount
/ $contributionDAO->total_amount
);
3833 $addFinancialEntry = array(
3834 'transaction_date' => $financialTrxn->trxn_date
,
3835 'contact_id' => $contributionDAO->contact_id
,
3836 'amount' => round($paid, 2),
3837 'status_id' => array_search('Paid', $financialItemStatus),
3838 'entity_id' => $lineItemId,
3839 'entity_table' => 'civicrm_line_item',
3841 $trxnIds['id'] = $financialTrxn->id
;
3842 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3845 if ($participantId) {
3846 // update participant status
3847 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3848 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3849 foreach ($ids as $val) {
3850 $participantUpdate['id'] = $val;
3851 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3852 CRM_Event_BAO_Participant
::add($participantUpdate);
3857 // activity creation
3858 if (!empty($financialTrxn)) {
3859 if ($participantId) {
3860 $inputParams['id'] = $participantId;
3863 $component = 'event';
3864 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3865 $entityObj = $entityObj[$participantId];
3867 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3869 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3871 return $financialTrxn;
3877 * @param $activityType
3879 * @param int $contributionId
3881 * @throws CRM_Core_Exception
3883 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3884 if ($component == 'event') {
3885 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3886 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3887 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3888 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3889 $targetCid = $entityObj->contact_id
;
3890 // source record id would be the contribution id
3891 $srcRecId = $contributionId;
3895 $activityParams = array(
3896 'source_contact_id' => $targetCid,
3897 'source_record_id' => $srcRecId,
3898 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3902 'subject' => $subject,
3903 'activity_date_time' => $date,
3904 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3908 'skipRecentView' => TRUE,
3911 // create activity with target contacts
3912 $session = CRM_Core_Session
::singleton();
3913 $id = $session->get('userID');
3915 $activityParams['source_contact_id'] = $id;
3916 $activityParams['target_contact_id'][] = $targetCid;
3918 CRM_Activity_BAO_Activity
::create($activityParams);
3922 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3926 * @param bool $getTrxnInfo
3927 * @param bool $usingLineTotal
3931 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3932 if ($component == 'event') {
3933 $entity = 'participant';
3934 $entityTable = 'civicrm_participant';
3935 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3937 if (!$contributionId) {
3938 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3939 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3940 $id = $primaryParticipantId;
3942 if (!$contributionId) {
3948 $contributionId = $id;
3949 $entity = 'contribution';
3950 $entityTable = 'civicrm_contribution';
3953 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3954 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3960 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3961 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3964 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3965 // for additional participants
3966 if ($entityTable == 'civicrm_participant') {
3967 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3969 foreach ($ids as $val) {
3970 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3974 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3978 $baseTrxnId = $total['trxn_id'];
3979 $total = $total['total_amount'];
3982 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3983 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3985 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3986 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3987 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3989 if ($paymentBalance == 0 && $contributionIsPayLater) {
3990 $paymentBalance = $total;
3993 $info['total'] = $total;
3994 $info['paid'] = $total - $paymentBalance;
3995 $info['balance'] = $paymentBalance;
3997 $info['component'] = $component;
3998 $info['payLater'] = $contributionIsPayLater;
4000 if ($getTrxnInfo && $baseTrxnId) {
4001 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4003 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4005 ft.payment_instrument_id,
4006 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, con.currency
4008 FROM civicrm_contribution con
4009 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4010 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4011 AND ft.to_financial_account_id != {$feeFinancialAccount}
4012 INNER JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4013 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4014 INNER JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4016 WHERE con.id = {$contributionId}
4020 // conditioned WHERE clause
4022 // if balance trxn exists don't include details of it in transaction info
4023 $sql .= " AND ft.id != {$baseTrxnId} ";
4025 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
4027 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4029 while ($resultDAO->fetch()) {
4030 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4031 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4033 'total_amount' => $resultDAO->total_amount
,
4034 'financial_type' => $resultDAO->financial_account
,
4035 'payment_instrument' => $paidByLabel,
4036 'receive_date' => $resultDAO->trxn_date
,
4037 'trxn_id' => $resultDAO->trxn_id
,
4038 'status' => $statuses[$resultDAO->status_id
],
4039 'currency' => $resultDAO->currency
,
4041 if ($paidByName == 'Check') {
4042 $val['check_number'] = $resultDAO->check_number
;
4046 $info['transaction'] = $rows;
4052 * Get financial account id has 'Sales Tax Account is'
4053 * account relationship with financial type
4055 * @param int $financialTypeId
4057 * @return FinancialAccountId
4059 public static function getFinancialAccountId($financialTypeId) {
4060 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4061 $searchParams = array(
4062 'entity_table' => 'civicrm_financial_type',
4063 'entity_id' => $financialTypeId,
4064 'account_relationship' => $accountRel,
4067 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
4069 return CRM_Utils_Array
::value('financial_account_id', $result);
4075 * @param array $params
4076 * @param bool $isLineItem
4080 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4081 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4083 // Update contribution.
4084 if (!empty($params['id'])) {
4085 $id = $params['id'];
4086 $values = $ids = array();
4087 $contrbutionParams = array('id' => $id);
4088 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
4090 // To assign pervious finantial type on update of contribution
4091 if (!isset($params['financial_type_id'])) {
4092 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
4094 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
4095 // Assisn tax Amount on update of contrbution
4096 if (!empty($prevContributionValue->tax_amount
)) {
4097 $params['tax_amount'] = 'null';
4098 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4099 foreach ($params['line_item'] as $setID => $priceField) {
4100 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4101 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4108 // New Contrbution and update of contribution with tax rate financial type
4109 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4110 empty($params['skipLineItem']) && !$isLineItem
4112 $taxRateParams = $taxRates[$params['financial_type_id']];
4113 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4114 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4116 // Get Line Item on update of contribution
4117 if (isset($params['id'])) {
4118 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4121 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4123 foreach ($params['line_item'] as $setID => $priceField) {
4124 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4125 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4128 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4130 elseif (isset($params['api.line_item.create'])) {
4131 // Update total amount of contribution using lineItem
4132 $taxAmountArray = array();
4133 foreach ($params['api.line_item.create'] as $key => $value) {
4134 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4135 $taxRate = $taxRates[$value['financial_type_id']];
4136 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4137 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4140 $params['tax_amount'] = array_sum($taxAmountArray);
4141 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4144 // update line item of contrbution
4145 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4146 $taxRate = $taxRates[$params['financial_type_id']];
4147 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
4148 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4155 * Check financial type validation on update of a contribution.
4157 * @param Integer $financialTypeId
4158 * Value of latest Financial Type.
4160 * @param Integer $contributionId
4163 * @param array $errors
4168 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4169 if (!empty($financialTypeId)) {
4170 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4171 if ($oldFinancialTypeId == $financialTypeId) {
4175 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4177 '1' => array($contributionId, 'Integer'),
4179 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4180 if ($result->N
> 1) {
4181 $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.');
4186 * Update related pledge payment payments.
4188 * This function has been refactored out of the back office contribution form and may
4189 * still overlap with other functions.
4191 * @param string $action
4192 * @param int $pledgePaymentID
4193 * @param int $contributionID
4194 * @param bool $adjustTotalAmount
4195 * @param float $total_amount
4196 * @param float $original_total_amount
4197 * @param int $contribution_status_id
4198 * @param int $original_contribution_status_id
4200 public static function updateRelatedPledge(
4206 $original_total_amount,
4207 $contribution_status_id,
4208 $original_contribution_status_id
4210 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4214 if ($pledgePaymentID) {
4215 //store contribution id in payment record.
4216 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4219 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4226 if (!$pledgePaymentID) {
4229 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4235 $updatePledgePaymentStatus = FALSE;
4237 // If either the status or the amount has changed we update the pledge status.
4238 if ($action & CRM_Core_Action
::ADD
) {
4239 $updatePledgePaymentStatus = TRUE;
4241 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4242 ($original_total_amount != $total_amount))
4244 $updatePledgePaymentStatus = TRUE;
4247 if ($updatePledgePaymentStatus) {
4248 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4249 array($pledgePaymentID),
4250 $contribution_status_id,
4259 * Compute the stats values
4261 * @param $stat either 'mode' or 'median'
4263 * @param $alias of civicrm_contribution
4265 public static function computeStats($stat, $sql, $alias = NULL) {
4266 $mode = $median = array();
4269 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4270 while ($modeDAO->fetch()) {
4271 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4272 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4281 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4282 foreach ($currencies as $currency => $val) {
4284 $where = "AND {$alias}.currency = '{$currency}'";
4285 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4289 $medianRow = floor($rowCount / 2);
4290 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4296 $medianValue = "SELECT {$alias}.total_amount as median
4298 ORDER BY median LIMIT {$medianRow},{$offset}";
4299 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4300 while ($medianValDAO->fetch()) {
4302 $midValue = $midValue +
$medianValDAO->median
;
4305 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4309 $midValue = $midValue / 2;
4310 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4321 * Is there only one line item attached to the contribution.
4327 * @throws \CiviCRM_API3_Exception
4329 public static function isSingleLineItem($id) {
4330 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4331 return ($lineItemCount == 1);
4335 * Complete an order.
4337 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4339 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4341 * Moving it out of the BaseIPN class is just the first step.
4343 * @param array $input
4345 * @param array $objects
4346 * @param CRM_Core_Transaction $transaction
4348 * @param CRM_Contribute_BAO_Contribution $contribution
4349 * @param bool $isRecurring
4350 * Duplication of param needs review. Only used by AuthorizeNetIPN
4351 * @param int $isFirstOrLastRecurringPayment
4352 * Deprecated param only used by AuthorizeNetIPN.
4354 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4355 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4356 // The previous details are used when calculating line items so keep it before any code that 'does something'
4357 if (!empty($contribution->id
)) {
4358 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4359 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4361 $inputContributionWhiteList = array(
4366 'payment_instrument_id',
4371 'contribution_status_id',
4373 if (self
::isSingleLineItem($primaryContributionID)) {
4374 $inputContributionWhiteList[] = 'financial_type_id';
4377 $participant = CRM_Utils_Array
::value('participant', $objects);
4378 $memberships = CRM_Utils_Array
::value('membership', $objects);
4379 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4380 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4381 $event = CRM_Utils_Array
::value('event', $objects);
4383 $paymentProcessorId = '';
4384 if (isset($objects['paymentProcessor'])) {
4385 if (is_array($objects['paymentProcessor'])) {
4386 $paymentProcessorId = $objects['paymentProcessor']['id'];
4389 $paymentProcessorId = $objects['paymentProcessor']->id
;
4393 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4395 $contributionParams = array_merge(array(
4396 'contribution_status_id' => $completedContributionStatusID,
4397 'source' => self
::getRecurringContributionDescription($contribution, $event),
4398 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4401 if ($recurringContributionID) {
4402 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4404 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4406 if (empty($contributionParams['receive_date']) && $changeDate) {
4407 $contributionParams['receive_date'] = $changeDate;
4410 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4411 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4413 if (is_numeric($memberships)) {
4414 $memberships = array($objects['membership']);
4418 if (isset($input['is_email_receipt'])) {
4419 $values['is_email_receipt'] = $input['is_email_receipt'];
4422 if ($input['component'] == 'contribute') {
4423 if ($contribution->contribution_page_id
) {
4424 // Figure out what we gain from this.
4425 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4427 elseif ($recurContrib && $recurringContributionID) {
4428 $values['amount'] = $recurContrib->amount
;
4429 $values['financial_type_id'] = $objects['contributionType']->id
;
4430 $values['title'] = $source = ts('Offline Recurring Contribution');
4433 if ($recurContrib && $recurringContributionID && !isset($input['is_email_receipt'])) {
4434 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4435 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4436 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4439 if (!empty($memberships)) {
4440 foreach ($memberships as $membershipTypeIdKey => $membership) {
4442 $membershipParams = array(
4443 'id' => $membership->id
,
4444 'contact_id' => $membership->contact_id
,
4445 'is_test' => $membership->is_test
,
4446 'membership_type_id' => $membership->membership_type_id
,
4449 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4450 $membershipParams['membership_type_id'],
4451 $membershipParams['is_test'],
4452 $membershipParams['id']
4455 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4456 // this picks up membership type changes during renewals
4458 SELECT membership_type_id
4459 FROM civicrm_membership_log
4460 WHERE membership_id={$membershipParams['id']}
4463 $dao = CRM_Core_DAO
::executeQuery($sql);
4464 if ($dao->fetch()) {
4465 if (!empty($dao->membership_type_id
)) {
4466 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4471 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4472 $membershipParams['membership_type_id'],
4473 $primaryContributionID
4475 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4476 if ($currentMembership) {
4478 * Fixed FOR CRM-4433
4479 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4480 * when Contribution mode is notify and membership is for renewal )
4482 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4484 // @todo - we should pass membership_type_id instead of null here but not
4485 // adding as not sure of testing
4486 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4487 $changeDate, NULL, $membershipParams['num_terms']
4490 $dates['join_date'] = $currentMembership['join_date'];
4493 //get the status for membership.
4494 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4496 $dates['join_date'],
4499 $membershipParams['membership_type_id'],
4503 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4504 //we might be renewing membership,
4505 //so make status override false.
4506 $membershipParams['is_override'] = FALSE;
4507 //CRM-17723 - reset static $relatedContactIds array()
4509 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
4510 civicrm_api3('Membership', 'create', $membershipParams);
4516 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4517 if ($event->is_email_confirm
) {
4518 // @todo this should be set by the function that sends the mail after sending.
4519 $contributionParams['receipt_date'] = $changeDate;
4521 $participantParams['id'] = $participant->id
;
4522 $participantParams['status_id'] = 'Registered';
4523 civicrm_api3('Participant', 'create', $participantParams);
4527 $contributionParams['id'] = $contribution->id
;
4529 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4531 // Add new soft credit against current $contribution.
4532 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4533 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4536 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4537 'labelColumn' => 'name',
4540 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4541 $input['payment_processor'] = $paymentProcessorId;
4544 if (!empty($contribution->_relatedObjects
['participant'])) {
4545 $input['contribution_mode'] = 'participant';
4546 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4548 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4549 $input['contribution_mode'] = 'membership';
4550 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4551 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4552 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4555 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4556 $transaction->commit();
4558 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4559 $contributionParams['contribution_status_id'], $input['amount']);
4561 // create an activity record
4562 if ($input['component'] == 'contribute') {
4564 $targetContactID = NULL;
4565 if (!empty($ids['related_contact'])) {
4566 $targetContactID = $contribution->contact_id
;
4567 $contribution->contact_id
= $ids['related_contact'];
4569 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4573 CRM_Activity_BAO_Activity
::addActivity($participant);
4576 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4577 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4578 if (!array_key_exists('is_email_receipt', $values) ||
4579 $values['is_email_receipt'] == 1
4581 civicrm_api3('Contribution', 'sendconfirmation', array(
4582 'id' => $contribution->id
,
4583 'payment_processor_id' => $paymentProcessorId,
4585 CRM_Core_Error
::debug_log_message("Receipt sent");
4588 CRM_Core_Error
::debug_log_message("Success: Database updated");
4590 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4591 $isFirstOrLastRecurringPayment);
4593 return $contributionResult;
4597 * Send receipt from contribution.
4599 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4601 * Note that the compose message part has been moved to contribution
4602 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4604 * @param array $input
4605 * Incoming data from Payment processor.
4607 * Related object IDs.
4608 * @param int $contributionID
4609 * @param array $values
4610 * Values related to objects that have already been loaded.
4611 * @param bool $recur
4612 * Is it part of a recurring contribution.
4613 * @param bool $returnMessageText
4614 * Should text be returned instead of sent. This.
4615 * is because the function is also used to generate pdfs
4618 * @throws \CRM_Core_Exception
4619 * @throws \CiviCRM_API3_Exception
4621 public static function sendMail(&$input, &$ids, $contributionID, &$values, $recur = FALSE,
4622 $returnMessageText = FALSE) {
4623 $input['is_recur'] = $recur;
4625 $contribution = new CRM_Contribute_BAO_Contribution();
4626 $contribution->id
= $contributionID;
4627 if (!$contribution->find(TRUE)) {
4628 throw new CRM_Core_Exception('Contribution does not exist');
4630 $contribution->loadRelatedObjects($input, $ids, TRUE);
4631 // set receipt from e-mail and name in value
4632 if (!$returnMessageText) {
4633 $session = CRM_Core_Session
::singleton();
4634 $userID = $session->get('userID');
4635 if (!empty($userID)) {
4636 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4637 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4638 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4642 $return = $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4643 // Contribution ID should really always be set. But ?
4644 if (!$returnMessageText && (!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4645 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4651 * Generate credit note id with next avaible number
4656 public static function createCreditNoteId() {
4657 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4659 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4660 $creditNoteId = NULL;
4664 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4665 $result = civicrm_api3('Contribution', 'getcount', array(
4667 'creditnote_id' => $creditNoteId,
4669 } while ($result > 0);
4671 return $creditNoteId;
4675 * Load related memberships.
4677 * Note that in theory it should be possible to retrieve these from the line_item table
4678 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4679 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4680 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4681 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4683 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4689 public function loadRelatedMembershipObjects(&$ids) {
4691 SELECT membership_id
4692 FROM civicrm_membership_payment
4693 WHERE contribution_id = %1 ";
4694 $params = array(1 => array($this->id
, 'Integer'));
4696 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4697 while ($dao->fetch()) {
4698 if ($dao->membership_id
) {
4699 if (!is_array($ids['membership'])) {
4700 $ids['membership'] = array();
4702 $ids['membership'][] = $dao->membership_id
;
4706 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4707 foreach ($ids['membership'] as $id) {
4709 $membership = new CRM_Member_BAO_Membership();
4710 $membership->id
= $id;
4711 if (!$membership->find(TRUE)) {
4712 throw new Exception("Could not find membership record: $id");
4714 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4715 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4716 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4717 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4718 $membership->free();
4725 * This function is used to record partial payments for contribution
4727 * @param array $contribution
4729 * @param array $params
4733 public static function recordPartialPayment($contribution, $params) {
4734 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4735 $pendingStatus = array(
4736 array_search('Pending', $contributionStatuses),
4737 array_search('In Progress', $contributionStatuses),
4739 $statusId = array_search('Completed', $contributionStatuses);
4740 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4741 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4742 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4744 elseif (!empty($params['payment_processor'])) {
4745 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4747 elseif (!empty($params['payment_instrument_id'])) {
4748 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4751 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4752 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4753 $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);
4755 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4756 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4757 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4758 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4759 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4760 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4761 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4762 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4763 $balanceTrxnParams['currency'] = $contribution['currency'];
4764 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4765 $balanceTrxnParams['status_id'] = $statusId;
4766 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4767 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4768 if ($fromFinancialAccountId != NULL &&
4769 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4771 $balanceTrxnParams['is_payment'] = 1;
4773 if (!empty($params['payment_processor'])) {
4774 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4776 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4780 * Get the description (source field) for the recurring contribution.
4782 * @param CRM_Contribute_BAO_Contribution $contribution
4783 * @param CRM_Event_DAO_Event|null $event
4786 * @throws \CiviCRM_API3_Exception
4788 protected static function getRecurringContributionDescription($contribution, $event) {
4789 if (!empty($contribution->source
)) {
4790 return $contribution->source
;
4792 elseif (!empty($contribution->contribution_page_id
)) {
4793 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4794 'id' => $contribution->contribution_page_id
,
4795 'return' => 'title',
4797 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4800 return ts('Online Event Registration') . ': ' . $event->title
;
4802 return 'recurring contribution';
4806 * Function to add payments for contribution
4807 * for Partially Paid status
4809 * @param array $lineItems
4810 * @param array $contributions
4813 public static function addPayments($lineItems, $contributions) {
4814 // get financial trxn which is a payment
4815 $ftSql = "SELECT ft.id, ft.total_amount
4816 FROM civicrm_financial_trxn ft
4817 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4818 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4819 $sql = "SELECT fi.id, li.price_field_value_id
4820 FROM civicrm_financial_item fi
4821 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id
4822 WHERE li.contribution_id = %1";
4824 foreach ($contributions as $k => $contribution) {
4825 if ($contribution->contribution_status_id
!= CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name')) {
4828 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4830 $trxnAmount = $ftDao->total_amount
;
4833 // get financial item
4834 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contribution->id
, 'Integer')));
4835 while ($dao->fetch()) {
4836 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4840 'entity_table' => 'civicrm_financial_item',
4841 'financial_trxn_id' => $ftId,
4843 foreach ($lineItems as $key => $value) {
4844 $paid = $value['line_total'] * ($trxnAmount / $contribution->total_amount
);
4845 // Record Entity Financial Trxn
4846 $params['amount'] = round($paid, 2);
4847 $params['entity_id'] = $ftIds[$value['price_field_value_id']];
4849 civicrm_api3('EntityFinancialTrxn', 'create', $params);
4855 * Function use to store line item proportionaly in
4856 * in entity financial trxn table
4858 * @param array $params
4859 * array of contribution params.
4860 * @param object $trxn
4861 * CRM_Financial_DAO_FinancialTrxn object
4862 * @param array $contribution
4865 public static function assignProportionalLineItems($params, $trxn, $contribution) {
4866 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution_id']);
4867 if (!empty($lineItems)) {
4868 // get financial item
4869 $sql = "SELECT fi.id, li.price_field_value_id
4870 FROM civicrm_financial_item fi
4871 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
4872 WHERE li.contribution_id = %1";
4873 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($params['contribution_id'], 'Integer')));
4874 while ($dao->fetch()) {
4875 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4878 'entity_table' => 'civicrm_financial_item',
4879 'financial_trxn_id' => $trxn->id
,
4881 foreach ($lineItems as $key => $value) {
4882 $paid = $value['line_total'] * ($params['total_amount'] / $contribution['total_amount']);
4883 // Record Entity Financial Trxn
4884 $eftParams['amount'] = round($paid, 2);
4885 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
4887 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
4893 * Function to check line items
4895 * @param array $params
4896 * array of order params.
4899 public static function checkLineItems(&$params) {
4900 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4901 $lineItemAmount = 0;
4902 foreach ($params['line_items'] as &$lineItems) {
4903 foreach ($lineItems['line_item'] as &$item) {
4904 if (empty($item['financial_type_id'])) {
4905 $item['financial_type_id'] = $params['financial_type_id'];
4907 $lineItemAmount +
= $item['line_total'];
4910 if (!isset($totalAmount)) {
4911 $params['total_amount'] = $lineItemAmount;
4913 elseif ($totalAmount != $lineItemAmount) {
4914 throw new API_Exception("Line item total doesn't match with total amount.");
4919 * Get the financial account for the item associated with the new transaction.
4921 * @param array $params
4922 * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem
4926 public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) {
4928 if (!empty($params['financial_account_id'])) {
4929 return $params['financial_account_id'];
4931 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4932 $preferredAccountsRelationships = array(
4933 'Refunded' => 'Credit/Contra Revenue Account is',
4934 'Chargeback' => 'Chargeback Account is',
4936 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4937 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4938 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4940 $preferredAccountsRelationships[$contributionStatus]
4943 return $prevFinancialItem->financial_account_id
;
4947 * ContributionPage values were being imposed onto values.
4949 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4950 * REALLY didn't want superimposed. The rest are left there in their overkill out
4953 * The rationale for making this explicit is that it was a case of carefully set values being
4954 * seemingly randonly overwritten without much care. In general I think array randomly setting
4955 * variables en mass is risky.
4957 * @param array $values
4961 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4962 $contributionPageValues = array();
4963 CRM_Contribute_BAO_ContributionPage
::setValues(
4964 $this->contribution_page_id
,
4965 $contributionPageValues
4967 $valuesToCopy = array(
4968 // These are the values that I believe to be useful.
4971 'pay_later_receipt',
4973 'receipt_from_email',
4974 'receipt_from_name',
4978 'honoree_profile_id',
4979 'onbehalf_profile_id',
4980 'honor_block_is_active',
4981 // Kinda might be - but would be on the contribution...
4984 // Included for 'fear of regression' but can't justify any use for these....
4986 'payment_processor',
4987 'financial_type_id',
4988 'amount_block_is_active',
4993 'default_amount_id',
4997 'initial_amount_help_text',
4998 'initial_amount_label',
5000 'is_allow_other_amount',
5001 'is_billing_required',
5002 'is_confirm_enabled',
5003 'is_credit_card_only',
5005 'is_partial_payment',
5006 'is_recur_installments',
5007 'is_recur_interval',
5011 'min_initial_amount',
5012 'recur_frequency_unit',
5019 foreach ($valuesToCopy as $valueToCopy) {
5020 if (isset($contributionPageValues[$valueToCopy])) {
5021 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];