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',
545 //CRM-18406: Update activity when edit contribution.
546 if ($activity->find(TRUE)) {
547 // CRM-13237 : if activity record found, update it with campaign id of contribution
548 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
549 $contribution->activity_id
= $activity->id
;
551 if (empty($contribution->contact_id
)) {
552 $contribution->find(TRUE);
554 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
556 // do not add to recent items for import, CRM-4399
557 if (empty($params['skipRecentView'])) {
558 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
559 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
561 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
562 $titleFields = array(
568 $retrieveRequired = 0;
569 foreach ($titleFields as $titleField) {
570 if (!isset($contribution->$titleField)) {
571 $retrieveRequired = 1;
575 if ($retrieveRequired == 1) {
576 $contribution->find(TRUE);
578 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
579 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
581 $recentOther = array();
582 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
583 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
584 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
588 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
589 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
590 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
594 // add the recently created Contribution
595 CRM_Utils_Recent
::add($title,
599 $contribution->contact_id
,
605 return $contribution;
609 * Get the values for pseudoconstants for name->value and reverse.
611 * @param array $defaults
612 * (reference) the default values, some of which need to be resolved.
613 * @param bool $reverse
614 * True if we want to resolve the values in the reverse direction (value -> name).
616 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
617 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
618 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
619 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
620 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
624 * Convert associative array names to values and vice-versa.
626 * This function is used by both the web form layer and the api. Note that
627 * the api needs the name => value conversion, also the view layer typically
628 * requires value => name conversion
630 * @param array $defaults
631 * @param string $property
632 * @param array $lookup
633 * @param bool $reverse
637 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
638 $id = $property . '_id';
640 $src = $reverse ?
$property : $id;
641 $dst = $reverse ?
$id : $property;
643 if (!array_key_exists($src, $defaults)) {
647 $look = $reverse ?
array_flip($lookup) : $lookup;
649 if (is_array($look)) {
650 if (!array_key_exists($defaults[$src], $look)) {
654 $defaults[$dst] = $look[$defaults[$src]];
659 * Retrieve DB object based on input parameters.
661 * It also stores all the retrieved values in the default array.
663 * @param array $params
664 * (reference ) an assoc array of name/value pairs.
665 * @param array $defaults
666 * (reference ) an assoc array to hold the name / value pairs.
667 * in a hierarchical manner
669 * (reference) the array that holds all the db ids.
671 * @return CRM_Contribute_BAO_Contribution
673 public static function retrieve(&$params, &$defaults, &$ids) {
674 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
675 return $contribution;
679 * Combine all the importable fields from the lower levels object.
681 * The ordering is important, since currently we do not have a weight
682 * scheme. Adding weight is super important and should be done in the
683 * next week or so, before this can be called complete.
685 * @param string $contactType
686 * @param bool $status
689 * array of importable Fields
691 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
692 if (!self
::$_importableFields) {
693 if (!self
::$_importableFields) {
694 self
::$_importableFields = array();
698 $fields = array('' => array('title' => ts('- do not import -')));
701 $fields = array('' => array('title' => ts('- Contribution Fields -')));
704 $note = CRM_Core_DAO_Note
::import();
705 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
706 unset($tmpFields['option_value']);
707 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
708 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
710 // Using new Dedupe rule.
712 'contact_type' => $contactType,
713 'used' => 'Unsupervised',
715 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
716 $tmpContactField = array();
717 if (is_array($fieldsArray)) {
718 foreach ($fieldsArray as $value) {
719 //skip if there is no dupe rule
720 if ($value == 'none') {
723 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
728 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
729 $tmpContactField[trim($value)] = $contactFields[trim($value)];
731 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
734 $title = $tmpContactField[trim($value)]['title'];
736 $tmpContactField[trim($value)]['title'] = $title;
740 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
741 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
742 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
743 $fields = array_merge($fields, $tmpContactField);
744 $fields = array_merge($fields, $tmpFields);
745 $fields = array_merge($fields, $note);
746 $fields = array_merge($fields, $optionFields);
747 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
748 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
749 self
::$_importableFields = $fields;
751 return self
::$_importableFields;
755 * Combine all the exportable fields from the lower level objects.
757 * @param bool $checkPermission
760 * array of exportable Fields
762 public static function &exportableFields($checkPermission = TRUE) {
763 if (!self
::$_exportableFields) {
764 if (!self
::$_exportableFields) {
765 self
::$_exportableFields = array();
768 $impFields = CRM_Contribute_DAO_Contribution
::export();
769 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
770 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
771 $typeField = CRM_Financial_DAO_FinancialType
::export();
772 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
773 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
774 $contributionStatus = array(
775 'contribution_status' => array(
776 'title' => ts('Contribution Status'),
777 'name' => 'contribution_status',
778 'data_type' => CRM_Utils_Type
::T_STRING
,
782 $contributionPage = array(
783 'contribution_page' => array(
784 'title' => ts('Contribution Page'),
785 'name' => 'contribution_page',
786 'where' => 'civicrm_contribution_page.title',
787 'data_type' => CRM_Utils_Type
::T_STRING
,
791 $contributionNote = array(
792 'contribution_note' => array(
793 'title' => ts('Contribution Note'),
794 'name' => 'contribution_note',
795 'data_type' => CRM_Utils_Type
::T_TEXT
,
799 $contributionRecurId = array(
800 'contribution_recur_id' => array(
801 'title' => ts('Recurring Contributions ID'),
802 'name' => 'contribution_recur_id',
803 'where' => 'civicrm_contribution.contribution_recur_id',
804 'data_type' => CRM_Utils_Type
::T_INT
,
808 $extraFields = array(
809 'contribution_batch' => array(
810 'title' => ts('Batch Name'),
815 $campaignTitle = array(
816 'contribution_campaign_title' => array(
817 'title' => ts('Campaign Title'),
818 'name' => 'campaign_title',
819 'where' => 'civicrm_campaign.title',
820 'data_type' => CRM_Utils_Type
::T_STRING
,
823 $softCreditFields = array(
824 'contribution_soft_credit_name' => array(
825 'name' => 'contribution_soft_credit_name',
826 'title' => 'Soft Credit For',
827 'where' => 'civicrm_contact_d.display_name',
828 'data_type' => CRM_Utils_Type
::T_STRING
,
830 'contribution_soft_credit_amount' => array(
831 'name' => 'contribution_soft_credit_amount',
832 'title' => 'Soft Credit Amount',
833 'where' => 'civicrm_contribution_soft.amount',
834 'data_type' => CRM_Utils_Type
::T_MONEY
,
836 'contribution_soft_credit_type' => array(
837 'name' => 'contribution_soft_credit_type',
838 'title' => 'Soft Credit Type',
839 'where' => 'contribution_softcredit_type.label',
840 'data_type' => CRM_Utils_Type
::T_STRING
,
842 'contribution_soft_credit_contribution_id' => array(
843 'name' => 'contribution_soft_credit_contribution_id',
844 'title' => 'Soft Credit For Contribution ID',
845 'where' => 'civicrm_contribution_soft.contribution_id',
846 'data_type' => CRM_Utils_Type
::T_INT
,
848 'contribution_soft_credit_contact_id' => array(
849 'name' => 'contribution_soft_credit_contact_id',
850 'title' => 'Soft Credit For Contact ID',
851 'where' => 'civicrm_contact_d.id',
852 'data_type' => CRM_Utils_Type
::T_INT
,
856 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
858 'contribution_product_id' => array(
859 'title' => ts('Premium'),
860 'name' => 'contribution_product_id',
861 'where' => 'civicrm_product.id',
862 'data_type' => CRM_Utils_Type
::T_INT
,
866 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
867 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
868 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
871 self
::$_exportableFields = $fields;
874 return self
::$_exportableFields;
878 * @param null $status
879 * @param null $startDate
880 * @param null $endDate
884 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
888 $where[] = 'contribution_status_id = 1';
892 $where[] = 'contribution_status_id = 3';
897 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
900 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
902 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
903 if ($financialTypes) {
904 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
905 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
908 $where[] = "c.financial_type_id IN (0)";
911 $whereCond = implode(' AND ', $where);
914 SELECT sum( total_amount ) as total_amount,
915 count( c.id ) as total_count,
917 FROM civicrm_contribution c
918 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
919 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
921 AND ( is_test = 0 OR is_test IS NULL )
922 AND contact.is_deleted = 0
926 $dao = CRM_Core_DAO
::executeQuery($query);
929 while ($dao->fetch()) {
930 $count +
= $dao->total_count
;
931 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
935 'amount' => implode(', ', $amount),
943 * Delete the indirect records associated with this contribution first.
948 * $results no of deleted Contribution on success, false otherwise
950 public static function deleteContribution($id) {
951 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
953 $transaction = new CRM_Core_Transaction();
956 //delete activity record
958 'source_record_id' => $id,
959 // activity type id for contribution
960 'activity_type_id' => 6,
963 CRM_Activity_BAO_Activity
::deleteActivity($params);
965 //delete billing address if exists for this contribution.
966 self
::deleteAddress($id);
968 //update pledge and pledge payment, CRM-3961
969 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
971 // remove entry from civicrm_price_set_entity, CRM-5095
972 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
973 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
975 // cleanup line items.
976 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
978 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
979 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
981 if ($participantId) {
982 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
985 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
989 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
990 $noteId = key($note);
992 CRM_Core_BAO_Note
::del($noteId, FALSE);
995 $dao = new CRM_Contribute_DAO_Contribution();
998 $results = $dao->delete();
1000 $transaction->commit();
1002 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1004 // delete the recently created Contribution
1005 $contributionRecent = array(
1007 'type' => 'Contribution',
1009 CRM_Utils_Recent
::del($contributionRecent);
1015 * React to a financial transaction (payment) failure.
1017 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1018 * payments is important for forensic and outreach reasons.
1020 * @param int $contributionID
1021 * @param int $contactID
1022 * @param string $message
1024 * @throws \CiviCRM_API3_Exception
1026 public static function failPayment($contributionID, $contactID, $message) {
1027 civicrm_api3('activity', 'create', array(
1028 'activity_type_id' => 'Failed Payment',
1029 'details' => $message,
1030 'subject' => ts('Payment failed at payment processor'),
1031 'source_record_id' => $contributionID,
1032 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1038 * Check if there is a contribution with the same trxn_id or invoice_id.
1040 * @param array $input
1041 * An assoc array of name/value pairs.
1042 * @param array $duplicates
1043 * (reference) store ids of duplicate contribs.
1047 * true if duplicate, false otherwise
1049 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1051 $id = CRM_Utils_Array
::value('id', $input);
1053 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1054 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1060 $clause[] = "trxn_id = %1";
1061 $input[1] = array($trxn_id, 'String');
1065 $clause[] = "invoice_id = %2";
1066 $input[2] = array($invoice_id, 'String');
1069 if (empty($clause)) {
1073 $clause = implode(' OR ', $clause);
1075 $clause = "( $clause ) AND id != %3";
1076 $input[3] = array($id, 'Integer');
1079 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1080 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1082 while ($dao->fetch()) {
1083 $duplicates[] = $dao->id
;
1090 * Takes an associative array and creates a contribution_product object.
1092 * the function extract all the params it needs to initialize the create a
1093 * contribution_product object. the params array could contain additional unused name/value
1096 * @param array $params
1097 * (reference) an assoc array of name/value pairs.
1099 * @return CRM_Contribute_DAO_ContributionProduct
1101 public static function addPremium(&$params) {
1102 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1103 $contributionProduct->copyValues($params);
1104 return $contributionProduct->save();
1108 * Get list of contribution fields for profile.
1109 * For now we only allow custom contribution fields to be in
1112 * @param bool $addExtraFields
1113 * True if special fields needs to be added.
1116 * the list of contribution fields
1118 public static function getContributionFields($addExtraFields = TRUE) {
1119 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1120 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1122 if ($addExtraFields) {
1123 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1126 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1128 foreach ($contributionFields as $key => $var) {
1129 if ($key == 'contribution_contact_id') {
1132 elseif ($key == 'contribution_campaign_id') {
1133 $var['title'] = ts('Campaign');
1135 $fields[$key] = $var;
1138 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1143 * Add extra fields specific to contribution.
1145 public static function getSpecialContributionFields() {
1146 $extraFields = array(
1147 'contribution_soft_credit_name' => array(
1148 'name' => 'contribution_soft_credit_name',
1149 'title' => 'Soft Credit Name',
1150 'headerPattern' => '/^soft_credit_name$/i',
1151 'where' => 'civicrm_contact_d.display_name',
1153 'contribution_soft_credit_email' => array(
1154 'name' => 'contribution_soft_credit_email',
1155 'title' => 'Soft Credit Email',
1156 'headerPattern' => '/^soft_credit_email$/i',
1157 'where' => 'soft_email.email',
1159 'contribution_soft_credit_phone' => array(
1160 'name' => 'contribution_soft_credit_phone',
1161 'title' => 'Soft Credit Phone',
1162 'headerPattern' => '/^soft_credit_phone$/i',
1163 'where' => 'soft_phone.phone',
1165 'contribution_soft_credit_contact_id' => array(
1166 'name' => 'contribution_soft_credit_contact_id',
1167 'title' => 'Soft Credit Contact ID',
1168 'headerPattern' => '/^soft_credit_contact_id$/i',
1169 'where' => 'civicrm_contribution_soft.contact_id',
1171 'contribution_pcp_title' => array(
1172 'name' => 'contribution_pcp_title',
1173 'title' => 'Personal Campaign Page Title',
1174 'headerPattern' => '/^contribution_pcp_title$/i',
1175 'where' => 'contribution_pcp.title',
1179 return $extraFields;
1183 * @param int $pageID
1187 public static function getCurrentandGoalAmount($pageID) {
1189 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1190 FROM civicrm_contribution_page p,
1191 civicrm_contribution c
1192 WHERE p.id = c.contribution_page_id
1194 AND c.cancel_date is null
1198 $config = CRM_Core_Config
::singleton();
1199 $params = array(1 => array($pageID, 'Integer'));
1200 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1202 if ($dao->fetch()) {
1203 return array($dao->goal
, $dao->total
);
1206 return array(NULL, NULL);
1211 * Get list of contributions which credit the passed in contact ID.
1213 * The returned array provides details about the original contribution & donor.
1215 * @todo - this is a confusing function called from one place. It has a test. It would be
1216 * nice to deprecate it.
1218 * @param int $honorId
1219 * In Honor of Contact ID.
1222 * list of contribution fields
1224 public static function getHonorContacts($honorId) {
1226 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1227 $honorDAO->contact_id
= $honorId;
1230 $type = CRM_Contribute_PseudoConstant
::financialType();
1232 while ($honorDAO->fetch()) {
1233 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1234 $contributionDAO->id
= $honorDAO->contribution_id
;
1236 if ($contributionDAO->find(TRUE)) {
1237 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1238 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1239 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1240 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1241 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1242 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1243 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1244 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1245 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1253 * Get the sort name of a contact for a particular contribution.
1256 * Id of the contribution.
1258 * @return null|string
1259 * sort name of the contact if found
1261 public static function sortName($id) {
1262 $id = CRM_Utils_Type
::escape($id, 'Integer');
1265 SELECT civicrm_contact.sort_name
1266 FROM civicrm_contribution, civicrm_contact
1267 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1268 AND civicrm_contribution.id = {$id}
1270 return CRM_Core_DAO
::singleValueQuery($query);
1274 * @param int $contactID
1278 public static function annual($contactID) {
1279 if (is_array($contactID)) {
1280 $contactIDs = implode(',', $contactID);
1283 $contactIDs = $contactID;
1286 $config = CRM_Core_Config
::singleton();
1287 $startDate = $endDate = NULL;
1289 $currentMonth = date('m');
1290 $currentDay = date('d');
1291 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1292 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1293 (int ) $config->fiscalYearStart
['d'] > $currentDay
1296 $year = date('Y') - 1;
1301 $nextYear = $year +
1;
1303 if ($config->fiscalYearStart
) {
1304 $newFiscalYearStart = $config->fiscalYearStart
;
1305 if ($newFiscalYearStart['M'] < 10) {
1306 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1308 if ($newFiscalYearStart['d'] < 10) {
1309 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1311 $config->fiscalYearStart
= $newFiscalYearStart;
1312 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1317 $startDate = "$year$monthDay";
1318 $endDate = "$nextYear$monthDay";
1319 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1320 $additionalWhere = " AND b.financial_type_id IN (0)";
1321 $liWhere = " AND i.financial_type_id IN (0)";
1322 if (!empty($financialTypes)) {
1323 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1324 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1327 SELECT count(*) as count,
1328 sum(total_amount) as amount,
1329 avg(total_amount) as average,
1331 FROM civicrm_contribution b
1332 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1333 WHERE b.contact_id IN ( $contactIDs )
1334 AND b.contribution_status_id = 1
1336 AND b.receive_date >= $startDate
1337 AND b.receive_date < $endDate
1341 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1343 $amount = $average = array();
1344 while ($dao->fetch()) {
1345 if ($dao->count
> 0 && $dao->amount
> 0) {
1346 $count +
= $dao->count
;
1347 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1348 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1354 implode(', ', $amount),
1355 implode(', ', $average),
1358 return array(0, 0, 0);
1362 * Check if there is a contribution with the params passed in.
1364 * Used for trxn_id,invoice_id and contribution_id
1366 * @param array $params
1367 * An assoc array of name/value pairs.
1370 * contribution id if success else NULL
1372 public static function checkDuplicateIds($params) {
1373 $dao = new CRM_Contribute_DAO_Contribution();
1377 foreach ($params as $k => $v) {
1379 $clause[] = "$k = '$v'";
1382 $clause = implode(' AND ', $clause);
1383 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1384 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1386 while ($dao->fetch()) {
1394 * Get the contribution details for component export.
1396 * @param int $exportMode
1398 * @param string $componentIds
1404 public static function getContributionDetails($exportMode, $componentIds) {
1405 $paymentDetails = array();
1406 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1408 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1409 $componentSelect = " civicrm_participant_payment.participant_id id";
1410 $additionalClause = "
1411 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1412 AND civicrm_participant_payment.participant_id {$componentClause} )
1415 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1416 $componentSelect = " civicrm_membership_payment.membership_id id";
1417 $additionalClause = "
1418 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1419 AND civicrm_membership_payment.membership_id {$componentClause} )
1422 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1423 $componentSelect = " civicrm_pledge_payment.id id";
1424 $additionalClause = "
1425 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1426 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1430 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1431 trxn_id, {$componentSelect}
1432 FROM civicrm_contribution
1433 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1434 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1435 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1436 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1437 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1438 AND option_group_contribution_status.id = contribution_status.option_group_id )
1442 $dao = CRM_Core_DAO
::executeQuery($query);
1444 while ($dao->fetch()) {
1445 $paymentDetails[$dao->id
] = array(
1446 'total_amount' => $dao->total_amount
,
1447 'contribution_status' => $dao->status
,
1448 'receive_date' => $dao->receive_date
,
1449 'pay_instru' => $dao->payment_instrument
,
1450 'trxn_id' => $dao->trxn_id
,
1454 return $paymentDetails;
1458 * Create address associated with contribution record.
1460 * As long as there is one or more billing field in the parameters we will create the address.
1462 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1465 * @param array $params
1466 * @param int $billingLocationTypeID
1471 public static function createAddress($params, $billingLocationTypeID) {
1472 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1473 if ($hasBillingField) {
1474 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1475 return $address->id
;
1482 * Delete billing address record related contribution.
1484 * @param int $contributionId
1485 * @param int $contactId
1487 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1489 $contactJoin = NULL;
1491 if ($contributionId) {
1492 $clauses[] = "cc.id = {$contributionId}";
1496 $clauses[] = "cco.id = {$contactId}";
1497 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1500 if (empty($clauses)) {
1501 CRM_Core_Error
::fatal();
1504 $condition = implode(' OR ', $clauses);
1508 FROM civicrm_address ca
1509 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1513 $dao = CRM_Core_DAO
::executeQuery($query);
1515 while ($dao->fetch()) {
1516 $params = array('id' => $dao->id
);
1517 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1522 * This function check online pending contribution associated w/
1523 * Online Event Registration or Online Membership signup.
1525 * @param int $componentId
1526 * Participant/membership id.
1527 * @param string $componentName
1531 * pending contribution id.
1533 public static function checkOnlinePendingContribution($componentId, $componentName) {
1534 $contributionId = NULL;
1535 if (!$componentId ||
1536 !in_array($componentName, array('Event', 'Membership'))
1538 return $contributionId;
1541 if ($componentName == 'Event') {
1542 $idName = 'participant_id';
1543 $componentTable = 'civicrm_participant';
1544 $paymentTable = 'civicrm_participant_payment';
1545 $source = ts('Online Event Registration');
1548 if ($componentName == 'Membership') {
1549 $idName = 'membership_id';
1550 $componentTable = 'civicrm_membership';
1551 $paymentTable = 'civicrm_membership_payment';
1552 $source = ts('Online Contribution');
1555 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1558 SELECT component.id as {$idName},
1559 componentPayment.contribution_id as contribution_id,
1560 contribution.source source,
1561 contribution.contribution_status_id as contribution_status_id,
1562 contribution.is_pay_later as is_pay_later
1563 FROM $componentTable component
1564 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1565 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1566 WHERE component.id = {$componentId}";
1568 $dao = CRM_Core_DAO
::executeQuery($query);
1570 while ($dao->fetch()) {
1571 if ($dao->contribution_id
&&
1572 $dao->is_pay_later
&&
1573 $dao->contribution_status_id
== $pendingStatusId &&
1574 strpos($dao->source
, $source) !== FALSE
1576 $contributionId = $dao->contribution_id
;
1581 return $contributionId;
1585 * Update contribution as well as related objects.
1587 * This function by-passes hooks - to address this - don't use this function.
1591 * Use api contribute.completetransaction
1592 * For failures use failPayment (preferably exposing by api in the process).
1594 * @param array $params
1595 * @param bool $processContributionObject
1598 * @throws \Exception
1600 public static function transitionComponents($params, $processContributionObject = FALSE) {
1601 // get minimum required values.
1602 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1603 $componentId = CRM_Utils_Array
::value('component_id', $params);
1604 $componentName = CRM_Utils_Array
::value('componentName', $params);
1605 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1606 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1608 // if we already processed contribution object pass previous status id.
1609 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1611 $updateResult = array();
1613 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1615 // we process only ( Completed, Cancelled, or Failed ) contributions.
1616 if (!$contributionId ||
1617 !in_array($contributionStatusId, array(
1618 array_search('Completed', $contributionStatuses),
1619 array_search('Cancelled', $contributionStatuses),
1620 array_search('Failed', $contributionStatuses),
1623 return $updateResult;
1626 if (!$componentName ||
!$componentId) {
1627 // get the related component details.
1628 $componentDetails = self
::getComponentDetails($contributionId);
1631 $componentDetails['contact_id'] = $contactId;
1632 $componentDetails['component'] = $componentName;
1634 if ($componentName == 'event') {
1635 $componentDetails['participant'] = $componentId;
1638 $componentDetails['membership'] = $componentId;
1642 if (!empty($componentDetails['contact_id'])) {
1643 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1649 // do check for required ids.
1650 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1651 return $updateResult;
1654 //now we are ready w/ required ids, start processing.
1656 $baseIPN = new CRM_Core_Payment_BaseIPN();
1658 $input = $ids = $objects = array();
1660 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1661 $ids['contribution'] = $contributionId;
1662 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1663 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1664 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1665 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1666 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1667 $ids['contributionRecur'] = NULL;
1668 $ids['contributionPage'] = NULL;
1670 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1671 CRM_Core_Error
::fatal();
1674 $memberships = &$objects['membership'];
1675 $participant = &$objects['participant'];
1676 $pledgePayment = &$objects['pledge_payment'];
1677 $contribution = &$objects['contribution'];
1679 if ($pledgePayment) {
1680 $pledgePaymentIDs = array();
1681 foreach ($pledgePayment as $key => $object) {
1682 $pledgePaymentIDs[] = $object->id
;
1684 $pledgeID = $pledgePayment[0]->pledge_id
;
1687 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1690 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1691 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1696 // we might want to process contribution object.
1697 $processContribution = FALSE;
1698 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1699 if (is_array($memberships)) {
1700 foreach ($memberships as $membership) {
1702 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1703 $membership->save();
1705 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1706 if ($processContributionObject) {
1707 $processContribution = TRUE;
1714 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1715 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1717 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1718 if ($processContributionObject) {
1719 $processContribution = TRUE;
1723 if ($pledgePayment) {
1724 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1726 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1727 if ($processContributionObject) {
1728 $processContribution = TRUE;
1732 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1733 if (is_array($memberships)) {
1734 foreach ($memberships as $membership) {
1736 $membership->status_id
= array_search('Expired', $membershipStatuses);
1737 $membership->save();
1739 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1740 if ($processContributionObject) {
1741 $processContribution = TRUE;
1747 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1748 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1750 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1751 if ($processContributionObject) {
1752 $processContribution = TRUE;
1756 if ($pledgePayment) {
1757 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1759 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1760 if ($processContributionObject) {
1761 $processContribution = TRUE;
1765 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1767 // only pending contribution related object processed.
1768 if ($previousContriStatusId &&
1769 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1771 // this is case when we already processed contribution object.
1772 return $updateResult;
1774 elseif (!$previousContriStatusId &&
1775 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1777 // this is case when we are going to process contribution object later.
1778 return $updateResult;
1781 if (is_array($memberships)) {
1782 foreach ($memberships as $membership) {
1787 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1788 $membership->membership_type_id
,
1789 $membership->is_test
, $membership->id
1792 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1793 // this picks up membership type changes during renewals
1795 SELECT membership_type_id
1796 FROM civicrm_membership_log
1797 WHERE membership_id=$membership->id
1800 $dao = new CRM_Core_DAO();
1802 if ($dao->fetch()) {
1803 if (!empty($dao->membership_type_id
)) {
1804 $membership->membership_type_id
= $dao->membership_type_id
;
1805 $membership->save();
1808 // else fall back to using current membership type
1811 // Figure out number of terms
1813 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1814 foreach ($lineitems as $lineitem) {
1815 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1816 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1818 // in case membership_num_terms comes through as null or zero
1819 $numterms = $numterms >= 1 ?
$numterms : 1;
1824 // CRM-15735-to update the membership status as per the contribution receive date
1826 if (!empty($params['receive_date'])) {
1827 $joinDate = $params['receive_date'];
1828 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1829 $membership->end_date
,
1830 $membership->join_date
,
1831 $params['receive_date'],
1833 $membership->membership_type_id
,
1836 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1837 $membership->save();
1840 if ($currentMembership) {
1841 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1842 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1843 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1846 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1849 //get the status for membership.
1850 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1852 $dates['join_date'],
1855 $membership->membership_type_id
,
1859 $formattedParams = array(
1860 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1861 array_search('Current', $membershipStatuses)
1863 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1864 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1865 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1868 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1870 $membership->copyValues($formattedParams);
1871 $membership->save();
1873 //updating the membership log
1874 $membershipLog = array();
1875 $membershipLog = $formattedParams;
1876 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1877 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1879 $membershipLog['start_date'] = $logStartDate;
1880 $membershipLog['membership_id'] = $membership->id
;
1881 $membershipLog['modified_id'] = $membership->contact_id
;
1882 $membershipLog['modified_date'] = date('Ymd');
1883 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1885 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1887 //update related Memberships.
1888 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1890 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1893 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1894 if ($processContributionObject) {
1895 $processContribution = TRUE;
1898 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1904 $updatedStatusId = array_search('Registered', $participantStatuses);
1905 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1907 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1908 if ($processContributionObject) {
1909 $processContribution = TRUE;
1913 if ($pledgePayment) {
1914 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1916 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1917 if ($processContributionObject) {
1918 $processContribution = TRUE;
1923 // process contribution object.
1924 if ($processContribution) {
1925 $contributionParams = array();
1932 'payment_instrument_id',
1935 'financial_type_id',
1936 'contribution_status_id',
1937 'non_deductible_amount',
1941 foreach ($fields as $field) {
1942 if (empty($params[$field])) {
1945 $contributionParams[$field] = $params[$field];
1948 $ids = array('contribution' => $contributionId);
1949 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1952 return $updateResult;
1956 * Returns all contribution related object ids.
1958 * @param $contributionId
1962 public static function getComponentDetails($contributionId) {
1963 $componentDetails = $pledgePayment = array();
1964 if (!$contributionId) {
1965 return $componentDetails;
1969 SELECT c.id as contribution_id,
1970 c.contact_id as contact_id,
1971 c.contribution_recur_id,
1972 mp.membership_id as membership_id,
1973 m.membership_type_id as membership_type_id,
1974 pp.participant_id as participant_id,
1975 p.event_id as event_id,
1976 pgp.id as pledge_payment_id
1977 FROM civicrm_contribution c
1978 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1979 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1980 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1981 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1982 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1983 WHERE c.id = $contributionId";
1985 $dao = CRM_Core_DAO
::executeQuery($query);
1986 $componentDetails = array();
1988 while ($dao->fetch()) {
1989 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1990 $componentDetails['contact_id'] = $dao->contact_id
;
1991 if ($dao->event_id
) {
1992 $componentDetails['event'] = $dao->event_id
;
1994 if ($dao->participant_id
) {
1995 $componentDetails['participant'] = $dao->participant_id
;
1997 if ($dao->membership_id
) {
1998 if (!isset($componentDetails['membership'])) {
1999 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2001 $componentDetails['membership'][] = $dao->membership_id
;
2002 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2004 if ($dao->pledge_payment_id
) {
2005 $pledgePayment[] = $dao->pledge_payment_id
;
2007 if ($dao->contribution_recur_id
) {
2008 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2012 if ($pledgePayment) {
2013 $componentDetails['pledge_payment'] = $pledgePayment;
2016 return $componentDetails;
2020 * @param int $contactId
2021 * @param bool $includeSoftCredit
2023 * @return null|string
2025 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2029 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
2030 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2031 $liWhere = " AND i.financial_type_id IN (0)";
2032 if (!empty($financialTypes)) {
2033 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2034 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2036 $contactContributionsSQL = "
2037 SELECT contribution.id AS id
2038 FROM civicrm_contribution contribution
2039 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2040 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2044 $contactSoftCreditContributionsSQL = "
2045 SELECT contribution.id
2046 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2047 ON ( contribution.id = softContribution.contribution_id )
2048 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2049 $query = "SELECT count( x.id ) count FROM ( ";
2050 $query .= $contactContributionsSQL;
2052 if ($includeSoftCredit) {
2053 $query .= " UNION ";
2054 $query .= $contactSoftCreditContributionsSQL;
2059 return CRM_Core_DAO
::singleValueQuery($query);
2063 * Repeat a transaction as part of a recurring series.
2065 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2066 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2067 * subsequent call to the contribution.completetransaction api.
2069 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2071 * @param CRM_Contribute_BAO_Contribution $contribution
2072 * @param array $input
2073 * @param array $contributionParams
2077 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
2078 if (!empty($contribution->id
)) {
2081 if (empty($contribution->id
)) {
2082 // Unclear why this would only be set for repeats.
2083 if (!empty($input['amount'])) {
2084 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2086 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution($contributionParams['contribution_recur_id']);
2087 if (!empty($contributionParams['contribution_recur_id'])) {
2088 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2089 'id' => $contributionParams['contribution_recur_id'],
2091 if (!empty($recurringContribution['campaign_id'])) {
2092 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2093 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2095 if (!empty($recurringContribution['financial_type_id'])) {
2096 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2097 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2100 $contributionParams['skipLineItem'] = TRUE;
2101 $contributionParams['status_id'] = 'Pending';
2102 if (isset($contributionParams['financial_type_id'])) {
2103 // Give precedence to passed in type.
2104 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2107 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2109 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2110 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2111 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2112 $contribution->id
= $createContribution['id'];
2113 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
2114 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2120 * Get individual id for onbehalf contribution.
2122 * @param int $contributionId
2124 * @param int $contributorId
2128 * containing organization id and individual id
2130 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2134 if (!$contributionId) {
2138 // fetch contributor id if null
2139 if (!$contributorId) {
2140 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2141 $contributionId, 'contact_id'
2145 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2146 $activityTypeId = array_search('Contribution', $activityTypeIds);
2148 if ($activityTypeId && $contributorId) {
2150 SELECT civicrm_activity_contact.contact_id
2151 FROM civicrm_activity_contact
2152 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2153 WHERE civicrm_activity.activity_type_id = %1
2154 AND civicrm_activity.source_record_id = %2
2155 AND civicrm_activity_contact.record_type_id = %3
2158 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2159 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2162 1 => array($activityTypeId, 'Integer'),
2163 2 => array($contributionId, 'Integer'),
2164 3 => array($sourceID, 'Integer'),
2167 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2169 // for on behalf contribution source is individual and contributor is organization
2170 if ($sourceContactId && $sourceContactId != $contributorId) {
2171 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2172 // get rel type id for employee of relation
2173 foreach ($relationshipTypeIds as $id => $typeVals) {
2174 if ($typeVals['name_a_b'] == 'Employee of') {
2175 $relationshipTypeId = $id;
2180 $rel = new CRM_Contact_DAO_Relationship();
2181 $rel->relationship_type_id
= $relationshipTypeId;
2182 $rel->contact_id_a
= $sourceContactId;
2183 $rel->contact_id_b
= $contributorId;
2184 if ($rel->find(TRUE)) {
2185 $ids['individual_id'] = $rel->contact_id_a
;
2186 $ids['organization_id'] = $rel->contact_id_b
;
2197 public static function getContributionDates() {
2198 $config = CRM_Core_Config
::singleton();
2199 $currentMonth = date('m');
2200 $currentDay = date('d');
2201 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2202 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2203 (int ) $config->fiscalYearStart
['d'] > $currentDay
2206 $year = date('Y') - 1;
2211 $year = array('Y' => $year);
2212 $yearDate = $config->fiscalYearStart
;
2213 $yearDate = array_merge($year, $yearDate);
2214 $yearDate = CRM_Utils_Date
::format($yearDate);
2216 $monthDate = date('Ym') . '01';
2222 'yearDate' => $yearDate,
2223 'monthDate' => $monthDate,
2228 * Load objects relations to contribution object.
2229 * Objects are stored in the $_relatedObjects property
2230 * In the first instance we are just moving functionality from BASEIpn -
2231 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2233 * Note that the unit test for the BaseIPN class tests this function
2235 * @param array $input
2236 * Input as delivered from Payment Processor.
2238 * Ids as Loaded by Payment Processor.
2239 * @param bool $loadAll
2240 * Load all related objects - even where id not passed in? (allows API to call this).
2245 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2247 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2248 if (empty($ids['contact']) && isset($this->contact_id
)) {
2249 $ids['contact'] = $this->contact_id
;
2252 if (empty($this->_component
)) {
2253 if (!empty($ids['event'])) {
2254 $this->_component
= 'event';
2257 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2261 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2262 // refactoring than anything else, and has unit test coverage.
2263 if (empty($this->financial_type_id
)) {
2267 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2272 if (!$paymentProcessorID && $this->contribution_page_id
) {
2273 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2274 $this->contribution_page_id
,
2277 if ($paymentProcessorID) {
2278 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2282 $ids['contributionType'] = $this->financial_type_id
;
2283 $ids['financialType'] = $this->financial_type_id
;
2286 'contact' => 'CRM_Contact_BAO_Contact',
2287 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2288 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2289 'financialType' => 'CRM_Financial_BAO_FinancialType',
2291 foreach ($entities as $entity => $bao) {
2292 if (!empty($ids[$entity])) {
2293 $this->_relatedObjects
[$entity] = new $bao();
2294 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2295 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2296 throw new CRM_Core_Exception($entity . ' could not be loaded');
2301 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2302 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2305 if (!empty($ids['pledge_payment'])) {
2306 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2307 if (empty($paymentID)) {
2310 $payment = new CRM_Pledge_BAO_PledgePayment();
2311 $payment->id
= $paymentID;
2312 if (!$payment->find(TRUE)) {
2313 throw new Exception("Could not find pledge payment record: " . $paymentID);
2315 $this->_relatedObjects
['pledge_payment'][] = $payment;
2319 $this->loadRelatedMembershipObjects($ids);
2321 if ($this->_component
!= 'contribute') {
2322 // we are in event mode
2323 // make sure event exists and is valid
2324 $event = new CRM_Event_BAO_Event();
2325 $event->id
= $ids['event'];
2326 if ($ids['event'] &&
2329 throw new Exception("Could not find event: " . $ids['event']);
2332 $this->_relatedObjects
['event'] = &$event;
2334 $participant = new CRM_Event_BAO_Participant();
2335 $participant->id
= $ids['participant'];
2336 if ($ids['participant'] &&
2337 !$participant->find(TRUE)
2339 throw new Exception("Could not find participant: " . $ids['participant']);
2341 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2343 $this->_relatedObjects
['participant'] = &$participant;
2345 // get the payment processor id from event - this is inaccurate see CRM-16923
2346 // in future we should look at throwing an exception here rather than an dubious guess.
2347 if (!$paymentProcessorID) {
2348 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2349 if ($paymentProcessorID) {
2350 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2355 if ($paymentProcessorID) {
2356 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2357 $this->is_test ?
'test' : 'live'
2359 $ids['paymentProcessor'] = $paymentProcessorID;
2360 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2366 * Create array of message information - ie. return html version, txt version, to field
2368 * @param array $input
2369 * Incoming information.
2370 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2371 * just check presence of recur object but maintaining legacy approach
2374 * IDs of related objects.
2375 * @param array $values
2376 * Any values that may have already been compiled by calling process.
2377 * This is augmented by values 'gathered' by gatherMessageValues
2378 * @param bool $recur
2379 * @param bool $returnMessageText
2380 * Distinguishes between whether to send message or return.
2381 * message text. We are working towards this function ALWAYS returning message text & calling
2382 * function doing emails / pdfs with it
2388 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2389 $this->loadRelatedObjects($input, $ids);
2391 if (empty($this->_component
)) {
2392 $this->_component
= CRM_Utils_Array
::value('component', $input);
2395 //not really sure what params might be passed in but lets merge em into values
2396 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2397 if (!empty($input['receipt_date'])) {
2398 $values['receipt_date'] = $input['receipt_date'];
2401 $template = CRM_Core_Smarty
::singleton();
2402 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2403 //what does recur 'mean here - to do with payment processor return functionality but
2404 // what is the importance
2405 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2406 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2408 $entityID = $entity = NULL;
2409 if (isset($ids['contribution'])) {
2410 $entity = 'contribution';
2411 $entityID = $ids['contribution'];
2413 if (!empty($ids['membership'])) {
2414 //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
2415 // 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
2416 // line having loaded an array
2417 $ids['membership'] = (array) $ids['membership'];
2418 $entity = 'membership';
2419 $entityID = $ids['membership'][0];
2422 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2423 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2424 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2426 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2427 //direct mode showing billing block, so use directIPN for temporary
2428 $template->assign('contributeMode', 'directIPN');
2431 // todo remove strtolower - check consistency
2432 if (strtolower($this->_component
) == 'event') {
2433 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2434 $values['event'] = array();
2436 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2438 //get location details
2439 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2440 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2442 $ufJoinParams = array(
2443 'entity_table' => 'civicrm_event',
2444 'entity_id' => $ids['event'],
2445 'module' => 'CiviEvent',
2448 list($custom_pre_id,
2450 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2452 $values['custom_pre_id'] = $custom_pre_id;
2453 $values['custom_post_id'] = $custom_post_ids;
2454 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2455 //and cases involving status updation through ipn
2456 // whatever that means!
2457 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2458 // perhaps we should throw an e-notice if amount is set & force total_amount?
2459 if (!empty($input['amount'])) {
2460 $values['totalAmount'] = $input['amount'];
2463 if ($values['event']['is_email_confirm']) {
2464 $values['is_email_receipt'] = 1;
2467 if (!empty($ids['contribution'])) {
2468 $values['contributionId'] = $ids['contribution'];
2471 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2472 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2476 $values['contribution_id'] = $this->id
;
2477 if (!empty($ids['related_contact'])) {
2478 $values['related_contact'] = $ids['related_contact'];
2479 if (isset($ids['onbehalf_dupe_alert'])) {
2480 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2482 $entityBlock = array(
2483 'contact_id' => $ids['contact'],
2484 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2485 'Home', 'id', 'name'
2488 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2489 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2492 if ($this->is_test
) {
2495 if (!empty($this->_relatedObjects
['membership'])) {
2496 foreach ($this->_relatedObjects
['membership'] as $membership) {
2497 if ($membership->id
) {
2498 $values['isMembership'] = TRUE;
2499 $values['membership_assign'] = TRUE;
2501 // need to set the membership values here
2502 $template->assign('membership_name',
2503 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2505 $template->assign('mem_start_date', $membership->start_date
);
2506 $template->assign('mem_join_date', $membership->join_date
);
2507 $template->assign('mem_end_date', $membership->end_date
);
2508 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2509 $template->assign('mem_status', $membership_status);
2510 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2511 $values['is_pay_later'] = 1;
2514 // if separate payment there are two contributions recorded and the
2515 // admin will need to send a receipt for each of them separately.
2516 // we dont link the two in the db (but can potentially infer it if needed)
2517 $template->assign('is_separate_payment', 0);
2519 if ($recur && $paymentObject) {
2520 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2521 $template->assign('cancelSubscriptionUrl', $url);
2522 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2523 $template->assign('updateSubscriptionBillingUrl', $url);
2524 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2525 $template->assign('updateSubscriptionUrl', $url);
2528 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2531 // otherwise if its about sending emails, continue sending without return, as we
2532 // don't want to exit the loop.
2537 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2543 * Gather values for contribution mail - this function has been created
2544 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2545 * Values related to the contribution in question are gathered
2547 * @param array $input
2548 * Input into function (probably from payment processor).
2549 * @param array $values
2551 * The set of ids related to the input.
2555 public function _gatherMessageValues($input, &$values, $ids = array()) {
2556 // set display address of contributor
2557 if ($this->address_id
) {
2558 $addressParams = array('id' => $this->address_id
);
2559 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2560 $addressDetails = array_values($addressDetails);
2562 // Else we assign the billing address of the contribution contact.
2564 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2565 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2566 $addressDetails = array_values($addressDetails);
2569 if (!empty($addressDetails[0]['display'])) {
2570 $values['address'] = $addressDetails[0]['display'];
2573 if ($this->_component
== 'contribute') {
2574 //get soft contributions
2575 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2576 if (!empty($softContributions)) {
2577 $values['softContributions'] = $softContributions['soft_credit'];
2579 if (isset($this->contribution_page_id
)) {
2580 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2581 if ($this->contribution_page_id
) {
2582 // CRM-8254 - override default currency if applicable
2583 $config = CRM_Core_Config
::singleton();
2584 $config->defaultCurrency
= CRM_Utils_Array
::value(
2587 $config->defaultCurrency
2591 // no contribution page -probably back office
2593 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2594 $values['is_email_receipt'] = 1;
2595 $values['title'] = 'Contribution';
2597 // set lineItem for contribution
2599 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2600 if (!empty($lineItem)) {
2601 $itemId = key($lineItem);
2602 foreach ($lineItem as &$eachItem) {
2603 if (isset($this->_relatedObjects
['membership'])
2604 && is_array($this->_relatedObjects
['membership'])
2605 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2606 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2607 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2608 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2611 $values['lineItem'][0] = $lineItem;
2612 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2616 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2620 // if this is onbehalf of contribution then set related contact
2621 if (!empty($relatedContact['individual_id'])) {
2622 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2627 $eventParams = array(
2628 'id' => $this->_relatedObjects
['event']->id
,
2630 $values['event'] = array();
2632 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2633 // add custom fields for event
2634 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2636 $eventCustomGroup = array();
2637 foreach ($eventGroupTree as $key => $group) {
2638 if ($key === 'info') {
2642 foreach ($group['fields'] as $k => $customField) {
2643 $groupLabel = $group['title'];
2644 if (!empty($customField['customValue'])) {
2645 foreach ($customField['customValue'] as $customFieldValues) {
2646 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2651 $values['event']['customGroup'] = $eventCustomGroup;
2653 //get participant details
2654 $participantParams = array(
2655 'id' => $this->_relatedObjects
['participant']->id
,
2658 $values['participant'] = array();
2660 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2661 // add custom fields for event
2662 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2663 $participantCustomGroup = array();
2664 foreach ($participantGroupTree as $key => $group) {
2665 if ($key === 'info') {
2669 foreach ($group['fields'] as $k => $customField) {
2670 $groupLabel = $group['title'];
2671 if (!empty($customField['customValue'])) {
2672 foreach ($customField['customValue'] as $customFieldValues) {
2673 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2678 $values['participant']['customGroup'] = $participantCustomGroup;
2680 //get location details
2681 $locationParams = array(
2682 'entity_id' => $this->_relatedObjects
['event']->id
,
2683 'entity_table' => 'civicrm_event',
2685 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2687 $ufJoinParams = array(
2688 'entity_table' => 'civicrm_event',
2689 'entity_id' => $ids['event'],
2690 'module' => 'CiviEvent',
2693 list($custom_pre_id,
2695 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2697 $values['custom_pre_id'] = $custom_pre_id;
2698 $values['custom_post_id'] = $custom_post_ids;
2700 // set lineItem for event contribution
2702 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2703 if (!empty($participantIds)) {
2704 foreach ($participantIds as $pIDs) {
2705 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2706 if (!CRM_Utils_System
::isNull($lineItem)) {
2707 $values['lineItem'][] = $lineItem;
2714 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2716 $customGroup = array();
2717 foreach ($groupTree as $key => $group) {
2718 if ($key === 'info') {
2722 foreach ($group['fields'] as $k => $customField) {
2723 $groupLabel = $group['title'];
2724 if (!empty($customField['customValue'])) {
2725 foreach ($customField['customValue'] as $customFieldValues) {
2726 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2731 $values['customGroup'] = $customGroup;
2737 * Assign message variables to template but try to break the habit.
2739 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2740 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2741 * multiple recurring payments for processors like IATS that use tokens.
2743 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2744 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2745 * Note we send directly from this function in some cases because it is only partly refactored.
2747 * Don't call this function directly as the signature will change.
2751 * @param CRM_Core_SMARTY $template
2752 * @param bool $recur
2753 * @param bool $returnMessageText
2757 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2758 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2759 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2760 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2761 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2762 $values['useForMember'] = TRUE;
2764 //assign honor information to receipt message
2765 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2767 if (isset($softRecord['soft_credit'])) {
2768 //if id of contribution page is present
2769 if (!empty($values['id'])) {
2770 $values['honor'] = array(
2771 'honor_profile_values' => array(),
2772 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2773 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2775 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2777 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2778 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2781 //offline contribution
2782 $softCreditTypes = $softCredits = array();
2783 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2784 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2785 $softCredits[$key] = array(
2786 'Name' => $softCredit['contact_name'],
2787 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2790 $template->assign('softCreditTypes', $softCreditTypes);
2791 $template->assign('softCredits', $softCredits);
2795 $dao = new CRM_Contribute_DAO_ContributionProduct();
2796 $dao->contribution_id
= $this->id
;
2797 if ($dao->find(TRUE)) {
2798 $premiumId = $dao->product_id
;
2799 $template->assign('option', $dao->product_option
);
2801 $productDAO = new CRM_Contribute_DAO_Product();
2802 $productDAO->id
= $premiumId;
2803 $productDAO->find(TRUE);
2804 $template->assign('selectPremium', TRUE);
2805 $template->assign('product_name', $productDAO->name
);
2806 $template->assign('price', $productDAO->price
);
2807 $template->assign('sku', $productDAO->sku
);
2809 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2810 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2811 if (!$values['amount'] && isset($this->total_amount
)) {
2812 $values['amount'] = $this->total_amount
;
2815 // add the new contribution values
2816 if (strtolower($this->_component
) == 'contribute') {
2818 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2819 $softDAO->contribution_id
= $this->id
;
2820 if ($softDAO->find(TRUE)) {
2821 $template->assign('pcpBlock', TRUE);
2822 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2823 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2824 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2826 //assign the pcp page title for email subject
2827 $pcpDAO = new CRM_PCP_DAO_PCP();
2828 $pcpDAO->id
= $softDAO->pcp_id
;
2829 if ($pcpDAO->find(TRUE)) {
2830 $template->assign('title', $pcpDAO->title
);
2835 if ($this->financial_type_id
) {
2836 $values['financial_type_id'] = $this->financial_type_id
;
2839 $template->assign('trxn_id', $this->trxn_id
);
2840 $template->assign('receive_date',
2841 CRM_Utils_Date
::processDate($this->receive_date
)
2843 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
2844 $template->assign('contributeMode', 'notify');
2845 $template->assign('action', $this->is_test ?
1024 : 1);
2846 $template->assign('receipt_text',
2847 CRM_Utils_Array
::value('receipt_text',
2851 $template->assign('is_monetary', 1);
2852 $template->assign('is_recur', (bool) $recur);
2853 $template->assign('currency', $this->currency
);
2854 $template->assign('address', CRM_Utils_Address
::format($input));
2855 if (!empty($values['customGroup'])) {
2856 $template->assign('customGroup', $values['customGroup']);
2858 if (!empty($values['softContributions'])) {
2859 $template->assign('softContributions', $values['softContributions']);
2861 if ($this->_component
== 'event') {
2862 $template->assign('title', $values['event']['title']);
2863 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2864 $viewRoles = array();
2865 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2866 $viewRoles[] = $participantRoles[$v];
2868 $values['event']['participant_role'] = implode(', ', $viewRoles);
2869 $template->assign('event', $values['event']);
2870 $template->assign('participant', $values['participant']);
2871 $template->assign('location', $values['location']);
2872 $template->assign('customPre', $values['custom_pre_id']);
2873 $template->assign('customPost', $values['custom_post_id']);
2876 if ($this->_relatedObjects
['participant']->is_test
) {
2880 $values['params'] = array();
2881 //to get email of primary participant.
2882 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2883 $primaryAmount[] = array(
2884 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2885 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2887 //build an array of cId/pId of participants
2888 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2889 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2890 //send receipt to additional participant if exists
2891 if (count($additionalIDs)) {
2892 $template->assign('isPrimary', 0);
2893 $template->assign('customProfile', NULL);
2894 //set additionalParticipant true
2895 $values['params']['additionalParticipant'] = TRUE;
2896 foreach ($additionalIDs as $pId => $cId) {
2898 //to change the status pending to completed
2899 $additional = new CRM_Event_DAO_Participant();
2900 $additional->id
= $pId;
2901 $additional->contact_id
= $cId;
2902 $additional->find(TRUE);
2903 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2904 $additional->status_id
= 1;
2905 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2906 //if additional participant dont have email
2908 if (!$additionalParticipantInfo) {
2909 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2911 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2912 $primaryAmount[] = array(
2913 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2914 'amount' => $additional->fee_amount
,
2916 $additional->save();
2917 $additional->free();
2918 $template->assign('amount', $amount);
2919 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2923 //build an array of custom profile and assigning it to template
2924 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2926 if (count($customProfile)) {
2927 $template->assign('customProfile', $customProfile);
2930 // for primary contact
2931 $values['params']['additionalParticipant'] = FALSE;
2932 $template->assign('isPrimary', 1);
2933 $template->assign('amount', $primaryAmount);
2934 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2935 if ($this->payment_instrument_id
) {
2936 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2937 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2939 // carry paylater, since we did not created billing,
2940 // so need to pull email from primary location, CRM-4395
2941 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2947 * Check whether payment processor supports
2948 * cancellation of contribution subscription
2950 * @param int $contributionId
2953 * @param bool $isNotCancelled
2957 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2958 $cacheKeyString = "$contributionId";
2959 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2961 static $supportsCancel = array();
2963 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2964 $supportsCancel[$cacheKeyString] = FALSE;
2965 $isCancelled = FALSE;
2967 if ($isNotCancelled) {
2968 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2971 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2972 if (!empty($paymentObject)) {
2973 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
2976 return $supportsCancel[$cacheKeyString];
2980 * Check whether subscription is already cancelled.
2982 * @param int $contributionId
2986 * contribution status
2988 public static function isSubscriptionCancelled($contributionId) {
2990 SELECT cr.contribution_status_id
2991 FROM civicrm_contribution_recur cr
2992 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2993 WHERE con.id = %1 LIMIT 1";
2994 $params = array(1 => array($contributionId, 'Integer'));
2995 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2996 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2997 if ($status == 'Cancelled') {
3004 * Create all financial accounts entry.
3006 * @param array $params
3007 * Contribution object, line item array and params for trxn.
3010 * @param array $financialTrxnValues
3012 * @return null|object
3014 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3015 $skipRecords = $update = $return = $isRelatedId = FALSE;
3017 $additionalParticipantId = array();
3018 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3019 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3021 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3022 $entityId = $params['participant_id'];
3023 $entityTable = 'civicrm_participant';
3024 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3026 elseif (!empty($params['membership_id'])) {
3027 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3028 // are created off one contribution should be handled elsewhere
3029 $entityId = $params['membership_id'];
3030 $entityTable = 'civicrm_membership';
3033 $entityId = $params['contribution']->id
;
3034 $entityTable = 'civicrm_contribution';
3037 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3038 $isRelatedId = TRUE;
3041 $entityID[] = $entityId;
3042 if (!empty($additionalParticipantId)) {
3043 $entityID +
= $additionalParticipantId;
3045 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3046 if (empty($params['prevContribution'])) {
3053 $statusId = $params['contribution']->contribution_status_id
;
3054 // CRM-13964 partial payment
3055 if ($contributionStatus == 'Partially paid'
3056 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3058 $partialAmtPay = $params['partial_amount_pay'];
3059 $partialAmtTotal = $params['partial_payment_total'];
3061 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3062 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3063 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3064 $params['total_amount'] = $partialAmtPay;
3066 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3067 if (empty($balanceTrxnInfo['trxn_id'])) {
3068 // create new balance transaction record
3069 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3070 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3072 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3073 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3074 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3075 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3076 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3077 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3078 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3079 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3080 $balanceTrxnParams['status_id'] = $statusId;
3081 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3082 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3083 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3084 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3086 $balanceTrxnParams['is_payment'] = 1;
3088 if (!empty($params['payment_processor'])) {
3089 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3091 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3095 // build line item array if its not set in $params
3096 if (empty($params['line_item']) ||
$additionalParticipantId) {
3097 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3100 if ($contributionStatus != 'Failed' &&
3101 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3103 $skipRecords = TRUE;
3104 $pendingStatus = array(
3108 if (in_array($contributionStatus, $pendingStatus)) {
3109 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3110 $params['financial_type_id'],
3111 'Accounts Receivable Account is'
3114 elseif (!empty($params['payment_processor'])) {
3115 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3117 elseif (!empty($params['payment_instrument_id'])) {
3118 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3121 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3122 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3123 $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);
3126 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3127 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3128 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3131 //build financial transaction params
3132 $trxnParams = array(
3133 'contribution_id' => $params['contribution']->id
,
3134 'to_financial_account_id' => $params['to_financial_account_id'],
3135 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3136 'total_amount' => $totalAmount,
3137 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3138 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3139 'currency' => $params['contribution']->currency
,
3140 'trxn_id' => $params['contribution']->trxn_id
,
3141 'status_id' => $statusId,
3142 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
3143 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3145 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback') {
3146 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3147 if (isset($params['refund_trxn_id'])) {
3148 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3149 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3152 //CRM-16259, set is_payment flag for non pending status
3153 if (!in_array($contributionStatus, $pendingStatus)) {
3154 $trxnParams['is_payment'] = 1;
3156 if (!empty($params['payment_processor'])) {
3157 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3160 if (isset($fromFinancialAccountId)) {
3161 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3164 // consider external values passed for recording transaction entry
3165 if (!empty($financialTrxnValues)) {
3166 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3169 $params['trxnParams'] = $trxnParams;
3171 if (!empty($params['prevContribution'])) {
3173 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3174 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3175 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3176 if (!isset($params['trxnParams']['trxn_id'])) {
3177 // Actually I have no idea why we are overwriting any values from the previous contribution.
3178 // (filling makes sense to me). However, only protecting this value as I really really know we
3179 // don't want this one overwritten.
3181 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3183 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3185 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3186 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3187 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3189 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3190 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3193 //if financial type is changed
3194 if (!empty($params['financial_type_id']) &&
3195 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3197 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3198 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3199 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3200 if ($oldFinancialAccount != $newFinancialAccount) {
3201 $params['total_amount'] = 0;
3202 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3203 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3204 $params['prevContribution']->financial_type_id
, $relationTypeId);
3207 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3208 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3209 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3212 self
::updateFinancialAccounts($params, 'changeFinancialType');
3213 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3214 $params['financial_account_id'] = $newFinancialAccount;
3215 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3216 self
::updateFinancialAccounts($params);
3217 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3222 //Update contribution status
3223 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3224 if (!isset($params['refund_trxn_id'])) {
3225 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3226 // gets preference over another so I am only 'protecting' a very specific tested flow
3227 // and letting natural justice take care of the rest.
3228 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3230 if (!empty($params['contribution_status_id']) &&
3231 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3233 //Update Financial Records
3234 self
::updateFinancialAccounts($params, 'changedStatus');
3238 // change Payment Instrument for a Completed contribution
3239 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3240 // instrument is null and now new payment instrument is added along with the payment
3241 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3242 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3243 if (array_key_exists('payment_instrument_id', $params)) {
3244 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3245 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3246 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3248 //check if status is changed from Pending to Completed
3249 // do not update payment instrument changes for Pending to Completed
3250 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3251 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3253 // for all other statuses create new financial records
3254 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3255 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3256 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3260 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3261 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3262 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3264 // for any other payment instrument changes create new financial records
3265 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3266 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3267 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3270 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3271 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3273 // another special case when check number is changed, create new financial records
3274 // create financial trxn with negative amount
3275 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3276 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3277 // create financial trxn with positive amount
3278 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3279 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3280 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3285 //if Change contribution amount
3286 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3287 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3288 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3289 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3290 if (isset($totalAmount) &&
3291 $totalAmount != $params['prevContribution']->total_amount
3293 //Update Financial Records
3294 $params['trxnParams']['from_financial_account_id'] = NULL;
3295 self
::updateFinancialAccounts($params, 'changedAmount');
3300 // Looks like we might have a data correction update.
3301 // This would be a case where a transaction id has been entered but it is incorrect &
3302 // the person goes back in & fixes it, as opposed to a new transaction.
3303 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3304 // the data fix scenario.
3306 if (isset($params['refund_trxn_id'])) {
3307 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3308 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3309 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3316 // records finanical trxn and entity financial trxn
3317 // also make it available as return value
3318 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3319 $params['entity_id'] = $financialTxn->id
;
3322 // record line items and financial items
3323 if (empty($params['skipLineItem'])) {
3324 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3327 // create batch entry if batch_id is passed and
3328 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3329 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3330 $entityParams = array(
3331 'batch_id' => $params['batch_id'],
3332 'entity_table' => 'civicrm_financial_trxn',
3333 'entity_id' => $financialTxn->id
,
3335 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3338 // when a fee is charged
3339 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3340 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3343 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3344 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3346 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3347 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3348 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3350 unset($params['line_item']);
3356 * Update all financial accounts entry.
3358 * @param array $params
3359 * Contribution object, line item array and params for trxn.
3361 * @param string $context
3364 * @param null $skipTrxn
3367 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3368 $itemAmount = $trxnID = NULL;
3369 //get all the statuses
3370 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3371 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3372 if (($previousContributionStatus == 'Pending'
3373 ||
$previousContributionStatus == 'In Progress')
3374 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3375 && $context == 'changePaymentInstrument'
3379 if ((($previousContributionStatus == 'Partially paid'
3380 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3381 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3382 && $params['contribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus)))
3383 && $context == 'changedStatus'
3387 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3388 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3390 if ($context == 'changedStatus') {
3391 //get all the statuses
3392 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3393 $cancelledTaxAmount = 0;
3394 if ($previousContributionStatus == 'Completed'
3395 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3397 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3398 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $params, '0.00');
3399 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3400 $creditNoteId = self
::createCreditNoteId();
3401 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3404 elseif (($previousContributionStatus == 'Pending'
3405 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3407 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3408 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3409 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3411 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3412 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3413 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3414 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3415 $creditNoteId = self
::createCreditNoteId();
3416 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3420 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3423 $itemAmount = $params['trxnParams']['total_amount'] +
$cancelledTaxAmount;
3425 elseif ($context == 'changePaymentInstrument') {
3426 if ($params['trxnParams']['total_amount'] < 0) {
3427 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3428 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3429 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3430 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3434 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3435 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3439 if ($context == 'changedStatus') {
3440 if (($previousContributionStatus == 'Pending'
3441 ||
$previousContributionStatus == 'In Progress')
3442 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3444 if (empty($params['line_item'])) {
3446 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3447 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3448 // & this can be removed
3451 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3452 $params['entity_id'] = $trxn->id
;
3453 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3454 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3456 $entityParams = array(
3457 'entity_table' => 'civicrm_financial_item',
3458 'financial_trxn_id' => $trxn->id
,
3460 foreach ($params['line_item'] as $fieldId => $fields) {
3461 foreach ($fields as $fieldValueId => $fieldValues) {
3463 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3464 2 => array($fieldValues['id'], 'Integer'),
3466 CRM_Core_DAO
::executeQuery($query, $fparams);
3468 1 => array($fieldValues['id'], 'Integer'),
3470 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3471 while ($financialItem->fetch()) {
3472 $entityParams['entity_id'] = $financialItem->id
;
3473 $entityParams['amount'] = $financialItem->amount
;
3474 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3482 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3483 $params['entity_id'] = $trxn->id
;
3484 if ($context != 'changePaymentInstrument') {
3485 $itemParams['entity_table'] = 'civicrm_line_item';
3486 $trxnIds['id'] = $params['entity_id'];
3487 foreach ($params['line_item'] as $fieldId => $fields) {
3488 foreach ($fields as $fieldValueId => $fieldValues) {
3489 $prevParams['entity_id'] = $fieldValues['id'];
3490 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3492 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3493 if ($params['contribution']->receive_date
) {
3494 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3497 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem);
3499 $currency = $params['prevContribution']->currency
;
3500 if ($params['contribution']->currency
) {
3501 $currency = $params['contribution']->currency
;
3504 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($params['contribution']->contribution_status_id
)) {
3507 if (!empty($params['is_quick_config'])) {
3508 $amount = $itemAmount;
3510 $amount = $params['total_amount'];
3514 $amount = $diff * $fieldValues['line_total'];
3517 $itemParams = array(
3518 'transaction_date' => $receiveDate,
3519 'contact_id' => $params['prevContribution']->contact_id
,
3520 'currency' => $currency,
3521 'amount' => $amount,
3522 'description' => $prevFinancialItem->description
,
3523 'status_id' => $prevFinancialItem->status_id
,
3524 'financial_account_id' => $financialAccount,
3525 'entity_table' => 'civicrm_line_item',
3526 'entity_id' => $fieldValues['id'],
3528 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3530 if ($fieldValues['tax_amount']) {
3531 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3532 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3533 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3534 $itemParams['description'] = $taxTerm;
3535 if ($fieldValues['financial_type_id']) {
3536 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3538 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3543 if ($context == 'changeFinancialType') {
3544 $params['skipLineItem'] = FALSE;
3545 foreach ($params['line_item'] as &$lineItems) {
3546 foreach ($lineItems as &$line) {
3547 $line['financial_type_id'] = $params['financial_type_id'];
3554 * Is this contribution status a reversal.
3556 * If so we would expect to record a negative value in the financial_trxn table.
3558 * @param int $status_id
3562 public static function isContributionStatusNegative($status_id) {
3563 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3564 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3568 * Check status validation on update of a contribution.
3570 * @param array $values
3571 * Previous form values before submit.
3573 * @param array $fields
3574 * The input form values.
3576 * @param array $errors
3581 public static function checkStatusValidation($values, &$fields, &$errors) {
3582 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3583 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3584 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3588 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3589 $checkStatus = array(
3590 'Cancelled' => array('Completed', 'Refunded'),
3591 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3592 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3593 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3594 'Refunded' => array('Cancelled', 'Completed'),
3595 'Partially paid' => array('Completed'),
3598 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3599 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3601 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3602 1 => $contributionStatuses[$values['contribution_status_id']],
3603 2 => $contributionStatuses[$fields['contribution_status_id']],
3609 * Delete contribution of contact.
3613 * @param int $contactId
3617 public static function deleteContactContribution($contactId) {
3618 $contribution = new CRM_Contribute_DAO_Contribution();
3619 $contribution->contact_id
= $contactId;
3620 $contribution->find();
3621 while ($contribution->fetch()) {
3622 self
::deleteContribution($contribution->id
);
3627 * Get options for a given contribution field.
3628 * @see CRM_Core_DAO::buildOptions
3630 * @param string $fieldName
3631 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3632 * @param array $props whatever is known about this dao object.
3634 * @return array|bool
3636 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3637 $className = __CLASS__
;
3639 switch ($fieldName) {
3640 // This field is not part of this object but the api supports it
3641 case 'payment_processor':
3642 $className = 'CRM_Contribute_BAO_ContributionPage';
3643 // Filter results by contribution page
3644 if (!empty($props['contribution_page_id'])) {
3645 $page = civicrm_api('contribution_page', 'getsingle', array(
3647 'id' => ($props['contribution_page_id']),
3649 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3650 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3654 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3655 case 'honor_type_id':
3656 $className = 'CRM_Contribute_BAO_ContributionSoft';
3657 $fieldName = 'soft_credit_type_id';
3658 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3661 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3665 * Validate financial type.
3669 * @param int $financialTypeId
3670 * Financial Type id.
3672 * @param string $relationName
3674 * @return array|bool
3676 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3677 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3678 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3680 if (!$financialAccount) {
3681 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3688 * Function to record additional payment for partial and refund contributions.
3690 * @param int $contributionId
3691 * is the invoice contribution id (got created after processing participant payment).
3692 * @param array $trxnsData
3693 * to take user provided input of transaction details.
3694 * @param string $paymentType
3695 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3696 * @param int $participantId
3698 * @return null|object
3700 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3701 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3702 $getInfoOf['id'] = $contributionId;
3703 $defaults = array();
3704 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3705 if (!$participantId) {
3706 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id');
3709 if ($paymentType == 'owed') {
3710 // build params for recording financial trxn entry
3711 $params['contribution'] = $contributionDAO;
3712 $params = array_merge($defaults, $params);
3713 $params['skipLineItem'] = TRUE;
3714 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3715 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3716 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3717 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3720 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3721 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3722 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3724 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3725 if (!empty($trxnId)) {
3726 $trxnId = $trxnId['trxn_id'];
3728 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3729 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3732 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3733 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3734 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3738 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3739 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3740 FROM civicrm_financial_trxn ft
3741 LEFT JOIN civicrm_entity_financial_trxn eft
3742 ON (ft.id = eft.financial_trxn_id)
3743 WHERE eft.entity_table = 'civicrm_contribution'
3744 AND eft.entity_id = {$contributionId}
3745 AND ft.to_financial_account_id != {$toFinancialAccount}
3746 AND ft.status_id = {$statusId}
3748 $query = CRM_Core_DAO
::executeQuery($sql);
3750 $sumOfPayments = $query->sum_of_payments
;
3753 if ($contributionDAO->total_amount
== $sumOfPayments) {
3754 // update contribution status and
3755 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3756 $contributionDAO->contribution_status_id
= $statusId;
3757 $contributionDAO->cancel_date
= 'null';
3758 $contributionDAO->cancel_reason
= NULL;
3759 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3760 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3761 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3762 $contributionDAO->save();
3764 //Change status of financial record too
3765 $financialTrxn->status_id
= $statusId;
3766 $financialTrxn->save();
3768 // note : not using the self::add method,
3769 // the reason because it performs 'status change' related code execution for financial records
3770 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3771 // are coded below i.e. just updating financial_item status to 'Paid'
3773 if ($participantId) {
3774 // update participant status
3775 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3776 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3777 foreach ($ids as $val) {
3778 $participantUpdate['id'] = $val;
3779 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3780 CRM_Event_BAO_Participant
::add($participantUpdate);
3784 // update financial item statuses
3785 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3786 $paidStatus = array_search('Paid', $financialItemStatus);
3788 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3789 $sqlFinancialItemUpdate = "
3790 UPDATE civicrm_financial_item fi
3791 LEFT JOIN civicrm_entity_financial_trxn eft
3792 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3793 SET status_id = {$paidStatus}
3794 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3796 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3799 elseif ($paymentType == 'refund') {
3800 // build params for recording financial trxn entry
3801 $params['contribution'] = $contributionDAO;
3802 $params = array_merge($defaults, $params);
3803 $params['skipLineItem'] = TRUE;
3804 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3805 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3807 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3808 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3809 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3811 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3813 // note : not using the self::add method,
3814 // the reason because it performs 'status change' related code execution for financial records
3815 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3816 // are coded below i.e. just updating financial_item status to 'Paid'
3817 if ($updateStatus) {
3818 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3820 // add financial item entry
3821 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3822 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionDAO->id
);
3823 if (!empty($lineItems)) {
3824 foreach ($lineItems as $lineItemId => $lineItemValue) {
3825 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount
/ $contributionDAO->total_amount
);
3826 $addFinancialEntry = array(
3827 'transaction_date' => $financialTrxn->trxn_date
,
3828 'contact_id' => $contributionDAO->contact_id
,
3829 'amount' => round($paid, 2),
3830 'status_id' => array_search('Paid', $financialItemStatus),
3831 'entity_id' => $lineItemId,
3832 'entity_table' => 'civicrm_line_item',
3834 $trxnIds['id'] = $financialTrxn->id
;
3835 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3838 if ($participantId) {
3839 // update participant status
3840 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3841 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3842 foreach ($ids as $val) {
3843 $participantUpdate['id'] = $val;
3844 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3845 CRM_Event_BAO_Participant
::add($participantUpdate);
3850 // activity creation
3851 if (!empty($financialTrxn)) {
3852 if ($participantId) {
3853 $inputParams['id'] = $participantId;
3856 $component = 'event';
3857 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3858 $entityObj = $entityObj[$participantId];
3860 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3862 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3864 return $financialTrxn;
3870 * @param $activityType
3872 * @param int $contributionId
3874 * @throws CRM_Core_Exception
3876 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3877 if ($component == 'event') {
3878 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3879 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3880 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3881 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3882 $targetCid = $entityObj->contact_id
;
3883 // source record id would be the contribution id
3884 $srcRecId = $contributionId;
3888 $activityParams = array(
3889 'source_contact_id' => $targetCid,
3890 'source_record_id' => $srcRecId,
3891 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3895 'subject' => $subject,
3896 'activity_date_time' => $date,
3897 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3901 'skipRecentView' => TRUE,
3904 // create activity with target contacts
3905 $session = CRM_Core_Session
::singleton();
3906 $id = $session->get('userID');
3908 $activityParams['source_contact_id'] = $id;
3909 $activityParams['target_contact_id'][] = $targetCid;
3911 CRM_Activity_BAO_Activity
::create($activityParams);
3915 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3919 * @param bool $getTrxnInfo
3920 * @param bool $usingLineTotal
3924 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3925 if ($component == 'event') {
3926 $entity = 'participant';
3927 $entityTable = 'civicrm_participant';
3928 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3930 if (!$contributionId) {
3931 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3932 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3933 $id = $primaryParticipantId;
3935 if (!$contributionId) {
3941 $contributionId = $id;
3942 $entity = 'contribution';
3943 $entityTable = 'civicrm_contribution';
3946 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3947 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3953 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3954 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3957 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3958 // for additional participants
3959 if ($entityTable == 'civicrm_participant') {
3960 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3962 foreach ($ids as $val) {
3963 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3967 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3971 $baseTrxnId = $total['trxn_id'];
3972 $total = $total['total_amount'];
3975 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3976 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3978 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3979 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3980 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3982 if ($paymentBalance == 0 && $contributionIsPayLater) {
3983 $paymentBalance = $total;
3986 $info['total'] = $total;
3987 $info['paid'] = $total - $paymentBalance;
3988 $info['balance'] = $paymentBalance;
3990 $info['component'] = $component;
3991 $info['payLater'] = $contributionIsPayLater;
3993 if ($getTrxnInfo && $baseTrxnId) {
3994 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3996 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
3998 ft.payment_instrument_id,
3999 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, con.currency
4001 FROM civicrm_contribution con
4002 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4003 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4004 AND ft.to_financial_account_id != {$feeFinancialAccount}
4005 INNER JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4006 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4007 INNER JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4009 WHERE con.id = {$contributionId}
4013 // conditioned WHERE clause
4015 // if balance trxn exists don't include details of it in transaction info
4016 $sql .= " AND ft.id != {$baseTrxnId} ";
4018 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
4020 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4022 while ($resultDAO->fetch()) {
4023 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4024 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4026 'total_amount' => $resultDAO->total_amount
,
4027 'financial_type' => $resultDAO->financial_account
,
4028 'payment_instrument' => $paidByLabel,
4029 'receive_date' => $resultDAO->trxn_date
,
4030 'trxn_id' => $resultDAO->trxn_id
,
4031 'status' => $statuses[$resultDAO->status_id
],
4032 'currency' => $resultDAO->currency
,
4034 if ($paidByName == 'Check') {
4035 $val['check_number'] = $resultDAO->check_number
;
4039 $info['transaction'] = $rows;
4045 * Get financial account id has 'Sales Tax Account is'
4046 * account relationship with financial type
4048 * @param int $financialTypeId
4050 * @return FinancialAccountId
4052 public static function getFinancialAccountId($financialTypeId) {
4053 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4054 $searchParams = array(
4055 'entity_table' => 'civicrm_financial_type',
4056 'entity_id' => $financialTypeId,
4057 'account_relationship' => $accountRel,
4060 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
4062 return CRM_Utils_Array
::value('financial_account_id', $result);
4068 * @param array $params
4069 * @param bool $isLineItem
4073 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4074 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4076 // Update contribution.
4077 if (!empty($params['id'])) {
4078 $id = $params['id'];
4079 $values = $ids = array();
4080 $contrbutionParams = array('id' => $id);
4081 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
4083 // To assign pervious finantial type on update of contribution
4084 if (!isset($params['financial_type_id'])) {
4085 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
4087 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
4088 // Assisn tax Amount on update of contrbution
4089 if (!empty($prevContributionValue->tax_amount
)) {
4090 $params['tax_amount'] = 'null';
4091 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4092 foreach ($params['line_item'] as $setID => $priceField) {
4093 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4094 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4101 // New Contrbution and update of contribution with tax rate financial type
4102 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4103 empty($params['skipLineItem']) && !$isLineItem
4105 $taxRateParams = $taxRates[$params['financial_type_id']];
4106 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4107 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4109 // Get Line Item on update of contribution
4110 if (isset($params['id'])) {
4111 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4114 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4116 foreach ($params['line_item'] as $setID => $priceField) {
4117 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4118 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4121 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4123 elseif (isset($params['api.line_item.create'])) {
4124 // Update total amount of contribution using lineItem
4125 $taxAmountArray = array();
4126 foreach ($params['api.line_item.create'] as $key => $value) {
4127 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4128 $taxRate = $taxRates[$value['financial_type_id']];
4129 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4130 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4133 $params['tax_amount'] = array_sum($taxAmountArray);
4134 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4137 // update line item of contrbution
4138 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4139 $taxRate = $taxRates[$params['financial_type_id']];
4140 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
4141 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4148 * Check financial type validation on update of a contribution.
4150 * @param Integer $financialTypeId
4151 * Value of latest Financial Type.
4153 * @param Integer $contributionId
4156 * @param array $errors
4161 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4162 if (!empty($financialTypeId)) {
4163 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4164 if ($oldFinancialTypeId == $financialTypeId) {
4168 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4170 '1' => array($contributionId, 'Integer'),
4172 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4173 if ($result->N
> 1) {
4174 $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.');
4179 * Update related pledge payment payments.
4181 * This function has been refactored out of the back office contribution form and may
4182 * still overlap with other functions.
4184 * @param string $action
4185 * @param int $pledgePaymentID
4186 * @param int $contributionID
4187 * @param bool $adjustTotalAmount
4188 * @param float $total_amount
4189 * @param float $original_total_amount
4190 * @param int $contribution_status_id
4191 * @param int $original_contribution_status_id
4193 public static function updateRelatedPledge(
4199 $original_total_amount,
4200 $contribution_status_id,
4201 $original_contribution_status_id
4203 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4207 if ($pledgePaymentID) {
4208 //store contribution id in payment record.
4209 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4212 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4219 if (!$pledgePaymentID) {
4222 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4228 $updatePledgePaymentStatus = FALSE;
4230 // If either the status or the amount has changed we update the pledge status.
4231 if ($action & CRM_Core_Action
::ADD
) {
4232 $updatePledgePaymentStatus = TRUE;
4234 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4235 ($original_total_amount != $total_amount))
4237 $updatePledgePaymentStatus = TRUE;
4240 if ($updatePledgePaymentStatus) {
4241 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4242 array($pledgePaymentID),
4243 $contribution_status_id,
4252 * Compute the stats values
4254 * @param $stat either 'mode' or 'median'
4256 * @param $alias of civicrm_contribution
4258 public static function computeStats($stat, $sql, $alias = NULL) {
4259 $mode = $median = array();
4262 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4263 while ($modeDAO->fetch()) {
4264 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4265 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4274 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4275 foreach ($currencies as $currency => $val) {
4277 $where = "AND {$alias}.currency = '{$currency}'";
4278 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4282 $medianRow = floor($rowCount / 2);
4283 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4289 $medianValue = "SELECT {$alias}.total_amount as median
4291 ORDER BY median LIMIT {$medianRow},{$offset}";
4292 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4293 while ($medianValDAO->fetch()) {
4295 $midValue = $midValue +
$medianValDAO->median
;
4298 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4302 $midValue = $midValue / 2;
4303 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4314 * Is there only one line item attached to the contribution.
4320 * @throws \CiviCRM_API3_Exception
4322 public static function isSingleLineItem($id) {
4323 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4324 return ($lineItemCount == 1);
4328 * Complete an order.
4330 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4332 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4334 * Moving it out of the BaseIPN class is just the first step.
4336 * @param array $input
4338 * @param array $objects
4339 * @param CRM_Core_Transaction $transaction
4341 * @param CRM_Contribute_BAO_Contribution $contribution
4342 * @param bool $isRecurring
4343 * Duplication of param needs review. Only used by AuthorizeNetIPN
4344 * @param int $isFirstOrLastRecurringPayment
4345 * Deprecated param only used by AuthorizeNetIPN.
4347 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4348 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4349 // The previous details are used when calculating line items so keep it before any code that 'does something'
4350 if (!empty($contribution->id
)) {
4351 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4352 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4354 $inputContributionWhiteList = array(
4359 'payment_instrument_id',
4364 'contribution_status_id',
4366 if (self
::isSingleLineItem($primaryContributionID)) {
4367 $inputContributionWhiteList[] = 'financial_type_id';
4370 $participant = CRM_Utils_Array
::value('participant', $objects);
4371 $memberships = CRM_Utils_Array
::value('membership', $objects);
4372 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4373 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4374 $event = CRM_Utils_Array
::value('event', $objects);
4376 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4378 $contributionParams = array_merge(array(
4379 'contribution_status_id' => $completedContributionStatusID,
4380 'source' => self
::getRecurringContributionDescription($contribution, $event),
4381 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4384 if ($recurringContributionID) {
4385 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4387 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4389 if (empty($contributionParams['receive_date']) && $changeDate) {
4390 $contributionParams['receive_date'] = $changeDate;
4393 self
::repeatTransaction($contribution, $input, $contributionParams);
4394 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4396 if (is_numeric($memberships)) {
4397 $memberships = array($objects['membership']);
4401 if (isset($input['is_email_receipt'])) {
4402 $values['is_email_receipt'] = $input['is_email_receipt'];
4405 if ($input['component'] == 'contribute') {
4406 if ($contribution->contribution_page_id
) {
4407 // Figure out what we gain from this.
4408 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4410 elseif ($recurContrib && $recurringContributionID) {
4411 $values['amount'] = $recurContrib->amount
;
4412 $values['financial_type_id'] = $objects['contributionType']->id
;
4413 $values['title'] = $source = ts('Offline Recurring Contribution');
4416 if ($recurContrib && $recurringContributionID && !isset($input['is_email_receipt'])) {
4417 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4418 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4419 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4422 if (!empty($memberships)) {
4423 foreach ($memberships as $membershipTypeIdKey => $membership) {
4425 $membershipParams = array(
4426 'id' => $membership->id
,
4427 'contact_id' => $membership->contact_id
,
4428 'is_test' => $membership->is_test
,
4429 'membership_type_id' => $membership->membership_type_id
,
4432 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4433 $membershipParams['membership_type_id'],
4434 $membershipParams['is_test'],
4435 $membershipParams['id']
4438 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4439 // this picks up membership type changes during renewals
4441 SELECT membership_type_id
4442 FROM civicrm_membership_log
4443 WHERE membership_id={$membershipParams['id']}
4446 $dao = CRM_Core_DAO
::executeQuery($sql);
4447 if ($dao->fetch()) {
4448 if (!empty($dao->membership_type_id
)) {
4449 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4454 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4455 $membershipParams['membership_type_id'],
4456 $primaryContributionID
4458 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4459 if ($currentMembership) {
4461 * Fixed FOR CRM-4433
4462 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4463 * when Contribution mode is notify and membership is for renewal )
4465 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4467 // @todo - we should pass membership_type_id instead of null here but not
4468 // adding as not sure of testing
4469 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4470 $changeDate, NULL, $membershipParams['num_terms']
4473 $dates['join_date'] = $currentMembership['join_date'];
4476 //get the status for membership.
4477 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4479 $dates['join_date'],
4482 $membershipParams['membership_type_id'],
4486 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4487 //we might be renewing membership,
4488 //so make status override false.
4489 $membershipParams['is_override'] = FALSE;
4490 //CRM-17723 - reset static $relatedContactIds array()
4492 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
4493 civicrm_api3('Membership', 'create', $membershipParams);
4499 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4500 if ($event->is_email_confirm
) {
4501 // @todo this should be set by the function that sends the mail after sending.
4502 $contributionParams['receipt_date'] = $changeDate;
4504 $participantParams['id'] = $participant->id
;
4505 $participantParams['status_id'] = 'Registered';
4506 civicrm_api3('Participant', 'create', $participantParams);
4510 $contributionParams['id'] = $contribution->id
;
4512 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4514 // Add new soft credit against current $contribution.
4515 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4516 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4519 $paymentProcessorId = '';
4520 if (isset($objects['paymentProcessor'])) {
4521 if (is_array($objects['paymentProcessor'])) {
4522 $paymentProcessorId = $objects['paymentProcessor']['id'];
4525 $paymentProcessorId = $objects['paymentProcessor']->id
;
4529 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4530 'labelColumn' => 'name',
4533 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4534 $input['payment_processor'] = $paymentProcessorId;
4537 if (!empty($contribution->_relatedObjects
['participant'])) {
4538 $input['contribution_mode'] = 'participant';
4539 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4540 $input['skipLineItem'] = 1;
4542 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4543 $input['skipLineItem'] = TRUE;
4544 $input['contribution_mode'] = 'membership';
4545 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4546 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4547 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4549 $input['contribution_status_id'] = $contributionParams['contribution_status_id'];
4550 $input['total_amount'] = $input['amount'];
4551 $input['contribution'] = $contribution;
4552 $input['financial_type_id'] = $contribution->financial_type_id
;
4553 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4554 // and subsequent payments. In this case the line items are created at
4555 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4556 // and since the contribution is saved prior to this line there is always a contribution-id,
4557 // however there is never a prevContribution (which appears to mean original contribution not previous
4558 // contribution - or preUpdateContributionObject most accurately)
4559 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4560 // to mean "are we updating an exisitng pending contribution"
4561 //I was able to make the unit test complete as fataling here doesn't prevent
4562 // the contribution being created - but activities would not be created or emails sent
4564 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4566 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4567 $transaction->commit();
4569 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4570 $input['contribution_status_id'], $input['total_amount']);
4572 // create an activity record
4573 if ($input['component'] == 'contribute') {
4575 $targetContactID = NULL;
4576 if (!empty($ids['related_contact'])) {
4577 $targetContactID = $contribution->contact_id
;
4578 $contribution->contact_id
= $ids['related_contact'];
4580 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4584 CRM_Activity_BAO_Activity
::addActivity($participant);
4587 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4588 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4589 if (!array_key_exists('is_email_receipt', $values) ||
4590 $values['is_email_receipt'] == 1
4592 civicrm_api3('Contribution', 'sendconfirmation', array(
4593 'id' => $contribution->id
,
4594 'payment_processor_id' => $paymentProcessorId,
4596 CRM_Core_Error
::debug_log_message("Receipt sent");
4599 CRM_Core_Error
::debug_log_message("Success: Database updated");
4601 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4602 $isFirstOrLastRecurringPayment);
4604 return $contributionResult;
4608 * Send receipt from contribution.
4610 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4612 * Note that the compose message part has been moved to contribution
4613 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4615 * @param array $input
4616 * Incoming data from Payment processor.
4618 * Related object IDs.
4619 * @param int $contributionID
4620 * @param array $values
4621 * Values related to objects that have already been loaded.
4622 * @param bool $recur
4623 * Is it part of a recurring contribution.
4624 * @param bool $returnMessageText
4625 * Should text be returned instead of sent. This.
4626 * is because the function is also used to generate pdfs
4629 * @throws \CRM_Core_Exception
4630 * @throws \CiviCRM_API3_Exception
4632 public static function sendMail(&$input, &$ids, $contributionID, &$values, $recur = FALSE,
4633 $returnMessageText = FALSE) {
4634 $input['is_recur'] = $recur;
4636 $contribution = new CRM_Contribute_BAO_Contribution();
4637 $contribution->id
= $contributionID;
4638 if (!$contribution->find(TRUE)) {
4639 throw new CRM_Core_Exception('Contribution does not exist');
4641 $contribution->loadRelatedObjects($input, $ids, TRUE);
4642 // set receipt from e-mail and name in value
4643 if (!$returnMessageText) {
4644 $session = CRM_Core_Session
::singleton();
4645 $userID = $session->get('userID');
4646 if (!empty($userID)) {
4647 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4648 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4649 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4653 $return = $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4654 // Contribution ID should really always be set. But ?
4655 if (!$returnMessageText && (!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4656 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4662 * Generate credit note id with next avaible number
4667 public static function createCreditNoteId() {
4668 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4670 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4671 $creditNoteId = NULL;
4675 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4676 $result = civicrm_api3('Contribution', 'getcount', array(
4678 'creditnote_id' => $creditNoteId,
4680 } while ($result > 0);
4682 return $creditNoteId;
4686 * Load related memberships.
4688 * Note that in theory it should be possible to retrieve these from the line_item table
4689 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4690 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4691 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4692 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4694 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4700 public function loadRelatedMembershipObjects(&$ids) {
4702 SELECT membership_id
4703 FROM civicrm_membership_payment
4704 WHERE contribution_id = %1 ";
4705 $params = array(1 => array($this->id
, 'Integer'));
4707 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4708 while ($dao->fetch()) {
4709 if ($dao->membership_id
) {
4710 if (!is_array($ids['membership'])) {
4711 $ids['membership'] = array();
4713 $ids['membership'][] = $dao->membership_id
;
4717 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4718 foreach ($ids['membership'] as $id) {
4720 $membership = new CRM_Member_BAO_Membership();
4721 $membership->id
= $id;
4722 if (!$membership->find(TRUE)) {
4723 throw new Exception("Could not find membership record: $id");
4725 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4726 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4727 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4728 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4729 $membership->free();
4736 * This function is used to record partial payments for contribution
4738 * @param array $contribution
4740 * @param array $params
4744 public static function recordPartialPayment($contribution, $params) {
4745 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4746 $pendingStatus = array(
4747 array_search('Pending', $contributionStatuses),
4748 array_search('In Progress', $contributionStatuses),
4750 $statusId = array_search('Completed', $contributionStatuses);
4751 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4752 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4753 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4755 elseif (!empty($params['payment_processor'])) {
4756 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4758 elseif (!empty($params['payment_instrument_id'])) {
4759 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4762 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4763 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4764 $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);
4766 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4767 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4768 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4769 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4770 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4771 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4772 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4773 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4774 $balanceTrxnParams['currency'] = $contribution['currency'];
4775 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4776 $balanceTrxnParams['status_id'] = $statusId;
4777 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4778 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4779 if ($fromFinancialAccountId != NULL &&
4780 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4782 $balanceTrxnParams['is_payment'] = 1;
4784 if (!empty($params['payment_processor'])) {
4785 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4787 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4791 * Get the description (source field) for the recurring contribution.
4793 * @param CRM_Contribute_BAO_Contribution $contribution
4794 * @param CRM_Event_DAO_Event|null $event
4797 * @throws \CiviCRM_API3_Exception
4799 protected static function getRecurringContributionDescription($contribution, $event) {
4800 if (!empty($contribution->source
)) {
4801 return $contribution->source
;
4803 elseif (!empty($contribution->contribution_page_id
)) {
4804 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4805 'id' => $contribution->contribution_page_id
,
4806 'return' => 'title',
4808 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4811 return ts('Online Event Registration') . ': ' . $event->title
;
4813 return 'recurring contribution';
4817 * Function to add payments for contribution
4818 * for Partially Paid status
4820 * @param array $lineItems
4821 * @param array $contributions
4824 public static function addPayments($lineItems, $contributions) {
4825 // get financial trxn which is a payment
4826 $ftSql = "SELECT ft.id, ft.total_amount
4827 FROM civicrm_financial_trxn ft
4828 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4829 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4830 $sql = "SELECT fi.id, li.price_field_value_id
4831 FROM civicrm_financial_item fi
4832 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id
4833 WHERE li.contribution_id = %1";
4835 foreach ($contributions as $k => $contribution) {
4836 if ($contribution->contribution_status_id
!= CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name')) {
4839 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4841 $trxnAmount = $ftDao->total_amount
;
4844 // get financial item
4845 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contribution->id
, 'Integer')));
4846 while ($dao->fetch()) {
4847 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4851 'entity_table' => 'civicrm_financial_item',
4852 'financial_trxn_id' => $ftId,
4854 foreach ($lineItems as $key => $value) {
4855 $paid = $value['line_total'] * ($trxnAmount / $contribution->total_amount
);
4856 // Record Entity Financial Trxn
4857 $params['amount'] = round($paid, 2);
4858 $params['entity_id'] = $ftIds[$value['price_field_value_id']];
4860 civicrm_api3('EntityFinancialTrxn', 'create', $params);
4866 * Function use to store line item proportionaly in
4867 * in entity financial trxn table
4869 * @param array $params
4870 * array of contribution params.
4871 * @param object $trxn
4872 * CRM_Financial_DAO_FinancialTrxn object
4873 * @param array $contribution
4876 public static function assignProportionalLineItems($params, $trxn, $contribution) {
4877 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution_id']);
4878 if (!empty($lineItems)) {
4879 // get financial item
4880 $sql = "SELECT fi.id, li.price_field_value_id
4881 FROM civicrm_financial_item fi
4882 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
4883 WHERE li.contribution_id = %1";
4884 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($params['contribution_id'], 'Integer')));
4885 while ($dao->fetch()) {
4886 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4889 'entity_table' => 'civicrm_financial_item',
4890 'financial_trxn_id' => $trxn->id
,
4892 foreach ($lineItems as $key => $value) {
4893 $paid = $value['line_total'] * ($params['total_amount'] / $contribution['total_amount']);
4894 // Record Entity Financial Trxn
4895 $eftParams['amount'] = round($paid, 2);
4896 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
4898 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
4904 * Function to check line items
4906 * @param array $params
4907 * array of order params.
4910 public static function checkLineItems(&$params) {
4911 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4912 $lineItemAmount = 0;
4913 foreach ($params['line_items'] as &$lineItems) {
4914 foreach ($lineItems['line_item'] as &$item) {
4915 if (empty($item['financial_type_id'])) {
4916 $item['financial_type_id'] = $params['financial_type_id'];
4918 $lineItemAmount +
= $item['line_total'];
4921 if (!isset($totalAmount)) {
4922 $params['total_amount'] = $lineItemAmount;
4924 elseif ($totalAmount != $lineItemAmount) {
4925 throw new API_Exception("Line item total doesn't match with total amount.");
4930 * Get the financial account for the item associated with the new transaction.
4932 * @param array $params
4933 * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem
4937 public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) {
4939 if (!empty($params['financial_account_id'])) {
4940 return $params['financial_account_id'];
4942 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4943 $preferredAccountsRelationships = array(
4944 'Refunded' => 'Credit/Contra Revenue Account is',
4945 'Chargeback' => 'Chargeback Account is',
4947 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4948 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4949 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4951 $preferredAccountsRelationships[$contributionStatus]
4954 return $prevFinancialItem->financial_account_id
;
4958 * ContributionPage values were being imposed onto values.
4960 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4961 * REALLY didn't want superimposed. The rest are left there in their overkill out
4964 * The rationale for making this explicit is that it was a case of carefully set values being
4965 * seemingly randonly overwritten without much care. In general I think array randomly setting
4966 * variables en mass is risky.
4968 * @param array $values
4972 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4973 $contributionPageValues = array();
4974 CRM_Contribute_BAO_ContributionPage
::setValues(
4975 $this->contribution_page_id
,
4976 $contributionPageValues
4978 $valuesToCopy = array(
4979 // These are the values that I believe to be useful.
4982 'pay_later_receipt',
4984 'receipt_from_email',
4985 'receipt_from_name',
4989 'honoree_profile_id',
4990 'onbehalf_profile_id',
4991 'honor_block_is_active',
4992 // Kinda might be - but would be on the contribution...
4995 // Included for 'fear of regression' but can't justify any use for these....
4997 'payment_processor',
4998 'financial_type_id',
4999 'amount_block_is_active',
5004 'default_amount_id',
5008 'initial_amount_help_text',
5009 'initial_amount_label',
5011 'is_allow_other_amount',
5012 'is_billing_required',
5013 'is_confirm_enabled',
5014 'is_credit_card_only',
5016 'is_partial_payment',
5017 'is_recur_installments',
5018 'is_recur_interval',
5022 'min_initial_amount',
5023 'recur_frequency_unit',
5030 foreach ($valuesToCopy as $valueToCopy) {
5031 if (isset($contributionPageValues[$valueToCopy])) {
5032 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];