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 // reset the group contact cache for this group
216 CRM_Contact_BAO_GroupContactCache
::remove();
218 if ($contributionID) {
219 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
222 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
229 * Is this contribution updating an existing recurring contribution.
231 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
232 * pending payment is being confirmed (or failing).
234 * @param array $params
238 public static function isUpdateToRecurringContribution($params) {
239 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
242 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
245 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
248 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
249 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
256 * Get defaults for new entity.
259 public static function getDefaults() {
261 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
262 FALSE, FALSE, FALSE, 'AND is_default = 1')
264 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
269 * Fetch the object and store the values in the values array.
271 * @param array $params
272 * Input parameters to find object.
273 * @param array $values
274 * Output values of the object.
276 * The array that holds all the db ids.
278 * @return CRM_Contribute_BAO_Contribution|null
279 * The found object or null
281 public static function getValues($params, &$values, &$ids) {
282 if (empty($params)) {
285 $contribution = new CRM_Contribute_BAO_Contribution();
287 $contribution->copyValues($params);
289 if ($contribution->find(TRUE)) {
290 $ids['contribution'] = $contribution->id
;
292 CRM_Core_DAO
::storeValues($contribution, $values);
294 return $contribution;
296 $null = NULL; // return by reference
301 * Get the values and resolve the most common mappings.
303 * Since contribution status is resolved in almost every function that calls getValues it makes
304 * sense to have an extra function to resolve it rather than repeat the code.
306 * Think carefully before adding more mappings to be resolved as there could be performance implications
307 * if this function starts to be called from more iterative functions.
309 * @param array $params
310 * Input parameters to find object.
313 * Array of the found contribution.
314 * @throws CRM_Core_Exception
316 public static function getValuesWithMappings($params) {
317 $values = $ids = array();
318 $contribution = self
::getValues($params, $values, $ids);
319 if (is_null($contribution)) {
320 throw new CRM_Core_Exception('No contribution found');
322 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
327 * Calculate net_amount & fee_amount if they are not set.
329 * Net amount should be total - fee.
330 * This should only be called for new contributions.
332 * @param array $params
333 * Params for a new contribution before they are saved.
334 * @param int|null $contributionID
335 * Contribution ID if we are dealing with an update.
337 * @throws \CiviCRM_API3_Exception
339 public static function calculateMissingAmountParams(&$params, $contributionID) {
340 if (!$contributionID && !isset($params['fee_amount'])) {
341 if (isset($params['total_amount']) && isset($params['net_amount'])) {
342 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
345 $params['fee_amount'] = 0;
348 if (!isset($params['net_amount'])) {
349 if (!$contributionID) {
350 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
353 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
354 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
355 // net_amount may need adjusting.
356 $contribution = civicrm_api3('Contribution', 'getsingle', array(
357 'id' => $contributionID,
358 'return' => array('total_amount', 'net_amount'),
360 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
361 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
362 $params['net_amount'] = $totalAmount - $feeAmount;
370 * @param $billingLocationTypeID
374 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
375 $hasBillingField = FALSE;
376 $billingFields = array(
384 //build address array
385 $addressParams = array();
386 $addressParams['location_type_id'] = $billingLocationTypeID;
387 $addressParams['is_billing'] = 1;
389 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
390 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
391 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
392 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
394 foreach ($billingFields as $value) {
395 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
396 if (!empty($addressParams[$value])) {
397 $hasBillingField = TRUE;
400 return array($hasBillingField, $addressParams);
404 * Get address params ready to be passed to the payment processor.
406 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
407 * To create an address we need state_province_id.
409 * @param array $params
410 * @param int $billingLocationTypeID
414 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
415 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
416 foreach ($addressParams as $name => $field) {
417 if (substr($name, 0, 8) == 'billing_') {
418 $addressParams[substr($name, 9)] = $addressParams[$field];
421 return array($hasBillingField, $addressParams);
425 * Get the number of terms for this contribution for a given membership type
426 * based on querying the line item table and relevant price field values
427 * Note that any one contribution should only be able to have one line item relating to a particular membership
430 * @param int $membershipTypeID
432 * @param int $contributionID
436 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
437 $numTerms = CRM_Core_DAO
::singleValueQuery("
438 SELECT membership_num_terms FROM civicrm_line_item li
439 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
440 WHERE contribution_id = %1 AND membership_type_id = %2",
441 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
443 // default of 1 is precautionary
444 return empty($numTerms) ?
1 : $numTerms;
448 * Takes an associative array and creates a contribution object.
450 * @param array $params
451 * (reference ) an assoc array of name/value pairs.
453 * The array that holds all the db ids.
455 * @return CRM_Contribute_BAO_Contribution
457 public static function create(&$params, $ids = array()) {
458 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
459 foreach ($dateFields as $df) {
460 if (isset($params[$df])) {
461 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
465 //if contribution is created with cancelled or refunded status, add credit note id
466 if (!empty($params['contribution_status_id'])) {
467 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
469 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
470 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
472 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
473 $params['creditnote_id'] = self
::createCreditNoteId();
478 $transaction = new CRM_Core_Transaction();
480 $contribution = self
::add($params, $ids);
482 if (is_a($contribution, 'CRM_Core_Error')) {
483 $transaction->rollback();
484 return $contribution;
487 $params['contribution_id'] = $contribution->id
;
489 if (!empty($params['custom']) &&
490 is_array($params['custom'])
492 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
495 $session = CRM_Core_Session
::singleton();
497 if (!empty($params['note'])) {
499 'entity_table' => 'civicrm_contribution',
500 'note' => $params['note'],
501 'entity_id' => $contribution->id
,
502 'contact_id' => $session->get('userID'),
503 'modified_date' => date('Ymd'),
505 if (!$noteParams['contact_id']) {
506 $noteParams['contact_id'] = $params['contact_id'];
508 CRM_Core_BAO_Note
::add($noteParams);
511 // make entry in batch entity batch table
512 if (!empty($params['batch_id'])) {
513 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
514 $titleFields = array(
520 $retrieveRequired = 0;
521 foreach ($titleFields as $titleField) {
522 if (!isset($contribution->$titleField)) {
523 $retrieveRequired = 1;
527 if ($retrieveRequired == 1) {
528 $contribution->find(TRUE);
532 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
534 $transaction->commit();
536 // check if activity record exist for this contribution, if
538 $activity = new CRM_Activity_DAO_Activity();
539 $activity->source_record_id
= $contribution->id
;
540 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
544 if (!$activity->find(TRUE)) {
545 if (empty($contribution->contact_id
)) {
546 $contribution->find(TRUE);
548 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
551 // CRM-13237 : if activity record found, update it with campaign id of contribution
552 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
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
2076 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
2077 if (!empty($contribution->id
)) {
2080 if (empty($contribution->id
)) {
2081 // Unclear why this would only be set for repeats.
2082 if (!empty($input['amount'])) {
2083 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2085 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution($contributionParams['contribution_recur_id']);
2086 if (!empty($contributionParams['contribution_recur_id'])) {
2087 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2088 'id' => $contributionParams['contribution_recur_id'],
2090 if (!empty($recurringContribution['campaign_id'])) {
2091 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2092 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2094 if (!empty($recurringContribution['financial_type_id'])) {
2095 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2096 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2099 $contributionParams['skipLineItem'] = TRUE;
2100 $contributionParams['status_id'] = 'Pending';
2101 if (isset($contributionParams['financial_type_id'])) {
2102 // Give precedence to passed in type.
2103 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2106 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2108 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2109 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2110 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2111 $contribution->id
= $createContribution['id'];
2112 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
2113 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2119 * Get individual id for onbehalf contribution.
2121 * @param int $contributionId
2123 * @param int $contributorId
2127 * containing organization id and individual id
2129 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2133 if (!$contributionId) {
2137 // fetch contributor id if null
2138 if (!$contributorId) {
2139 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2140 $contributionId, 'contact_id'
2144 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2145 $activityTypeId = array_search('Contribution', $activityTypeIds);
2147 if ($activityTypeId && $contributorId) {
2149 SELECT civicrm_activity_contact.contact_id
2150 FROM civicrm_activity_contact
2151 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2152 WHERE civicrm_activity.activity_type_id = %1
2153 AND civicrm_activity.source_record_id = %2
2154 AND civicrm_activity_contact.record_type_id = %3
2157 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2158 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2161 1 => array($activityTypeId, 'Integer'),
2162 2 => array($contributionId, 'Integer'),
2163 3 => array($sourceID, 'Integer'),
2166 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2168 // for on behalf contribution source is individual and contributor is organization
2169 if ($sourceContactId && $sourceContactId != $contributorId) {
2170 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2171 // get rel type id for employee of relation
2172 foreach ($relationshipTypeIds as $id => $typeVals) {
2173 if ($typeVals['name_a_b'] == 'Employee of') {
2174 $relationshipTypeId = $id;
2179 $rel = new CRM_Contact_DAO_Relationship();
2180 $rel->relationship_type_id
= $relationshipTypeId;
2181 $rel->contact_id_a
= $sourceContactId;
2182 $rel->contact_id_b
= $contributorId;
2183 if ($rel->find(TRUE)) {
2184 $ids['individual_id'] = $rel->contact_id_a
;
2185 $ids['organization_id'] = $rel->contact_id_b
;
2196 public static function getContributionDates() {
2197 $config = CRM_Core_Config
::singleton();
2198 $currentMonth = date('m');
2199 $currentDay = date('d');
2200 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2201 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2202 (int ) $config->fiscalYearStart
['d'] > $currentDay
2205 $year = date('Y') - 1;
2210 $year = array('Y' => $year);
2211 $yearDate = $config->fiscalYearStart
;
2212 $yearDate = array_merge($year, $yearDate);
2213 $yearDate = CRM_Utils_Date
::format($yearDate);
2215 $monthDate = date('Ym') . '01';
2221 'yearDate' => $yearDate,
2222 'monthDate' => $monthDate,
2227 * Load objects relations to contribution object.
2228 * Objects are stored in the $_relatedObjects property
2229 * In the first instance we are just moving functionality from BASEIpn -
2230 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2232 * Note that the unit test for the BaseIPN class tests this function
2234 * @param array $input
2235 * Input as delivered from Payment Processor.
2237 * Ids as Loaded by Payment Processor.
2238 * @param bool $loadAll
2239 * Load all related objects - even where id not passed in? (allows API to call this).
2244 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2246 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2247 if (empty($ids['contact']) && isset($this->contact_id
)) {
2248 $ids['contact'] = $this->contact_id
;
2251 if (empty($this->_component
)) {
2252 if (!empty($ids['event'])) {
2253 $this->_component
= 'event';
2256 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2260 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2261 // refactoring than anything else, and has unit test coverage.
2262 if (empty($this->financial_type_id
)) {
2266 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2271 if (!$paymentProcessorID && $this->contribution_page_id
) {
2272 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2273 $this->contribution_page_id
,
2276 if ($paymentProcessorID) {
2277 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2281 $ids['contributionType'] = $this->financial_type_id
;
2282 $ids['financialType'] = $this->financial_type_id
;
2285 'contact' => 'CRM_Contact_BAO_Contact',
2286 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2287 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2288 'financialType' => 'CRM_Financial_BAO_FinancialType',
2290 foreach ($entities as $entity => $bao) {
2291 if (!empty($ids[$entity])) {
2292 $this->_relatedObjects
[$entity] = new $bao();
2293 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2294 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2295 throw new CRM_Core_Exception($entity . ' could not be loaded');
2300 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2301 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2304 if (!empty($ids['pledge_payment'])) {
2305 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2306 if (empty($paymentID)) {
2309 $payment = new CRM_Pledge_BAO_PledgePayment();
2310 $payment->id
= $paymentID;
2311 if (!$payment->find(TRUE)) {
2312 throw new Exception("Could not find pledge payment record: " . $paymentID);
2314 $this->_relatedObjects
['pledge_payment'][] = $payment;
2318 $this->loadRelatedMembershipObjects($ids);
2320 if ($this->_component
!= 'contribute') {
2321 // we are in event mode
2322 // make sure event exists and is valid
2323 $event = new CRM_Event_BAO_Event();
2324 $event->id
= $ids['event'];
2325 if ($ids['event'] &&
2328 throw new Exception("Could not find event: " . $ids['event']);
2331 $this->_relatedObjects
['event'] = &$event;
2333 $participant = new CRM_Event_BAO_Participant();
2334 $participant->id
= $ids['participant'];
2335 if ($ids['participant'] &&
2336 !$participant->find(TRUE)
2338 throw new Exception("Could not find participant: " . $ids['participant']);
2340 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2342 $this->_relatedObjects
['participant'] = &$participant;
2344 // get the payment processor id from event - this is inaccurate see CRM-16923
2345 // in future we should look at throwing an exception here rather than an dubious guess.
2346 if (!$paymentProcessorID) {
2347 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2348 if ($paymentProcessorID) {
2349 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2354 if ($paymentProcessorID) {
2355 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2356 $this->is_test ?
'test' : 'live'
2358 $ids['paymentProcessor'] = $paymentProcessorID;
2359 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2365 * Create array of message information - ie. return html version, txt version, to field
2367 * @param array $input
2368 * Incoming information.
2369 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2370 * just check presence of recur object but maintaining legacy approach
2373 * IDs of related objects.
2374 * @param array $values
2375 * Any values that may have already been compiled by calling process.
2376 * This is augmented by values 'gathered' by gatherMessageValues
2377 * @param bool $recur
2378 * @param bool $returnMessageText
2379 * Distinguishes between whether to send message or return.
2380 * message text. We are working towards this function ALWAYS returning message text & calling
2381 * function doing emails / pdfs with it
2387 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2388 $this->loadRelatedObjects($input, $ids);
2390 if (empty($this->_component
)) {
2391 $this->_component
= CRM_Utils_Array
::value('component', $input);
2394 //not really sure what params might be passed in but lets merge em into values
2395 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2396 if (!empty($input['receipt_date'])) {
2397 $values['receipt_date'] = $input['receipt_date'];
2400 $template = CRM_Core_Smarty
::singleton();
2401 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2402 //what does recur 'mean here - to do with payment processor return functionality but
2403 // what is the importance
2404 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2405 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2407 $entityID = $entity = NULL;
2408 if (isset($ids['contribution'])) {
2409 $entity = 'contribution';
2410 $entityID = $ids['contribution'];
2412 if (!empty($ids['membership'])) {
2413 //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
2414 // 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
2415 // line having loaded an array
2416 $ids['membership'] = (array) $ids['membership'];
2417 $entity = 'membership';
2418 $entityID = $ids['membership'][0];
2421 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2422 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2423 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2425 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2426 //direct mode showing billing block, so use directIPN for temporary
2427 $template->assign('contributeMode', 'directIPN');
2430 // todo remove strtolower - check consistency
2431 if (strtolower($this->_component
) == 'event') {
2432 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2433 $values['event'] = array();
2435 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2437 //get location details
2438 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2439 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2441 $ufJoinParams = array(
2442 'entity_table' => 'civicrm_event',
2443 'entity_id' => $ids['event'],
2444 'module' => 'CiviEvent',
2447 list($custom_pre_id,
2449 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2451 $values['custom_pre_id'] = $custom_pre_id;
2452 $values['custom_post_id'] = $custom_post_ids;
2453 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2454 //and cases involving status updation through ipn
2455 // whatever that means!
2456 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2457 // perhaps we should throw an e-notice if amount is set & force total_amount?
2458 if (!empty($input['amount'])) {
2459 $values['totalAmount'] = $input['amount'];
2462 if ($values['event']['is_email_confirm']) {
2463 $values['is_email_receipt'] = 1;
2466 if (!empty($ids['contribution'])) {
2467 $values['contributionId'] = $ids['contribution'];
2470 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2471 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2475 $values['contribution_id'] = $this->id
;
2476 if (!empty($ids['related_contact'])) {
2477 $values['related_contact'] = $ids['related_contact'];
2478 if (isset($ids['onbehalf_dupe_alert'])) {
2479 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2481 $entityBlock = array(
2482 'contact_id' => $ids['contact'],
2483 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2484 'Home', 'id', 'name'
2487 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2488 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2491 if ($this->is_test
) {
2494 if (!empty($this->_relatedObjects
['membership'])) {
2495 foreach ($this->_relatedObjects
['membership'] as $membership) {
2496 if ($membership->id
) {
2497 $values['isMembership'] = TRUE;
2498 $values['membership_assign'] = TRUE;
2500 // need to set the membership values here
2501 $template->assign('membership_name',
2502 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2504 $template->assign('mem_start_date', $membership->start_date
);
2505 $template->assign('mem_join_date', $membership->join_date
);
2506 $template->assign('mem_end_date', $membership->end_date
);
2507 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2508 $template->assign('mem_status', $membership_status);
2509 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2510 $values['is_pay_later'] = 1;
2513 // if separate payment there are two contributions recorded and the
2514 // admin will need to send a receipt for each of them separately.
2515 // we dont link the two in the db (but can potentially infer it if needed)
2516 $template->assign('is_separate_payment', 0);
2518 if ($recur && $paymentObject) {
2519 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2520 $template->assign('cancelSubscriptionUrl', $url);
2521 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2522 $template->assign('updateSubscriptionBillingUrl', $url);
2523 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2524 $template->assign('updateSubscriptionUrl', $url);
2527 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2530 // otherwise if its about sending emails, continue sending without return, as we
2531 // don't want to exit the loop.
2536 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2542 * Gather values for contribution mail - this function has been created
2543 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2544 * Values related to the contribution in question are gathered
2546 * @param array $input
2547 * Input into function (probably from payment processor).
2548 * @param array $values
2550 * The set of ids related to the input.
2554 public function _gatherMessageValues($input, &$values, $ids = array()) {
2555 // set display address of contributor
2556 if ($this->address_id
) {
2557 $addressParams = array('id' => $this->address_id
);
2558 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2559 $addressDetails = array_values($addressDetails);
2561 // Else we assign the billing address of the contribution contact.
2563 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2564 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2565 $addressDetails = array_values($addressDetails);
2568 if (!empty($addressDetails[0]['display'])) {
2569 $values['address'] = $addressDetails[0]['display'];
2572 if ($this->_component
== 'contribute') {
2573 //get soft contributions
2574 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2575 if (!empty($softContributions)) {
2576 $values['softContributions'] = $softContributions['soft_credit'];
2578 if (isset($this->contribution_page_id
)) {
2579 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2580 if ($this->contribution_page_id
) {
2581 // CRM-8254 - override default currency if applicable
2582 $config = CRM_Core_Config
::singleton();
2583 $config->defaultCurrency
= CRM_Utils_Array
::value(
2586 $config->defaultCurrency
2590 // no contribution page -probably back office
2592 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2593 $values['is_email_receipt'] = 1;
2594 $values['title'] = 'Contribution';
2596 // set lineItem for contribution
2598 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2599 if (!empty($lineItem)) {
2600 $itemId = key($lineItem);
2601 foreach ($lineItem as &$eachItem) {
2602 if (isset($this->_relatedObjects
['membership'])
2603 && is_array($this->_relatedObjects
['membership'])
2604 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2605 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2606 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2607 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2610 $values['lineItem'][0] = $lineItem;
2611 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2615 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2619 // if this is onbehalf of contribution then set related contact
2620 if (!empty($relatedContact['individual_id'])) {
2621 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2626 $eventParams = array(
2627 'id' => $this->_relatedObjects
['event']->id
,
2629 $values['event'] = array();
2631 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2632 // add custom fields for event
2633 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2635 $eventCustomGroup = array();
2636 foreach ($eventGroupTree as $key => $group) {
2637 if ($key === 'info') {
2641 foreach ($group['fields'] as $k => $customField) {
2642 $groupLabel = $group['title'];
2643 if (!empty($customField['customValue'])) {
2644 foreach ($customField['customValue'] as $customFieldValues) {
2645 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2650 $values['event']['customGroup'] = $eventCustomGroup;
2652 //get participant details
2653 $participantParams = array(
2654 'id' => $this->_relatedObjects
['participant']->id
,
2657 $values['participant'] = array();
2659 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2660 // add custom fields for event
2661 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2662 $participantCustomGroup = array();
2663 foreach ($participantGroupTree as $key => $group) {
2664 if ($key === 'info') {
2668 foreach ($group['fields'] as $k => $customField) {
2669 $groupLabel = $group['title'];
2670 if (!empty($customField['customValue'])) {
2671 foreach ($customField['customValue'] as $customFieldValues) {
2672 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2677 $values['participant']['customGroup'] = $participantCustomGroup;
2679 //get location details
2680 $locationParams = array(
2681 'entity_id' => $this->_relatedObjects
['event']->id
,
2682 'entity_table' => 'civicrm_event',
2684 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2686 $ufJoinParams = array(
2687 'entity_table' => 'civicrm_event',
2688 'entity_id' => $ids['event'],
2689 'module' => 'CiviEvent',
2692 list($custom_pre_id,
2694 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2696 $values['custom_pre_id'] = $custom_pre_id;
2697 $values['custom_post_id'] = $custom_post_ids;
2699 // set lineItem for event contribution
2701 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2702 if (!empty($participantIds)) {
2703 foreach ($participantIds as $pIDs) {
2704 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2705 if (!CRM_Utils_System
::isNull($lineItem)) {
2706 $values['lineItem'][] = $lineItem;
2713 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2715 $customGroup = array();
2716 foreach ($groupTree as $key => $group) {
2717 if ($key === 'info') {
2721 foreach ($group['fields'] as $k => $customField) {
2722 $groupLabel = $group['title'];
2723 if (!empty($customField['customValue'])) {
2724 foreach ($customField['customValue'] as $customFieldValues) {
2725 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2730 $values['customGroup'] = $customGroup;
2736 * Assign message variables to template but try to break the habit.
2738 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2739 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2740 * multiple recurring payments for processors like IATS that use tokens.
2742 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2743 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2744 * Note we send directly from this function in some cases because it is only partly refactored.
2746 * Don't call this function directly as the signature will change.
2750 * @param CRM_Core_SMARTY $template
2751 * @param bool $recur
2752 * @param bool $returnMessageText
2756 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2757 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2758 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2759 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2760 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2761 $values['useForMember'] = TRUE;
2763 //assign honor information to receipt message
2764 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2766 if (isset($softRecord['soft_credit'])) {
2767 //if id of contribution page is present
2768 if (!empty($values['id'])) {
2769 $values['honor'] = array(
2770 'honor_profile_values' => array(),
2771 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2772 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2774 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2776 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2777 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2780 //offline contribution
2781 $softCreditTypes = $softCredits = array();
2782 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2783 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2784 $softCredits[$key] = array(
2785 'Name' => $softCredit['contact_name'],
2786 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2789 $template->assign('softCreditTypes', $softCreditTypes);
2790 $template->assign('softCredits', $softCredits);
2794 $dao = new CRM_Contribute_DAO_ContributionProduct();
2795 $dao->contribution_id
= $this->id
;
2796 if ($dao->find(TRUE)) {
2797 $premiumId = $dao->product_id
;
2798 $template->assign('option', $dao->product_option
);
2800 $productDAO = new CRM_Contribute_DAO_Product();
2801 $productDAO->id
= $premiumId;
2802 $productDAO->find(TRUE);
2803 $template->assign('selectPremium', TRUE);
2804 $template->assign('product_name', $productDAO->name
);
2805 $template->assign('price', $productDAO->price
);
2806 $template->assign('sku', $productDAO->sku
);
2808 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2809 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2810 if (!$values['amount'] && isset($this->total_amount
)) {
2811 $values['amount'] = $this->total_amount
;
2814 // add the new contribution values
2815 if (strtolower($this->_component
) == 'contribute') {
2817 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2818 $softDAO->contribution_id
= $this->id
;
2819 if ($softDAO->find(TRUE)) {
2820 $template->assign('pcpBlock', TRUE);
2821 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2822 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2823 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2825 //assign the pcp page title for email subject
2826 $pcpDAO = new CRM_PCP_DAO_PCP();
2827 $pcpDAO->id
= $softDAO->pcp_id
;
2828 if ($pcpDAO->find(TRUE)) {
2829 $template->assign('title', $pcpDAO->title
);
2834 if ($this->financial_type_id
) {
2835 $values['financial_type_id'] = $this->financial_type_id
;
2838 $template->assign('trxn_id', $this->trxn_id
);
2839 $template->assign('receive_date',
2840 CRM_Utils_Date
::processDate($this->receive_date
)
2842 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
2843 $template->assign('contributeMode', 'notify');
2844 $template->assign('action', $this->is_test ?
1024 : 1);
2845 $template->assign('receipt_text',
2846 CRM_Utils_Array
::value('receipt_text',
2850 $template->assign('is_monetary', 1);
2851 $template->assign('is_recur', (bool) $recur);
2852 $template->assign('currency', $this->currency
);
2853 $template->assign('address', CRM_Utils_Address
::format($input));
2854 if (!empty($values['customGroup'])) {
2855 $template->assign('customGroup', $values['customGroup']);
2857 if (!empty($values['softContributions'])) {
2858 $template->assign('softContributions', $values['softContributions']);
2860 if ($this->_component
== 'event') {
2861 $template->assign('title', $values['event']['title']);
2862 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2863 $viewRoles = array();
2864 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2865 $viewRoles[] = $participantRoles[$v];
2867 $values['event']['participant_role'] = implode(', ', $viewRoles);
2868 $template->assign('event', $values['event']);
2869 $template->assign('participant', $values['participant']);
2870 $template->assign('location', $values['location']);
2871 $template->assign('customPre', $values['custom_pre_id']);
2872 $template->assign('customPost', $values['custom_post_id']);
2875 if ($this->_relatedObjects
['participant']->is_test
) {
2879 $values['params'] = array();
2880 //to get email of primary participant.
2881 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2882 $primaryAmount[] = array(
2883 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2884 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2886 //build an array of cId/pId of participants
2887 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2888 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2889 //send receipt to additional participant if exists
2890 if (count($additionalIDs)) {
2891 $template->assign('isPrimary', 0);
2892 $template->assign('customProfile', NULL);
2893 //set additionalParticipant true
2894 $values['params']['additionalParticipant'] = TRUE;
2895 foreach ($additionalIDs as $pId => $cId) {
2897 //to change the status pending to completed
2898 $additional = new CRM_Event_DAO_Participant();
2899 $additional->id
= $pId;
2900 $additional->contact_id
= $cId;
2901 $additional->find(TRUE);
2902 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2903 $additional->status_id
= 1;
2904 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2905 //if additional participant dont have email
2907 if (!$additionalParticipantInfo) {
2908 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2910 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2911 $primaryAmount[] = array(
2912 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2913 'amount' => $additional->fee_amount
,
2915 $additional->save();
2916 $additional->free();
2917 $template->assign('amount', $amount);
2918 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2922 //build an array of custom profile and assigning it to template
2923 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2925 if (count($customProfile)) {
2926 $template->assign('customProfile', $customProfile);
2929 // for primary contact
2930 $values['params']['additionalParticipant'] = FALSE;
2931 $template->assign('isPrimary', 1);
2932 $template->assign('amount', $primaryAmount);
2933 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2934 if ($this->payment_instrument_id
) {
2935 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2936 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2938 // carry paylater, since we did not created billing,
2939 // so need to pull email from primary location, CRM-4395
2940 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2946 * Check whether payment processor supports
2947 * cancellation of contribution subscription
2949 * @param int $contributionId
2952 * @param bool $isNotCancelled
2956 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2957 $cacheKeyString = "$contributionId";
2958 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2960 static $supportsCancel = array();
2962 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2963 $supportsCancel[$cacheKeyString] = FALSE;
2964 $isCancelled = FALSE;
2966 if ($isNotCancelled) {
2967 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2970 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2971 if (!empty($paymentObject)) {
2972 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
2975 return $supportsCancel[$cacheKeyString];
2979 * Check whether subscription is already cancelled.
2981 * @param int $contributionId
2985 * contribution status
2987 public static function isSubscriptionCancelled($contributionId) {
2989 SELECT cr.contribution_status_id
2990 FROM civicrm_contribution_recur cr
2991 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2992 WHERE con.id = %1 LIMIT 1";
2993 $params = array(1 => array($contributionId, 'Integer'));
2994 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2995 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2996 if ($status == 'Cancelled') {
3003 * Create all financial accounts entry.
3005 * @param array $params
3006 * Contribution object, line item array and params for trxn.
3009 * @param array $financialTrxnValues
3011 * @return null|object
3013 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3014 $skipRecords = $update = $return = $isRelatedId = FALSE;
3016 $additionalParticipantId = array();
3017 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3018 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3020 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3021 $entityId = $params['participant_id'];
3022 $entityTable = 'civicrm_participant';
3023 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3025 elseif (!empty($params['membership_id'])) {
3026 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3027 // are created off one contribution should be handled elsewhere
3028 $entityId = $params['membership_id'];
3029 $entityTable = 'civicrm_membership';
3032 $entityId = $params['contribution']->id
;
3033 $entityTable = 'civicrm_contribution';
3036 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3037 $isRelatedId = TRUE;
3040 $entityID[] = $entityId;
3041 if (!empty($additionalParticipantId)) {
3042 $entityID +
= $additionalParticipantId;
3044 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3045 if (empty($params['prevContribution'])) {
3052 $statusId = $params['contribution']->contribution_status_id
;
3053 // CRM-13964 partial payment
3054 if ($contributionStatus == 'Partially paid'
3055 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3057 $partialAmtPay = $params['partial_amount_pay'];
3058 $partialAmtTotal = $params['partial_payment_total'];
3060 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3061 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3062 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3063 $params['total_amount'] = $partialAmtPay;
3065 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3066 if (empty($balanceTrxnInfo['trxn_id'])) {
3067 // create new balance transaction record
3068 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3069 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3071 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3072 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3073 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3074 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3075 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3076 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3077 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3078 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3079 $balanceTrxnParams['status_id'] = $statusId;
3080 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3081 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3082 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3083 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3085 $balanceTrxnParams['is_payment'] = 1;
3087 if (!empty($params['payment_processor'])) {
3088 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3090 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3094 // build line item array if its not set in $params
3095 if (empty($params['line_item']) ||
$additionalParticipantId) {
3096 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3099 if ($contributionStatus != 'Failed' &&
3100 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3102 $skipRecords = TRUE;
3103 $pendingStatus = array(
3107 if (in_array($contributionStatus, $pendingStatus)) {
3108 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3109 $params['financial_type_id'],
3110 'Accounts Receivable Account is'
3113 elseif (!empty($params['payment_processor'])) {
3114 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3116 elseif (!empty($params['payment_instrument_id'])) {
3117 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3120 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3121 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3122 $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);
3125 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3126 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3127 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3130 //build financial transaction params
3131 $trxnParams = array(
3132 'contribution_id' => $params['contribution']->id
,
3133 'to_financial_account_id' => $params['to_financial_account_id'],
3134 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3135 'total_amount' => $totalAmount,
3136 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3137 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3138 'currency' => $params['contribution']->currency
,
3139 'trxn_id' => $params['contribution']->trxn_id
,
3140 'status_id' => $statusId,
3141 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
3142 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3144 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback') {
3145 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3146 if (isset($params['refund_trxn_id'])) {
3147 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3148 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3151 //CRM-16259, set is_payment flag for non pending status
3152 if (!in_array($contributionStatus, $pendingStatus)) {
3153 $trxnParams['is_payment'] = 1;
3155 if (!empty($params['payment_processor'])) {
3156 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3159 if (isset($fromFinancialAccountId)) {
3160 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3163 // consider external values passed for recording transaction entry
3164 if (!empty($financialTrxnValues)) {
3165 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3168 $params['trxnParams'] = $trxnParams;
3170 if (!empty($params['prevContribution'])) {
3172 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3173 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3174 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3175 if (!isset($params['trxnParams']['trxn_id'])) {
3176 // Actually I have no idea why we are overwriting any values from the previous contribution.
3177 // (filling makes sense to me). However, only protecting this value as I really really know we
3178 // don't want this one overwritten.
3180 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3182 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3184 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3185 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3186 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3188 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3189 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3192 //if financial type is changed
3193 if (!empty($params['financial_type_id']) &&
3194 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3196 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3197 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3198 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3199 if ($oldFinancialAccount != $newFinancialAccount) {
3200 $params['total_amount'] = 0;
3201 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3202 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3203 $params['prevContribution']->financial_type_id
, $relationTypeId);
3206 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3207 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3208 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3211 self
::updateFinancialAccounts($params, 'changeFinancialType');
3212 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3213 $params['financial_account_id'] = $newFinancialAccount;
3214 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3215 self
::updateFinancialAccounts($params);
3216 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3221 //Update contribution status
3222 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3223 if (!isset($params['refund_trxn_id'])) {
3224 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3225 // gets preference over another so I am only 'protecting' a very specific tested flow
3226 // and letting natural justice take care of the rest.
3227 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3229 if (!empty($params['contribution_status_id']) &&
3230 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3232 //Update Financial Records
3233 self
::updateFinancialAccounts($params, 'changedStatus');
3237 // change Payment Instrument for a Completed contribution
3238 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3239 // instrument is null and now new payment instrument is added along with the payment
3240 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3241 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3242 if (array_key_exists('payment_instrument_id', $params)) {
3243 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3244 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3245 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3247 //check if status is changed from Pending to Completed
3248 // do not update payment instrument changes for Pending to Completed
3249 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3250 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3252 // for all other statuses create new financial records
3253 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3254 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3255 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3259 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3260 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3261 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3263 // for any other payment instrument changes create new financial records
3264 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3265 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3266 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3269 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3270 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3272 // another special case when check number is changed, create new financial records
3273 // create financial trxn with negative amount
3274 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3275 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3276 // create financial trxn with positive amount
3277 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3278 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3279 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3284 //if Change contribution amount
3285 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3286 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3287 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3288 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3289 if (isset($totalAmount) &&
3290 $totalAmount != $params['prevContribution']->total_amount
3292 //Update Financial Records
3293 $params['trxnParams']['from_financial_account_id'] = NULL;
3294 self
::updateFinancialAccounts($params, 'changedAmount');
3299 // Looks like we might have a data correction update.
3300 // This would be a case where a transaction id has been entered but it is incorrect &
3301 // the person goes back in & fixes it, as opposed to a new transaction.
3302 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3303 // the data fix scenario.
3305 if (isset($params['refund_trxn_id'])) {
3306 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3307 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3308 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3315 // records finanical trxn and entity financial trxn
3316 // also make it available as return value
3317 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3318 $params['entity_id'] = $financialTxn->id
;
3321 // record line items and financial items
3322 if (empty($params['skipLineItem'])) {
3323 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3326 // create batch entry if batch_id is passed and
3327 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3328 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3329 $entityParams = array(
3330 'batch_id' => $params['batch_id'],
3331 'entity_table' => 'civicrm_financial_trxn',
3332 'entity_id' => $financialTxn->id
,
3334 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3337 // when a fee is charged
3338 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3339 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3342 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3343 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3345 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3346 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3347 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3349 unset($params['line_item']);
3355 * Update all financial accounts entry.
3357 * @param array $params
3358 * Contribution object, line item array and params for trxn.
3360 * @param string $context
3363 * @param null $skipTrxn
3366 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3367 $itemAmount = $trxnID = NULL;
3368 //get all the statuses
3369 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3370 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3371 if (($previousContributionStatus == 'Pending'
3372 ||
$previousContributionStatus == 'In Progress')
3373 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3374 && $context == 'changePaymentInstrument'
3378 if ((($previousContributionStatus == 'Partially paid'
3379 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3380 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3381 && $params['contribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus)))
3382 && $context == 'changedStatus'
3386 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3387 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3389 if ($context == 'changedStatus') {
3390 //get all the statuses
3391 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3392 $cancelledTaxAmount = 0;
3393 if ($previousContributionStatus == 'Completed'
3394 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3396 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3397 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $params, '0.00');
3398 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3399 $creditNoteId = self
::createCreditNoteId();
3400 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3403 elseif (($previousContributionStatus == 'Pending'
3404 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3406 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3407 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3408 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3410 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3411 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3412 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3413 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3414 $creditNoteId = self
::createCreditNoteId();
3415 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3419 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3422 $itemAmount = $params['trxnParams']['total_amount'] +
$cancelledTaxAmount;
3424 elseif ($context == 'changePaymentInstrument') {
3425 if ($params['trxnParams']['total_amount'] < 0) {
3426 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3427 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3428 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3429 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3433 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3434 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3438 if ($context == 'changedStatus') {
3439 if (($previousContributionStatus == 'Pending'
3440 ||
$previousContributionStatus == 'In Progress')
3441 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3443 if (empty($params['line_item'])) {
3445 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3446 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3447 // & this can be removed
3450 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3451 $params['entity_id'] = $trxn->id
;
3452 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3453 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3455 $entityParams = array(
3456 'entity_table' => 'civicrm_financial_item',
3457 'financial_trxn_id' => $trxn->id
,
3459 foreach ($params['line_item'] as $fieldId => $fields) {
3460 foreach ($fields as $fieldValueId => $fieldValues) {
3462 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3463 2 => array($fieldValues['id'], 'Integer'),
3465 CRM_Core_DAO
::executeQuery($query, $fparams);
3467 1 => array($fieldValues['id'], 'Integer'),
3469 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3470 while ($financialItem->fetch()) {
3471 $entityParams['entity_id'] = $financialItem->id
;
3472 $entityParams['amount'] = $financialItem->amount
;
3473 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3481 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3482 $params['entity_id'] = $trxn->id
;
3483 if ($context != 'changePaymentInstrument') {
3484 $itemParams['entity_table'] = 'civicrm_line_item';
3485 $trxnIds['id'] = $params['entity_id'];
3486 foreach ($params['line_item'] as $fieldId => $fields) {
3487 foreach ($fields as $fieldValueId => $fieldValues) {
3488 $prevParams['entity_id'] = $fieldValues['id'];
3489 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3491 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3492 if ($params['contribution']->receive_date
) {
3493 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3496 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem);
3498 $currency = $params['prevContribution']->currency
;
3499 if ($params['contribution']->currency
) {
3500 $currency = $params['contribution']->currency
;
3503 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($params['contribution']->contribution_status_id
)) {
3506 if (!empty($params['is_quick_config'])) {
3507 $amount = $itemAmount;
3509 $amount = $params['total_amount'];
3513 $amount = $diff * $fieldValues['line_total'];
3516 $itemParams = array(
3517 'transaction_date' => $receiveDate,
3518 'contact_id' => $params['prevContribution']->contact_id
,
3519 'currency' => $currency,
3520 'amount' => $amount,
3521 'description' => $prevFinancialItem->description
,
3522 'status_id' => $prevFinancialItem->status_id
,
3523 'financial_account_id' => $financialAccount,
3524 'entity_table' => 'civicrm_line_item',
3525 'entity_id' => $fieldValues['id'],
3527 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3529 if ($fieldValues['tax_amount']) {
3530 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3531 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3532 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3533 $itemParams['description'] = $taxTerm;
3534 if ($fieldValues['financial_type_id']) {
3535 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3537 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3542 if ($context == 'changeFinancialType') {
3543 $params['skipLineItem'] = FALSE;
3544 foreach ($params['line_item'] as &$lineItems) {
3545 foreach ($lineItems as &$line) {
3546 $line['financial_type_id'] = $params['financial_type_id'];
3553 * Is this contribution status a reversal.
3555 * If so we would expect to record a negative value in the financial_trxn table.
3557 * @param int $status_id
3561 public static function isContributionStatusNegative($status_id) {
3562 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3563 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3567 * Check status validation on update of a contribution.
3569 * @param array $values
3570 * Previous form values before submit.
3572 * @param array $fields
3573 * The input form values.
3575 * @param array $errors
3580 public static function checkStatusValidation($values, &$fields, &$errors) {
3581 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3582 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3583 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3587 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3588 $checkStatus = array(
3589 'Cancelled' => array('Completed', 'Refunded'),
3590 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3591 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3592 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3593 'Refunded' => array('Cancelled', 'Completed'),
3594 'Partially paid' => array('Completed'),
3597 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3598 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3600 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3601 1 => $contributionStatuses[$values['contribution_status_id']],
3602 2 => $contributionStatuses[$fields['contribution_status_id']],
3608 * Delete contribution of contact.
3612 * @param int $contactId
3616 public static function deleteContactContribution($contactId) {
3617 $contribution = new CRM_Contribute_DAO_Contribution();
3618 $contribution->contact_id
= $contactId;
3619 $contribution->find();
3620 while ($contribution->fetch()) {
3621 self
::deleteContribution($contribution->id
);
3626 * Get options for a given contribution field.
3627 * @see CRM_Core_DAO::buildOptions
3629 * @param string $fieldName
3630 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3631 * @param array $props whatever is known about this dao object.
3633 * @return array|bool
3635 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3636 $className = __CLASS__
;
3638 switch ($fieldName) {
3639 // This field is not part of this object but the api supports it
3640 case 'payment_processor':
3641 $className = 'CRM_Contribute_BAO_ContributionPage';
3642 // Filter results by contribution page
3643 if (!empty($props['contribution_page_id'])) {
3644 $page = civicrm_api('contribution_page', 'getsingle', array(
3646 'id' => ($props['contribution_page_id']),
3648 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3649 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3653 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3654 case 'honor_type_id':
3655 $className = 'CRM_Contribute_BAO_ContributionSoft';
3656 $fieldName = 'soft_credit_type_id';
3657 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3660 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3664 * Validate financial type.
3668 * @param int $financialTypeId
3669 * Financial Type id.
3671 * @param string $relationName
3673 * @return array|bool
3675 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3676 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3677 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3679 if (!$financialAccount) {
3680 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3687 * Function to record additional payment for partial and refund contributions.
3689 * @param int $contributionId
3690 * is the invoice contribution id (got created after processing participant payment).
3691 * @param array $trxnsData
3692 * to take user provided input of transaction details.
3693 * @param string $paymentType
3694 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3695 * @param int $participantId
3697 * @return null|object
3699 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3700 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3701 $getInfoOf['id'] = $contributionId;
3702 $defaults = array();
3703 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3704 if (!$participantId) {
3705 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id');
3708 if ($paymentType == 'owed') {
3709 // build params for recording financial trxn entry
3710 $params['contribution'] = $contributionDAO;
3711 $params = array_merge($defaults, $params);
3712 $params['skipLineItem'] = TRUE;
3713 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3714 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3715 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3716 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3719 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3720 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3721 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3723 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3724 if (!empty($trxnId)) {
3725 $trxnId = $trxnId['trxn_id'];
3727 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3728 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3731 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3732 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3733 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3737 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3738 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3739 FROM civicrm_financial_trxn ft
3740 LEFT JOIN civicrm_entity_financial_trxn eft
3741 ON (ft.id = eft.financial_trxn_id)
3742 WHERE eft.entity_table = 'civicrm_contribution'
3743 AND eft.entity_id = {$contributionId}
3744 AND ft.to_financial_account_id != {$toFinancialAccount}
3745 AND ft.status_id = {$statusId}
3747 $query = CRM_Core_DAO
::executeQuery($sql);
3749 $sumOfPayments = $query->sum_of_payments
;
3752 if ($contributionDAO->total_amount
== $sumOfPayments) {
3753 // update contribution status and
3754 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3755 $contributionDAO->contribution_status_id
= $statusId;
3756 $contributionDAO->cancel_date
= 'null';
3757 $contributionDAO->cancel_reason
= NULL;
3758 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3759 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3760 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3761 $contributionDAO->save();
3763 //Change status of financial record too
3764 $financialTrxn->status_id
= $statusId;
3765 $financialTrxn->save();
3767 // note : not using the self::add method,
3768 // the reason because it performs 'status change' related code execution for financial records
3769 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3770 // are coded below i.e. just updating financial_item status to 'Paid'
3772 if ($participantId) {
3773 // update participant status
3774 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3775 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3776 foreach ($ids as $val) {
3777 $participantUpdate['id'] = $val;
3778 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3779 CRM_Event_BAO_Participant
::add($participantUpdate);
3783 // update financial item statuses
3784 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3785 $paidStatus = array_search('Paid', $financialItemStatus);
3787 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3788 $sqlFinancialItemUpdate = "
3789 UPDATE civicrm_financial_item fi
3790 LEFT JOIN civicrm_entity_financial_trxn eft
3791 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3792 SET status_id = {$paidStatus}
3793 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3795 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3798 elseif ($paymentType == 'refund') {
3799 // build params for recording financial trxn entry
3800 $params['contribution'] = $contributionDAO;
3801 $params = array_merge($defaults, $params);
3802 $params['skipLineItem'] = TRUE;
3803 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3804 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3806 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3807 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3808 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3810 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3812 // note : not using the self::add method,
3813 // the reason because it performs 'status change' related code execution for financial records
3814 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3815 // are coded below i.e. just updating financial_item status to 'Paid'
3816 if ($updateStatus) {
3817 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3819 // add financial item entry
3820 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3821 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionDAO->id
);
3822 if (!empty($lineItems)) {
3823 foreach ($lineItems as $lineItemId => $lineItemValue) {
3824 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount
/ $contributionDAO->total_amount
);
3825 $addFinancialEntry = array(
3826 'transaction_date' => $financialTrxn->trxn_date
,
3827 'contact_id' => $contributionDAO->contact_id
,
3828 'amount' => round($paid, 2),
3829 'status_id' => array_search('Paid', $financialItemStatus),
3830 'entity_id' => $lineItemId,
3831 'entity_table' => 'civicrm_line_item',
3833 $trxnIds['id'] = $financialTrxn->id
;
3834 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3837 if ($participantId) {
3838 // update participant status
3839 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3840 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3841 foreach ($ids as $val) {
3842 $participantUpdate['id'] = $val;
3843 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3844 CRM_Event_BAO_Participant
::add($participantUpdate);
3849 // activity creation
3850 if (!empty($financialTrxn)) {
3851 if ($participantId) {
3852 $inputParams['id'] = $participantId;
3855 $component = 'event';
3856 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3857 $entityObj = $entityObj[$participantId];
3859 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3861 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3863 return $financialTrxn;
3869 * @param $activityType
3871 * @param int $contributionId
3873 * @throws CRM_Core_Exception
3875 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3876 if ($component == 'event') {
3877 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3878 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3879 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3880 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3881 $targetCid = $entityObj->contact_id
;
3882 // source record id would be the contribution id
3883 $srcRecId = $contributionId;
3887 $activityParams = array(
3888 'source_contact_id' => $targetCid,
3889 'source_record_id' => $srcRecId,
3890 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3894 'subject' => $subject,
3895 'activity_date_time' => $date,
3896 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3900 'skipRecentView' => TRUE,
3903 // create activity with target contacts
3904 $session = CRM_Core_Session
::singleton();
3905 $id = $session->get('userID');
3907 $activityParams['source_contact_id'] = $id;
3908 $activityParams['target_contact_id'][] = $targetCid;
3910 CRM_Activity_BAO_Activity
::create($activityParams);
3914 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3918 * @param bool $getTrxnInfo
3919 * @param bool $usingLineTotal
3923 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3924 if ($component == 'event') {
3925 $entity = 'participant';
3926 $entityTable = 'civicrm_participant';
3927 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3929 if (!$contributionId) {
3930 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3931 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3932 $id = $primaryParticipantId;
3934 if (!$contributionId) {
3940 $contributionId = $id;
3941 $entity = 'contribution';
3942 $entityTable = 'civicrm_contribution';
3945 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3946 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3952 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3953 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3956 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3957 // for additional participants
3958 if ($entityTable == 'civicrm_participant') {
3959 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3961 foreach ($ids as $val) {
3962 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3966 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3970 $baseTrxnId = $total['trxn_id'];
3971 $total = $total['total_amount'];
3974 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3975 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3977 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3978 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3979 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3981 if ($paymentBalance == 0 && $contributionIsPayLater) {
3982 $paymentBalance = $total;
3985 $info['total'] = $total;
3986 $info['paid'] = $total - $paymentBalance;
3987 $info['balance'] = $paymentBalance;
3989 $info['component'] = $component;
3990 $info['payLater'] = $contributionIsPayLater;
3992 if ($getTrxnInfo && $baseTrxnId) {
3993 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3995 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
3997 ft.payment_instrument_id,
3998 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, con.currency
4000 FROM civicrm_contribution con
4001 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4002 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4003 AND ft.to_financial_account_id != {$feeFinancialAccount}
4004 INNER JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4005 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4006 INNER JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4008 WHERE con.id = {$contributionId}
4012 // conditioned WHERE clause
4014 // if balance trxn exists don't include details of it in transaction info
4015 $sql .= " AND ft.id != {$baseTrxnId} ";
4017 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
4019 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4021 while ($resultDAO->fetch()) {
4022 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4023 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4025 'total_amount' => $resultDAO->total_amount
,
4026 'financial_type' => $resultDAO->financial_account
,
4027 'payment_instrument' => $paidByLabel,
4028 'receive_date' => $resultDAO->trxn_date
,
4029 'trxn_id' => $resultDAO->trxn_id
,
4030 'status' => $statuses[$resultDAO->status_id
],
4031 'currency' => $resultDAO->currency
,
4033 if ($paidByName == 'Check') {
4034 $val['check_number'] = $resultDAO->check_number
;
4038 $info['transaction'] = $rows;
4044 * Get financial account id has 'Sales Tax Account is'
4045 * account relationship with financial type
4047 * @param int $financialTypeId
4049 * @return FinancialAccountId
4051 public static function getFinancialAccountId($financialTypeId) {
4052 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4053 $searchParams = array(
4054 'entity_table' => 'civicrm_financial_type',
4055 'entity_id' => $financialTypeId,
4056 'account_relationship' => $accountRel,
4059 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
4061 return CRM_Utils_Array
::value('financial_account_id', $result);
4067 * @param array $params
4068 * @param bool $isLineItem
4072 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4073 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4075 // Update contribution.
4076 if (!empty($params['id'])) {
4077 $id = $params['id'];
4078 $values = $ids = array();
4079 $contrbutionParams = array('id' => $id);
4080 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
4082 // To assign pervious finantial type on update of contribution
4083 if (!isset($params['financial_type_id'])) {
4084 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
4086 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
4087 // Assisn tax Amount on update of contrbution
4088 if (!empty($prevContributionValue->tax_amount
)) {
4089 $params['tax_amount'] = 'null';
4090 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4091 foreach ($params['line_item'] as $setID => $priceField) {
4092 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4093 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4100 // New Contrbution and update of contribution with tax rate financial type
4101 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4102 empty($params['skipLineItem']) && !$isLineItem
4104 $taxRateParams = $taxRates[$params['financial_type_id']];
4105 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4106 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4108 // Get Line Item on update of contribution
4109 if (isset($params['id'])) {
4110 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4113 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4115 foreach ($params['line_item'] as $setID => $priceField) {
4116 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4117 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4120 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4122 elseif (isset($params['api.line_item.create'])) {
4123 // Update total amount of contribution using lineItem
4124 $taxAmountArray = array();
4125 foreach ($params['api.line_item.create'] as $key => $value) {
4126 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4127 $taxRate = $taxRates[$value['financial_type_id']];
4128 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4129 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4132 $params['tax_amount'] = array_sum($taxAmountArray);
4133 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4136 // update line item of contrbution
4137 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4138 $taxRate = $taxRates[$params['financial_type_id']];
4139 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
4140 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4147 * Check financial type validation on update of a contribution.
4149 * @param Integer $financialTypeId
4150 * Value of latest Financial Type.
4152 * @param Integer $contributionId
4155 * @param array $errors
4160 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4161 if (!empty($financialTypeId)) {
4162 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4163 if ($oldFinancialTypeId == $financialTypeId) {
4167 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4169 '1' => array($contributionId, 'Integer'),
4171 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4172 if ($result->N
> 1) {
4173 $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.');
4178 * Update related pledge payment payments.
4180 * This function has been refactored out of the back office contribution form and may
4181 * still overlap with other functions.
4183 * @param string $action
4184 * @param int $pledgePaymentID
4185 * @param int $contributionID
4186 * @param bool $adjustTotalAmount
4187 * @param float $total_amount
4188 * @param float $original_total_amount
4189 * @param int $contribution_status_id
4190 * @param int $original_contribution_status_id
4192 public static function updateRelatedPledge(
4198 $original_total_amount,
4199 $contribution_status_id,
4200 $original_contribution_status_id
4202 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4206 if ($pledgePaymentID) {
4207 //store contribution id in payment record.
4208 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4211 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4218 if (!$pledgePaymentID) {
4221 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4227 $updatePledgePaymentStatus = FALSE;
4229 // If either the status or the amount has changed we update the pledge status.
4230 if ($action & CRM_Core_Action
::ADD
) {
4231 $updatePledgePaymentStatus = TRUE;
4233 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4234 ($original_total_amount != $total_amount))
4236 $updatePledgePaymentStatus = TRUE;
4239 if ($updatePledgePaymentStatus) {
4240 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4241 array($pledgePaymentID),
4242 $contribution_status_id,
4251 * Compute the stats values
4253 * @param $stat either 'mode' or 'median'
4255 * @param $alias of civicrm_contribution
4257 public static function computeStats($stat, $sql, $alias = NULL) {
4258 $mode = $median = array();
4261 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4262 while ($modeDAO->fetch()) {
4263 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4264 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4273 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4274 foreach ($currencies as $currency => $val) {
4276 $where = "AND {$alias}.currency = '{$currency}'";
4277 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4281 $medianRow = floor($rowCount / 2);
4282 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4288 $medianValue = "SELECT {$alias}.total_amount as median
4290 ORDER BY median LIMIT {$medianRow},{$offset}";
4291 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4292 while ($medianValDAO->fetch()) {
4294 $midValue = $midValue +
$medianValDAO->median
;
4297 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4301 $midValue = $midValue / 2;
4302 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4313 * Is there only one line item attached to the contribution.
4319 * @throws \CiviCRM_API3_Exception
4321 public static function isSingleLineItem($id) {
4322 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4323 return ($lineItemCount == 1);
4327 * Complete an order.
4329 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4331 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4333 * Moving it out of the BaseIPN class is just the first step.
4335 * @param array $input
4337 * @param array $objects
4338 * @param CRM_Core_Transaction $transaction
4340 * @param CRM_Contribute_BAO_Contribution $contribution
4341 * @param bool $isRecurring
4342 * Duplication of param needs review. Only used by AuthorizeNetIPN
4343 * @param int $isFirstOrLastRecurringPayment
4344 * Deprecated param only used by AuthorizeNetIPN.
4346 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4347 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4348 // The previous details are used when calculating line items so keep it before any code that 'does something'
4349 if (!empty($contribution->id
)) {
4350 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4351 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4353 $inputContributionWhiteList = array(
4358 'payment_instrument_id',
4363 'contribution_status_id',
4365 if (self
::isSingleLineItem($primaryContributionID)) {
4366 $inputContributionWhiteList[] = 'financial_type_id';
4369 $participant = CRM_Utils_Array
::value('participant', $objects);
4370 $memberships = CRM_Utils_Array
::value('membership', $objects);
4371 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4372 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4373 $event = CRM_Utils_Array
::value('event', $objects);
4375 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4377 $contributionParams = array_merge(array(
4378 'contribution_status_id' => $completedContributionStatusID,
4379 'source' => self
::getRecurringContributionDescription($contribution, $event),
4380 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4383 if ($recurringContributionID) {
4384 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4386 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4388 if (empty($contributionParams['receive_date']) && $changeDate) {
4389 $contributionParams['receive_date'] = $changeDate;
4392 self
::repeatTransaction($contribution, $input, $contributionParams);
4393 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4395 if (is_numeric($memberships)) {
4396 $memberships = array($objects['membership']);
4400 if (isset($input['is_email_receipt'])) {
4401 $values['is_email_receipt'] = $input['is_email_receipt'];
4404 if ($input['component'] == 'contribute') {
4405 if ($contribution->contribution_page_id
) {
4406 // Figure out what we gain from this.
4407 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4409 elseif ($recurContrib && $recurringContributionID) {
4410 $values['amount'] = $recurContrib->amount
;
4411 $values['financial_type_id'] = $objects['contributionType']->id
;
4412 $values['title'] = $source = ts('Offline Recurring Contribution');
4415 if ($recurContrib && $recurringContributionID && !isset($input['is_email_receipt'])) {
4416 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4417 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4418 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4421 if (!empty($memberships)) {
4422 foreach ($memberships as $membershipTypeIdKey => $membership) {
4424 $membershipParams = array(
4425 'id' => $membership->id
,
4426 'contact_id' => $membership->contact_id
,
4427 'is_test' => $membership->is_test
,
4428 'membership_type_id' => $membership->membership_type_id
,
4431 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4432 $membershipParams['membership_type_id'],
4433 $membershipParams['is_test'],
4434 $membershipParams['id']
4437 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4438 // this picks up membership type changes during renewals
4440 SELECT membership_type_id
4441 FROM civicrm_membership_log
4442 WHERE membership_id={$membershipParams['id']}
4445 $dao = CRM_Core_DAO
::executeQuery($sql);
4446 if ($dao->fetch()) {
4447 if (!empty($dao->membership_type_id
)) {
4448 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4453 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4454 $membershipParams['membership_type_id'],
4455 $primaryContributionID
4457 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4458 if ($currentMembership) {
4460 * Fixed FOR CRM-4433
4461 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4462 * when Contribution mode is notify and membership is for renewal )
4464 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4466 // @todo - we should pass membership_type_id instead of null here but not
4467 // adding as not sure of testing
4468 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4469 $changeDate, NULL, $membershipParams['num_terms']
4472 $dates['join_date'] = $currentMembership['join_date'];
4475 //get the status for membership.
4476 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4478 $dates['join_date'],
4481 $membershipParams['membership_type_id'],
4485 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4486 //we might be renewing membership,
4487 //so make status override false.
4488 $membershipParams['is_override'] = FALSE;
4489 //CRM-17723 - reset static $relatedContactIds array()
4491 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
4492 civicrm_api3('Membership', 'create', $membershipParams);
4498 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4499 if ($event->is_email_confirm
) {
4500 // @todo this should be set by the function that sends the mail after sending.
4501 $contributionParams['receipt_date'] = $changeDate;
4503 $participantParams['id'] = $participant->id
;
4504 $participantParams['status_id'] = 'Registered';
4505 civicrm_api3('Participant', 'create', $participantParams);
4509 $contributionParams['id'] = $contribution->id
;
4511 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4513 // Add new soft credit against current $contribution.
4514 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4515 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4518 $paymentProcessorId = '';
4519 if (isset($objects['paymentProcessor'])) {
4520 if (is_array($objects['paymentProcessor'])) {
4521 $paymentProcessorId = $objects['paymentProcessor']['id'];
4524 $paymentProcessorId = $objects['paymentProcessor']->id
;
4528 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4529 'labelColumn' => 'name',
4532 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4533 $input['payment_processor'] = $paymentProcessorId;
4536 if (!empty($contribution->_relatedObjects
['participant'])) {
4537 $input['contribution_mode'] = 'participant';
4538 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4539 $input['skipLineItem'] = 1;
4541 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4542 $input['skipLineItem'] = TRUE;
4543 $input['contribution_mode'] = 'membership';
4544 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4545 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4546 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4548 $input['contribution_status_id'] = $contributionParams['contribution_status_id'];
4549 $input['total_amount'] = $input['amount'];
4550 $input['contribution'] = $contribution;
4551 $input['financial_type_id'] = $contribution->financial_type_id
;
4552 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4553 // and subsequent payments. In this case the line items are created at
4554 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4555 // and since the contribution is saved prior to this line there is always a contribution-id,
4556 // however there is never a prevContribution (which appears to mean original contribution not previous
4557 // contribution - or preUpdateContributionObject most accurately)
4558 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4559 // to mean "are we updating an exisitng pending contribution"
4560 //I was able to make the unit test complete as fataling here doesn't prevent
4561 // the contribution being created - but activities would not be created or emails sent
4563 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4565 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4566 $transaction->commit();
4568 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4569 $input['contribution_status_id'], $input['total_amount']);
4571 // create an activity record
4572 if ($input['component'] == 'contribute') {
4574 $targetContactID = NULL;
4575 if (!empty($ids['related_contact'])) {
4576 $targetContactID = $contribution->contact_id
;
4577 $contribution->contact_id
= $ids['related_contact'];
4579 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4583 CRM_Activity_BAO_Activity
::addActivity($participant);
4586 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4587 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4588 if (!array_key_exists('is_email_receipt', $values) ||
4589 $values['is_email_receipt'] == 1
4591 civicrm_api3('Contribution', 'sendconfirmation', array(
4592 'id' => $contribution->id
,
4593 'payment_processor_id' => $paymentProcessorId,
4595 CRM_Core_Error
::debug_log_message("Receipt sent");
4598 CRM_Core_Error
::debug_log_message("Success: Database updated");
4600 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4601 $isFirstOrLastRecurringPayment);
4603 return $contributionResult;
4607 * Send receipt from contribution.
4609 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4611 * Note that the compose message part has been moved to contribution
4612 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4614 * @param array $input
4615 * Incoming data from Payment processor.
4617 * Related object IDs.
4618 * @param int $contributionID
4619 * @param array $values
4620 * Values related to objects that have already been loaded.
4621 * @param bool $recur
4622 * Is it part of a recurring contribution.
4623 * @param bool $returnMessageText
4624 * Should text be returned instead of sent. This.
4625 * is because the function is also used to generate pdfs
4628 * @throws \CRM_Core_Exception
4629 * @throws \CiviCRM_API3_Exception
4631 public static function sendMail(&$input, &$ids, $contributionID, &$values, $recur = FALSE,
4632 $returnMessageText = FALSE) {
4633 $input['is_recur'] = $recur;
4635 $contribution = new CRM_Contribute_BAO_Contribution();
4636 $contribution->id
= $contributionID;
4637 if (!$contribution->find(TRUE)) {
4638 throw new CRM_Core_Exception('Contribution does not exist');
4640 $contribution->loadRelatedObjects($input, $ids, TRUE);
4641 // set receipt from e-mail and name in value
4642 if (!$returnMessageText) {
4643 $session = CRM_Core_Session
::singleton();
4644 $userID = $session->get('userID');
4645 if (!empty($userID)) {
4646 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4647 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4648 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4652 $return = $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4653 // Contribution ID should really always be set. But ?
4654 if (!$returnMessageText && (!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4655 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4661 * Generate credit note id with next avaible number
4666 public static function createCreditNoteId() {
4667 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4669 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4670 $creditNoteId = NULL;
4674 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4675 $result = civicrm_api3('Contribution', 'getcount', array(
4677 'creditnote_id' => $creditNoteId,
4679 } while ($result > 0);
4681 return $creditNoteId;
4685 * Load related memberships.
4687 * Note that in theory it should be possible to retrieve these from the line_item table
4688 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4689 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4690 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4691 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4693 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4699 public function loadRelatedMembershipObjects(&$ids) {
4701 SELECT membership_id
4702 FROM civicrm_membership_payment
4703 WHERE contribution_id = %1 ";
4704 $params = array(1 => array($this->id
, 'Integer'));
4706 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4707 while ($dao->fetch()) {
4708 if ($dao->membership_id
) {
4709 if (!is_array($ids['membership'])) {
4710 $ids['membership'] = array();
4712 $ids['membership'][] = $dao->membership_id
;
4716 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4717 foreach ($ids['membership'] as $id) {
4719 $membership = new CRM_Member_BAO_Membership();
4720 $membership->id
= $id;
4721 if (!$membership->find(TRUE)) {
4722 throw new Exception("Could not find membership record: $id");
4724 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4725 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4726 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4727 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4728 $membership->free();
4735 * This function is used to record partial payments for contribution
4737 * @param array $contribution
4739 * @param array $params
4743 public static function recordPartialPayment($contribution, $params) {
4744 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4745 $pendingStatus = array(
4746 array_search('Pending', $contributionStatuses),
4747 array_search('In Progress', $contributionStatuses),
4749 $statusId = array_search('Completed', $contributionStatuses);
4750 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4751 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4752 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4754 elseif (!empty($params['payment_processor'])) {
4755 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4757 elseif (!empty($params['payment_instrument_id'])) {
4758 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4761 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4762 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4763 $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);
4765 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4766 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4767 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4768 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4769 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4770 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4771 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4772 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4773 $balanceTrxnParams['currency'] = $contribution['currency'];
4774 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4775 $balanceTrxnParams['status_id'] = $statusId;
4776 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4777 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4778 if ($fromFinancialAccountId != NULL &&
4779 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4781 $balanceTrxnParams['is_payment'] = 1;
4783 if (!empty($params['payment_processor'])) {
4784 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4786 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4790 * Get the description (source field) for the recurring contribution.
4792 * @param CRM_Contribute_BAO_Contribution $contribution
4793 * @param CRM_Event_DAO_Event|null $event
4796 * @throws \CiviCRM_API3_Exception
4798 protected static function getRecurringContributionDescription($contribution, $event) {
4799 if (!empty($contribution->source
)) {
4800 return $contribution->source
;
4802 elseif (!empty($contribution->contribution_page_id
)) {
4803 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4804 'id' => $contribution->contribution_page_id
,
4805 'return' => 'title',
4807 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4810 return ts('Online Event Registration') . ': ' . $event->title
;
4812 return 'recurring contribution';
4816 * Function to add payments for contribution
4817 * for Partially Paid status
4819 * @param array $lineItems
4820 * @param array $contributions
4823 public static function addPayments($lineItems, $contributions) {
4824 // get financial trxn which is a payment
4825 $ftSql = "SELECT ft.id, ft.total_amount
4826 FROM civicrm_financial_trxn ft
4827 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4828 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4829 $sql = "SELECT fi.id, li.price_field_value_id
4830 FROM civicrm_financial_item fi
4831 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id
4832 WHERE li.contribution_id = %1";
4834 foreach ($contributions as $k => $contribution) {
4835 if ($contribution->contribution_status_id
!= CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name')) {
4838 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4840 $trxnAmount = $ftDao->total_amount
;
4843 // get financial item
4844 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contribution->id
, 'Integer')));
4845 while ($dao->fetch()) {
4846 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4850 'entity_table' => 'civicrm_financial_item',
4851 'financial_trxn_id' => $ftId,
4853 foreach ($lineItems as $key => $value) {
4854 $paid = $value['line_total'] * ($trxnAmount / $contribution->total_amount
);
4855 // Record Entity Financial Trxn
4856 $params['amount'] = round($paid, 2);
4857 $params['entity_id'] = $ftIds[$value['price_field_value_id']];
4859 civicrm_api3('EntityFinancialTrxn', 'create', $params);
4865 * Function use to store line item proportionaly in
4866 * in entity financial trxn table
4868 * @param array $params
4869 * array of contribution params.
4870 * @param object $trxn
4871 * CRM_Financial_DAO_FinancialTrxn object
4872 * @param array $contribution
4875 public static function assignProportionalLineItems($params, $trxn, $contribution) {
4876 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution_id']);
4877 if (!empty($lineItems)) {
4878 // get financial item
4879 $sql = "SELECT fi.id, li.price_field_value_id
4880 FROM civicrm_financial_item fi
4881 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
4882 WHERE li.contribution_id = %1";
4883 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($params['contribution_id'], 'Integer')));
4884 while ($dao->fetch()) {
4885 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4888 'entity_table' => 'civicrm_financial_item',
4889 'financial_trxn_id' => $trxn->id
,
4891 foreach ($lineItems as $key => $value) {
4892 $paid = $value['line_total'] * ($params['total_amount'] / $contribution['total_amount']);
4893 // Record Entity Financial Trxn
4894 $eftParams['amount'] = round($paid, 2);
4895 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
4897 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
4903 * Function to check line items
4905 * @param array $params
4906 * array of order params.
4909 public static function checkLineItems(&$params) {
4910 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4911 $lineItemAmount = 0;
4912 foreach ($params['line_items'] as &$lineItems) {
4913 foreach ($lineItems['line_item'] as &$item) {
4914 if (empty($item['financial_type_id'])) {
4915 $item['financial_type_id'] = $params['financial_type_id'];
4917 $lineItemAmount +
= $item['line_total'];
4920 if (!isset($totalAmount)) {
4921 $params['total_amount'] = $lineItemAmount;
4923 elseif ($totalAmount != $lineItemAmount) {
4924 throw new API_Exception("Line item total doesn't match with total amount.");
4929 * Get the financial account for the item associated with the new transaction.
4931 * @param array $params
4932 * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem
4936 public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) {
4938 if (!empty($params['financial_account_id'])) {
4939 return $params['financial_account_id'];
4941 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4942 $preferredAccountsRelationships = array(
4943 'Refunded' => 'Credit/Contra Revenue Account is',
4944 'Chargeback' => 'Chargeback Account is',
4946 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4947 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4948 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4950 $preferredAccountsRelationships[$contributionStatus]
4953 return $prevFinancialItem->financial_account_id
;
4957 * ContributionPage values were being imposed onto values.
4959 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4960 * REALLY didn't want superimposed. The rest are left there in their overkill out
4963 * The rationale for making this explicit is that it was a case of carefully set values being
4964 * seemingly randonly overwritten without much care. In general I think array randomly setting
4965 * variables en mass is risky.
4967 * @param array $values
4971 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4972 $contributionPageValues = array();
4973 CRM_Contribute_BAO_ContributionPage
::setValues(
4974 $this->contribution_page_id
,
4975 $contributionPageValues
4977 $valuesToCopy = array(
4978 // These are the values that I believe to be useful.
4981 'pay_later_receipt',
4983 'receipt_from_email',
4984 'receipt_from_name',
4988 'honoree_profile_id',
4989 'onbehalf_profile_id',
4990 'honor_block_is_active',
4991 // Kinda might be - but would be on the contribution...
4994 // Included for 'fear of regression' but can't justify any use for these....
4996 'payment_processor',
4997 'financial_type_id',
4998 'amount_block_is_active',
5003 'default_amount_id',
5007 'initial_amount_help_text',
5008 'initial_amount_label',
5010 'is_allow_other_amount',
5011 'is_billing_required',
5012 'is_confirm_enabled',
5013 'is_credit_card_only',
5015 'is_partial_payment',
5016 'is_recur_installments',
5017 'is_recur_interval',
5021 'min_initial_amount',
5022 'recur_frequency_unit',
5029 foreach ($valuesToCopy as $valueToCopy) {
5030 if (isset($contributionPageValues[$valueToCopy])) {
5031 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];