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 * @return \CRM_Contribute_DAO_Contribution
81 public function __construct() {
82 parent
::__construct();
86 * Takes an associative array and creates a contribution object.
88 * the function extract all the params it needs to initialize the create a
89 * contribution object. the params array could contain additional unused name/value
92 * @param array $params
93 * (reference ) an assoc array of name/value pairs.
95 * The array that holds all the db ids.
97 * @return CRM_Contribute_BAO_Contribution|void
99 public static function add(&$params, $ids = array()) {
100 if (empty($params)) {
103 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
104 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
105 $duplicates = array();
106 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
107 $error = CRM_Core_Error
::singleton();
108 $d = implode(', ', $duplicates);
109 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
112 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
117 // first clean up all the money fields
118 $moneyFields = array(
122 'non_deductible_amount',
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
127 unset($moneyFields[0]);
130 foreach ($moneyFields as $field) {
131 if (isset($params[$field])) {
132 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
136 //set defaults in create mode
137 if (!$contributionID) {
138 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
140 self
::calculateMissingAmountParams($params, $contributionID);
142 if (!empty($params['payment_instrument_id'])) {
143 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
144 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
145 $params['check_number'] = 'null';
149 $setPrevContribution = TRUE;
150 // CRM-13964 partial payment
151 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
152 $partialAmtTotal = $params['partial_payment_total'];
153 $partialAmtPay = $params['partial_amount_pay'];
154 $params['total_amount'] = $partialAmtTotal;
155 if ($partialAmtPay < $partialAmtTotal) {
156 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
157 $params['is_pay_later'] = 0;
158 $setPrevContribution = FALSE;
161 if ($contributionID && $setPrevContribution) {
162 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
165 if ($contributionID) {
166 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
169 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
171 $contribution = new CRM_Contribute_BAO_Contribution();
172 $contribution->copyValues($params);
174 $contribution->id
= $contributionID;
176 if (empty($contribution->id
)) {
177 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
178 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
179 $config = CRM_Core_Config
::singleton();
180 $contribution->currency
= $config->defaultCurrency
;
184 $result = $contribution->save();
186 // Add financial_trxn details as part of fix for CRM-4724
187 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
188 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
190 //add Account details
191 $params['contribution'] = $contribution;
192 self
::recordFinancialAccounts($params);
194 // reset the group contact cache for this group
195 CRM_Contact_BAO_GroupContactCache
::remove();
197 if ($contributionID) {
198 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
201 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
208 * Get defaults for new entity.
211 public static function getDefaults() {
213 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
214 FALSE, FALSE, FALSE, 'AND is_default = 1')
216 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
221 * Given the list of params in the params array, fetch the object
222 * and store the values in the values array
224 * @param array $params
225 * Input parameters to find object.
226 * @param array $values
227 * Output values of the object.
229 * The array that holds all the db ids.
231 * @return CRM_Contribute_BAO_Contribution|null
232 * The found object or null
234 public static function getValues($params, &$values, &$ids) {
235 if (empty($params)) {
238 $contribution = new CRM_Contribute_BAO_Contribution();
240 $contribution->copyValues($params);
242 if ($contribution->find(TRUE)) {
243 $ids['contribution'] = $contribution->id
;
245 CRM_Core_DAO
::storeValues($contribution, $values);
247 return $contribution;
249 $null = NULL; // return by reference
254 * Calculate net_amount & fee_amount if they are not set.
256 * Net amount should be total - fee.
257 * This should only be called for new contributions.
259 * @param array $params
260 * Params for a new contribution before they are saved.
261 * @param int|null $contributionID
262 * Contribution ID if we are dealing with an update.
264 * @throws \CiviCRM_API3_Exception
266 public static function calculateMissingAmountParams(&$params, $contributionID) {
267 if (!$contributionID && !isset($params['fee_amount'])) {
268 if (isset($params['total_amount']) && isset($params['net_amount'])) {
269 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
272 $params['fee_amount'] = 0;
275 if (!isset($params['net_amount'])) {
276 if (!$contributionID) {
277 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
280 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
281 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
282 // net_amount may need adjusting.
283 $contribution = civicrm_api3('Contribution', 'getsingle', array(
284 'id' => $contributionID,
285 'return' => array('total_amount', 'net_amount'),
287 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
288 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
289 $params['net_amount'] = $totalAmount - $feeAmount;
297 * @param $billingLocationTypeID
301 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
302 $hasBillingField = FALSE;
303 $billingFields = array(
311 //build address array
312 $addressParams = array();
313 $addressParams['location_type_id'] = $billingLocationTypeID;
314 $addressParams['is_billing'] = 1;
316 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
317 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
318 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
319 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
321 foreach ($billingFields as $value) {
322 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
323 if (!empty($addressParams[$value])) {
324 $hasBillingField = TRUE;
327 return array($hasBillingField, $addressParams);
331 * Get address params ready to be passed to the payment processor.
333 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
334 * To create an address we need state_province_id.
336 * @param array $params
337 * @param int $billingLocationTypeID
341 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
342 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
343 foreach ($addressParams as $name => $field) {
344 if (substr($name, 0, 8) == 'billing_') {
345 $addressParams[substr($name, 9)] = $addressParams[$field];
348 return array($hasBillingField, $addressParams);
352 * Get the number of terms for this contribution for a given membership type
353 * based on querying the line item table and relevant price field values
354 * Note that any one contribution should only be able to have one line item relating to a particular membership
357 * @param int $membershipTypeID
359 * @param int $contributionID
363 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
364 $numTerms = CRM_Core_DAO
::singleValueQuery("
365 SELECT membership_num_terms FROM civicrm_line_item li
366 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
367 WHERE contribution_id = %1 AND membership_type_id = %2",
368 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
370 // default of 1 is precautionary
371 return empty($numTerms) ?
1 : $numTerms;
375 * Takes an associative array and creates a contribution object.
377 * @param array $params
378 * (reference ) an assoc array of name/value pairs.
380 * The array that holds all the db ids.
382 * @return CRM_Contribute_BAO_Contribution
384 public static function create(&$params, $ids = array()) {
385 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
386 foreach ($dateFields as $df) {
387 if (isset($params[$df])) {
388 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
392 $transaction = new CRM_Core_Transaction();
394 $contribution = self
::add($params, $ids);
396 if (is_a($contribution, 'CRM_Core_Error')) {
397 $transaction->rollback();
398 return $contribution;
401 $params['contribution_id'] = $contribution->id
;
403 if (!empty($params['custom']) &&
404 is_array($params['custom'])
406 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
409 $session = CRM_Core_Session
::singleton();
411 if (!empty($params['note'])) {
413 'entity_table' => 'civicrm_contribution',
414 'note' => $params['note'],
415 'entity_id' => $contribution->id
,
416 'contact_id' => $session->get('userID'),
417 'modified_date' => date('Ymd'),
419 if (!$noteParams['contact_id']) {
420 $noteParams['contact_id'] = $params['contact_id'];
422 CRM_Core_BAO_Note
::add($noteParams);
425 // make entry in batch entity batch table
426 if (!empty($params['batch_id'])) {
427 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
428 $titleFields = array(
434 $retrieveRequired = 0;
435 foreach ($titleFields as $titleField) {
436 if (!isset($contribution->$titleField)) {
437 $retrieveRequired = 1;
441 if ($retrieveRequired == 1) {
442 $contribution->find(TRUE);
446 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
448 $transaction->commit();
450 // check if activity record exist for this contribution, if
452 $activity = new CRM_Activity_DAO_Activity();
453 $activity->source_record_id
= $contribution->id
;
454 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
458 if (!$activity->find(TRUE)) {
459 if (empty($contribution->contact_id
)) {
460 $contribution->find(TRUE);
462 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
465 // CRM-13237 : if activity record found, update it with campaign id of contribution
466 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
469 // do not add to recent items for import, CRM-4399
470 if (empty($params['skipRecentView'])) {
471 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
472 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
474 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
475 $titleFields = array(
481 $retrieveRequired = 0;
482 foreach ($titleFields as $titleField) {
483 if (!isset($contribution->$titleField)) {
484 $retrieveRequired = 1;
488 if ($retrieveRequired == 1) {
489 $contribution->find(TRUE);
491 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
492 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
494 $recentOther = array();
495 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
496 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
497 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
501 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
502 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
503 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
507 // add the recently created Contribution
508 CRM_Utils_Recent
::add($title,
512 $contribution->contact_id
,
518 return $contribution;
522 * Get the values for pseudoconstants for name->value and reverse.
524 * @param array $defaults
525 * (reference) the default values, some of which need to be resolved.
526 * @param bool $reverse
527 * True if we want to resolve the values in the reverse direction (value -> name).
529 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
530 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
531 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
532 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
533 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
537 * Convert associative array names to values and vice-versa.
539 * This function is used by both the web form layer and the api. Note that
540 * the api needs the name => value conversion, also the view layer typically
541 * requires value => name conversion
543 * @param array $defaults
544 * @param string $property
545 * @param array $lookup
546 * @param bool $reverse
550 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
551 $id = $property . '_id';
553 $src = $reverse ?
$property : $id;
554 $dst = $reverse ?
$id : $property;
556 if (!array_key_exists($src, $defaults)) {
560 $look = $reverse ?
array_flip($lookup) : $lookup;
562 if (is_array($look)) {
563 if (!array_key_exists($defaults[$src], $look)) {
567 $defaults[$dst] = $look[$defaults[$src]];
572 * Retrieve DB object based on input parameters.
574 * It also stores all the retrieved values in the default array.
576 * @param array $params
577 * (reference ) an assoc array of name/value pairs.
578 * @param array $defaults
579 * (reference ) an assoc array to hold the name / value pairs.
580 * in a hierarchical manner
582 * (reference) the array that holds all the db ids.
584 * @return CRM_Contribute_BAO_Contribution
586 public static function retrieve(&$params, &$defaults, &$ids) {
587 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
588 return $contribution;
592 * Combine all the importable fields from the lower levels object.
594 * The ordering is important, since currently we do not have a weight
595 * scheme. Adding weight is super important and should be done in the
596 * next week or so, before this can be called complete.
598 * @param string $contactType
599 * @param bool $status
602 * array of importable Fields
604 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
605 if (!self
::$_importableFields) {
606 if (!self
::$_importableFields) {
607 self
::$_importableFields = array();
611 $fields = array('' => array('title' => ts('- do not import -')));
614 $fields = array('' => array('title' => ts('- Contribution Fields -')));
617 $note = CRM_Core_DAO_Note
::import();
618 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
619 unset($tmpFields['option_value']);
620 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
621 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
623 // Using new Dedupe rule.
625 'contact_type' => $contactType,
626 'used' => 'Unsupervised',
628 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
629 $tmpContactField = array();
630 if (is_array($fieldsArray)) {
631 foreach ($fieldsArray as $value) {
632 //skip if there is no dupe rule
633 if ($value == 'none') {
636 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
641 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
642 $tmpContactField[trim($value)] = $contactFields[trim($value)];
644 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
647 $title = $tmpContactField[trim($value)]['title'];
649 $tmpContactField[trim($value)]['title'] = $title;
653 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
654 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
655 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
656 $fields = array_merge($fields, $tmpContactField);
657 $fields = array_merge($fields, $tmpFields);
658 $fields = array_merge($fields, $note);
659 $fields = array_merge($fields, $optionFields);
660 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
661 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
662 self
::$_importableFields = $fields;
664 return self
::$_importableFields;
670 public static function &exportableFields() {
671 if (!self
::$_exportableFields) {
672 if (!self
::$_exportableFields) {
673 self
::$_exportableFields = array();
676 $impFields = CRM_Contribute_DAO_Contribution
::export();
677 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
678 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
679 $typeField = CRM_Financial_DAO_FinancialType
::export();
680 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
681 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
682 $contributionStatus = array(
683 'contribution_status' => array(
684 'title' => ts('Contribution Status'),
685 'name' => 'contribution_status',
686 'data_type' => CRM_Utils_Type
::T_STRING
,
690 $contributionPage = array(
691 'contribution_page' => array(
692 'title' => ts('Contribution Page'),
693 'name' => 'contribution_page',
694 'where' => 'civicrm_contribution_page.title',
695 'data_type' => CRM_Utils_Type
::T_STRING
,
699 $contributionNote = array(
700 'contribution_note' => array(
701 'title' => ts('Contribution Note'),
702 'name' => 'contribution_note',
703 'data_type' => CRM_Utils_Type
::T_TEXT
,
707 $contributionRecurId = array(
708 'contribution_recur_id' => array(
709 'title' => ts('Recurring Contributions ID'),
710 'name' => 'contribution_recur_id',
711 'where' => 'civicrm_contribution.contribution_recur_id',
712 'data_type' => CRM_Utils_Type
::T_INT
,
716 $extraFields = array(
717 'contribution_batch' => array(
718 'title' => ts('Batch Name'),
722 $softCreditFields = array(
723 'contribution_soft_credit_name' => array(
724 'name' => 'contribution_soft_credit_name',
725 'title' => 'Soft Credit For',
726 'where' => 'civicrm_contact_d.display_name',
727 'data_type' => CRM_Utils_Type
::T_STRING
,
729 'contribution_soft_credit_amount' => array(
730 'name' => 'contribution_soft_credit_amount',
731 'title' => 'Soft Credit Amount',
732 'where' => 'civicrm_contribution_soft.amount',
733 'data_type' => CRM_Utils_Type
::T_MONEY
,
735 'contribution_soft_credit_type' => array(
736 'name' => 'contribution_soft_credit_type',
737 'title' => 'Soft Credit Type',
738 'where' => 'contribution_softcredit_type.label',
739 'data_type' => CRM_Utils_Type
::T_STRING
,
741 'contribution_soft_credit_contribution_id' => array(
742 'name' => 'contribution_soft_credit_contribution_id',
743 'title' => 'Soft Credit For Contribution ID',
744 'where' => 'civicrm_contribution_soft.contribution_id',
745 'data_type' => CRM_Utils_Type
::T_INT
,
749 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
751 'contribution_product_id' => array(
752 'title' => ts('Premium'),
753 'name' => 'contribution_product_id',
754 'where' => 'civicrm_product.id',
755 'data_type' => CRM_Utils_Type
::T_INT
,
759 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
760 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums,
761 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
764 self
::$_exportableFields = $fields;
767 return self
::$_exportableFields;
771 * @param null $status
772 * @param null $startDate
773 * @param null $endDate
777 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
781 $where[] = 'contribution_status_id = 1';
785 $where[] = 'contribution_status_id = 3';
790 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
793 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
796 $whereCond = implode(' AND ', $where);
799 SELECT sum( total_amount ) as total_amount,
800 count( civicrm_contribution.id ) as total_count,
802 FROM civicrm_contribution
803 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
805 AND ( is_test = 0 OR is_test IS NULL )
806 AND contact.is_deleted = 0
810 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
813 while ($dao->fetch()) {
814 $count +
= $dao->total_count
;
815 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
819 'amount' => implode(', ', $amount),
827 * Delete the indirect records associated with this contribution first.
832 * $results no of deleted Contribution on success, false otherwise
834 public static function deleteContribution($id) {
835 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
837 $transaction = new CRM_Core_Transaction();
840 //delete activity record
842 'source_record_id' => $id,
843 // activity type id for contribution
844 'activity_type_id' => 6,
847 CRM_Activity_BAO_Activity
::deleteActivity($params);
849 //delete billing address if exists for this contribution.
850 self
::deleteAddress($id);
852 //update pledge and pledge payment, CRM-3961
853 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
855 // remove entry from civicrm_price_set_entity, CRM-5095
856 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
857 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
859 // cleanup line items.
860 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
862 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
863 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
865 if ($participantId) {
866 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
869 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
873 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
874 $noteId = key($note);
876 CRM_Core_BAO_Note
::del($noteId, FALSE);
879 $dao = new CRM_Contribute_DAO_Contribution();
882 $results = $dao->delete();
884 $transaction->commit();
886 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
888 // delete the recently created Contribution
889 $contributionRecent = array(
891 'type' => 'Contribution',
893 CRM_Utils_Recent
::del($contributionRecent);
899 * React to a financial transaction (payment) failure.
901 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
902 * payments is important for forensic and outreach reasons.
904 * @param int $contributionID
905 * @param string $message
907 public static function failPayment($contributionID, $contactID, $message) {
908 civicrm_api3('activity', 'create', array(
909 'activity_type_id' => 'Failed Payment',
910 'details' => $message,
911 'subject' => ts('Payment failed at payment processor'),
912 'source_record_id' => $contributionID,
913 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
919 * Check if there is a contribution with the same trxn_id or invoice_id.
921 * @param array $input
922 * An assoc array of name/value pairs.
923 * @param array $duplicates
924 * (reference) store ids of duplicate contribs.
928 * true if duplicate, false otherwise
930 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
932 $id = CRM_Utils_Array
::value('id', $input);
934 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
935 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
941 $clause[] = "trxn_id = %1";
942 $input[1] = array($trxn_id, 'String');
946 $clause[] = "invoice_id = %2";
947 $input[2] = array($invoice_id, 'String');
950 if (empty($clause)) {
954 $clause = implode(' OR ', $clause);
956 $clause = "( $clause ) AND id != %3";
957 $input[3] = array($id, 'Integer');
960 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
961 $dao = CRM_Core_DAO
::executeQuery($query, $input);
963 while ($dao->fetch()) {
964 $duplicates[] = $dao->id
;
971 * Takes an associative array and creates a contribution_product object.
973 * the function extract all the params it needs to initialize the create a
974 * contribution_product object. the params array could contain additional unused name/value
977 * @param array $params
978 * (reference) an assoc array of name/value pairs.
980 * @return CRM_Contribute_DAO_ContributionProduct
982 public static function addPremium(&$params) {
983 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
984 $contributionProduct->copyValues($params);
985 return $contributionProduct->save();
989 * Get list of contribution fields for profile.
990 * For now we only allow custom contribution fields to be in
993 * @param bool $addExtraFields
994 * True if special fields needs to be added.
997 * the list of contribution fields
999 public static function getContributionFields($addExtraFields = TRUE) {
1000 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1001 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1003 if ($addExtraFields) {
1004 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1007 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1009 foreach ($contributionFields as $key => $var) {
1010 if ($key == 'contribution_contact_id') {
1013 elseif ($key == 'contribution_campaign_id') {
1014 $var['title'] = ts('Campaign');
1016 $fields[$key] = $var;
1019 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1024 * Add extra fields specific to contribution.
1026 public static function getSpecialContributionFields() {
1027 $extraFields = array(
1028 'contribution_soft_credit_name' => array(
1029 'name' => 'contribution_soft_credit_name',
1030 'title' => 'Soft Credit Name',
1031 'headerPattern' => '/^soft_credit_name$/i',
1032 'where' => 'civicrm_contact_d.display_name',
1034 'contribution_soft_credit_email' => array(
1035 'name' => 'contribution_soft_credit_email',
1036 'title' => 'Soft Credit Email',
1037 'headerPattern' => '/^soft_credit_email$/i',
1038 'where' => 'soft_email.email',
1040 'contribution_soft_credit_phone' => array(
1041 'name' => 'contribution_soft_credit_phone',
1042 'title' => 'Soft Credit Phone',
1043 'headerPattern' => '/^soft_credit_phone$/i',
1044 'where' => 'soft_phone.phone',
1046 'contribution_soft_credit_contact_id' => array(
1047 'name' => 'contribution_soft_credit_contact_id',
1048 'title' => 'Soft Credit Contact ID',
1049 'headerPattern' => '/^soft_credit_contact_id$/i',
1050 'where' => 'civicrm_contribution_soft.contact_id',
1054 return $extraFields;
1058 * @param int $pageID
1062 public static function getCurrentandGoalAmount($pageID) {
1064 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1065 FROM civicrm_contribution_page p,
1066 civicrm_contribution c
1067 WHERE p.id = c.contribution_page_id
1069 AND c.cancel_date is null
1073 $config = CRM_Core_Config
::singleton();
1074 $params = array(1 => array($pageID, 'Integer'));
1075 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1077 if ($dao->fetch()) {
1078 return array($dao->goal
, $dao->total
);
1081 return array(NULL, NULL);
1086 * Get list of contribution In Honor of contact Ids.
1088 * @param int $honorId
1089 * In Honor of Contact ID.
1092 * list of contribution fields
1094 public static function getHonorContacts($honorId) {
1096 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1097 $honorDAO->contact_id
= $honorId;
1100 $type = CRM_Contribute_PseudoConstant
::financialType();
1102 while ($honorDAO->fetch()) {
1103 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1104 $contributionDAO->id
= $honorDAO->contribution_id
;
1106 if ($contributionDAO->find(TRUE)) {
1107 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1108 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1109 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1110 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1111 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1112 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1113 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1114 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1115 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1123 * Get the sort name of a contact for a particular contribution.
1126 * Id of the contribution.
1128 * @return null|string
1129 * sort name of the contact if found
1131 public static function sortName($id) {
1132 $id = CRM_Utils_Type
::escape($id, 'Integer');
1135 SELECT civicrm_contact.sort_name
1136 FROM civicrm_contribution, civicrm_contact
1137 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1138 AND civicrm_contribution.id = {$id}
1140 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1144 * @param int $contactID
1148 public static function annual($contactID) {
1149 if (is_array($contactID)) {
1150 $contactIDs = implode(',', $contactID);
1153 $contactIDs = $contactID;
1156 $config = CRM_Core_Config
::singleton();
1157 $startDate = $endDate = NULL;
1159 $currentMonth = date('m');
1160 $currentDay = date('d');
1161 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1162 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1163 (int ) $config->fiscalYearStart
['d'] > $currentDay
1166 $year = date('Y') - 1;
1171 $nextYear = $year +
1;
1173 if ($config->fiscalYearStart
) {
1174 if ($config->fiscalYearStart
['M'] < 10) {
1175 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1177 if ($config->fiscalYearStart
['d'] < 10) {
1178 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1180 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1185 $startDate = "$year$monthDay";
1186 $endDate = "$nextYear$monthDay";
1189 SELECT count(*) as count,
1190 sum(total_amount) as amount,
1191 avg(total_amount) as average,
1193 FROM civicrm_contribution b
1194 WHERE b.contact_id IN ( $contactIDs )
1195 AND b.contribution_status_id = 1
1197 AND b.receive_date >= $startDate
1198 AND b.receive_date < $endDate
1201 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1203 $amount = $average = array();
1204 while ($dao->fetch()) {
1205 if ($dao->count
> 0 && $dao->amount
> 0) {
1206 $count +
= $dao->count
;
1207 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1208 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1214 implode(', ', $amount),
1215 implode(', ', $average),
1218 return array(0, 0, 0);
1222 * Check if there is a contribution with the params passed in.
1224 * Used for trxn_id,invoice_id and contribution_id
1226 * @param array $params
1227 * An assoc array of name/value pairs.
1230 * contribution id if success else NULL
1232 public static function checkDuplicateIds($params) {
1233 $dao = new CRM_Contribute_DAO_Contribution();
1237 foreach ($params as $k => $v) {
1239 $clause[] = "$k = '$v'";
1242 $clause = implode(' AND ', $clause);
1243 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1244 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1246 while ($dao->fetch()) {
1254 * Get the contribution details for component export.
1256 * @param int $exportMode
1258 * @param string $componentIds
1264 public static function getContributionDetails($exportMode, $componentIds) {
1265 $paymentDetails = array();
1266 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1268 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1269 $componentSelect = " civicrm_participant_payment.participant_id id";
1270 $additionalClause = "
1271 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1272 AND civicrm_participant_payment.participant_id {$componentClause} )
1275 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1276 $componentSelect = " civicrm_membership_payment.membership_id id";
1277 $additionalClause = "
1278 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1279 AND civicrm_membership_payment.membership_id {$componentClause} )
1282 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1283 $componentSelect = " civicrm_pledge_payment.id id";
1284 $additionalClause = "
1285 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1286 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1290 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1291 trxn_id, {$componentSelect}
1292 FROM civicrm_contribution
1293 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1294 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1295 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1296 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1297 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1298 AND option_group_contribution_status.id = contribution_status.option_group_id )
1302 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1304 while ($dao->fetch()) {
1305 $paymentDetails[$dao->id
] = array(
1306 'total_amount' => $dao->total_amount
,
1307 'contribution_status' => $dao->status
,
1308 'receive_date' => $dao->receive_date
,
1309 'pay_instru' => $dao->payment_instrument
,
1310 'trxn_id' => $dao->trxn_id
,
1314 return $paymentDetails;
1318 * Create address associated with contribution record.
1320 * As long as there is one or more billing field in the parameters we will create the address.
1322 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1325 * @param array $params
1326 * @param int $billingLocationTypeID
1331 public static function createAddress($params, $billingLocationTypeID) {
1332 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1333 if ($hasBillingField) {
1334 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1335 return $address->id
;
1342 * Delete billing address record related contribution.
1344 * @param int $contributionId
1345 * @param int $contactId
1347 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1349 $contactJoin = NULL;
1351 if ($contributionId) {
1352 $clauses[] = "cc.id = {$contributionId}";
1356 $clauses[] = "cco.id = {$contactId}";
1357 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1360 if (empty($clauses)) {
1361 CRM_Core_Error
::fatal();
1364 $condition = implode(' OR ', $clauses);
1368 FROM civicrm_address ca
1369 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1373 $dao = CRM_Core_DAO
::executeQuery($query);
1375 while ($dao->fetch()) {
1376 $params = array('id' => $dao->id
);
1377 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1382 * This function check online pending contribution associated w/
1383 * Online Event Registration or Online Membership signup.
1385 * @param int $componentId
1386 * Participant/membership id.
1387 * @param string $componentName
1391 * pending contribution id.
1393 public static function checkOnlinePendingContribution($componentId, $componentName) {
1394 $contributionId = NULL;
1395 if (!$componentId ||
1396 !in_array($componentName, array('Event', 'Membership'))
1398 return $contributionId;
1401 if ($componentName == 'Event') {
1402 $idName = 'participant_id';
1403 $componentTable = 'civicrm_participant';
1404 $paymentTable = 'civicrm_participant_payment';
1405 $source = ts('Online Event Registration');
1408 if ($componentName == 'Membership') {
1409 $idName = 'membership_id';
1410 $componentTable = 'civicrm_membership';
1411 $paymentTable = 'civicrm_membership_payment';
1412 $source = ts('Online Contribution');
1415 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1418 SELECT component.id as {$idName},
1419 componentPayment.contribution_id as contribution_id,
1420 contribution.source source,
1421 contribution.contribution_status_id as contribution_status_id,
1422 contribution.is_pay_later as is_pay_later
1423 FROM $componentTable component
1424 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1425 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1426 WHERE component.id = {$componentId}";
1428 $dao = CRM_Core_DAO
::executeQuery($query);
1430 while ($dao->fetch()) {
1431 if ($dao->contribution_id
&&
1432 $dao->is_pay_later
&&
1433 $dao->contribution_status_id
== $pendingStatusId &&
1434 strpos($dao->source
, $source) !== FALSE
1436 $contributionId = $dao->contribution_id
;
1441 return $contributionId;
1445 * Update contribution as well as related objects.
1447 * This function by-passes hooks - to address this - don't use this function.
1451 * Use api contribute.completetransaction
1452 * For failures use failPayment (preferably exposing by api in the process).
1454 * @param array $params
1455 * @param bool $processContributionObject
1458 * @throws \Exception
1460 public static function transitionComponents($params, $processContributionObject = FALSE) {
1461 // get minimum required values.
1462 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1463 $componentId = CRM_Utils_Array
::value('component_id', $params);
1464 $componentName = CRM_Utils_Array
::value('componentName', $params);
1465 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1466 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1468 // if we already processed contribution object pass previous status id.
1469 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1471 $updateResult = array();
1473 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1475 // we process only ( Completed, Cancelled, or Failed ) contributions.
1476 if (!$contributionId ||
1477 !in_array($contributionStatusId, array(
1478 array_search('Completed', $contributionStatuses),
1479 array_search('Cancelled', $contributionStatuses),
1480 array_search('Failed', $contributionStatuses),
1483 return $updateResult;
1486 if (!$componentName ||
!$componentId) {
1487 // get the related component details.
1488 $componentDetails = self
::getComponentDetails($contributionId);
1491 $componentDetails['contact_id'] = $contactId;
1492 $componentDetails['component'] = $componentName;
1494 if ($componentName == 'event') {
1495 $componentDetails['participant'] = $componentId;
1498 $componentDetails['membership'] = $componentId;
1502 if (!empty($componentDetails['contact_id'])) {
1503 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1509 // do check for required ids.
1510 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1511 return $updateResult;
1514 //now we are ready w/ required ids, start processing.
1516 $baseIPN = new CRM_Core_Payment_BaseIPN();
1518 $input = $ids = $objects = array();
1520 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1521 $ids['contribution'] = $contributionId;
1522 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1523 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1524 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1525 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1526 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1527 $ids['contributionRecur'] = NULL;
1528 $ids['contributionPage'] = NULL;
1530 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1531 CRM_Core_Error
::fatal();
1534 $memberships = &$objects['membership'];
1535 $participant = &$objects['participant'];
1536 $pledgePayment = &$objects['pledge_payment'];
1537 $contribution = &$objects['contribution'];
1539 if ($pledgePayment) {
1540 $pledgePaymentIDs = array();
1541 foreach ($pledgePayment as $key => $object) {
1542 $pledgePaymentIDs[] = $object->id
;
1544 $pledgeID = $pledgePayment[0]->pledge_id
;
1547 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1550 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1551 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1556 // we might want to process contribution object.
1557 $processContribution = FALSE;
1558 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1559 if (is_array($memberships)) {
1560 foreach ($memberships as $membership) {
1562 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1563 $membership->save();
1565 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1566 if ($processContributionObject) {
1567 $processContribution = TRUE;
1574 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1575 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1577 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1578 if ($processContributionObject) {
1579 $processContribution = TRUE;
1583 if ($pledgePayment) {
1584 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1586 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1587 if ($processContributionObject) {
1588 $processContribution = TRUE;
1592 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1593 if (is_array($memberships)) {
1594 foreach ($memberships as $membership) {
1596 $membership->status_id
= array_search('Expired', $membershipStatuses);
1597 $membership->save();
1599 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1600 if ($processContributionObject) {
1601 $processContribution = TRUE;
1607 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1608 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1610 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1611 if ($processContributionObject) {
1612 $processContribution = TRUE;
1616 if ($pledgePayment) {
1617 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1619 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1620 if ($processContributionObject) {
1621 $processContribution = TRUE;
1625 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1627 // only pending contribution related object processed.
1628 if ($previousContriStatusId &&
1629 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1631 // this is case when we already processed contribution object.
1632 return $updateResult;
1634 elseif (!$previousContriStatusId &&
1635 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1637 // this is case when we are going to process contribution object later.
1638 return $updateResult;
1641 if (is_array($memberships)) {
1642 foreach ($memberships as $membership) {
1647 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1648 $membership->membership_type_id
,
1649 $membership->is_test
, $membership->id
1652 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1653 // this picks up membership type changes during renewals
1655 SELECT membership_type_id
1656 FROM civicrm_membership_log
1657 WHERE membership_id=$membership->id
1660 $dao = new CRM_Core_DAO();
1662 if ($dao->fetch()) {
1663 if (!empty($dao->membership_type_id
)) {
1664 $membership->membership_type_id
= $dao->membership_type_id
;
1665 $membership->save();
1668 // else fall back to using current membership type
1671 // Figure out number of terms
1673 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1674 foreach ($lineitems as $lineitem) {
1675 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1676 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1678 // in case membership_num_terms comes through as null or zero
1679 $numterms = $numterms >= 1 ?
$numterms : 1;
1684 // CRM-15735-to update the membership status as per the contribution receive date
1686 if (!empty($params['receive_date'])) {
1687 $joinDate = $params['receive_date'];
1688 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1689 $membership->end_date
,
1690 $membership->join_date
,
1691 $params['receive_date'],
1693 $membership->membership_type_id
,
1696 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1697 $membership->save();
1700 if ($currentMembership) {
1701 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1702 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1703 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1706 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1709 //get the status for membership.
1710 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1712 $dates['join_date'],
1715 $membership->membership_type_id
,
1719 $formattedParams = array(
1720 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1721 array_search('Current', $membershipStatuses)
1723 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1724 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1725 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1728 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1730 $membership->copyValues($formattedParams);
1731 $membership->save();
1733 //updating the membership log
1734 $membershipLog = array();
1735 $membershipLog = $formattedParams;
1736 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1737 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1739 $membershipLog['start_date'] = $logStartDate;
1740 $membershipLog['membership_id'] = $membership->id
;
1741 $membershipLog['modified_id'] = $membership->contact_id
;
1742 $membershipLog['modified_date'] = date('Ymd');
1743 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1745 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1747 //update related Memberships.
1748 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1750 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1753 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1754 if ($processContributionObject) {
1755 $processContribution = TRUE;
1758 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1764 $updatedStatusId = array_search('Registered', $participantStatuses);
1765 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1767 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1768 if ($processContributionObject) {
1769 $processContribution = TRUE;
1773 if ($pledgePayment) {
1774 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1776 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1777 if ($processContributionObject) {
1778 $processContribution = TRUE;
1783 // process contribution object.
1784 if ($processContribution) {
1785 $contributionParams = array();
1792 'payment_instrument_id',
1795 'financial_type_id',
1796 'contribution_status_id',
1797 'non_deductible_amount',
1801 foreach ($fields as $field) {
1802 if (empty($params[$field])) {
1805 $contributionParams[$field] = $params[$field];
1808 $ids = array('contribution' => $contributionId);
1809 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1812 return $updateResult;
1816 * Returns all contribution related object ids.
1818 * @param $contributionId
1822 public static function getComponentDetails($contributionId) {
1823 $componentDetails = $pledgePayment = array();
1824 if (!$contributionId) {
1825 return $componentDetails;
1829 SELECT c.id as contribution_id,
1830 c.contact_id as contact_id,
1831 c.contribution_recur_id,
1832 mp.membership_id as membership_id,
1833 m.membership_type_id as membership_type_id,
1834 pp.participant_id as participant_id,
1835 p.event_id as event_id,
1836 pgp.id as pledge_payment_id
1837 FROM civicrm_contribution c
1838 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1839 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1840 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1841 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1842 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1843 WHERE c.id = $contributionId";
1845 $dao = CRM_Core_DAO
::executeQuery($query);
1846 $componentDetails = array();
1848 while ($dao->fetch()) {
1849 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1850 $componentDetails['contact_id'] = $dao->contact_id
;
1851 if ($dao->event_id
) {
1852 $componentDetails['event'] = $dao->event_id
;
1854 if ($dao->participant_id
) {
1855 $componentDetails['participant'] = $dao->participant_id
;
1857 if ($dao->membership_id
) {
1858 if (!isset($componentDetails['membership'])) {
1859 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1861 $componentDetails['membership'][] = $dao->membership_id
;
1862 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1864 if ($dao->pledge_payment_id
) {
1865 $pledgePayment[] = $dao->pledge_payment_id
;
1867 if ($dao->contribution_recur_id
) {
1868 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1872 if ($pledgePayment) {
1873 $componentDetails['pledge_payment'] = $pledgePayment;
1876 return $componentDetails;
1880 * @param int $contactId
1881 * @param bool $includeSoftCredit
1883 * @return null|string
1885 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1890 $contactContributionsSQL = "
1891 SELECT contribution.id AS id
1892 FROM civicrm_contribution contribution
1893 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1895 $contactSoftCreditContributionsSQL = "
1896 SELECT contribution.id
1897 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1898 ON ( contribution.id = softContribution.contribution_id )
1899 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1900 $query = "SELECT count( x.id ) count FROM ( ";
1901 $query .= $contactContributionsSQL;
1903 if ($includeSoftCredit) {
1904 $query .= " UNION ";
1905 $query .= $contactSoftCreditContributionsSQL;
1910 return CRM_Core_DAO
::singleValueQuery($query);
1914 * Repeat a transaction as part of a recurring series.
1916 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
1917 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
1918 * subsequent call to the contribution.completetransaction api.
1920 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
1922 * @param CRM_Contribute_BAO_Contribution $contribution
1923 * @param array $input
1924 * @param array $contributionParams
1928 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
1929 if (!empty($contribution->id
)) {
1932 if (empty($contribution->id
)) {
1933 // Unclear why this would only be set for repeats.
1934 if (!empty($input['amount'])) {
1935 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
1937 $templateContribution = civicrm_api3('Contribution', 'getsingle', array(
1938 'contribution_recur_id' => $contributionParams['contribution_recur_id'],
1939 'options' => array('limit' => 1),
1941 $contributionParams['skipLineItem'] = TRUE;
1942 $contributionParams['status_id'] = 'Pending';
1943 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
1944 $contributionParams['contact_id'] = $templateContribution['contact_id'];
1945 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
1946 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
1947 $contribution->id
= $createContribution['id'];
1948 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
1949 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
1955 * Get individual id for onbehalf contribution.
1957 * @param int $contributionId
1959 * @param int $contributorId
1963 * containing organization id and individual id
1965 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1969 if (!$contributionId) {
1973 // fetch contributor id if null
1974 if (!$contributorId) {
1975 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1976 $contributionId, 'contact_id'
1980 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1981 $activityTypeId = array_search('Contribution', $activityTypeIds);
1983 if ($activityTypeId && $contributorId) {
1985 SELECT civicrm_activity_contact.contact_id
1986 FROM civicrm_activity_contact
1987 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1988 WHERE civicrm_activity.activity_type_id = %1
1989 AND civicrm_activity.source_record_id = %2
1990 AND civicrm_activity_contact.record_type_id = %3
1993 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1994 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1997 1 => array($activityTypeId, 'Integer'),
1998 2 => array($contributionId, 'Integer'),
1999 3 => array($sourceID, 'Integer'),
2002 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2004 // for on behalf contribution source is individual and contributor is organization
2005 if ($sourceContactId && $sourceContactId != $contributorId) {
2006 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2007 // get rel type id for employee of relation
2008 foreach ($relationshipTypeIds as $id => $typeVals) {
2009 if ($typeVals['name_a_b'] == 'Employee of') {
2010 $relationshipTypeId = $id;
2015 $rel = new CRM_Contact_DAO_Relationship();
2016 $rel->relationship_type_id
= $relationshipTypeId;
2017 $rel->contact_id_a
= $sourceContactId;
2018 $rel->contact_id_b
= $contributorId;
2019 if ($rel->find(TRUE)) {
2020 $ids['individual_id'] = $rel->contact_id_a
;
2021 $ids['organization_id'] = $rel->contact_id_b
;
2032 public static function getContributionDates() {
2033 $config = CRM_Core_Config
::singleton();
2034 $currentMonth = date('m');
2035 $currentDay = date('d');
2036 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2037 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2038 (int ) $config->fiscalYearStart
['d'] > $currentDay
2041 $year = date('Y') - 1;
2046 $year = array('Y' => $year);
2047 $yearDate = $config->fiscalYearStart
;
2048 $yearDate = array_merge($year, $yearDate);
2049 $yearDate = CRM_Utils_Date
::format($yearDate);
2051 $monthDate = date('Ym') . '01';
2057 'yearDate' => $yearDate,
2058 'monthDate' => $monthDate,
2063 * Load objects relations to contribution object.
2064 * Objects are stored in the $_relatedObjects property
2065 * In the first instance we are just moving functionality from BASEIpn -
2066 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2068 * Note that the unit test for the BaseIPN class tests this function
2070 * @param array $input
2071 * Input as delivered from Payment Processor.
2073 * Ids as Loaded by Payment Processor.
2074 * @param bool $loadAll
2075 * Load all related objects - even where id not passed in? (allows API to call this).
2080 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2082 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2083 if (empty($ids['contact']) && isset($this->contact_id
)) {
2084 $ids['contact'] = $this->contact_id
;
2087 if (empty($this->_component
)) {
2088 if (!empty($ids['event'])) {
2089 $this->_component
= 'event';
2092 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2096 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2097 // refactoring than anything else, and has unit test coverage.
2098 if (empty($this->financial_type_id
)) {
2102 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2107 if (!$paymentProcessorID && $this->contribution_page_id
) {
2108 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2109 $this->contribution_page_id
,
2112 if ($paymentProcessorID) {
2113 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2117 $ids['contributionType'] = $this->financial_type_id
;
2118 $ids['financialType'] = $this->financial_type_id
;
2121 'contact' => 'CRM_Contact_BAO_Contact',
2122 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2123 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2124 'financialType' => 'CRM_Financial_BAO_FinancialType',
2126 foreach ($entities as $entity => $bao) {
2127 if (!empty($ids[$entity])) {
2128 $this->_relatedObjects
[$entity] = new $bao();
2129 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2130 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2131 throw new CRM_Core_Exception($entity . ' could not be loaded');
2136 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2137 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2140 if (!empty($ids['pledge_payment'])) {
2141 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2142 if (empty($paymentID)) {
2145 $payment = new CRM_Pledge_BAO_PledgePayment();
2146 $payment->id
= $paymentID;
2147 if (!$payment->find(TRUE)) {
2148 throw new Exception("Could not find pledge payment record: " . $paymentID);
2150 $this->_relatedObjects
['pledge_payment'][] = $payment;
2154 if ($this->_component
== 'contribute') {
2155 // retrieve the other optional objects first so
2156 // stuff down the line can use this info and do things
2158 //in any case get the memberships associated with the contribution
2159 //because we now support multiple memberships w/ price set
2160 // see if there are any other memberships to be considered for same contribution.
2162 SELECT membership_id
2163 FROM civicrm_membership_payment
2164 WHERE contribution_id = %1 ";
2165 $params = array(1 => array($this->id
, 'Integer'));
2167 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2168 while ($dao->fetch()) {
2169 if ($dao->membership_id
) {
2170 if (!is_array($ids['membership'])) {
2171 $ids['membership'] = array();
2173 $ids['membership'][] = $dao->membership_id
;
2177 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2178 foreach ($ids['membership'] as $id) {
2180 $membership = new CRM_Member_BAO_Membership();
2181 $membership->id
= $id;
2182 if (!$membership->find(TRUE)) {
2183 throw new Exception("Could not find membership record: $id");
2185 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2186 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2187 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2188 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2189 $membership->free();
2195 // we are in event mode
2196 // make sure event exists and is valid
2197 $event = new CRM_Event_BAO_Event();
2198 $event->id
= $ids['event'];
2199 if ($ids['event'] &&
2202 throw new Exception("Could not find event: " . $ids['event']);
2205 $this->_relatedObjects
['event'] = &$event;
2207 $participant = new CRM_Event_BAO_Participant();
2208 $participant->id
= $ids['participant'];
2209 if ($ids['participant'] &&
2210 !$participant->find(TRUE)
2212 throw new Exception("Could not find participant: " . $ids['participant']);
2214 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2216 $this->_relatedObjects
['participant'] = &$participant;
2218 // get the payment processor id from event - this is inaccurate see CRM-16923
2219 // in future we should look at throwing an exception here rather than an dubious guess.
2220 if (!$paymentProcessorID) {
2221 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2222 if ($paymentProcessorID) {
2223 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2228 if ($paymentProcessorID) {
2229 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2230 $this->is_test ?
'test' : 'live'
2232 $ids['paymentProcessor'] = $paymentProcessorID;
2233 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2239 * Create array of message information - ie. return html version, txt version, to field
2241 * @param array $input
2242 * Incoming information.
2243 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2244 * just check presence of recur object but maintaining legacy approach
2247 * IDs of related objects.
2248 * @param array $values
2249 * Any values that may have already been compiled by calling process.
2250 * This is augmented by values 'gathered' by gatherMessageValues
2251 * @param bool $recur
2252 * @param bool $returnMessageText
2253 * Distinguishes between whether to send message or return.
2254 * message text. We are working towards this function ALWAYS returning message text & calling
2255 * function doing emails / pdfs with it
2261 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2262 $this->loadRelatedObjects($input, $ids);
2264 if (empty($this->_component
)) {
2265 $this->_component
= CRM_Utils_Array
::value('component', $input);
2268 //not really sure what params might be passed in but lets merge em into values
2269 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2270 $template = CRM_Core_Smarty
::singleton();
2271 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2272 //what does recur 'mean here - to do with payment processor return functionality but
2273 // what is the importance
2274 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2275 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2277 $entityID = $entity = NULL;
2278 if (isset($ids['contribution'])) {
2279 $entity = 'contribution';
2280 $entityID = $ids['contribution'];
2282 if (!empty($ids['membership'])) {
2283 //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
2284 // 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
2285 // line having loaded an array
2286 $ids['membership'] = (array) $ids['membership'];
2287 $entity = 'membership';
2288 $entityID = $ids['membership'][0];
2291 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity));
2292 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2293 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2295 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2296 //direct mode showing billing block, so use directIPN for temporary
2297 $template->assign('contributeMode', 'directIPN');
2300 // todo remove strtolower - check consistency
2301 if (strtolower($this->_component
) == 'event') {
2302 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2303 $values['event'] = array();
2305 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2307 //get location details
2308 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2309 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2311 $ufJoinParams = array(
2312 'entity_table' => 'civicrm_event',
2313 'entity_id' => $ids['event'],
2314 'module' => 'CiviEvent',
2317 list($custom_pre_id,
2319 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2321 $values['custom_pre_id'] = $custom_pre_id;
2322 $values['custom_post_id'] = $custom_post_ids;
2323 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
2324 //and cases involving status updation through ipn
2325 // whatever that means!
2326 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2327 // perhaps we should throw an e-notice if amount is set & force total_amount?
2328 if (!empty($input['amount'])) {
2329 $values['totalAmount'] = $input['amount'];
2332 if ($values['event']['is_email_confirm']) {
2333 $values['is_email_receipt'] = 1;
2335 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2336 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2340 $values['contribution_id'] = $this->id
;
2341 if (!empty($ids['related_contact'])) {
2342 $values['related_contact'] = $ids['related_contact'];
2343 if (isset($ids['onbehalf_dupe_alert'])) {
2344 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2346 $entityBlock = array(
2347 'contact_id' => $ids['contact'],
2348 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2349 'Home', 'id', 'name'
2352 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2353 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2356 if ($this->is_test
) {
2359 if (!empty($this->_relatedObjects
['membership'])) {
2360 foreach ($this->_relatedObjects
['membership'] as $membership) {
2361 if ($membership->id
) {
2362 $values['isMembership'] = TRUE;
2364 // need to set the membership values here
2365 $template->assign('membership_assign', 1);
2366 $template->assign('membership_name',
2367 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2369 $template->assign('mem_start_date', $membership->start_date
);
2370 $template->assign('mem_join_date', $membership->join_date
);
2371 $template->assign('mem_end_date', $membership->end_date
);
2372 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2373 $template->assign('mem_status', $membership_status);
2374 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2375 $template->assign('is_pay_later', 1);
2378 // if separate payment there are two contributions recorded and the
2379 // admin will need to send a receipt for each of them separately.
2380 // we dont link the two in the db (but can potentially infer it if needed)
2381 $template->assign('is_separate_payment', 0);
2383 if ($recur && $paymentObject) {
2384 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2385 $template->assign('cancelSubscriptionUrl', $url);
2386 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2387 $template->assign('updateSubscriptionBillingUrl', $url);
2388 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2389 $template->assign('updateSubscriptionUrl', $url);
2392 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2395 // otherwise if its about sending emails, continue sending without return, as we
2396 // don't want to exit the loop.
2401 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2407 * Gather values for contribution mail - this function has been created
2408 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2409 * Values related to the contribution in question are gathered
2411 * @param array $input
2412 * Input into function (probably from payment processor).
2413 * @param array $values
2415 * The set of ids related to the input.
2419 public function _gatherMessageValues($input, &$values, $ids = array()) {
2420 // set display address of contributor
2421 if ($this->address_id
) {
2422 $addressParams = array('id' => $this->address_id
);
2423 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2424 $addressDetails = array_values($addressDetails);
2425 $values['address'] = $addressDetails[0]['display'];
2427 if ($this->_component
== 'contribute') {
2428 //get soft contributions
2429 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2430 if (!empty($softContributions)) {
2431 $values['softContributions'] = $softContributions['soft_credit'];
2433 if (isset($this->contribution_page_id
)) {
2434 CRM_Contribute_BAO_ContributionPage
::setValues(
2435 $this->contribution_page_id
,
2438 if ($this->contribution_page_id
) {
2439 // CRM-8254 - override default currency if applicable
2440 $config = CRM_Core_Config
::singleton();
2441 $config->defaultCurrency
= CRM_Utils_Array
::value(
2444 $config->defaultCurrency
2448 // no contribution page -probably back office
2450 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2451 $values['is_email_receipt'] = 1;
2452 $values['title'] = 'Contribution';
2454 // set lineItem for contribution
2456 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2457 if (!empty($lineItem)) {
2458 $itemId = key($lineItem);
2459 foreach ($lineItem as &$eachItem) {
2460 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2461 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2462 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2463 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2466 $values['lineItem'][0] = $lineItem;
2467 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2471 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2475 // if this is onbehalf of contribution then set related contact
2476 if (!empty($relatedContact['individual_id'])) {
2477 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2482 $eventParams = array(
2483 'id' => $this->_relatedObjects
['event']->id
,
2485 $values['event'] = array();
2487 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2488 // add custom fields for event
2489 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2491 $eventCustomGroup = array();
2492 foreach ($eventGroupTree as $key => $group) {
2493 if ($key === 'info') {
2497 foreach ($group['fields'] as $k => $customField) {
2498 $groupLabel = $group['title'];
2499 if (!empty($customField['customValue'])) {
2500 foreach ($customField['customValue'] as $customFieldValues) {
2501 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2506 $values['event']['customGroup'] = $eventCustomGroup;
2508 //get participant details
2509 $participantParams = array(
2510 'id' => $this->_relatedObjects
['participant']->id
,
2513 $values['participant'] = array();
2515 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2516 // add custom fields for event
2517 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2518 $participantCustomGroup = array();
2519 foreach ($participantGroupTree as $key => $group) {
2520 if ($key === 'info') {
2524 foreach ($group['fields'] as $k => $customField) {
2525 $groupLabel = $group['title'];
2526 if (!empty($customField['customValue'])) {
2527 foreach ($customField['customValue'] as $customFieldValues) {
2528 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2533 $values['participant']['customGroup'] = $participantCustomGroup;
2535 //get location details
2536 $locationParams = array(
2537 'entity_id' => $this->_relatedObjects
['event']->id
,
2538 'entity_table' => 'civicrm_event',
2540 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2542 $ufJoinParams = array(
2543 'entity_table' => 'civicrm_event',
2544 'entity_id' => $ids['event'],
2545 'module' => 'CiviEvent',
2548 list($custom_pre_id,
2550 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2552 $values['custom_pre_id'] = $custom_pre_id;
2553 $values['custom_post_id'] = $custom_post_ids;
2555 // set lineItem for event contribution
2557 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2558 if (!empty($participantIds)) {
2559 foreach ($participantIds as $pIDs) {
2560 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2561 if (!CRM_Utils_System
::isNull($lineItem)) {
2562 $values['lineItem'][] = $lineItem;
2569 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2571 $customGroup = array();
2572 foreach ($groupTree as $key => $group) {
2573 if ($key === 'info') {
2577 foreach ($group['fields'] as $k => $customField) {
2578 $groupLabel = $group['title'];
2579 if (!empty($customField['customValue'])) {
2580 foreach ($customField['customValue'] as $customFieldValues) {
2581 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2586 $values['customGroup'] = $customGroup;
2592 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2593 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2594 * Note we send directly from this function in some cases because it is only partly refactored
2595 * Don't call this function directly as the signature will change
2599 * @param CRM_Core_SMARTY $template
2600 * @param bool $recur
2601 * @param bool $returnMessageText
2605 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2606 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2607 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2608 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2609 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2610 $template->assign('useForMember', TRUE);
2612 //assign honor information to receipt message
2613 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2615 if (isset($softRecord['soft_credit'])) {
2616 //if id of contribution page is present
2617 if (!empty($values['id'])) {
2618 $values['honor'] = array(
2619 'honor_profile_values' => array(),
2620 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2621 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2623 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2625 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2626 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2629 //offline contribution
2630 $softCreditTypes = $softCredits = array();
2631 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2632 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2633 $softCredits[$key] = array(
2634 'Name' => $softCredit['contact_name'],
2635 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2638 $template->assign('softCreditTypes', $softCreditTypes);
2639 $template->assign('softCredits', $softCredits);
2643 $dao = new CRM_Contribute_DAO_ContributionProduct();
2644 $dao->contribution_id
= $this->id
;
2645 if ($dao->find(TRUE)) {
2646 $premiumId = $dao->product_id
;
2647 $template->assign('option', $dao->product_option
);
2649 $productDAO = new CRM_Contribute_DAO_Product();
2650 $productDAO->id
= $premiumId;
2651 $productDAO->find(TRUE);
2652 $template->assign('selectPremium', TRUE);
2653 $template->assign('product_name', $productDAO->name
);
2654 $template->assign('price', $productDAO->price
);
2655 $template->assign('sku', $productDAO->sku
);
2657 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2658 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2659 if (empty($amount) && isset($this->total_amount
)) {
2660 $amount = $this->total_amount
;
2662 $template->assign('amount', $amount);
2663 // add the new contribution values
2664 if (strtolower($this->_component
) == 'contribute') {
2666 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2667 $softDAO->contribution_id
= $this->id
;
2668 if ($softDAO->find(TRUE)) {
2669 $template->assign('pcpBlock', TRUE);
2670 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2671 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2672 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2674 //assign the pcp page title for email subject
2675 $pcpDAO = new CRM_PCP_DAO_PCP();
2676 $pcpDAO->id
= $softDAO->pcp_id
;
2677 if ($pcpDAO->find(TRUE)) {
2678 $template->assign('title', $pcpDAO->title
);
2683 if ($this->financial_type_id
) {
2684 $values['financial_type_id'] = $this->financial_type_id
;
2687 $template->assign('trxn_id', $this->trxn_id
);
2688 $template->assign('receive_date',
2689 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2691 $template->assign('contributeMode', 'notify');
2692 $template->assign('action', $this->is_test ?
1024 : 1);
2693 $template->assign('receipt_text',
2694 CRM_Utils_Array
::value('receipt_text',
2698 $template->assign('is_monetary', 1);
2699 $template->assign('is_recur', (bool) $recur);
2700 $template->assign('currency', $this->currency
);
2701 $template->assign('address', CRM_Utils_Address
::format($input));
2702 if (!empty($values['customGroup'])) {
2703 $template->assign('customGroup', $values['customGroup']);
2705 if (!empty($values['softContributions'])) {
2706 $template->assign('softContributions', $values['softContributions']);
2708 if ($this->_component
== 'event') {
2709 $template->assign('title', $values['event']['title']);
2710 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2711 $viewRoles = array();
2712 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2713 $viewRoles[] = $participantRoles[$v];
2715 $values['event']['participant_role'] = implode(', ', $viewRoles);
2716 $template->assign('event', $values['event']);
2717 $template->assign('participant', $values['participant']);
2718 $template->assign('location', $values['location']);
2719 $template->assign('customPre', $values['custom_pre_id']);
2720 $template->assign('customPost', $values['custom_post_id']);
2723 if ($this->_relatedObjects
['participant']->is_test
) {
2727 $values['params'] = array();
2728 //to get email of primary participant.
2729 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2730 $primaryAmount[] = array(
2731 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2732 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2734 //build an array of cId/pId of participants
2735 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2736 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2737 //send receipt to additional participant if exists
2738 if (count($additionalIDs)) {
2739 $template->assign('isPrimary', 0);
2740 $template->assign('customProfile', NULL);
2741 //set additionalParticipant true
2742 $values['params']['additionalParticipant'] = TRUE;
2743 foreach ($additionalIDs as $pId => $cId) {
2745 //to change the status pending to completed
2746 $additional = new CRM_Event_DAO_Participant();
2747 $additional->id
= $pId;
2748 $additional->contact_id
= $cId;
2749 $additional->find(TRUE);
2750 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2751 $additional->status_id
= 1;
2752 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2753 //if additional participant dont have email
2755 if (!$additionalParticipantInfo) {
2756 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2758 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2759 $primaryAmount[] = array(
2760 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2761 'amount' => $additional->fee_amount
,
2763 $additional->save();
2764 $additional->free();
2765 $template->assign('amount', $amount);
2766 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2770 //build an array of custom profile and assigning it to template
2771 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2773 if (count($customProfile)) {
2774 $template->assign('customProfile', $customProfile);
2777 // for primary contact
2778 $values['params']['additionalParticipant'] = FALSE;
2779 $template->assign('isPrimary', 1);
2780 $template->assign('amount', $primaryAmount);
2781 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2782 if ($this->payment_instrument_id
) {
2783 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2784 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2786 // carry paylater, since we did not created billing,
2787 // so need to pull email from primary location, CRM-4395
2788 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2794 * Check whether payment processor supports
2795 * cancellation of contribution subscription
2797 * @param int $contributionId
2800 * @param bool $isNotCancelled
2804 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2805 $cacheKeyString = "$contributionId";
2806 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2808 static $supportsCancel = array();
2810 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2811 $supportsCancel[$cacheKeyString] = FALSE;
2812 $isCancelled = FALSE;
2814 if ($isNotCancelled) {
2815 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2818 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2819 if (!empty($paymentObject)) {
2820 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2823 return $supportsCancel[$cacheKeyString];
2827 * Check whether subscription is already cancelled.
2829 * @param int $contributionId
2833 * contribution status
2835 public static function isSubscriptionCancelled($contributionId) {
2837 SELECT cr.contribution_status_id
2838 FROM civicrm_contribution_recur cr
2839 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2840 WHERE con.id = %1 LIMIT 1";
2841 $params = array(1 => array($contributionId, 'Integer'));
2842 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2843 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2844 if ($status == 'Cancelled') {
2851 * Create all financial accounts entry.
2853 * @param array $params
2854 * Contribution object, line item array and params for trxn.
2857 * @param array $financialTrxnValues
2859 * @return null|object
2861 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2862 $skipRecords = $update = $return = $isRelatedId = FALSE;
2864 $additionalParticipantId = array();
2865 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2867 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2868 $entityId = $params['participant_id'];
2869 $entityTable = 'civicrm_participant';
2870 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2872 elseif (!empty($params['membership_id'])) {
2873 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2874 // are created off one contribution should be handled elsewhere
2875 $entityId = $params['membership_id'];
2876 $entityTable = 'civicrm_membership';
2879 $entityId = $params['contribution']->id
;
2880 $entityTable = 'civicrm_contribution';
2883 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2884 $isRelatedId = TRUE;
2887 $entityID[] = $entityId;
2888 if (!empty($additionalParticipantId)) {
2889 $entityID +
= $additionalParticipantId;
2891 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2892 if (empty($params['prevContribution'])) {
2899 $statusId = $params['contribution']->contribution_status_id
;
2900 // CRM-13964 partial payment
2901 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2902 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2904 $partialAmtPay = $params['partial_amount_pay'];
2905 $partialAmtTotal = $params['partial_payment_total'];
2907 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2908 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2909 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2910 $params['total_amount'] = $partialAmtPay;
2912 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2913 if (empty($balanceTrxnInfo['trxn_id'])) {
2914 // create new balance transaction record
2915 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2916 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2918 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2919 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2920 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2921 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2922 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2923 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2924 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2925 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2926 $balanceTrxnParams['status_id'] = $statusId;
2927 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2928 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2929 if (!empty($params['payment_processor'])) {
2930 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2932 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2936 // build line item array if its not set in $params
2937 if (empty($params['line_item']) ||
$additionalParticipantId) {
2938 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2941 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2942 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2944 $skipRecords = TRUE;
2945 $pendingStatus = array(
2946 array_search('Pending', $contributionStatuses),
2947 array_search('In Progress', $contributionStatuses),
2949 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2950 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2951 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2953 elseif (!empty($params['payment_processor'])) {
2954 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2956 elseif (!empty($params['payment_instrument_id'])) {
2957 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2960 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2961 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2962 $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);
2965 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2966 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2967 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2970 //build financial transaction params
2971 $trxnParams = array(
2972 'contribution_id' => $params['contribution']->id
,
2973 'to_financial_account_id' => $params['to_financial_account_id'],
2974 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2975 'total_amount' => $totalAmount,
2976 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2977 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2978 'currency' => $params['contribution']->currency
,
2979 'trxn_id' => $params['contribution']->trxn_id
,
2980 'status_id' => $statusId,
2981 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2982 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2985 if (!empty($params['payment_processor'])) {
2986 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2989 if (isset($fromFinancialAccountId)) {
2990 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2993 // consider external values passed for recording transaction entry
2994 if (!empty($financialTrxnValues)) {
2995 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2998 $params['trxnParams'] = $trxnParams;
3000 if (!empty($params['prevContribution'])) {
3001 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3002 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3003 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3004 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3005 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3007 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3008 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3009 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3011 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3012 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3015 //if financial type is changed
3016 if (!empty($params['financial_type_id']) &&
3017 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3019 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3020 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3021 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3022 if ($oldFinancialAccount != $newFinancialAccount) {
3023 $params['total_amount'] = 0;
3024 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3025 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3026 $params['prevContribution']->financial_type_id
, $relationTypeId);
3029 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3030 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3031 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3034 self
::updateFinancialAccounts($params, 'changeFinancialType');
3035 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3036 $params['financial_account_id'] = $newFinancialAccount;
3037 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3038 self
::updateFinancialAccounts($params);
3039 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3043 //Update contribution status
3044 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3045 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3046 if (!empty($params['contribution_status_id']) &&
3047 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3049 //Update Financial Records
3050 self
::updateFinancialAccounts($params, 'changedStatus');
3053 // change Payment Instrument for a Completed contribution
3054 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3055 // instrument is null and now new payment instrument is added along with the payment
3056 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3057 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3058 if (array_key_exists('payment_instrument_id', $params)) {
3059 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3060 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3061 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3063 //check if status is changed from Pending to Completed
3064 // do not update payment instrument changes for Pending to Completed
3065 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3066 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3068 // for all other statuses create new financial records
3069 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3070 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3071 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3074 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3075 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3076 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3078 // for any other payment instrument changes create new financial records
3079 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3080 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3081 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3083 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3084 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3086 // another special case when check number is changed, create new financial records
3087 // create financial trxn with negative amount
3088 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3089 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3090 // create financial trxn with positive amount
3091 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3092 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3093 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3097 //if Change contribution amount
3098 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3099 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3100 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3101 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3102 if (isset($totalAmount) &&
3103 $totalAmount != $params['prevContribution']->total_amount
3105 //Update Financial Records
3106 $params['trxnParams']['from_financial_account_id'] = NULL;
3107 self
::updateFinancialAccounts($params, 'changedAmount');
3112 // records finanical trxn and entity financial trxn
3113 // also make it available as return value
3114 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3115 $params['entity_id'] = $financialTxn->id
;
3118 // record line items and financial items
3119 if (empty($params['skipLineItem'])) {
3120 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3123 // create batch entry if batch_id is passed and
3124 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3125 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3126 $entityParams = array(
3127 'batch_id' => $params['batch_id'],
3128 'entity_table' => 'civicrm_financial_trxn',
3129 'entity_id' => $financialTxn->id
,
3131 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3134 // when a fee is charged
3135 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3136 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3139 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3140 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3142 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3143 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3144 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3146 unset($params['line_item']);
3152 * Update all financial accounts entry.
3154 * @param array $params
3155 * Contribution object, line item array and params for trxn.
3157 * @param string $context
3160 * @param null $skipTrxn
3163 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3164 $itemAmount = $trxnID = NULL;
3165 //get all the statuses
3166 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3167 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3168 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3169 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3170 && $context == 'changePaymentInstrument'
3174 if (($params['prevContribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus))
3175 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3176 && $context == 'changedStatus'
3180 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3181 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3183 if ($context == 'changedStatus') {
3184 //get all the statuses
3185 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3187 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3188 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3189 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3191 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3193 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3194 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3196 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3197 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3198 $params['trxnParams']['to_financial_account_id'] = NULL;
3199 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3201 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3202 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3203 $financialTypeID, $relationTypeId);
3205 $itemAmount = $params['trxnParams']['total_amount'];
3207 elseif ($context == 'changePaymentInstrument') {
3208 if ($params['trxnParams']['total_amount'] < 0) {
3209 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3210 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3211 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3212 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3216 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3217 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3220 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3221 $params['entity_id'] = $trxn->id
;
3223 if ($context == 'changedStatus') {
3224 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3225 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3226 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3228 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3229 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3231 $entityParams = array(
3232 'entity_table' => 'civicrm_financial_item',
3233 'financial_trxn_id' => $trxn->id
,
3235 if (empty($params['line_item'])) {
3237 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3238 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3239 // & this can be removed
3242 foreach ($params['line_item'] as $fieldId => $fields) {
3243 foreach ($fields as $fieldValueId => $fieldValues) {
3245 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3246 2 => array($fieldValues['id'], 'Integer'),
3248 CRM_Core_DAO
::executeQuery($query, $fparams);
3250 1 => array($fieldValues['id'], 'Integer'),
3252 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3253 while ($financialItem->fetch()) {
3254 $entityParams['entity_id'] = $financialItem->id
;
3255 $entityParams['amount'] = $financialItem->amount
;
3256 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3263 if ($context != 'changePaymentInstrument') {
3264 $itemParams['entity_table'] = 'civicrm_line_item';
3265 $trxnIds['id'] = $params['entity_id'];
3266 foreach ($params['line_item'] as $fieldId => $fields) {
3267 foreach ($fields as $fieldValueId => $fieldValues) {
3268 $prevParams['entity_id'] = $fieldValues['id'];
3269 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3271 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3272 if ($params['contribution']->receive_date
) {
3273 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3276 $financialAccount = $prevfinancialItem->financial_account_id
;
3277 if (!empty($params['financial_account_id'])) {
3278 $financialAccount = $params['financial_account_id'];
3281 $currency = $params['prevContribution']->currency
;
3282 if ($params['contribution']->currency
) {
3283 $currency = $params['contribution']->currency
;
3286 if (!empty($params['is_quick_config'])) {
3287 $amount = $itemAmount;
3289 $amount = $params['total_amount'];
3293 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3294 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3298 $amount = $diff * $fieldValues['line_total'];
3301 $itemParams = array(
3302 'transaction_date' => $receiveDate,
3303 'contact_id' => $params['prevContribution']->contact_id
,
3304 'currency' => $currency,
3305 'amount' => $amount,
3306 'description' => $prevfinancialItem->description
,
3307 'status_id' => $prevfinancialItem->status_id
,
3308 'financial_account_id' => $financialAccount,
3309 'entity_table' => 'civicrm_line_item',
3310 'entity_id' => $fieldValues['id'],
3312 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3314 if ($fieldValues['tax_amount']) {
3315 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3316 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3317 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3318 $itemParams['description'] = $taxTerm;
3319 if ($fieldValues['financial_type_id']) {
3320 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3322 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3327 if ($context == 'changeFinancialType') {
3328 $params['skipLineItem'] = FALSE;
3329 foreach ($params['line_item'] as &$lineItems) {
3330 foreach ($lineItems as &$line) {
3331 $line['financial_type_id'] = $params['financial_type_id'];
3338 * Check status validation on update of a contribution.
3340 * @param array $values
3341 * Previous form values before submit.
3343 * @param array $fields
3344 * The input form values.
3346 * @param array $errors
3351 public static function checkStatusValidation($values, &$fields, &$errors) {
3352 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3353 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3354 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3358 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3359 $checkStatus = array(
3360 'Cancelled' => array('Completed', 'Refunded'),
3361 'Completed' => array('Cancelled', 'Refunded'),
3362 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3363 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3364 'Refunded' => array('Cancelled', 'Completed'),
3365 'Partially paid' => array('Completed'),
3368 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3369 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3370 1 => $contributionStatuses[$values['contribution_status_id']],
3371 2 => $contributionStatuses[$fields['contribution_status_id']],
3377 * Delete contribution of contact.
3381 * @param int $contactId
3385 public static function deleteContactContribution($contactId) {
3386 $contribution = new CRM_Contribute_DAO_Contribution();
3387 $contribution->contact_id
= $contactId;
3388 $contribution->find();
3389 while ($contribution->fetch()) {
3390 self
::deleteContribution($contribution->id
);
3395 * Get options for a given contribution field.
3396 * @see CRM_Core_DAO::buildOptions
3398 * @param string $fieldName
3399 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3400 * @param array $props whatever is known about this dao object.
3402 * @return array|bool
3404 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3405 $className = __CLASS__
;
3407 switch ($fieldName) {
3408 // This field is not part of this object but the api supports it
3409 case 'payment_processor':
3410 $className = 'CRM_Contribute_BAO_ContributionPage';
3411 // Filter results by contribution page
3412 if (!empty($props['contribution_page_id'])) {
3413 $page = civicrm_api('contribution_page', 'getsingle', array(
3415 'id' => ($props['contribution_page_id']),
3417 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3418 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3422 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3423 case 'honor_type_id':
3424 $className = 'CRM_Contribute_BAO_ContributionSoft';
3425 $fieldName = 'soft_credit_type_id';
3426 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3429 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3433 * Validate financial type.
3437 * @param int $financialTypeId
3438 * Financial Type id.
3440 * @param string $relationName
3442 * @return array|bool
3444 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3445 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3446 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3448 if (!$financialAccount) {
3449 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3456 * Function to record additional payment for partial and refund contributions.
3458 * @param int $contributionId
3459 * is the invoice contribution id (got created after processing participant payment).
3460 * @param array $trxnsData
3461 * to take user provided input of transaction details.
3462 * @param string $paymentType
3463 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3464 * @param int $participantId
3466 * @return null|object
3468 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3469 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3470 $getInfoOf['id'] = $contributionId;
3471 $defaults = array();
3472 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3474 if ($paymentType == 'owed') {
3475 // build params for recording financial trxn entry
3476 $params['contribution'] = $contributionDAO;
3477 $params = array_merge($defaults, $params);
3478 $params['skipLineItem'] = TRUE;
3479 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3480 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3481 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3482 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3485 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3486 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3487 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3489 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3490 if (!empty($trxnId)) {
3491 $trxnId = $trxnId['trxn_id'];
3493 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3494 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3497 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3498 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3499 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3503 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3504 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3505 FROM civicrm_financial_trxn ft
3506 LEFT JOIN civicrm_entity_financial_trxn eft
3507 ON (ft.id = eft.financial_trxn_id)
3508 WHERE eft.entity_table = 'civicrm_contribution'
3509 AND eft.entity_id = {$contributionId}
3510 AND ft.to_financial_account_id != {$toFinancialAccount}
3511 AND ft.status_id = {$statusId}
3513 $query = CRM_Core_DAO
::executeQuery($sql);
3515 $sumOfPayments = $query->sum_of_payments
;
3518 if ($contributionDAO->total_amount
== $sumOfPayments) {
3519 // update contribution status and
3520 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3521 $contributionDAO->contribution_status_id
= $statusId;
3522 $contributionDAO->cancel_date
= 'null';
3523 $contributionDAO->cancel_reason
= NULL;
3524 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3525 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3526 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3527 $contributionDAO->save();
3529 //Change status of financial record too
3530 $financialTrxn->status_id
= $statusId;
3531 $financialTrxn->save();
3533 // note : not using the self::add method,
3534 // the reason because it performs 'status change' related code execution for financial records
3535 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3536 // are coded below i.e. just updating financial_item status to 'Paid'
3538 if ($participantId) {
3539 // update participant status
3540 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3541 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3542 foreach ($ids as $val) {
3543 $participantUpdate['id'] = $val;
3544 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3545 CRM_Event_BAO_Participant
::add($participantUpdate);
3549 // update financial item statuses
3550 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3551 $paidStatus = array_search('Paid', $financialItemStatus);
3553 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3554 $sqlFinancialItemUpdate = "
3555 UPDATE civicrm_financial_item fi
3556 LEFT JOIN civicrm_entity_financial_trxn eft
3557 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3558 SET status_id = {$paidStatus}
3559 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3561 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3564 elseif ($paymentType == 'refund') {
3565 // build params for recording financial trxn entry
3566 $params['contribution'] = $contributionDAO;
3567 $params = array_merge($defaults, $params);
3568 $params['skipLineItem'] = TRUE;
3569 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3570 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3572 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3573 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3574 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3576 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3578 // note : not using the self::add method,
3579 // the reason because it performs 'status change' related code execution for financial records
3580 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3581 // are coded below i.e. just updating financial_item status to 'Paid'
3582 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3584 // add financial item entry
3585 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3586 $getLine['entity_id'] = $contributionDAO->id
;
3587 $getLine['entity_table'] = 'civicrm_contribution';
3588 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3589 if (!empty($lineItemId->id
)) {
3590 $addFinancialEntry = array(
3591 'transaction_date' => $financialTrxn->trxn_date
,
3592 'contact_id' => $contributionDAO->contact_id
,
3593 'amount' => $financialTrxn->total_amount
,
3594 'status_id' => array_search('Paid', $financialItemStatus),
3595 'entity_id' => $lineItemId->id
,
3596 'entity_table' => 'civicrm_line_item',
3598 $trxnIds['id'] = $financialTrxn->id
;
3599 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3601 if ($participantId) {
3602 // update participant status
3603 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3604 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3605 foreach ($ids as $val) {
3606 $participantUpdate['id'] = $val;
3607 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3608 CRM_Event_BAO_Participant
::add($participantUpdate);
3613 // activity creation
3614 if (!empty($financialTrxn)) {
3615 if ($participantId) {
3616 $inputParams['id'] = $participantId;
3619 $component = 'event';
3620 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3621 $entityObj = $entityObj[$participantId];
3623 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3625 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3627 return $financialTrxn;
3633 * @param $activityType
3635 * @param int $contributionId
3637 * @throws CRM_Core_Exception
3639 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3640 if ($component == 'event') {
3641 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3642 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3643 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3644 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3645 $targetCid = $entityObj->contact_id
;
3646 // source record id would be the contribution id
3647 $srcRecId = $contributionId;
3651 $activityParams = array(
3652 'source_contact_id' => $targetCid,
3653 'source_record_id' => $srcRecId,
3654 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3658 'subject' => $subject,
3659 'activity_date_time' => $date,
3660 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3664 'skipRecentView' => TRUE,
3667 // create activity with target contacts
3668 $session = CRM_Core_Session
::singleton();
3669 $id = $session->get('userID');
3671 $activityParams['source_contact_id'] = $id;
3672 $activityParams['target_contact_id'][] = $targetCid;
3674 CRM_Activity_BAO_Activity
::create($activityParams);
3678 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3682 * @param bool $getTrxnInfo
3683 * @param bool $usingLineTotal
3687 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3688 if ($component == 'event') {
3689 $entity = 'participant';
3690 $entityTable = 'civicrm_participant';
3691 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3693 if (!$contributionId) {
3694 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3695 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3696 $id = $primaryParticipantId;
3698 if (!$contributionId) {
3703 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3704 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3710 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3711 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3714 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3715 // for additional participants
3716 if ($entityTable == 'civicrm_participant') {
3717 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3719 foreach ($ids as $val) {
3720 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3724 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3728 $baseTrxnId = $total['trxn_id'];
3729 $total = $total['total_amount'];
3732 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3733 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3735 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3736 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3737 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3739 if ($paymentBalance == 0 && $contributionIsPayLater) {
3740 $paymentBalance = $total;
3743 $info['total'] = $total;
3744 $info['paid'] = $total - $paymentBalance;
3745 $info['balance'] = $paymentBalance;
3747 $info['component'] = $component;
3748 $info['payLater'] = $contributionIsPayLater;
3750 if ($getTrxnInfo && $baseTrxnId) {
3751 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3753 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3754 FROM civicrm_contribution con
3755 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3756 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3757 WHERE con.id = {$contributionId}
3760 // conditioned WHERE clause
3762 // if balance trxn exists don't include details of it in transaction info
3763 $sql .= " AND ft.id != {$baseTrxnId} ";
3765 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3767 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3768 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3769 while ($resultDAO->fetch()) {
3770 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3771 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3773 'total_amount' => $resultDAO->total_amount
,
3774 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3775 'payment_instrument' => $paidByLabel,
3776 'receive_date' => $resultDAO->trxn_date
,
3777 'trxn_id' => $resultDAO->trxn_id
,
3778 'status' => $statuses[$resultDAO->status_id
],
3780 if ($paidByName == 'Check') {
3781 $val['check_number'] = $resultDAO->check_number
;
3785 $info['transaction'] = $rows;
3791 * Get financial account id has 'Sales Tax Account is'
3792 * account relationship with financial type
3794 * @param int $financialTypeId
3796 * @return FinancialAccountId
3798 public static function getFinancialAccountId($financialTypeId) {
3799 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3800 $searchParams = array(
3801 'entity_table' => 'civicrm_financial_type',
3802 'entity_id' => $financialTypeId,
3803 'account_relationship' => $accountRel,
3806 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3808 return CRM_Utils_Array
::value('financial_account_id', $result);
3814 * @param array $params
3815 * @param bool $isLineItem
3819 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3820 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3822 // Update contribution.
3823 if (!empty($params['id'])) {
3824 $id = $params['id'];
3825 $values = $ids = array();
3826 $contrbutionParams = array('id' => $id);
3827 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3829 // To assign pervious finantial type on update of contribution
3830 if (!isset($params['financial_type_id'])) {
3831 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3833 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3834 // Assisn tax Amount on update of contrbution
3835 if (!empty($prevContributionValue->tax_amount
)) {
3836 $params['tax_amount'] = 'null';
3837 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3838 foreach ($params['line_item'] as $setID => $priceField) {
3839 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3840 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3847 // New Contrbution and update of contribution with tax rate financial type
3848 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3849 empty($params['skipLineItem']) && !$isLineItem
3851 $taxRateParams = $taxRates[$params['financial_type_id']];
3852 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3853 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3855 // Get Line Item on update of contribution
3856 if (isset($params['id'])) {
3857 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3860 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3862 foreach ($params['line_item'] as $setID => $priceField) {
3863 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3864 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3867 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3869 elseif (isset($params['api.line_item.create'])) {
3870 // Update total amount of contribution using lineItem
3871 $taxAmountArray = array();
3872 foreach ($params['api.line_item.create'] as $key => $value) {
3873 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3874 $taxRate = $taxRates[$value['financial_type_id']];
3875 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3876 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3879 $params['tax_amount'] = array_sum($taxAmountArray);
3880 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3883 // update line item of contrbution
3884 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3885 $taxRate = $taxRates[$params['financial_type_id']];
3886 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3887 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3894 * Check financial type validation on update of a contribution.
3896 * @param Integer $financialTypeId
3897 * Value of latest Financial Type.
3899 * @param Integer $contributionId
3902 * @param array $errors
3907 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3908 if (!empty($financialTypeId)) {
3909 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3910 if ($oldFinancialTypeId == $financialTypeId) {
3914 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3916 '1' => array($contributionId, 'Integer'),
3918 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3919 if ($result->N
> 1) {
3920 $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.');
3925 * Update related pledge payment payments.
3927 * This function has been refactored out of the back office contribution form and may
3928 * still overlap with other functions.
3930 * @param string $action
3931 * @param int $pledgePaymentID
3932 * @param int $contributionID
3933 * @param bool $adjustTotalAmount
3934 * @param float $total_amount
3935 * @param float $original_total_amount
3936 * @param int $contribution_status_id
3937 * @param int $original_contribution_status_id
3939 public static function updateRelatedPledge(
3945 $original_total_amount,
3946 $contribution_status_id,
3947 $original_contribution_status_id
3949 if (!$pledgePaymentID ||
$action & CRM_Core_Action
::ADD
&& !$contributionID) {
3953 if ($pledgePaymentID) {
3954 //store contribution id in payment record.
3955 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
3958 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3964 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3970 $updatePledgePaymentStatus = FALSE;
3972 // If either the status or the amount has changed we update the pledge status.
3973 if ($action & CRM_Core_Action
::ADD
) {
3974 $updatePledgePaymentStatus = TRUE;
3976 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
3977 ($original_total_amount != $total_amount))
3979 $updatePledgePaymentStatus = TRUE;
3982 if ($updatePledgePaymentStatus) {
3983 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
3984 array($pledgePaymentID),
3985 $contribution_status_id,
3994 * Compute the stats values
3996 * @param $stat either 'mode' or 'median'
3998 * @param $alias of civicrm_contribution
4000 public static function computeStats($stat, $sql, $alias = NULL) {
4001 $mode = $median = array();
4004 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4005 while ($modeDAO->fetch()) {
4006 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4007 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4016 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4017 foreach ($currencies as $currency => $val) {
4019 $where = "AND {$alias}.currency = '{$currency}'";
4020 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4024 $medianRow = floor($rowCount / 2);
4025 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4031 $medianValue = "SELECT {$alias}.total_amount as median
4033 ORDER BY median LIMIT {$medianRow},{$offset}";
4034 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4035 while ($medianValDAO->fetch()) {
4037 $midValue = $midValue +
$medianValDAO->median
;
4040 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4044 $midValue = $midValue / 2;
4045 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4056 * Complete an order.
4058 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4060 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4062 * Moving it out of the BaseIPN class is just the first step.
4064 * @param array $input
4066 * @param array $objects
4067 * @param CRM_Core_Transaction $transaction
4069 * @param CRM_Contribute_BAO_Contribution $contribution
4070 * @param bool $isRecurring
4071 * Duplication of param needs review. Only used by AuthorizeNetIPN
4072 * @param int $isFirstOrLastRecurringPayment
4073 * Deprecated param only used by AuthorizeNetIPN.
4075 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4076 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4077 // The previous details are used when calculating line items so keep it before any code that 'does something'
4078 if (!empty($contribution->id
)) {
4079 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4080 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4082 $inputContributionWhiteList = array(
4087 'payment_instrument_id',
4093 $contributionParams = array_merge(array(
4094 'contribution_status_id' => 'Completed',
4095 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4098 $participant = CRM_Utils_Array
::value('participant', $objects);
4099 $memberships = CRM_Utils_Array
::value('membership', $objects);
4100 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4101 if (!empty($recurContrib->id
)) {
4102 $contributionParams['contribution_recur_id'] = $recurContrib->id
;
4104 self
::repeatTransaction($contribution, $input, $contributionParams);
4106 if (is_numeric($memberships)) {
4107 $memberships = array($objects['membership']);
4110 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4113 if (isset($input['is_email_receipt'])) {
4114 $values['is_email_receipt'] = $input['is_email_receipt'];
4117 if ($input['component'] == 'contribute') {
4118 if ($contribution->contribution_page_id
) {
4119 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4120 $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
4122 elseif ($recurContrib && $recurContrib->id
) {
4123 $contributionParams['contribution_page_id'] = NULL;
4124 $values['amount'] = $recurContrib->amount
;
4125 $values['financial_type_id'] = $objects['contributionType']->id
;
4126 $values['title'] = $source = ts('Offline Recurring Contribution');
4127 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
4128 $values['receipt_from_name'] = $domainValues[0];
4129 $values['receipt_from_email'] = $domainValues[1];
4132 if (empty($contributionParams['receive_date']) && $changeDate) {
4133 $contributionParams['receive_date'] = $changeDate;
4136 if ($recurContrib && $recurContrib->id
&& !isset($input['is_email_receipt'])) {
4137 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4138 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4139 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4142 if (!empty($values['is_email_receipt'])) {
4143 $contributionParams['receipt_date'] = $changeDate;
4146 if (!empty($memberships)) {
4147 foreach ($memberships as $membershipTypeIdKey => $membership) {
4149 $membershipParams = array(
4150 'id' => $membership->id
,
4151 'contact_id' => $membership->contact_id
,
4152 'is_test' => $membership->is_test
,
4153 'membership_type_id' => $membership->membership_type_id
,
4156 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4157 $membershipParams['membership_type_id'],
4158 $membershipParams['is_test'],
4159 $membershipParams['id']
4162 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4163 // this picks up membership type changes during renewals
4165 SELECT membership_type_id
4166 FROM civicrm_membership_log
4167 WHERE membership_id={$membershipParams['id']}
4170 $dao = CRM_Core_DAO
::executeQuery($sql);
4171 if ($dao->fetch()) {
4172 if (!empty($dao->membership_type_id
)) {
4173 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4178 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4179 $membershipParams['membership_type_id'],
4180 $primaryContributionID
4182 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4183 if ($currentMembership) {
4185 * Fixed FOR CRM-4433
4186 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4187 * when Contribution mode is notify and membership is for renewal )
4189 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4191 // @todo - we should pass membership_type_id instead of null here but not
4192 // adding as not sure of testing
4193 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4194 $changeDate, NULL, $membershipParams['num_terms']
4197 $dates['join_date'] = $currentMembership['join_date'];
4200 //get the status for membership.
4201 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4203 $dates['join_date'],
4206 $membershipParams['membership_type_id'],
4210 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4211 //we might be renewing membership,
4212 //so make status override false.
4213 $membershipParams['is_override'] = FALSE;
4214 civicrm_api3('Membership', 'create', $membershipParams);
4216 //update related Memberships.
4217 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $membershipParams);
4223 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4224 $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id
));
4225 $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
4226 if ($eventDetail['is_email_confirm']) {
4227 // @todo this should be set by the function that sends the mail after sending.
4228 $contributionParams['receipt_date'] = $changeDate;
4230 $participantParams['id'] = $participant->id
;
4231 $participantParams['status_id'] = 'Registered';
4232 civicrm_api3('Participant', 'create', $participantParams);
4236 $contributionParams['id'] = $contribution->id
;
4238 civicrm_api3('Contribution', 'create', $contributionParams);
4240 // Add new soft credit against current $contribution.
4241 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4242 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4245 $paymentProcessorId = '';
4246 if (isset($objects['paymentProcessor'])) {
4247 if (is_array($objects['paymentProcessor'])) {
4248 $paymentProcessorId = $objects['paymentProcessor']['id'];
4251 $paymentProcessorId = $objects['paymentProcessor']->id
;
4255 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4256 'labelColumn' => 'name',
4259 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4260 $input['payment_processor'] = $paymentProcessorId;
4262 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4263 $input['total_amount'] = $input['amount'];
4264 $input['contribution'] = $contribution;
4265 $input['financial_type_id'] = $contribution->financial_type_id
;
4267 if (!empty($contribution->_relatedObjects
['participant'])) {
4268 $input['contribution_mode'] = 'participant';
4269 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4270 $input['skipLineItem'] = 1;
4272 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4273 $input['skipLineItem'] = TRUE;
4274 $input['contribution_mode'] = 'membership';
4276 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4277 // and subsequent payments. In this case the line items are created at
4278 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4279 // and since the contribution is saved prior to this line there is always a contribution-id,
4280 // however there is never a prevContribution (which appears to mean original contribution not previous
4281 // contribution - or preUpdateContributionObject most accurately)
4282 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4283 // to mean "are we updating an exisitng pending contribution"
4284 //I was able to make the unit test complete as fataling here doesn't prevent
4285 // the contribution being created - but activities would not be created or emails sent
4287 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4289 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4290 $transaction->commit();
4292 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution);
4294 // create an activity record
4295 if ($input['component'] == 'contribute') {
4297 $targetContactID = NULL;
4298 if (!empty($ids['related_contact'])) {
4299 $targetContactID = $contribution->contact_id
;
4300 $contribution->contact_id
= $ids['related_contact'];
4302 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4306 CRM_Activity_BAO_Activity
::addActivity($participant);
4309 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4310 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4311 if (!array_key_exists('is_email_receipt', $values) ||
4312 $values['is_email_receipt'] == 1
4314 self
::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
4315 CRM_Core_Error
::debug_log_message("Receipt sent");
4318 CRM_Core_Error
::debug_log_message("Success: Database updated");
4320 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4321 $isFirstOrLastRecurringPayment);
4326 * Send receipt from contribution.
4328 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4330 * Note that the compose message part has been moved to contribution
4331 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4333 * @param array $input
4334 * Incoming data from Payment processor.
4336 * Related object IDs.
4337 * @param CRM_Contribute_BAO_Contribution $contribution
4338 * @param array $values
4339 * Values related to objects that have already been loaded.
4340 * @param bool $recur
4341 * Is it part of a recurring contribution.
4342 * @param bool $returnMessageText
4343 * Should text be returned instead of sent. This.
4344 * is because the function is also used to generate pdfs
4348 public static function sendMail(&$input, &$ids, $contribution, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4349 $input['is_recur'] = $recur;
4350 // set receipt from e-mail and name in value
4351 if (!$returnMessageText) {
4352 $session = CRM_Core_Session
::singleton();
4353 $userID = $session->get('userID');
4354 if (!empty($userID)) {
4355 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4356 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4357 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4360 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);