3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 //if contribution is created with cancelled or refunded status, add credit note id
133 if (!empty($params['contribution_status_id'])) {
134 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
136 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
137 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
139 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
140 $params['creditnote_id'] = self
::createCreditNoteId();
145 //set defaults in create mode
146 if (!$contributionID) {
147 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
149 self
::calculateMissingAmountParams($params, $contributionID);
151 if (!empty($params['payment_instrument_id'])) {
152 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
153 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
154 $params['check_number'] = 'null';
158 $setPrevContribution = TRUE;
159 // CRM-13964 partial payment
160 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
161 $partialAmtTotal = $params['partial_payment_total'];
162 $partialAmtPay = $params['partial_amount_pay'];
163 $params['total_amount'] = $partialAmtTotal;
164 if ($partialAmtPay < $partialAmtTotal) {
165 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
166 $params['is_pay_later'] = 0;
167 $setPrevContribution = FALSE;
170 if ($contributionID && $setPrevContribution) {
171 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
174 if ($contributionID) {
175 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
178 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
180 $contribution = new CRM_Contribute_BAO_Contribution();
181 $contribution->copyValues($params);
183 $contribution->id
= $contributionID;
185 if (empty($contribution->id
)) {
186 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
187 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
188 $config = CRM_Core_Config
::singleton();
189 $contribution->currency
= $config->defaultCurrency
;
193 $result = $contribution->save();
195 // Add financial_trxn details as part of fix for CRM-4724
196 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
197 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
199 //add Account details
200 $params['contribution'] = $contribution;
201 self
::recordFinancialAccounts($params);
203 if (self
::isUpdateToRecurringContribution($params)) {
204 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
205 $params['contribution_recur_id'],
206 $contributionStatus[$params['contribution_status_id']]
210 // reset the group contact cache for this group
211 CRM_Contact_BAO_GroupContactCache
::remove();
213 if ($contributionID) {
214 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
217 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
224 * Is this contribution updating an existing recurring contribution.
226 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
227 * pending payment is being confirmed (or failing).
229 * @param array $params
233 public static function isUpdateToRecurringContribution($params) {
234 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
237 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
240 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
243 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
244 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
251 * Get defaults for new entity.
254 public static function getDefaults() {
256 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
257 FALSE, FALSE, FALSE, 'AND is_default = 1')
259 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
264 * Fetch the object and store the values in the values array.
266 * @param array $params
267 * Input parameters to find object.
268 * @param array $values
269 * Output values of the object.
271 * The array that holds all the db ids.
273 * @return CRM_Contribute_BAO_Contribution|null
274 * The found object or null
276 public static function getValues($params, &$values, &$ids) {
277 if (empty($params)) {
280 $contribution = new CRM_Contribute_BAO_Contribution();
282 $contribution->copyValues($params);
284 if ($contribution->find(TRUE)) {
285 $ids['contribution'] = $contribution->id
;
287 CRM_Core_DAO
::storeValues($contribution, $values);
289 return $contribution;
291 $null = NULL; // return by reference
296 * Calculate net_amount & fee_amount if they are not set.
298 * Net amount should be total - fee.
299 * This should only be called for new contributions.
301 * @param array $params
302 * Params for a new contribution before they are saved.
303 * @param int|null $contributionID
304 * Contribution ID if we are dealing with an update.
306 * @throws \CiviCRM_API3_Exception
308 public static function calculateMissingAmountParams(&$params, $contributionID) {
309 if (!$contributionID && !isset($params['fee_amount'])) {
310 if (isset($params['total_amount']) && isset($params['net_amount'])) {
311 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
314 $params['fee_amount'] = 0;
317 if (!isset($params['net_amount'])) {
318 if (!$contributionID) {
319 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
322 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
323 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
324 // net_amount may need adjusting.
325 $contribution = civicrm_api3('Contribution', 'getsingle', array(
326 'id' => $contributionID,
327 'return' => array('total_amount', 'net_amount'),
329 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
330 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
331 $params['net_amount'] = $totalAmount - $feeAmount;
339 * @param $billingLocationTypeID
343 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
344 $hasBillingField = FALSE;
345 $billingFields = array(
353 //build address array
354 $addressParams = array();
355 $addressParams['location_type_id'] = $billingLocationTypeID;
356 $addressParams['is_billing'] = 1;
358 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
359 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
360 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
361 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
363 foreach ($billingFields as $value) {
364 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
365 if (!empty($addressParams[$value])) {
366 $hasBillingField = TRUE;
369 return array($hasBillingField, $addressParams);
373 * Get address params ready to be passed to the payment processor.
375 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
376 * To create an address we need state_province_id.
378 * @param array $params
379 * @param int $billingLocationTypeID
383 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
384 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
385 foreach ($addressParams as $name => $field) {
386 if (substr($name, 0, 8) == 'billing_') {
387 $addressParams[substr($name, 9)] = $addressParams[$field];
390 return array($hasBillingField, $addressParams);
394 * Get the number of terms for this contribution for a given membership type
395 * based on querying the line item table and relevant price field values
396 * Note that any one contribution should only be able to have one line item relating to a particular membership
399 * @param int $membershipTypeID
401 * @param int $contributionID
405 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
406 $numTerms = CRM_Core_DAO
::singleValueQuery("
407 SELECT membership_num_terms FROM civicrm_line_item li
408 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
409 WHERE contribution_id = %1 AND membership_type_id = %2",
410 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
412 // default of 1 is precautionary
413 return empty($numTerms) ?
1 : $numTerms;
417 * Takes an associative array and creates a contribution object.
419 * @param array $params
420 * (reference ) an assoc array of name/value pairs.
422 * The array that holds all the db ids.
424 * @return CRM_Contribute_BAO_Contribution
426 public static function create(&$params, $ids = array()) {
427 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
428 foreach ($dateFields as $df) {
429 if (isset($params[$df])) {
430 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
434 //if contribution is created with cancelled or refunded status, add credit note id
435 if (!empty($params['contribution_status_id'])) {
436 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
438 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
439 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
441 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
442 $params['creditnote_id'] = self
::createCreditNoteId();
447 $transaction = new CRM_Core_Transaction();
449 $contribution = self
::add($params, $ids);
451 if (is_a($contribution, 'CRM_Core_Error')) {
452 $transaction->rollback();
453 return $contribution;
456 $params['contribution_id'] = $contribution->id
;
458 if (!empty($params['custom']) &&
459 is_array($params['custom'])
461 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
464 $session = CRM_Core_Session
::singleton();
466 if (!empty($params['note'])) {
468 'entity_table' => 'civicrm_contribution',
469 'note' => $params['note'],
470 'entity_id' => $contribution->id
,
471 'contact_id' => $session->get('userID'),
472 'modified_date' => date('Ymd'),
474 if (!$noteParams['contact_id']) {
475 $noteParams['contact_id'] = $params['contact_id'];
477 CRM_Core_BAO_Note
::add($noteParams);
480 // make entry in batch entity batch table
481 if (!empty($params['batch_id'])) {
482 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
483 $titleFields = array(
489 $retrieveRequired = 0;
490 foreach ($titleFields as $titleField) {
491 if (!isset($contribution->$titleField)) {
492 $retrieveRequired = 1;
496 if ($retrieveRequired == 1) {
497 $contribution->find(TRUE);
501 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
503 $transaction->commit();
505 // check if activity record exist for this contribution, if
507 $activity = new CRM_Activity_DAO_Activity();
508 $activity->source_record_id
= $contribution->id
;
509 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
513 if (!$activity->find(TRUE)) {
514 if (empty($contribution->contact_id
)) {
515 $contribution->find(TRUE);
517 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
520 // CRM-13237 : if activity record found, update it with campaign id of contribution
521 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
524 // do not add to recent items for import, CRM-4399
525 if (empty($params['skipRecentView'])) {
526 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
527 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
529 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
530 $titleFields = array(
536 $retrieveRequired = 0;
537 foreach ($titleFields as $titleField) {
538 if (!isset($contribution->$titleField)) {
539 $retrieveRequired = 1;
543 if ($retrieveRequired == 1) {
544 $contribution->find(TRUE);
546 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
547 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
549 $recentOther = array();
550 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
551 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
552 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
556 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
557 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
558 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
562 // add the recently created Contribution
563 CRM_Utils_Recent
::add($title,
567 $contribution->contact_id
,
573 return $contribution;
577 * Get the values for pseudoconstants for name->value and reverse.
579 * @param array $defaults
580 * (reference) the default values, some of which need to be resolved.
581 * @param bool $reverse
582 * True if we want to resolve the values in the reverse direction (value -> name).
584 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
585 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
586 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
587 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
588 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
592 * Convert associative array names to values and vice-versa.
594 * This function is used by both the web form layer and the api. Note that
595 * the api needs the name => value conversion, also the view layer typically
596 * requires value => name conversion
598 * @param array $defaults
599 * @param string $property
600 * @param array $lookup
601 * @param bool $reverse
605 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
606 $id = $property . '_id';
608 $src = $reverse ?
$property : $id;
609 $dst = $reverse ?
$id : $property;
611 if (!array_key_exists($src, $defaults)) {
615 $look = $reverse ?
array_flip($lookup) : $lookup;
617 if (is_array($look)) {
618 if (!array_key_exists($defaults[$src], $look)) {
622 $defaults[$dst] = $look[$defaults[$src]];
627 * Retrieve DB object based on input parameters.
629 * It also stores all the retrieved values in the default array.
631 * @param array $params
632 * (reference ) an assoc array of name/value pairs.
633 * @param array $defaults
634 * (reference ) an assoc array to hold the name / value pairs.
635 * in a hierarchical manner
637 * (reference) the array that holds all the db ids.
639 * @return CRM_Contribute_BAO_Contribution
641 public static function retrieve(&$params, &$defaults, &$ids) {
642 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
643 return $contribution;
647 * Combine all the importable fields from the lower levels object.
649 * The ordering is important, since currently we do not have a weight
650 * scheme. Adding weight is super important and should be done in the
651 * next week or so, before this can be called complete.
653 * @param string $contactType
654 * @param bool $status
657 * array of importable Fields
659 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
660 if (!self
::$_importableFields) {
661 if (!self
::$_importableFields) {
662 self
::$_importableFields = array();
666 $fields = array('' => array('title' => ts('- do not import -')));
669 $fields = array('' => array('title' => ts('- Contribution Fields -')));
672 $note = CRM_Core_DAO_Note
::import();
673 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
674 unset($tmpFields['option_value']);
675 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
676 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
678 // Using new Dedupe rule.
680 'contact_type' => $contactType,
681 'used' => 'Unsupervised',
683 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
684 $tmpContactField = array();
685 if (is_array($fieldsArray)) {
686 foreach ($fieldsArray as $value) {
687 //skip if there is no dupe rule
688 if ($value == 'none') {
691 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
696 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
697 $tmpContactField[trim($value)] = $contactFields[trim($value)];
699 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
702 $title = $tmpContactField[trim($value)]['title'];
704 $tmpContactField[trim($value)]['title'] = $title;
708 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
709 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
710 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
711 $fields = array_merge($fields, $tmpContactField);
712 $fields = array_merge($fields, $tmpFields);
713 $fields = array_merge($fields, $note);
714 $fields = array_merge($fields, $optionFields);
715 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
716 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
717 self
::$_importableFields = $fields;
719 return self
::$_importableFields;
723 * Combine all the exportable fields from the lower level objects.
725 * @param bool $checkPermission
728 * array of exportable Fields
730 public static function &exportableFields($checkPermission = TRUE) {
731 if (!self
::$_exportableFields) {
732 if (!self
::$_exportableFields) {
733 self
::$_exportableFields = array();
736 $impFields = CRM_Contribute_DAO_Contribution
::export();
737 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
738 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
739 $typeField = CRM_Financial_DAO_FinancialType
::export();
740 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
741 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
742 $contributionStatus = array(
743 'contribution_status' => array(
744 'title' => ts('Contribution Status'),
745 'name' => 'contribution_status',
746 'data_type' => CRM_Utils_Type
::T_STRING
,
750 $contributionPage = array(
751 'contribution_page' => array(
752 'title' => ts('Contribution Page'),
753 'name' => 'contribution_page',
754 'where' => 'civicrm_contribution_page.title',
755 'data_type' => CRM_Utils_Type
::T_STRING
,
759 $contributionNote = array(
760 'contribution_note' => array(
761 'title' => ts('Contribution Note'),
762 'name' => 'contribution_note',
763 'data_type' => CRM_Utils_Type
::T_TEXT
,
767 $contributionRecurId = array(
768 'contribution_recur_id' => array(
769 'title' => ts('Recurring Contributions ID'),
770 'name' => 'contribution_recur_id',
771 'where' => 'civicrm_contribution.contribution_recur_id',
772 'data_type' => CRM_Utils_Type
::T_INT
,
776 $extraFields = array(
777 'contribution_batch' => array(
778 'title' => ts('Batch Name'),
782 $softCreditFields = array(
783 'contribution_soft_credit_name' => array(
784 'name' => 'contribution_soft_credit_name',
785 'title' => 'Soft Credit For',
786 'where' => 'civicrm_contact_d.display_name',
787 'data_type' => CRM_Utils_Type
::T_STRING
,
789 'contribution_soft_credit_amount' => array(
790 'name' => 'contribution_soft_credit_amount',
791 'title' => 'Soft Credit Amount',
792 'where' => 'civicrm_contribution_soft.amount',
793 'data_type' => CRM_Utils_Type
::T_MONEY
,
795 'contribution_soft_credit_type' => array(
796 'name' => 'contribution_soft_credit_type',
797 'title' => 'Soft Credit Type',
798 'where' => 'contribution_softcredit_type.label',
799 'data_type' => CRM_Utils_Type
::T_STRING
,
801 'contribution_soft_credit_contribution_id' => array(
802 'name' => 'contribution_soft_credit_contribution_id',
803 'title' => 'Soft Credit For Contribution ID',
804 'where' => 'civicrm_contribution_soft.contribution_id',
805 'data_type' => CRM_Utils_Type
::T_INT
,
807 'contribution_soft_credit_contact_id' => array(
808 'name' => 'contribution_soft_credit_contact_id',
809 'title' => 'Soft Credit For Contact ID',
810 'where' => 'civicrm_contact_d.id',
811 'data_type' => CRM_Utils_Type
::T_INT
,
815 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
817 'contribution_product_id' => array(
818 'title' => ts('Premium'),
819 'name' => 'contribution_product_id',
820 'where' => 'civicrm_product.id',
821 'data_type' => CRM_Utils_Type
::T_INT
,
825 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
826 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums,
827 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
830 self
::$_exportableFields = $fields;
833 return self
::$_exportableFields;
837 * @param null $status
838 * @param null $startDate
839 * @param null $endDate
843 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
847 $where[] = 'contribution_status_id = 1';
851 $where[] = 'contribution_status_id = 3';
856 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
859 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
861 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
862 if ($financialTypes) {
863 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
864 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
867 $where[] = "c.financial_type_id IN (0)";
870 $whereCond = implode(' AND ', $where);
873 SELECT sum( total_amount ) as total_amount,
874 count( c.id ) as total_count,
876 FROM civicrm_contribution c
877 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
878 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
880 AND ( is_test = 0 OR is_test IS NULL )
881 AND contact.is_deleted = 0
885 $dao = CRM_Core_DAO
::executeQuery($query);
888 while ($dao->fetch()) {
889 $count +
= $dao->total_count
;
890 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
894 'amount' => implode(', ', $amount),
902 * Delete the indirect records associated with this contribution first.
907 * $results no of deleted Contribution on success, false otherwise
909 public static function deleteContribution($id) {
910 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
912 $transaction = new CRM_Core_Transaction();
915 //delete activity record
917 'source_record_id' => $id,
918 // activity type id for contribution
919 'activity_type_id' => 6,
922 CRM_Activity_BAO_Activity
::deleteActivity($params);
924 //delete billing address if exists for this contribution.
925 self
::deleteAddress($id);
927 //update pledge and pledge payment, CRM-3961
928 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
930 // remove entry from civicrm_price_set_entity, CRM-5095
931 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
932 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
934 // cleanup line items.
935 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
937 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
938 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
940 if ($participantId) {
941 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
944 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
948 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
949 $noteId = key($note);
951 CRM_Core_BAO_Note
::del($noteId, FALSE);
954 $dao = new CRM_Contribute_DAO_Contribution();
957 $results = $dao->delete();
959 $transaction->commit();
961 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
963 // delete the recently created Contribution
964 $contributionRecent = array(
966 'type' => 'Contribution',
968 CRM_Utils_Recent
::del($contributionRecent);
974 * React to a financial transaction (payment) failure.
976 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
977 * payments is important for forensic and outreach reasons.
979 * @param int $contributionID
980 * @param int $contactID
981 * @param string $message
983 * @throws \CiviCRM_API3_Exception
985 public static function failPayment($contributionID, $contactID, $message) {
986 civicrm_api3('activity', 'create', array(
987 'activity_type_id' => 'Failed Payment',
988 'details' => $message,
989 'subject' => ts('Payment failed at payment processor'),
990 'source_record_id' => $contributionID,
991 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
997 * Check if there is a contribution with the same trxn_id or invoice_id.
999 * @param array $input
1000 * An assoc array of name/value pairs.
1001 * @param array $duplicates
1002 * (reference) store ids of duplicate contribs.
1006 * true if duplicate, false otherwise
1008 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1010 $id = CRM_Utils_Array
::value('id', $input);
1012 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1013 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1019 $clause[] = "trxn_id = %1";
1020 $input[1] = array($trxn_id, 'String');
1024 $clause[] = "invoice_id = %2";
1025 $input[2] = array($invoice_id, 'String');
1028 if (empty($clause)) {
1032 $clause = implode(' OR ', $clause);
1034 $clause = "( $clause ) AND id != %3";
1035 $input[3] = array($id, 'Integer');
1038 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1039 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1041 while ($dao->fetch()) {
1042 $duplicates[] = $dao->id
;
1049 * Takes an associative array and creates a contribution_product object.
1051 * the function extract all the params it needs to initialize the create a
1052 * contribution_product object. the params array could contain additional unused name/value
1055 * @param array $params
1056 * (reference) an assoc array of name/value pairs.
1058 * @return CRM_Contribute_DAO_ContributionProduct
1060 public static function addPremium(&$params) {
1061 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1062 $contributionProduct->copyValues($params);
1063 return $contributionProduct->save();
1067 * Get list of contribution fields for profile.
1068 * For now we only allow custom contribution fields to be in
1071 * @param bool $addExtraFields
1072 * True if special fields needs to be added.
1075 * the list of contribution fields
1077 public static function getContributionFields($addExtraFields = TRUE) {
1078 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1079 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1081 if ($addExtraFields) {
1082 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1085 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1087 foreach ($contributionFields as $key => $var) {
1088 if ($key == 'contribution_contact_id') {
1091 elseif ($key == 'contribution_campaign_id') {
1092 $var['title'] = ts('Campaign');
1094 $fields[$key] = $var;
1097 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1102 * Add extra fields specific to contribution.
1104 public static function getSpecialContributionFields() {
1105 $extraFields = array(
1106 'contribution_soft_credit_name' => array(
1107 'name' => 'contribution_soft_credit_name',
1108 'title' => 'Soft Credit Name',
1109 'headerPattern' => '/^soft_credit_name$/i',
1110 'where' => 'civicrm_contact_d.display_name',
1112 'contribution_soft_credit_email' => array(
1113 'name' => 'contribution_soft_credit_email',
1114 'title' => 'Soft Credit Email',
1115 'headerPattern' => '/^soft_credit_email$/i',
1116 'where' => 'soft_email.email',
1118 'contribution_soft_credit_phone' => array(
1119 'name' => 'contribution_soft_credit_phone',
1120 'title' => 'Soft Credit Phone',
1121 'headerPattern' => '/^soft_credit_phone$/i',
1122 'where' => 'soft_phone.phone',
1124 'contribution_soft_credit_contact_id' => array(
1125 'name' => 'contribution_soft_credit_contact_id',
1126 'title' => 'Soft Credit Contact ID',
1127 'headerPattern' => '/^soft_credit_contact_id$/i',
1128 'where' => 'civicrm_contribution_soft.contact_id',
1130 'contribution_pcp_title' => array(
1131 'name' => 'contribution_pcp_title',
1132 'title' => 'Personal Campaign Page Title',
1133 'headerPattern' => '/^contribution_pcp_title$/i',
1134 'where' => 'contribution_pcp.title',
1138 return $extraFields;
1142 * @param int $pageID
1146 public static function getCurrentandGoalAmount($pageID) {
1148 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1149 FROM civicrm_contribution_page p,
1150 civicrm_contribution c
1151 WHERE p.id = c.contribution_page_id
1153 AND c.cancel_date is null
1157 $config = CRM_Core_Config
::singleton();
1158 $params = array(1 => array($pageID, 'Integer'));
1159 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1161 if ($dao->fetch()) {
1162 return array($dao->goal
, $dao->total
);
1165 return array(NULL, NULL);
1170 * Get list of contribution In Honor of contact Ids.
1172 * @param int $honorId
1173 * In Honor of Contact ID.
1176 * list of contribution fields
1178 public static function getHonorContacts($honorId) {
1180 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1181 $honorDAO->contact_id
= $honorId;
1184 $type = CRM_Contribute_PseudoConstant
::financialType();
1186 while ($honorDAO->fetch()) {
1187 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1188 $contributionDAO->id
= $honorDAO->contribution_id
;
1190 if ($contributionDAO->find(TRUE)) {
1191 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1192 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1193 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1194 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1195 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1196 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1197 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1198 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1199 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1207 * Get the sort name of a contact for a particular contribution.
1210 * Id of the contribution.
1212 * @return null|string
1213 * sort name of the contact if found
1215 public static function sortName($id) {
1216 $id = CRM_Utils_Type
::escape($id, 'Integer');
1219 SELECT civicrm_contact.sort_name
1220 FROM civicrm_contribution, civicrm_contact
1221 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1222 AND civicrm_contribution.id = {$id}
1224 return CRM_Core_DAO
::singleValueQuery($query);
1228 * @param int $contactID
1232 public static function annual($contactID) {
1233 if (is_array($contactID)) {
1234 $contactIDs = implode(',', $contactID);
1237 $contactIDs = $contactID;
1240 $config = CRM_Core_Config
::singleton();
1241 $startDate = $endDate = NULL;
1243 $currentMonth = date('m');
1244 $currentDay = date('d');
1245 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1246 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1247 (int ) $config->fiscalYearStart
['d'] > $currentDay
1250 $year = date('Y') - 1;
1255 $nextYear = $year +
1;
1257 if ($config->fiscalYearStart
) {
1258 $newFiscalYearStart = $config->fiscalYearStart
;
1259 if ($newFiscalYearStart['M'] < 10) {
1260 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1262 if ($newFiscalYearStart['d'] < 10) {
1263 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1265 $config->fiscalYearStart
= $newFiscalYearStart;
1266 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1271 $startDate = "$year$monthDay";
1272 $endDate = "$nextYear$monthDay";
1273 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1274 $additionalWhere = " AND b.financial_type_id IN (0)";
1275 $liWhere = " AND i.financial_type_id IN (0)";
1276 if (!empty($financialTypes)) {
1277 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1278 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1281 SELECT count(*) as count,
1282 sum(total_amount) as amount,
1283 avg(total_amount) as average,
1285 FROM civicrm_contribution b
1286 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1287 WHERE b.contact_id IN ( $contactIDs )
1288 AND b.contribution_status_id = 1
1290 AND b.receive_date >= $startDate
1291 AND b.receive_date < $endDate
1295 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1297 $amount = $average = array();
1298 while ($dao->fetch()) {
1299 if ($dao->count
> 0 && $dao->amount
> 0) {
1300 $count +
= $dao->count
;
1301 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1302 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1308 implode(', ', $amount),
1309 implode(', ', $average),
1312 return array(0, 0, 0);
1316 * Check if there is a contribution with the params passed in.
1318 * Used for trxn_id,invoice_id and contribution_id
1320 * @param array $params
1321 * An assoc array of name/value pairs.
1324 * contribution id if success else NULL
1326 public static function checkDuplicateIds($params) {
1327 $dao = new CRM_Contribute_DAO_Contribution();
1331 foreach ($params as $k => $v) {
1333 $clause[] = "$k = '$v'";
1336 $clause = implode(' AND ', $clause);
1337 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1338 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1340 while ($dao->fetch()) {
1348 * Get the contribution details for component export.
1350 * @param int $exportMode
1352 * @param string $componentIds
1358 public static function getContributionDetails($exportMode, $componentIds) {
1359 $paymentDetails = array();
1360 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1362 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1363 $componentSelect = " civicrm_participant_payment.participant_id id";
1364 $additionalClause = "
1365 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1366 AND civicrm_participant_payment.participant_id {$componentClause} )
1369 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1370 $componentSelect = " civicrm_membership_payment.membership_id id";
1371 $additionalClause = "
1372 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1373 AND civicrm_membership_payment.membership_id {$componentClause} )
1376 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1377 $componentSelect = " civicrm_pledge_payment.id id";
1378 $additionalClause = "
1379 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1380 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1384 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1385 trxn_id, {$componentSelect}
1386 FROM civicrm_contribution
1387 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1388 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1389 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1390 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1391 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1392 AND option_group_contribution_status.id = contribution_status.option_group_id )
1396 $dao = CRM_Core_DAO
::executeQuery($query);
1398 while ($dao->fetch()) {
1399 $paymentDetails[$dao->id
] = array(
1400 'total_amount' => $dao->total_amount
,
1401 'contribution_status' => $dao->status
,
1402 'receive_date' => $dao->receive_date
,
1403 'pay_instru' => $dao->payment_instrument
,
1404 'trxn_id' => $dao->trxn_id
,
1408 return $paymentDetails;
1412 * Create address associated with contribution record.
1414 * As long as there is one or more billing field in the parameters we will create the address.
1416 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1419 * @param array $params
1420 * @param int $billingLocationTypeID
1425 public static function createAddress($params, $billingLocationTypeID) {
1426 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1427 if ($hasBillingField) {
1428 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1429 return $address->id
;
1436 * Delete billing address record related contribution.
1438 * @param int $contributionId
1439 * @param int $contactId
1441 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1443 $contactJoin = NULL;
1445 if ($contributionId) {
1446 $clauses[] = "cc.id = {$contributionId}";
1450 $clauses[] = "cco.id = {$contactId}";
1451 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1454 if (empty($clauses)) {
1455 CRM_Core_Error
::fatal();
1458 $condition = implode(' OR ', $clauses);
1462 FROM civicrm_address ca
1463 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1467 $dao = CRM_Core_DAO
::executeQuery($query);
1469 while ($dao->fetch()) {
1470 $params = array('id' => $dao->id
);
1471 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1476 * This function check online pending contribution associated w/
1477 * Online Event Registration or Online Membership signup.
1479 * @param int $componentId
1480 * Participant/membership id.
1481 * @param string $componentName
1485 * pending contribution id.
1487 public static function checkOnlinePendingContribution($componentId, $componentName) {
1488 $contributionId = NULL;
1489 if (!$componentId ||
1490 !in_array($componentName, array('Event', 'Membership'))
1492 return $contributionId;
1495 if ($componentName == 'Event') {
1496 $idName = 'participant_id';
1497 $componentTable = 'civicrm_participant';
1498 $paymentTable = 'civicrm_participant_payment';
1499 $source = ts('Online Event Registration');
1502 if ($componentName == 'Membership') {
1503 $idName = 'membership_id';
1504 $componentTable = 'civicrm_membership';
1505 $paymentTable = 'civicrm_membership_payment';
1506 $source = ts('Online Contribution');
1509 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1512 SELECT component.id as {$idName},
1513 componentPayment.contribution_id as contribution_id,
1514 contribution.source source,
1515 contribution.contribution_status_id as contribution_status_id,
1516 contribution.is_pay_later as is_pay_later
1517 FROM $componentTable component
1518 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1519 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1520 WHERE component.id = {$componentId}";
1522 $dao = CRM_Core_DAO
::executeQuery($query);
1524 while ($dao->fetch()) {
1525 if ($dao->contribution_id
&&
1526 $dao->is_pay_later
&&
1527 $dao->contribution_status_id
== $pendingStatusId &&
1528 strpos($dao->source
, $source) !== FALSE
1530 $contributionId = $dao->contribution_id
;
1535 return $contributionId;
1539 * Update contribution as well as related objects.
1541 * This function by-passes hooks - to address this - don't use this function.
1545 * Use api contribute.completetransaction
1546 * For failures use failPayment (preferably exposing by api in the process).
1548 * @param array $params
1549 * @param bool $processContributionObject
1552 * @throws \Exception
1554 public static function transitionComponents($params, $processContributionObject = FALSE) {
1555 // get minimum required values.
1556 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1557 $componentId = CRM_Utils_Array
::value('component_id', $params);
1558 $componentName = CRM_Utils_Array
::value('componentName', $params);
1559 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1560 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1562 // if we already processed contribution object pass previous status id.
1563 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1565 $updateResult = array();
1567 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1569 // we process only ( Completed, Cancelled, or Failed ) contributions.
1570 if (!$contributionId ||
1571 !in_array($contributionStatusId, array(
1572 array_search('Completed', $contributionStatuses),
1573 array_search('Cancelled', $contributionStatuses),
1574 array_search('Failed', $contributionStatuses),
1577 return $updateResult;
1580 if (!$componentName ||
!$componentId) {
1581 // get the related component details.
1582 $componentDetails = self
::getComponentDetails($contributionId);
1585 $componentDetails['contact_id'] = $contactId;
1586 $componentDetails['component'] = $componentName;
1588 if ($componentName == 'event') {
1589 $componentDetails['participant'] = $componentId;
1592 $componentDetails['membership'] = $componentId;
1596 if (!empty($componentDetails['contact_id'])) {
1597 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1603 // do check for required ids.
1604 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1605 return $updateResult;
1608 //now we are ready w/ required ids, start processing.
1610 $baseIPN = new CRM_Core_Payment_BaseIPN();
1612 $input = $ids = $objects = array();
1614 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1615 $ids['contribution'] = $contributionId;
1616 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1617 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1618 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1619 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1620 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1621 $ids['contributionRecur'] = NULL;
1622 $ids['contributionPage'] = NULL;
1624 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1625 CRM_Core_Error
::fatal();
1628 $memberships = &$objects['membership'];
1629 $participant = &$objects['participant'];
1630 $pledgePayment = &$objects['pledge_payment'];
1631 $contribution = &$objects['contribution'];
1633 if ($pledgePayment) {
1634 $pledgePaymentIDs = array();
1635 foreach ($pledgePayment as $key => $object) {
1636 $pledgePaymentIDs[] = $object->id
;
1638 $pledgeID = $pledgePayment[0]->pledge_id
;
1641 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1644 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1645 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1650 // we might want to process contribution object.
1651 $processContribution = FALSE;
1652 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1653 if (is_array($memberships)) {
1654 foreach ($memberships as $membership) {
1656 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1657 $membership->save();
1659 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1660 if ($processContributionObject) {
1661 $processContribution = TRUE;
1668 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1669 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1671 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1672 if ($processContributionObject) {
1673 $processContribution = TRUE;
1677 if ($pledgePayment) {
1678 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1680 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1681 if ($processContributionObject) {
1682 $processContribution = TRUE;
1686 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1687 if (is_array($memberships)) {
1688 foreach ($memberships as $membership) {
1690 $membership->status_id
= array_search('Expired', $membershipStatuses);
1691 $membership->save();
1693 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1694 if ($processContributionObject) {
1695 $processContribution = TRUE;
1701 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1702 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1704 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1705 if ($processContributionObject) {
1706 $processContribution = TRUE;
1710 if ($pledgePayment) {
1711 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1713 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1714 if ($processContributionObject) {
1715 $processContribution = TRUE;
1719 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1721 // only pending contribution related object processed.
1722 if ($previousContriStatusId &&
1723 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1725 // this is case when we already processed contribution object.
1726 return $updateResult;
1728 elseif (!$previousContriStatusId &&
1729 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1731 // this is case when we are going to process contribution object later.
1732 return $updateResult;
1735 if (is_array($memberships)) {
1736 foreach ($memberships as $membership) {
1741 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1742 $membership->membership_type_id
,
1743 $membership->is_test
, $membership->id
1746 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1747 // this picks up membership type changes during renewals
1749 SELECT membership_type_id
1750 FROM civicrm_membership_log
1751 WHERE membership_id=$membership->id
1754 $dao = new CRM_Core_DAO();
1756 if ($dao->fetch()) {
1757 if (!empty($dao->membership_type_id
)) {
1758 $membership->membership_type_id
= $dao->membership_type_id
;
1759 $membership->save();
1762 // else fall back to using current membership type
1765 // Figure out number of terms
1767 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1768 foreach ($lineitems as $lineitem) {
1769 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1770 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1772 // in case membership_num_terms comes through as null or zero
1773 $numterms = $numterms >= 1 ?
$numterms : 1;
1778 // CRM-15735-to update the membership status as per the contribution receive date
1780 if (!empty($params['receive_date'])) {
1781 $joinDate = $params['receive_date'];
1782 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1783 $membership->end_date
,
1784 $membership->join_date
,
1785 $params['receive_date'],
1787 $membership->membership_type_id
,
1790 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1791 $membership->save();
1794 if ($currentMembership) {
1795 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1796 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1797 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1800 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1803 //get the status for membership.
1804 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1806 $dates['join_date'],
1809 $membership->membership_type_id
,
1813 $formattedParams = array(
1814 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1815 array_search('Current', $membershipStatuses)
1817 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1818 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1819 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1822 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1824 $membership->copyValues($formattedParams);
1825 $membership->save();
1827 //updating the membership log
1828 $membershipLog = array();
1829 $membershipLog = $formattedParams;
1830 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1831 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1833 $membershipLog['start_date'] = $logStartDate;
1834 $membershipLog['membership_id'] = $membership->id
;
1835 $membershipLog['modified_id'] = $membership->contact_id
;
1836 $membershipLog['modified_date'] = date('Ymd');
1837 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1839 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1841 //update related Memberships.
1842 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1844 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1847 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1848 if ($processContributionObject) {
1849 $processContribution = TRUE;
1852 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1858 $updatedStatusId = array_search('Registered', $participantStatuses);
1859 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1861 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1862 if ($processContributionObject) {
1863 $processContribution = TRUE;
1867 if ($pledgePayment) {
1868 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1870 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1871 if ($processContributionObject) {
1872 $processContribution = TRUE;
1877 // process contribution object.
1878 if ($processContribution) {
1879 $contributionParams = array();
1886 'payment_instrument_id',
1889 'financial_type_id',
1890 'contribution_status_id',
1891 'non_deductible_amount',
1895 foreach ($fields as $field) {
1896 if (empty($params[$field])) {
1899 $contributionParams[$field] = $params[$field];
1902 $ids = array('contribution' => $contributionId);
1903 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1906 return $updateResult;
1910 * Returns all contribution related object ids.
1912 * @param $contributionId
1916 public static function getComponentDetails($contributionId) {
1917 $componentDetails = $pledgePayment = array();
1918 if (!$contributionId) {
1919 return $componentDetails;
1923 SELECT c.id as contribution_id,
1924 c.contact_id as contact_id,
1925 c.contribution_recur_id,
1926 mp.membership_id as membership_id,
1927 m.membership_type_id as membership_type_id,
1928 pp.participant_id as participant_id,
1929 p.event_id as event_id,
1930 pgp.id as pledge_payment_id
1931 FROM civicrm_contribution c
1932 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1933 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1934 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1935 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1936 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1937 WHERE c.id = $contributionId";
1939 $dao = CRM_Core_DAO
::executeQuery($query);
1940 $componentDetails = array();
1942 while ($dao->fetch()) {
1943 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1944 $componentDetails['contact_id'] = $dao->contact_id
;
1945 if ($dao->event_id
) {
1946 $componentDetails['event'] = $dao->event_id
;
1948 if ($dao->participant_id
) {
1949 $componentDetails['participant'] = $dao->participant_id
;
1951 if ($dao->membership_id
) {
1952 if (!isset($componentDetails['membership'])) {
1953 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1955 $componentDetails['membership'][] = $dao->membership_id
;
1956 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1958 if ($dao->pledge_payment_id
) {
1959 $pledgePayment[] = $dao->pledge_payment_id
;
1961 if ($dao->contribution_recur_id
) {
1962 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1966 if ($pledgePayment) {
1967 $componentDetails['pledge_payment'] = $pledgePayment;
1970 return $componentDetails;
1974 * @param int $contactId
1975 * @param bool $includeSoftCredit
1977 * @return null|string
1979 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1983 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1984 $additionalWhere = " AND contribution.financial_type_id IN (0)";
1985 $liWhere = " AND i.financial_type_id IN (0)";
1986 if (!empty($financialTypes)) {
1987 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1988 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1990 $contactContributionsSQL = "
1991 SELECT contribution.id AS id
1992 FROM civicrm_contribution contribution
1993 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
1994 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
1998 $contactSoftCreditContributionsSQL = "
1999 SELECT contribution.id
2000 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2001 ON ( contribution.id = softContribution.contribution_id )
2002 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2003 $query = "SELECT count( x.id ) count FROM ( ";
2004 $query .= $contactContributionsSQL;
2006 if ($includeSoftCredit) {
2007 $query .= " UNION ";
2008 $query .= $contactSoftCreditContributionsSQL;
2013 return CRM_Core_DAO
::singleValueQuery($query);
2017 * Repeat a transaction as part of a recurring series.
2019 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2020 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2021 * subsequent call to the contribution.completetransaction api.
2023 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2025 * @param CRM_Contribute_BAO_Contribution $contribution
2026 * @param array $input
2027 * @param array $contributionParams
2031 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
2032 if (!empty($contribution->id
)) {
2035 if (empty($contribution->id
)) {
2036 // Unclear why this would only be set for repeats.
2037 if (!empty($input['amount'])) {
2038 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2040 $templateContribution = civicrm_api3('Contribution', 'getsingle', array(
2041 'contribution_recur_id' => $contributionParams['contribution_recur_id'],
2042 'options' => array('limit' => 1),
2044 $contributionParams['skipLineItem'] = TRUE;
2045 $contributionParams['status_id'] = 'Pending';
2046 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2047 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2048 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2049 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2050 $contribution->id
= $createContribution['id'];
2051 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
2052 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2058 * Get individual id for onbehalf contribution.
2060 * @param int $contributionId
2062 * @param int $contributorId
2066 * containing organization id and individual id
2068 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2072 if (!$contributionId) {
2076 // fetch contributor id if null
2077 if (!$contributorId) {
2078 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2079 $contributionId, 'contact_id'
2083 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2084 $activityTypeId = array_search('Contribution', $activityTypeIds);
2086 if ($activityTypeId && $contributorId) {
2088 SELECT civicrm_activity_contact.contact_id
2089 FROM civicrm_activity_contact
2090 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2091 WHERE civicrm_activity.activity_type_id = %1
2092 AND civicrm_activity.source_record_id = %2
2093 AND civicrm_activity_contact.record_type_id = %3
2096 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2097 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2100 1 => array($activityTypeId, 'Integer'),
2101 2 => array($contributionId, 'Integer'),
2102 3 => array($sourceID, 'Integer'),
2105 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2107 // for on behalf contribution source is individual and contributor is organization
2108 if ($sourceContactId && $sourceContactId != $contributorId) {
2109 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2110 // get rel type id for employee of relation
2111 foreach ($relationshipTypeIds as $id => $typeVals) {
2112 if ($typeVals['name_a_b'] == 'Employee of') {
2113 $relationshipTypeId = $id;
2118 $rel = new CRM_Contact_DAO_Relationship();
2119 $rel->relationship_type_id
= $relationshipTypeId;
2120 $rel->contact_id_a
= $sourceContactId;
2121 $rel->contact_id_b
= $contributorId;
2122 if ($rel->find(TRUE)) {
2123 $ids['individual_id'] = $rel->contact_id_a
;
2124 $ids['organization_id'] = $rel->contact_id_b
;
2135 public static function getContributionDates() {
2136 $config = CRM_Core_Config
::singleton();
2137 $currentMonth = date('m');
2138 $currentDay = date('d');
2139 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2140 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2141 (int ) $config->fiscalYearStart
['d'] > $currentDay
2144 $year = date('Y') - 1;
2149 $year = array('Y' => $year);
2150 $yearDate = $config->fiscalYearStart
;
2151 $yearDate = array_merge($year, $yearDate);
2152 $yearDate = CRM_Utils_Date
::format($yearDate);
2154 $monthDate = date('Ym') . '01';
2160 'yearDate' => $yearDate,
2161 'monthDate' => $monthDate,
2166 * Load objects relations to contribution object.
2167 * Objects are stored in the $_relatedObjects property
2168 * In the first instance we are just moving functionality from BASEIpn -
2169 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2171 * Note that the unit test for the BaseIPN class tests this function
2173 * @param array $input
2174 * Input as delivered from Payment Processor.
2176 * Ids as Loaded by Payment Processor.
2177 * @param bool $loadAll
2178 * Load all related objects - even where id not passed in? (allows API to call this).
2183 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2185 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2186 if (empty($ids['contact']) && isset($this->contact_id
)) {
2187 $ids['contact'] = $this->contact_id
;
2190 if (empty($this->_component
)) {
2191 if (!empty($ids['event'])) {
2192 $this->_component
= 'event';
2195 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2199 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2200 // refactoring than anything else, and has unit test coverage.
2201 if (empty($this->financial_type_id
)) {
2205 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2210 if (!$paymentProcessorID && $this->contribution_page_id
) {
2211 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2212 $this->contribution_page_id
,
2215 if ($paymentProcessorID) {
2216 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2220 $ids['contributionType'] = $this->financial_type_id
;
2221 $ids['financialType'] = $this->financial_type_id
;
2224 'contact' => 'CRM_Contact_BAO_Contact',
2225 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2226 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2227 'financialType' => 'CRM_Financial_BAO_FinancialType',
2229 foreach ($entities as $entity => $bao) {
2230 if (!empty($ids[$entity])) {
2231 $this->_relatedObjects
[$entity] = new $bao();
2232 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2233 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2234 throw new CRM_Core_Exception($entity . ' could not be loaded');
2239 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2240 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2243 if (!empty($ids['pledge_payment'])) {
2244 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2245 if (empty($paymentID)) {
2248 $payment = new CRM_Pledge_BAO_PledgePayment();
2249 $payment->id
= $paymentID;
2250 if (!$payment->find(TRUE)) {
2251 throw new Exception("Could not find pledge payment record: " . $paymentID);
2253 $this->_relatedObjects
['pledge_payment'][] = $payment;
2257 $this->loadRelatedMembershipObjects($ids);
2259 if ($this->_component
!= 'contribute') {
2260 // we are in event mode
2261 // make sure event exists and is valid
2262 $event = new CRM_Event_BAO_Event();
2263 $event->id
= $ids['event'];
2264 if ($ids['event'] &&
2267 throw new Exception("Could not find event: " . $ids['event']);
2270 $this->_relatedObjects
['event'] = &$event;
2272 $participant = new CRM_Event_BAO_Participant();
2273 $participant->id
= $ids['participant'];
2274 if ($ids['participant'] &&
2275 !$participant->find(TRUE)
2277 throw new Exception("Could not find participant: " . $ids['participant']);
2279 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2281 $this->_relatedObjects
['participant'] = &$participant;
2283 // get the payment processor id from event - this is inaccurate see CRM-16923
2284 // in future we should look at throwing an exception here rather than an dubious guess.
2285 if (!$paymentProcessorID) {
2286 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2287 if ($paymentProcessorID) {
2288 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2293 if ($paymentProcessorID) {
2294 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2295 $this->is_test ?
'test' : 'live'
2297 $ids['paymentProcessor'] = $paymentProcessorID;
2298 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2304 * Create array of message information - ie. return html version, txt version, to field
2306 * @param array $input
2307 * Incoming information.
2308 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2309 * just check presence of recur object but maintaining legacy approach
2312 * IDs of related objects.
2313 * @param array $values
2314 * Any values that may have already been compiled by calling process.
2315 * This is augmented by values 'gathered' by gatherMessageValues
2316 * @param bool $recur
2317 * @param bool $returnMessageText
2318 * Distinguishes between whether to send message or return.
2319 * message text. We are working towards this function ALWAYS returning message text & calling
2320 * function doing emails / pdfs with it
2326 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2327 $this->loadRelatedObjects($input, $ids);
2329 if (empty($this->_component
)) {
2330 $this->_component
= CRM_Utils_Array
::value('component', $input);
2333 //not really sure what params might be passed in but lets merge em into values
2334 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2335 $template = CRM_Core_Smarty
::singleton();
2336 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2337 //what does recur 'mean here - to do with payment processor return functionality but
2338 // what is the importance
2339 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2340 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2342 $entityID = $entity = NULL;
2343 if (isset($ids['contribution'])) {
2344 $entity = 'contribution';
2345 $entityID = $ids['contribution'];
2347 if (!empty($ids['membership'])) {
2348 //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
2349 // 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
2350 // line having loaded an array
2351 $ids['membership'] = (array) $ids['membership'];
2352 $entity = 'membership';
2353 $entityID = $ids['membership'][0];
2356 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity));
2357 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2358 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2360 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2361 //direct mode showing billing block, so use directIPN for temporary
2362 $template->assign('contributeMode', 'directIPN');
2365 // todo remove strtolower - check consistency
2366 if (strtolower($this->_component
) == 'event') {
2367 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2368 $values['event'] = array();
2370 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2372 //get location details
2373 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2374 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2376 $ufJoinParams = array(
2377 'entity_table' => 'civicrm_event',
2378 'entity_id' => $ids['event'],
2379 'module' => 'CiviEvent',
2382 list($custom_pre_id,
2384 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2386 $values['custom_pre_id'] = $custom_pre_id;
2387 $values['custom_post_id'] = $custom_post_ids;
2388 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2389 //and cases involving status updation through ipn
2390 // whatever that means!
2391 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2392 // perhaps we should throw an e-notice if amount is set & force total_amount?
2393 if (!empty($input['amount'])) {
2394 $values['totalAmount'] = $input['amount'];
2397 if ($values['event']['is_email_confirm']) {
2398 $values['is_email_receipt'] = 1;
2400 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2401 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2405 $values['contribution_id'] = $this->id
;
2406 if (!empty($ids['related_contact'])) {
2407 $values['related_contact'] = $ids['related_contact'];
2408 if (isset($ids['onbehalf_dupe_alert'])) {
2409 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2411 $entityBlock = array(
2412 'contact_id' => $ids['contact'],
2413 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2414 'Home', 'id', 'name'
2417 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2418 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2421 if ($this->is_test
) {
2424 if (!empty($this->_relatedObjects
['membership'])) {
2425 foreach ($this->_relatedObjects
['membership'] as $membership) {
2426 if ($membership->id
) {
2427 $values['isMembership'] = TRUE;
2428 $values['membership_assign'] = TRUE;
2430 // need to set the membership values here
2431 $template->assign('membership_name',
2432 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2434 $template->assign('mem_start_date', $membership->start_date
);
2435 $template->assign('mem_join_date', $membership->join_date
);
2436 $template->assign('mem_end_date', $membership->end_date
);
2437 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2438 $template->assign('mem_status', $membership_status);
2439 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2440 $template->assign('is_pay_later', 1);
2443 // if separate payment there are two contributions recorded and the
2444 // admin will need to send a receipt for each of them separately.
2445 // we dont link the two in the db (but can potentially infer it if needed)
2446 $template->assign('is_separate_payment', 0);
2448 if ($recur && $paymentObject) {
2449 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2450 $template->assign('cancelSubscriptionUrl', $url);
2451 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2452 $template->assign('updateSubscriptionBillingUrl', $url);
2453 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2454 $template->assign('updateSubscriptionUrl', $url);
2457 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2460 // otherwise if its about sending emails, continue sending without return, as we
2461 // don't want to exit the loop.
2466 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2472 * Gather values for contribution mail - this function has been created
2473 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2474 * Values related to the contribution in question are gathered
2476 * @param array $input
2477 * Input into function (probably from payment processor).
2478 * @param array $values
2480 * The set of ids related to the input.
2484 public function _gatherMessageValues($input, &$values, $ids = array()) {
2485 // set display address of contributor
2486 if ($this->address_id
) {
2487 $addressParams = array('id' => $this->address_id
);
2488 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2489 $addressDetails = array_values($addressDetails);
2490 $values['address'] = $addressDetails[0]['display'];
2492 if ($this->_component
== 'contribute') {
2493 //get soft contributions
2494 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2495 if (!empty($softContributions)) {
2496 $values['softContributions'] = $softContributions['soft_credit'];
2498 if (isset($this->contribution_page_id
)) {
2499 CRM_Contribute_BAO_ContributionPage
::setValues(
2500 $this->contribution_page_id
,
2503 if ($this->contribution_page_id
) {
2504 // CRM-8254 - override default currency if applicable
2505 $config = CRM_Core_Config
::singleton();
2506 $config->defaultCurrency
= CRM_Utils_Array
::value(
2509 $config->defaultCurrency
2513 // no contribution page -probably back office
2515 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2516 $values['is_email_receipt'] = 1;
2517 $values['title'] = 'Contribution';
2519 // set lineItem for contribution
2521 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2522 if (!empty($lineItem)) {
2523 $itemId = key($lineItem);
2524 foreach ($lineItem as &$eachItem) {
2525 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2526 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2527 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2528 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2531 $values['lineItem'][0] = $lineItem;
2532 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2536 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2540 // if this is onbehalf of contribution then set related contact
2541 if (!empty($relatedContact['individual_id'])) {
2542 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2547 $eventParams = array(
2548 'id' => $this->_relatedObjects
['event']->id
,
2550 $values['event'] = array();
2552 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2553 // add custom fields for event
2554 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2556 $eventCustomGroup = array();
2557 foreach ($eventGroupTree as $key => $group) {
2558 if ($key === 'info') {
2562 foreach ($group['fields'] as $k => $customField) {
2563 $groupLabel = $group['title'];
2564 if (!empty($customField['customValue'])) {
2565 foreach ($customField['customValue'] as $customFieldValues) {
2566 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2571 $values['event']['customGroup'] = $eventCustomGroup;
2573 //get participant details
2574 $participantParams = array(
2575 'id' => $this->_relatedObjects
['participant']->id
,
2578 $values['participant'] = array();
2580 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2581 // add custom fields for event
2582 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2583 $participantCustomGroup = array();
2584 foreach ($participantGroupTree as $key => $group) {
2585 if ($key === 'info') {
2589 foreach ($group['fields'] as $k => $customField) {
2590 $groupLabel = $group['title'];
2591 if (!empty($customField['customValue'])) {
2592 foreach ($customField['customValue'] as $customFieldValues) {
2593 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2598 $values['participant']['customGroup'] = $participantCustomGroup;
2600 //get location details
2601 $locationParams = array(
2602 'entity_id' => $this->_relatedObjects
['event']->id
,
2603 'entity_table' => 'civicrm_event',
2605 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2607 $ufJoinParams = array(
2608 'entity_table' => 'civicrm_event',
2609 'entity_id' => $ids['event'],
2610 'module' => 'CiviEvent',
2613 list($custom_pre_id,
2615 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2617 $values['custom_pre_id'] = $custom_pre_id;
2618 $values['custom_post_id'] = $custom_post_ids;
2620 // set lineItem for event contribution
2622 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2623 if (!empty($participantIds)) {
2624 foreach ($participantIds as $pIDs) {
2625 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2626 if (!CRM_Utils_System
::isNull($lineItem)) {
2627 $values['lineItem'][] = $lineItem;
2634 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2636 $customGroup = array();
2637 foreach ($groupTree 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 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2651 $values['customGroup'] = $customGroup;
2657 * Assign message variables to template but try to break the habit.
2659 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2660 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2661 * multiple recurring payments for processors like IATS that use tokens.
2663 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2664 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2665 * Note we send directly from this function in some cases because it is only partly refactored.
2667 * Don't call this function directly as the signature will change.
2671 * @param CRM_Core_SMARTY $template
2672 * @param bool $recur
2673 * @param bool $returnMessageText
2677 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2678 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2679 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2680 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2681 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2682 $values['useForMember'] = TRUE;
2684 //assign honor information to receipt message
2685 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2687 if (isset($softRecord['soft_credit'])) {
2688 //if id of contribution page is present
2689 if (!empty($values['id'])) {
2690 $values['honor'] = array(
2691 'honor_profile_values' => array(),
2692 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2693 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2695 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2697 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2698 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2701 //offline contribution
2702 $softCreditTypes = $softCredits = array();
2703 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2704 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2705 $softCredits[$key] = array(
2706 'Name' => $softCredit['contact_name'],
2707 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2710 $template->assign('softCreditTypes', $softCreditTypes);
2711 $template->assign('softCredits', $softCredits);
2715 $dao = new CRM_Contribute_DAO_ContributionProduct();
2716 $dao->contribution_id
= $this->id
;
2717 if ($dao->find(TRUE)) {
2718 $premiumId = $dao->product_id
;
2719 $template->assign('option', $dao->product_option
);
2721 $productDAO = new CRM_Contribute_DAO_Product();
2722 $productDAO->id
= $premiumId;
2723 $productDAO->find(TRUE);
2724 $template->assign('selectPremium', TRUE);
2725 $template->assign('product_name', $productDAO->name
);
2726 $template->assign('price', $productDAO->price
);
2727 $template->assign('sku', $productDAO->sku
);
2729 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2730 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2731 if (!$values['amount'] && isset($this->total_amount
)) {
2732 $values['amount'] = $this->total_amount
;
2735 // add the new contribution values
2736 if (strtolower($this->_component
) == 'contribute') {
2738 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2739 $softDAO->contribution_id
= $this->id
;
2740 if ($softDAO->find(TRUE)) {
2741 $template->assign('pcpBlock', TRUE);
2742 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2743 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2744 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2746 //assign the pcp page title for email subject
2747 $pcpDAO = new CRM_PCP_DAO_PCP();
2748 $pcpDAO->id
= $softDAO->pcp_id
;
2749 if ($pcpDAO->find(TRUE)) {
2750 $template->assign('title', $pcpDAO->title
);
2755 if ($this->financial_type_id
) {
2756 $values['financial_type_id'] = $this->financial_type_id
;
2759 $template->assign('trxn_id', $this->trxn_id
);
2760 $template->assign('receive_date',
2761 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2763 $template->assign('contributeMode', 'notify');
2764 $template->assign('action', $this->is_test ?
1024 : 1);
2765 $template->assign('receipt_text',
2766 CRM_Utils_Array
::value('receipt_text',
2770 $template->assign('is_monetary', 1);
2771 $template->assign('is_recur', (bool) $recur);
2772 $template->assign('currency', $this->currency
);
2773 $template->assign('address', CRM_Utils_Address
::format($input));
2774 if (!empty($values['customGroup'])) {
2775 $template->assign('customGroup', $values['customGroup']);
2777 if (!empty($values['softContributions'])) {
2778 $template->assign('softContributions', $values['softContributions']);
2780 if ($this->_component
== 'event') {
2781 $template->assign('title', $values['event']['title']);
2782 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2783 $viewRoles = array();
2784 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2785 $viewRoles[] = $participantRoles[$v];
2787 $values['event']['participant_role'] = implode(', ', $viewRoles);
2788 $template->assign('event', $values['event']);
2789 $template->assign('participant', $values['participant']);
2790 $template->assign('location', $values['location']);
2791 $template->assign('customPre', $values['custom_pre_id']);
2792 $template->assign('customPost', $values['custom_post_id']);
2795 if ($this->_relatedObjects
['participant']->is_test
) {
2799 $values['params'] = array();
2800 //to get email of primary participant.
2801 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2802 $primaryAmount[] = array(
2803 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2804 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2806 //build an array of cId/pId of participants
2807 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2808 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2809 //send receipt to additional participant if exists
2810 if (count($additionalIDs)) {
2811 $template->assign('isPrimary', 0);
2812 $template->assign('customProfile', NULL);
2813 //set additionalParticipant true
2814 $values['params']['additionalParticipant'] = TRUE;
2815 foreach ($additionalIDs as $pId => $cId) {
2817 //to change the status pending to completed
2818 $additional = new CRM_Event_DAO_Participant();
2819 $additional->id
= $pId;
2820 $additional->contact_id
= $cId;
2821 $additional->find(TRUE);
2822 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2823 $additional->status_id
= 1;
2824 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2825 //if additional participant dont have email
2827 if (!$additionalParticipantInfo) {
2828 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2830 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2831 $primaryAmount[] = array(
2832 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2833 'amount' => $additional->fee_amount
,
2835 $additional->save();
2836 $additional->free();
2837 $template->assign('amount', $amount);
2838 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2842 //build an array of custom profile and assigning it to template
2843 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2845 if (count($customProfile)) {
2846 $template->assign('customProfile', $customProfile);
2849 // for primary contact
2850 $values['params']['additionalParticipant'] = FALSE;
2851 $template->assign('isPrimary', 1);
2852 $template->assign('amount', $primaryAmount);
2853 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2854 if ($this->payment_instrument_id
) {
2855 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2856 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2858 // carry paylater, since we did not created billing,
2859 // so need to pull email from primary location, CRM-4395
2860 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2866 * Check whether payment processor supports
2867 * cancellation of contribution subscription
2869 * @param int $contributionId
2872 * @param bool $isNotCancelled
2876 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2877 $cacheKeyString = "$contributionId";
2878 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2880 static $supportsCancel = array();
2882 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2883 $supportsCancel[$cacheKeyString] = FALSE;
2884 $isCancelled = FALSE;
2886 if ($isNotCancelled) {
2887 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2890 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2891 if (!empty($paymentObject)) {
2892 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2895 return $supportsCancel[$cacheKeyString];
2899 * Check whether subscription is already cancelled.
2901 * @param int $contributionId
2905 * contribution status
2907 public static function isSubscriptionCancelled($contributionId) {
2909 SELECT cr.contribution_status_id
2910 FROM civicrm_contribution_recur cr
2911 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2912 WHERE con.id = %1 LIMIT 1";
2913 $params = array(1 => array($contributionId, 'Integer'));
2914 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2915 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2916 if ($status == 'Cancelled') {
2923 * Create all financial accounts entry.
2925 * @param array $params
2926 * Contribution object, line item array and params for trxn.
2929 * @param array $financialTrxnValues
2931 * @return null|object
2933 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2934 $skipRecords = $update = $return = $isRelatedId = FALSE;
2936 $additionalParticipantId = array();
2937 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2938 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
2940 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2941 $entityId = $params['participant_id'];
2942 $entityTable = 'civicrm_participant';
2943 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2945 elseif (!empty($params['membership_id'])) {
2946 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2947 // are created off one contribution should be handled elsewhere
2948 $entityId = $params['membership_id'];
2949 $entityTable = 'civicrm_membership';
2952 $entityId = $params['contribution']->id
;
2953 $entityTable = 'civicrm_contribution';
2956 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2957 $isRelatedId = TRUE;
2960 $entityID[] = $entityId;
2961 if (!empty($additionalParticipantId)) {
2962 $entityID +
= $additionalParticipantId;
2964 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2965 if (empty($params['prevContribution'])) {
2972 $statusId = $params['contribution']->contribution_status_id
;
2973 // CRM-13964 partial payment
2974 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2975 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2977 $partialAmtPay = $params['partial_amount_pay'];
2978 $partialAmtTotal = $params['partial_payment_total'];
2980 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2981 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2982 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2983 $params['total_amount'] = $partialAmtPay;
2985 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2986 if (empty($balanceTrxnInfo['trxn_id'])) {
2987 // create new balance transaction record
2988 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2989 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2991 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2992 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2993 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2994 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2995 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2996 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2997 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2998 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2999 $balanceTrxnParams['status_id'] = $statusId;
3000 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3001 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3002 if (!empty($params['payment_processor'])) {
3003 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3005 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3009 // build line item array if its not set in $params
3010 if (empty($params['line_item']) ||
$additionalParticipantId) {
3011 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3014 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
3015 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
3017 $skipRecords = TRUE;
3018 $pendingStatus = array(
3019 array_search('Pending', $contributionStatuses),
3020 array_search('In Progress', $contributionStatuses),
3022 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
3023 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3024 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3026 elseif (!empty($params['payment_processor'])) {
3027 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3029 elseif (!empty($params['payment_instrument_id'])) {
3030 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3033 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3034 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3035 $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);
3038 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3039 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3040 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3043 //build financial transaction params
3044 $trxnParams = array(
3045 'contribution_id' => $params['contribution']->id
,
3046 'to_financial_account_id' => $params['to_financial_account_id'],
3047 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3048 'total_amount' => $totalAmount,
3049 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3050 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3051 'currency' => $params['contribution']->currency
,
3052 'trxn_id' => $params['contribution']->trxn_id
,
3053 'status_id' => $statusId,
3054 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
3055 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3057 if ($contributionStatus == 'Refunded') {
3058 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3061 if (!empty($params['payment_processor'])) {
3062 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3065 if (isset($fromFinancialAccountId)) {
3066 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3069 // consider external values passed for recording transaction entry
3070 if (!empty($financialTrxnValues)) {
3071 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3074 $params['trxnParams'] = $trxnParams;
3076 if (!empty($params['prevContribution'])) {
3077 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3078 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3079 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3080 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3081 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3083 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3084 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3085 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3087 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3088 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3091 //if financial type is changed
3092 if (!empty($params['financial_type_id']) &&
3093 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3095 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3096 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3097 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3098 if ($oldFinancialAccount != $newFinancialAccount) {
3099 $params['total_amount'] = 0;
3100 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3101 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3102 $params['prevContribution']->financial_type_id
, $relationTypeId);
3105 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3106 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3107 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3110 self
::updateFinancialAccounts($params, 'changeFinancialType');
3111 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3112 $params['financial_account_id'] = $newFinancialAccount;
3113 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3114 self
::updateFinancialAccounts($params);
3115 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3119 //Update contribution status
3120 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3121 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3122 if (!empty($params['contribution_status_id']) &&
3123 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3125 //Update Financial Records
3126 self
::updateFinancialAccounts($params, 'changedStatus');
3129 // change Payment Instrument for a Completed contribution
3130 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3131 // instrument is null and now new payment instrument is added along with the payment
3132 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3133 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3134 if (array_key_exists('payment_instrument_id', $params)) {
3135 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3136 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3137 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3139 //check if status is changed from Pending to Completed
3140 // do not update payment instrument changes for Pending to Completed
3141 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3142 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3144 // for all other statuses create new financial records
3145 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3146 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3147 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3150 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3151 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3152 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3154 // for any other payment instrument changes create new financial records
3155 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3156 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3157 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3159 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3160 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3162 // another special case when check number is changed, create new financial records
3163 // create financial trxn with negative amount
3164 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3165 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3166 // create financial trxn with positive amount
3167 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3168 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3169 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3173 //if Change contribution amount
3174 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3175 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3176 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3177 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3178 if (isset($totalAmount) &&
3179 $totalAmount != $params['prevContribution']->total_amount
3181 //Update Financial Records
3182 $params['trxnParams']['from_financial_account_id'] = NULL;
3183 self
::updateFinancialAccounts($params, 'changedAmount');
3188 // records finanical trxn and entity financial trxn
3189 // also make it available as return value
3190 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3191 $params['entity_id'] = $financialTxn->id
;
3194 // record line items and financial items
3195 if (empty($params['skipLineItem'])) {
3196 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3199 // create batch entry if batch_id is passed and
3200 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3201 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3202 $entityParams = array(
3203 'batch_id' => $params['batch_id'],
3204 'entity_table' => 'civicrm_financial_trxn',
3205 'entity_id' => $financialTxn->id
,
3207 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3210 // when a fee is charged
3211 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3212 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3215 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3216 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3218 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3219 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3220 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3222 unset($params['line_item']);
3228 * Update all financial accounts entry.
3230 * @param array $params
3231 * Contribution object, line item array and params for trxn.
3233 * @param string $context
3236 * @param null $skipTrxn
3239 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3240 $itemAmount = $trxnID = NULL;
3241 //get all the statuses
3242 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3243 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3244 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3245 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3246 && $context == 'changePaymentInstrument'
3250 if (($params['prevContribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus))
3251 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3252 && $context == 'changedStatus'
3256 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3257 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3259 if ($context == 'changedStatus') {
3260 //get all the statuses
3261 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3262 $cancelledTaxAmount = 0;
3263 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3264 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3265 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3267 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3268 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $params, '0.00');
3269 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3270 $creditNoteId = self
::createCreditNoteId();
3271 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3274 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3275 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3277 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3278 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3279 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3281 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3282 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3283 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3284 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3285 $creditNoteId = self
::createCreditNoteId();
3286 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3290 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3293 $itemAmount = $params['trxnParams']['total_amount'] +
$cancelledTaxAmount;
3295 elseif ($context == 'changePaymentInstrument') {
3296 if ($params['trxnParams']['total_amount'] < 0) {
3297 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3298 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3299 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3300 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3304 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3305 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3308 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3309 $params['entity_id'] = $trxn->id
;
3311 if ($context == 'changedStatus') {
3312 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3313 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3314 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3316 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3317 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3319 $entityParams = array(
3320 'entity_table' => 'civicrm_financial_item',
3321 'financial_trxn_id' => $trxn->id
,
3323 if (empty($params['line_item'])) {
3325 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3326 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3327 // & this can be removed
3330 foreach ($params['line_item'] as $fieldId => $fields) {
3331 foreach ($fields as $fieldValueId => $fieldValues) {
3333 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3334 2 => array($fieldValues['id'], 'Integer'),
3336 CRM_Core_DAO
::executeQuery($query, $fparams);
3338 1 => array($fieldValues['id'], 'Integer'),
3340 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3341 while ($financialItem->fetch()) {
3342 $entityParams['entity_id'] = $financialItem->id
;
3343 $entityParams['amount'] = $financialItem->amount
;
3344 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3351 if ($context != 'changePaymentInstrument') {
3352 $itemParams['entity_table'] = 'civicrm_line_item';
3353 $trxnIds['id'] = $params['entity_id'];
3354 foreach ($params['line_item'] as $fieldId => $fields) {
3355 foreach ($fields as $fieldValueId => $fieldValues) {
3356 $prevParams['entity_id'] = $fieldValues['id'];
3357 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3359 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3360 if ($params['contribution']->receive_date
) {
3361 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3364 $financialAccount = $prevfinancialItem->financial_account_id
;
3365 if (!empty($params['financial_account_id'])) {
3366 $financialAccount = $params['financial_account_id'];
3369 $currency = $params['prevContribution']->currency
;
3370 if ($params['contribution']->currency
) {
3371 $currency = $params['contribution']->currency
;
3374 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3375 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3379 if (!empty($params['is_quick_config'])) {
3380 $amount = $itemAmount;
3382 $amount = $params['total_amount'];
3386 $amount = $diff * $fieldValues['line_total'];
3389 $itemParams = array(
3390 'transaction_date' => $receiveDate,
3391 'contact_id' => $params['prevContribution']->contact_id
,
3392 'currency' => $currency,
3393 'amount' => $amount,
3394 'description' => $prevfinancialItem->description
,
3395 'status_id' => $prevfinancialItem->status_id
,
3396 'financial_account_id' => $financialAccount,
3397 'entity_table' => 'civicrm_line_item',
3398 'entity_id' => $fieldValues['id'],
3400 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3402 if ($fieldValues['tax_amount']) {
3403 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3404 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3405 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3406 $itemParams['description'] = $taxTerm;
3407 if ($fieldValues['financial_type_id']) {
3408 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3410 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3415 if ($context == 'changeFinancialType') {
3416 $params['skipLineItem'] = FALSE;
3417 foreach ($params['line_item'] as &$lineItems) {
3418 foreach ($lineItems as &$line) {
3419 $line['financial_type_id'] = $params['financial_type_id'];
3426 * Check status validation on update of a contribution.
3428 * @param array $values
3429 * Previous form values before submit.
3431 * @param array $fields
3432 * The input form values.
3434 * @param array $errors
3439 public static function checkStatusValidation($values, &$fields, &$errors) {
3440 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3441 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3442 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3446 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3447 $checkStatus = array(
3448 'Cancelled' => array('Completed', 'Refunded'),
3449 'Completed' => array('Cancelled', 'Refunded'),
3450 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3451 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3452 'Refunded' => array('Cancelled', 'Completed'),
3453 'Partially paid' => array('Completed'),
3456 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3457 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3459 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3460 1 => $contributionStatuses[$values['contribution_status_id']],
3461 2 => $contributionStatuses[$fields['contribution_status_id']],
3467 * Delete contribution of contact.
3471 * @param int $contactId
3475 public static function deleteContactContribution($contactId) {
3476 $contribution = new CRM_Contribute_DAO_Contribution();
3477 $contribution->contact_id
= $contactId;
3478 $contribution->find();
3479 while ($contribution->fetch()) {
3480 self
::deleteContribution($contribution->id
);
3485 * Get options for a given contribution field.
3486 * @see CRM_Core_DAO::buildOptions
3488 * @param string $fieldName
3489 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3490 * @param array $props whatever is known about this dao object.
3492 * @return array|bool
3494 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3495 $className = __CLASS__
;
3497 switch ($fieldName) {
3498 // This field is not part of this object but the api supports it
3499 case 'payment_processor':
3500 $className = 'CRM_Contribute_BAO_ContributionPage';
3501 // Filter results by contribution page
3502 if (!empty($props['contribution_page_id'])) {
3503 $page = civicrm_api('contribution_page', 'getsingle', array(
3505 'id' => ($props['contribution_page_id']),
3507 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3508 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3512 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3513 case 'honor_type_id':
3514 $className = 'CRM_Contribute_BAO_ContributionSoft';
3515 $fieldName = 'soft_credit_type_id';
3516 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3519 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3523 * Validate financial type.
3527 * @param int $financialTypeId
3528 * Financial Type id.
3530 * @param string $relationName
3532 * @return array|bool
3534 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3535 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3536 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3538 if (!$financialAccount) {
3539 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3546 * Function to record additional payment for partial and refund contributions.
3548 * @param int $contributionId
3549 * is the invoice contribution id (got created after processing participant payment).
3550 * @param array $trxnsData
3551 * to take user provided input of transaction details.
3552 * @param string $paymentType
3553 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3554 * @param int $participantId
3556 * @return null|object
3558 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3559 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3560 $getInfoOf['id'] = $contributionId;
3561 $defaults = array();
3562 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3564 if ($paymentType == 'owed') {
3565 // build params for recording financial trxn entry
3566 $params['contribution'] = $contributionDAO;
3567 $params = array_merge($defaults, $params);
3568 $params['skipLineItem'] = TRUE;
3569 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3570 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3571 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3572 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3575 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3576 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3577 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3579 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3580 if (!empty($trxnId)) {
3581 $trxnId = $trxnId['trxn_id'];
3583 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3584 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3587 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3588 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3589 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3593 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3594 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3595 FROM civicrm_financial_trxn ft
3596 LEFT JOIN civicrm_entity_financial_trxn eft
3597 ON (ft.id = eft.financial_trxn_id)
3598 WHERE eft.entity_table = 'civicrm_contribution'
3599 AND eft.entity_id = {$contributionId}
3600 AND ft.to_financial_account_id != {$toFinancialAccount}
3601 AND ft.status_id = {$statusId}
3603 $query = CRM_Core_DAO
::executeQuery($sql);
3605 $sumOfPayments = $query->sum_of_payments
;
3608 if ($contributionDAO->total_amount
== $sumOfPayments) {
3609 // update contribution status and
3610 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3611 $contributionDAO->contribution_status_id
= $statusId;
3612 $contributionDAO->cancel_date
= 'null';
3613 $contributionDAO->cancel_reason
= NULL;
3614 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3615 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3616 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3617 $contributionDAO->save();
3619 //Change status of financial record too
3620 $financialTrxn->status_id
= $statusId;
3621 $financialTrxn->save();
3623 // note : not using the self::add method,
3624 // the reason because it performs 'status change' related code execution for financial records
3625 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3626 // are coded below i.e. just updating financial_item status to 'Paid'
3628 if ($participantId) {
3629 // update participant status
3630 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3631 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3632 foreach ($ids as $val) {
3633 $participantUpdate['id'] = $val;
3634 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3635 CRM_Event_BAO_Participant
::add($participantUpdate);
3639 // update financial item statuses
3640 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3641 $paidStatus = array_search('Paid', $financialItemStatus);
3643 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3644 $sqlFinancialItemUpdate = "
3645 UPDATE civicrm_financial_item fi
3646 LEFT JOIN civicrm_entity_financial_trxn eft
3647 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3648 SET status_id = {$paidStatus}
3649 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3651 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3654 elseif ($paymentType == 'refund') {
3655 // build params for recording financial trxn entry
3656 $params['contribution'] = $contributionDAO;
3657 $params = array_merge($defaults, $params);
3658 $params['skipLineItem'] = TRUE;
3659 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3660 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3662 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3663 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3664 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3666 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3668 // note : not using the self::add method,
3669 // the reason because it performs 'status change' related code execution for financial records
3670 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3671 // are coded below i.e. just updating financial_item status to 'Paid'
3672 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3674 // add financial item entry
3675 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3676 $getLine['entity_id'] = $contributionDAO->id
;
3677 $getLine['entity_table'] = 'civicrm_contribution';
3678 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3679 if (!empty($lineItemId->id
)) {
3680 $addFinancialEntry = array(
3681 'transaction_date' => $financialTrxn->trxn_date
,
3682 'contact_id' => $contributionDAO->contact_id
,
3683 'amount' => $financialTrxn->total_amount
,
3684 'status_id' => array_search('Paid', $financialItemStatus),
3685 'entity_id' => $lineItemId->id
,
3686 'entity_table' => 'civicrm_line_item',
3688 $trxnIds['id'] = $financialTrxn->id
;
3689 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3691 if ($participantId) {
3692 // update participant status
3693 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3694 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3695 foreach ($ids as $val) {
3696 $participantUpdate['id'] = $val;
3697 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3698 CRM_Event_BAO_Participant
::add($participantUpdate);
3703 // activity creation
3704 if (!empty($financialTrxn)) {
3705 if ($participantId) {
3706 $inputParams['id'] = $participantId;
3709 $component = 'event';
3710 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3711 $entityObj = $entityObj[$participantId];
3713 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3715 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3717 return $financialTrxn;
3723 * @param $activityType
3725 * @param int $contributionId
3727 * @throws CRM_Core_Exception
3729 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3730 if ($component == 'event') {
3731 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3732 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3733 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3734 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3735 $targetCid = $entityObj->contact_id
;
3736 // source record id would be the contribution id
3737 $srcRecId = $contributionId;
3741 $activityParams = array(
3742 'source_contact_id' => $targetCid,
3743 'source_record_id' => $srcRecId,
3744 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3748 'subject' => $subject,
3749 'activity_date_time' => $date,
3750 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3754 'skipRecentView' => TRUE,
3757 // create activity with target contacts
3758 $session = CRM_Core_Session
::singleton();
3759 $id = $session->get('userID');
3761 $activityParams['source_contact_id'] = $id;
3762 $activityParams['target_contact_id'][] = $targetCid;
3764 CRM_Activity_BAO_Activity
::create($activityParams);
3768 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3772 * @param bool $getTrxnInfo
3773 * @param bool $usingLineTotal
3777 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3778 if ($component == 'event') {
3779 $entity = 'participant';
3780 $entityTable = 'civicrm_participant';
3781 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3783 if (!$contributionId) {
3784 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3785 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3786 $id = $primaryParticipantId;
3788 if (!$contributionId) {
3794 $contributionId = $id;
3795 $entity = 'contribution';
3796 $entityTable = 'civicrm_contribution';
3799 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3800 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3806 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3807 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3810 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3811 // for additional participants
3812 if ($entityTable == 'civicrm_participant') {
3813 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3815 foreach ($ids as $val) {
3816 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3820 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3824 $baseTrxnId = $total['trxn_id'];
3825 $total = $total['total_amount'];
3828 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3829 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3831 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3832 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3833 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3835 if ($paymentBalance == 0 && $contributionIsPayLater) {
3836 $paymentBalance = $total;
3839 $info['total'] = $total;
3840 $info['paid'] = $total - $paymentBalance;
3841 $info['balance'] = $paymentBalance;
3843 $info['component'] = $component;
3844 $info['payLater'] = $contributionIsPayLater;
3846 if ($getTrxnInfo && $baseTrxnId) {
3847 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3849 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3850 FROM civicrm_contribution con
3851 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3852 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3853 WHERE con.id = {$contributionId}
3856 // conditioned WHERE clause
3858 // if balance trxn exists don't include details of it in transaction info
3859 $sql .= " AND ft.id != {$baseTrxnId} ";
3861 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3863 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3864 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3865 while ($resultDAO->fetch()) {
3866 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3867 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3869 'total_amount' => $resultDAO->total_amount
,
3870 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3871 'payment_instrument' => $paidByLabel,
3872 'receive_date' => $resultDAO->trxn_date
,
3873 'trxn_id' => $resultDAO->trxn_id
,
3874 'status' => $statuses[$resultDAO->status_id
],
3876 if ($paidByName == 'Check') {
3877 $val['check_number'] = $resultDAO->check_number
;
3881 $info['transaction'] = $rows;
3887 * Get financial account id has 'Sales Tax Account is'
3888 * account relationship with financial type
3890 * @param int $financialTypeId
3892 * @return FinancialAccountId
3894 public static function getFinancialAccountId($financialTypeId) {
3895 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3896 $searchParams = array(
3897 'entity_table' => 'civicrm_financial_type',
3898 'entity_id' => $financialTypeId,
3899 'account_relationship' => $accountRel,
3902 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3904 return CRM_Utils_Array
::value('financial_account_id', $result);
3910 * @param array $params
3911 * @param bool $isLineItem
3915 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3916 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3918 // Update contribution.
3919 if (!empty($params['id'])) {
3920 $id = $params['id'];
3921 $values = $ids = array();
3922 $contrbutionParams = array('id' => $id);
3923 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3925 // To assign pervious finantial type on update of contribution
3926 if (!isset($params['financial_type_id'])) {
3927 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3929 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3930 // Assisn tax Amount on update of contrbution
3931 if (!empty($prevContributionValue->tax_amount
)) {
3932 $params['tax_amount'] = 'null';
3933 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3934 foreach ($params['line_item'] as $setID => $priceField) {
3935 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3936 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3943 // New Contrbution and update of contribution with tax rate financial type
3944 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3945 empty($params['skipLineItem']) && !$isLineItem
3947 $taxRateParams = $taxRates[$params['financial_type_id']];
3948 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3949 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3951 // Get Line Item on update of contribution
3952 if (isset($params['id'])) {
3953 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3956 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3958 foreach ($params['line_item'] as $setID => $priceField) {
3959 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3960 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3963 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3965 elseif (isset($params['api.line_item.create'])) {
3966 // Update total amount of contribution using lineItem
3967 $taxAmountArray = array();
3968 foreach ($params['api.line_item.create'] as $key => $value) {
3969 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3970 $taxRate = $taxRates[$value['financial_type_id']];
3971 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3972 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3975 $params['tax_amount'] = array_sum($taxAmountArray);
3976 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3979 // update line item of contrbution
3980 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3981 $taxRate = $taxRates[$params['financial_type_id']];
3982 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3983 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3990 * Check financial type validation on update of a contribution.
3992 * @param Integer $financialTypeId
3993 * Value of latest Financial Type.
3995 * @param Integer $contributionId
3998 * @param array $errors
4003 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4004 if (!empty($financialTypeId)) {
4005 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4006 if ($oldFinancialTypeId == $financialTypeId) {
4010 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4012 '1' => array($contributionId, 'Integer'),
4014 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4015 if ($result->N
> 1) {
4016 $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.');
4021 * Update related pledge payment payments.
4023 * This function has been refactored out of the back office contribution form and may
4024 * still overlap with other functions.
4026 * @param string $action
4027 * @param int $pledgePaymentID
4028 * @param int $contributionID
4029 * @param bool $adjustTotalAmount
4030 * @param float $total_amount
4031 * @param float $original_total_amount
4032 * @param int $contribution_status_id
4033 * @param int $original_contribution_status_id
4035 public static function updateRelatedPledge(
4041 $original_total_amount,
4042 $contribution_status_id,
4043 $original_contribution_status_id
4045 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4049 if ($pledgePaymentID) {
4050 //store contribution id in payment record.
4051 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4054 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4061 if (!$pledgePaymentID) {
4064 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4070 $updatePledgePaymentStatus = FALSE;
4072 // If either the status or the amount has changed we update the pledge status.
4073 if ($action & CRM_Core_Action
::ADD
) {
4074 $updatePledgePaymentStatus = TRUE;
4076 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4077 ($original_total_amount != $total_amount))
4079 $updatePledgePaymentStatus = TRUE;
4082 if ($updatePledgePaymentStatus) {
4083 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4084 array($pledgePaymentID),
4085 $contribution_status_id,
4094 * Compute the stats values
4096 * @param $stat either 'mode' or 'median'
4098 * @param $alias of civicrm_contribution
4100 public static function computeStats($stat, $sql, $alias = NULL) {
4101 $mode = $median = array();
4104 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4105 while ($modeDAO->fetch()) {
4106 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4107 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4116 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4117 foreach ($currencies as $currency => $val) {
4119 $where = "AND {$alias}.currency = '{$currency}'";
4120 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4124 $medianRow = floor($rowCount / 2);
4125 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4131 $medianValue = "SELECT {$alias}.total_amount as median
4133 ORDER BY median LIMIT {$medianRow},{$offset}";
4134 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4135 while ($medianValDAO->fetch()) {
4137 $midValue = $midValue +
$medianValDAO->median
;
4140 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4144 $midValue = $midValue / 2;
4145 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4156 * Complete an order.
4158 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4160 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4162 * Moving it out of the BaseIPN class is just the first step.
4164 * @param array $input
4166 * @param array $objects
4167 * @param CRM_Core_Transaction $transaction
4169 * @param CRM_Contribute_BAO_Contribution $contribution
4170 * @param bool $isRecurring
4171 * Duplication of param needs review. Only used by AuthorizeNetIPN
4172 * @param int $isFirstOrLastRecurringPayment
4173 * Deprecated param only used by AuthorizeNetIPN.
4175 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4176 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4177 // The previous details are used when calculating line items so keep it before any code that 'does something'
4178 if (!empty($contribution->id
)) {
4179 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4180 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4182 $inputContributionWhiteList = array(
4187 'payment_instrument_id',
4193 $contributionParams = array_merge(array(
4194 'contribution_status_id' => 'Completed',
4195 'financial_type_id' => $contribution->financial_type_id
,
4196 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4199 $participant = CRM_Utils_Array
::value('participant', $objects);
4200 $memberships = CRM_Utils_Array
::value('membership', $objects);
4201 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4202 if (!empty($recurContrib->id
)) {
4203 $contributionParams['contribution_recur_id'] = $recurContrib->id
;
4205 self
::repeatTransaction($contribution, $input, $contributionParams);
4207 if (is_numeric($memberships)) {
4208 $memberships = array($objects['membership']);
4211 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4214 if (isset($input['is_email_receipt'])) {
4215 $values['is_email_receipt'] = $input['is_email_receipt'];
4218 if ($input['component'] == 'contribute') {
4219 if ($contribution->contribution_page_id
) {
4220 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4221 $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
4223 elseif ($recurContrib && $recurContrib->id
) {
4224 $contributionParams['contribution_page_id'] = NULL;
4225 $values['amount'] = $recurContrib->amount
;
4226 $values['financial_type_id'] = $objects['contributionType']->id
;
4227 $values['title'] = $source = ts('Offline Recurring Contribution');
4228 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
4229 $values['receipt_from_name'] = $domainValues[0];
4230 $values['receipt_from_email'] = $domainValues[1];
4233 if (empty($contributionParams['receive_date']) && $changeDate) {
4234 $contributionParams['receive_date'] = $changeDate;
4237 if ($recurContrib && $recurContrib->id
&& !isset($input['is_email_receipt'])) {
4238 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4239 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4240 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4243 if (!empty($values['is_email_receipt'])) {
4244 $contributionParams['receipt_date'] = $changeDate;
4247 if (!empty($memberships)) {
4248 foreach ($memberships as $membershipTypeIdKey => $membership) {
4250 $membershipParams = array(
4251 'id' => $membership->id
,
4252 'contact_id' => $membership->contact_id
,
4253 'is_test' => $membership->is_test
,
4254 'membership_type_id' => $membership->membership_type_id
,
4257 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4258 $membershipParams['membership_type_id'],
4259 $membershipParams['is_test'],
4260 $membershipParams['id']
4263 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4264 // this picks up membership type changes during renewals
4266 SELECT membership_type_id
4267 FROM civicrm_membership_log
4268 WHERE membership_id={$membershipParams['id']}
4271 $dao = CRM_Core_DAO
::executeQuery($sql);
4272 if ($dao->fetch()) {
4273 if (!empty($dao->membership_type_id
)) {
4274 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4279 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4280 $membershipParams['membership_type_id'],
4281 $primaryContributionID
4283 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4284 if ($currentMembership) {
4286 * Fixed FOR CRM-4433
4287 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4288 * when Contribution mode is notify and membership is for renewal )
4290 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4292 // @todo - we should pass membership_type_id instead of null here but not
4293 // adding as not sure of testing
4294 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4295 $changeDate, NULL, $membershipParams['num_terms']
4298 $dates['join_date'] = $currentMembership['join_date'];
4301 //get the status for membership.
4302 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4304 $dates['join_date'],
4307 $membershipParams['membership_type_id'],
4311 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4312 //we might be renewing membership,
4313 //so make status override false.
4314 $membershipParams['is_override'] = FALSE;
4315 civicrm_api3('Membership', 'create', $membershipParams);
4317 //update related Memberships.
4318 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $membershipParams);
4324 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4325 $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id
));
4326 $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
4327 if ($eventDetail['is_email_confirm']) {
4328 // @todo this should be set by the function that sends the mail after sending.
4329 $contributionParams['receipt_date'] = $changeDate;
4331 $participantParams['id'] = $participant->id
;
4332 $participantParams['status_id'] = 'Registered';
4333 civicrm_api3('Participant', 'create', $participantParams);
4337 $contributionParams['id'] = $contribution->id
;
4339 civicrm_api3('Contribution', 'create', $contributionParams);
4341 // Add new soft credit against current $contribution.
4342 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4343 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4346 $paymentProcessorId = '';
4347 if (isset($objects['paymentProcessor'])) {
4348 if (is_array($objects['paymentProcessor'])) {
4349 $paymentProcessorId = $objects['paymentProcessor']['id'];
4352 $paymentProcessorId = $objects['paymentProcessor']->id
;
4356 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4357 'labelColumn' => 'name',
4360 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4361 $input['payment_processor'] = $paymentProcessorId;
4363 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4364 $input['total_amount'] = $input['amount'];
4365 $input['contribution'] = $contribution;
4366 $input['financial_type_id'] = $contribution->financial_type_id
;
4368 if (!empty($contribution->_relatedObjects
['participant'])) {
4369 $input['contribution_mode'] = 'participant';
4370 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4371 $input['skipLineItem'] = 1;
4373 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4374 $input['skipLineItem'] = TRUE;
4375 $input['contribution_mode'] = 'membership';
4377 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4378 // and subsequent payments. In this case the line items are created at
4379 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4380 // and since the contribution is saved prior to this line there is always a contribution-id,
4381 // however there is never a prevContribution (which appears to mean original contribution not previous
4382 // contribution - or preUpdateContributionObject most accurately)
4383 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4384 // to mean "are we updating an exisitng pending contribution"
4385 //I was able to make the unit test complete as fataling here doesn't prevent
4386 // the contribution being created - but activities would not be created or emails sent
4388 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4390 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4391 $transaction->commit();
4393 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution);
4395 // create an activity record
4396 if ($input['component'] == 'contribute') {
4398 $targetContactID = NULL;
4399 if (!empty($ids['related_contact'])) {
4400 $targetContactID = $contribution->contact_id
;
4401 $contribution->contact_id
= $ids['related_contact'];
4403 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4407 CRM_Activity_BAO_Activity
::addActivity($participant);
4410 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4411 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4412 if (!array_key_exists('is_email_receipt', $values) ||
4413 $values['is_email_receipt'] == 1
4415 self
::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
4416 CRM_Core_Error
::debug_log_message("Receipt sent");
4419 CRM_Core_Error
::debug_log_message("Success: Database updated");
4421 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4422 $isFirstOrLastRecurringPayment);
4427 * Send receipt from contribution.
4429 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4431 * Note that the compose message part has been moved to contribution
4432 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4434 * @param array $input
4435 * Incoming data from Payment processor.
4437 * Related object IDs.
4438 * @param CRM_Contribute_BAO_Contribution $contribution
4439 * @param array $values
4440 * Values related to objects that have already been loaded.
4441 * @param bool $recur
4442 * Is it part of a recurring contribution.
4443 * @param bool $returnMessageText
4444 * Should text be returned instead of sent. This.
4445 * is because the function is also used to generate pdfs
4449 public static function sendMail(&$input, &$ids, $contribution, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4450 $input['is_recur'] = $recur;
4451 // set receipt from e-mail and name in value
4452 if (!$returnMessageText) {
4453 $session = CRM_Core_Session
::singleton();
4454 $userID = $session->get('userID');
4455 if (!empty($userID)) {
4456 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4457 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4458 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4461 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4465 * Generate credit note id with next avaible number
4470 public static function createCreditNoteId() {
4471 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4473 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4474 $creditNoteId = NULL;
4478 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4479 $result = civicrm_api3('Contribution', 'getcount', array(
4481 'creditnote_id' => $creditNoteId,
4483 } while ($result > 0);
4485 return $creditNoteId;
4489 * Load related memberships.
4491 * Note that in theory it should be possible to retrieve these from the line_item table
4492 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4493 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4494 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4495 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4497 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4503 public function loadRelatedMembershipObjects(&$ids) {
4505 SELECT membership_id
4506 FROM civicrm_membership_payment
4507 WHERE contribution_id = %1 ";
4508 $params = array(1 => array($this->id
, 'Integer'));
4510 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4511 while ($dao->fetch()) {
4512 if ($dao->membership_id
) {
4513 if (!is_array($ids['membership'])) {
4514 $ids['membership'] = array();
4516 $ids['membership'][] = $dao->membership_id
;
4520 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4521 foreach ($ids['membership'] as $id) {
4523 $membership = new CRM_Member_BAO_Membership();
4524 $membership->id
= $id;
4525 if (!$membership->find(TRUE)) {
4526 throw new Exception("Could not find membership record: $id");
4528 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4529 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4530 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4531 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4532 $membership->free();