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 $newFiscalYearStart = $config->fiscalYearStart
;
1175 if ($newFiscalYearStart['M'] < 10) {
1176 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1178 if ($newFiscalYearStart['d'] < 10) {
1179 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1181 $config->fiscalYearStart
= $newFiscalYearStart;
1182 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1187 $startDate = "$year$monthDay";
1188 $endDate = "$nextYear$monthDay";
1191 SELECT count(*) as count,
1192 sum(total_amount) as amount,
1193 avg(total_amount) as average,
1195 FROM civicrm_contribution b
1196 WHERE b.contact_id IN ( $contactIDs )
1197 AND b.contribution_status_id = 1
1199 AND b.receive_date >= $startDate
1200 AND b.receive_date < $endDate
1203 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1205 $amount = $average = array();
1206 while ($dao->fetch()) {
1207 if ($dao->count
> 0 && $dao->amount
> 0) {
1208 $count +
= $dao->count
;
1209 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1210 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1216 implode(', ', $amount),
1217 implode(', ', $average),
1220 return array(0, 0, 0);
1224 * Check if there is a contribution with the params passed in.
1226 * Used for trxn_id,invoice_id and contribution_id
1228 * @param array $params
1229 * An assoc array of name/value pairs.
1232 * contribution id if success else NULL
1234 public static function checkDuplicateIds($params) {
1235 $dao = new CRM_Contribute_DAO_Contribution();
1239 foreach ($params as $k => $v) {
1241 $clause[] = "$k = '$v'";
1244 $clause = implode(' AND ', $clause);
1245 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1246 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1248 while ($dao->fetch()) {
1256 * Get the contribution details for component export.
1258 * @param int $exportMode
1260 * @param string $componentIds
1266 public static function getContributionDetails($exportMode, $componentIds) {
1267 $paymentDetails = array();
1268 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1270 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1271 $componentSelect = " civicrm_participant_payment.participant_id id";
1272 $additionalClause = "
1273 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1274 AND civicrm_participant_payment.participant_id {$componentClause} )
1277 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1278 $componentSelect = " civicrm_membership_payment.membership_id id";
1279 $additionalClause = "
1280 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1281 AND civicrm_membership_payment.membership_id {$componentClause} )
1284 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1285 $componentSelect = " civicrm_pledge_payment.id id";
1286 $additionalClause = "
1287 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1288 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1292 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1293 trxn_id, {$componentSelect}
1294 FROM civicrm_contribution
1295 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1296 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1297 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1298 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1299 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1300 AND option_group_contribution_status.id = contribution_status.option_group_id )
1304 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1306 while ($dao->fetch()) {
1307 $paymentDetails[$dao->id
] = array(
1308 'total_amount' => $dao->total_amount
,
1309 'contribution_status' => $dao->status
,
1310 'receive_date' => $dao->receive_date
,
1311 'pay_instru' => $dao->payment_instrument
,
1312 'trxn_id' => $dao->trxn_id
,
1316 return $paymentDetails;
1320 * Create address associated with contribution record.
1322 * As long as there is one or more billing field in the parameters we will create the address.
1324 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1327 * @param array $params
1328 * @param int $billingLocationTypeID
1333 public static function createAddress($params, $billingLocationTypeID) {
1334 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1335 if ($hasBillingField) {
1336 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1337 return $address->id
;
1344 * Delete billing address record related contribution.
1346 * @param int $contributionId
1347 * @param int $contactId
1349 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1351 $contactJoin = NULL;
1353 if ($contributionId) {
1354 $clauses[] = "cc.id = {$contributionId}";
1358 $clauses[] = "cco.id = {$contactId}";
1359 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1362 if (empty($clauses)) {
1363 CRM_Core_Error
::fatal();
1366 $condition = implode(' OR ', $clauses);
1370 FROM civicrm_address ca
1371 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1375 $dao = CRM_Core_DAO
::executeQuery($query);
1377 while ($dao->fetch()) {
1378 $params = array('id' => $dao->id
);
1379 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1384 * This function check online pending contribution associated w/
1385 * Online Event Registration or Online Membership signup.
1387 * @param int $componentId
1388 * Participant/membership id.
1389 * @param string $componentName
1393 * pending contribution id.
1395 public static function checkOnlinePendingContribution($componentId, $componentName) {
1396 $contributionId = NULL;
1397 if (!$componentId ||
1398 !in_array($componentName, array('Event', 'Membership'))
1400 return $contributionId;
1403 if ($componentName == 'Event') {
1404 $idName = 'participant_id';
1405 $componentTable = 'civicrm_participant';
1406 $paymentTable = 'civicrm_participant_payment';
1407 $source = ts('Online Event Registration');
1410 if ($componentName == 'Membership') {
1411 $idName = 'membership_id';
1412 $componentTable = 'civicrm_membership';
1413 $paymentTable = 'civicrm_membership_payment';
1414 $source = ts('Online Contribution');
1417 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1420 SELECT component.id as {$idName},
1421 componentPayment.contribution_id as contribution_id,
1422 contribution.source source,
1423 contribution.contribution_status_id as contribution_status_id,
1424 contribution.is_pay_later as is_pay_later
1425 FROM $componentTable component
1426 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1427 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1428 WHERE component.id = {$componentId}";
1430 $dao = CRM_Core_DAO
::executeQuery($query);
1432 while ($dao->fetch()) {
1433 if ($dao->contribution_id
&&
1434 $dao->is_pay_later
&&
1435 $dao->contribution_status_id
== $pendingStatusId &&
1436 strpos($dao->source
, $source) !== FALSE
1438 $contributionId = $dao->contribution_id
;
1443 return $contributionId;
1447 * Update contribution as well as related objects.
1449 * This function by-passes hooks - to address this - don't use this function.
1453 * Use api contribute.completetransaction
1454 * For failures use failPayment (preferably exposing by api in the process).
1456 * @param array $params
1457 * @param bool $processContributionObject
1460 * @throws \Exception
1462 public static function transitionComponents($params, $processContributionObject = FALSE) {
1463 // get minimum required values.
1464 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1465 $componentId = CRM_Utils_Array
::value('component_id', $params);
1466 $componentName = CRM_Utils_Array
::value('componentName', $params);
1467 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1468 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1470 // if we already processed contribution object pass previous status id.
1471 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1473 $updateResult = array();
1475 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1477 // we process only ( Completed, Cancelled, or Failed ) contributions.
1478 if (!$contributionId ||
1479 !in_array($contributionStatusId, array(
1480 array_search('Completed', $contributionStatuses),
1481 array_search('Cancelled', $contributionStatuses),
1482 array_search('Failed', $contributionStatuses),
1485 return $updateResult;
1488 if (!$componentName ||
!$componentId) {
1489 // get the related component details.
1490 $componentDetails = self
::getComponentDetails($contributionId);
1493 $componentDetails['contact_id'] = $contactId;
1494 $componentDetails['component'] = $componentName;
1496 if ($componentName == 'event') {
1497 $componentDetails['participant'] = $componentId;
1500 $componentDetails['membership'] = $componentId;
1504 if (!empty($componentDetails['contact_id'])) {
1505 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1511 // do check for required ids.
1512 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1513 return $updateResult;
1516 //now we are ready w/ required ids, start processing.
1518 $baseIPN = new CRM_Core_Payment_BaseIPN();
1520 $input = $ids = $objects = array();
1522 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1523 $ids['contribution'] = $contributionId;
1524 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1525 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1526 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1527 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1528 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1529 $ids['contributionRecur'] = NULL;
1530 $ids['contributionPage'] = NULL;
1532 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1533 CRM_Core_Error
::fatal();
1536 $memberships = &$objects['membership'];
1537 $participant = &$objects['participant'];
1538 $pledgePayment = &$objects['pledge_payment'];
1539 $contribution = &$objects['contribution'];
1541 if ($pledgePayment) {
1542 $pledgePaymentIDs = array();
1543 foreach ($pledgePayment as $key => $object) {
1544 $pledgePaymentIDs[] = $object->id
;
1546 $pledgeID = $pledgePayment[0]->pledge_id
;
1549 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1552 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1553 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1558 // we might want to process contribution object.
1559 $processContribution = FALSE;
1560 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1561 if (is_array($memberships)) {
1562 foreach ($memberships as $membership) {
1564 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1565 $membership->save();
1567 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1568 if ($processContributionObject) {
1569 $processContribution = TRUE;
1576 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1577 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1579 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1580 if ($processContributionObject) {
1581 $processContribution = TRUE;
1585 if ($pledgePayment) {
1586 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1588 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1589 if ($processContributionObject) {
1590 $processContribution = TRUE;
1594 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1595 if (is_array($memberships)) {
1596 foreach ($memberships as $membership) {
1598 $membership->status_id
= array_search('Expired', $membershipStatuses);
1599 $membership->save();
1601 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1602 if ($processContributionObject) {
1603 $processContribution = TRUE;
1609 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1610 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1612 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1613 if ($processContributionObject) {
1614 $processContribution = TRUE;
1618 if ($pledgePayment) {
1619 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1621 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1622 if ($processContributionObject) {
1623 $processContribution = TRUE;
1627 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1629 // only pending contribution related object processed.
1630 if ($previousContriStatusId &&
1631 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1633 // this is case when we already processed contribution object.
1634 return $updateResult;
1636 elseif (!$previousContriStatusId &&
1637 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1639 // this is case when we are going to process contribution object later.
1640 return $updateResult;
1643 if (is_array($memberships)) {
1644 foreach ($memberships as $membership) {
1649 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1650 $membership->membership_type_id
,
1651 $membership->is_test
, $membership->id
1654 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1655 // this picks up membership type changes during renewals
1657 SELECT membership_type_id
1658 FROM civicrm_membership_log
1659 WHERE membership_id=$membership->id
1662 $dao = new CRM_Core_DAO();
1664 if ($dao->fetch()) {
1665 if (!empty($dao->membership_type_id
)) {
1666 $membership->membership_type_id
= $dao->membership_type_id
;
1667 $membership->save();
1670 // else fall back to using current membership type
1673 // Figure out number of terms
1675 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1676 foreach ($lineitems as $lineitem) {
1677 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1678 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1680 // in case membership_num_terms comes through as null or zero
1681 $numterms = $numterms >= 1 ?
$numterms : 1;
1686 // CRM-15735-to update the membership status as per the contribution receive date
1688 if (!empty($params['receive_date'])) {
1689 $joinDate = $params['receive_date'];
1690 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1691 $membership->end_date
,
1692 $membership->join_date
,
1693 $params['receive_date'],
1695 $membership->membership_type_id
,
1698 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1699 $membership->save();
1702 if ($currentMembership) {
1703 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1704 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1705 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1708 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1711 //get the status for membership.
1712 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1714 $dates['join_date'],
1717 $membership->membership_type_id
,
1721 $formattedParams = array(
1722 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1723 array_search('Current', $membershipStatuses)
1725 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1726 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1727 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1730 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1732 $membership->copyValues($formattedParams);
1733 $membership->save();
1735 //updating the membership log
1736 $membershipLog = array();
1737 $membershipLog = $formattedParams;
1738 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1739 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1741 $membershipLog['start_date'] = $logStartDate;
1742 $membershipLog['membership_id'] = $membership->id
;
1743 $membershipLog['modified_id'] = $membership->contact_id
;
1744 $membershipLog['modified_date'] = date('Ymd');
1745 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1747 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1749 //update related Memberships.
1750 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1752 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1755 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1756 if ($processContributionObject) {
1757 $processContribution = TRUE;
1760 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1766 $updatedStatusId = array_search('Registered', $participantStatuses);
1767 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1769 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1770 if ($processContributionObject) {
1771 $processContribution = TRUE;
1775 if ($pledgePayment) {
1776 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1778 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1779 if ($processContributionObject) {
1780 $processContribution = TRUE;
1785 // process contribution object.
1786 if ($processContribution) {
1787 $contributionParams = array();
1794 'payment_instrument_id',
1797 'financial_type_id',
1798 'contribution_status_id',
1799 'non_deductible_amount',
1803 foreach ($fields as $field) {
1804 if (empty($params[$field])) {
1807 $contributionParams[$field] = $params[$field];
1810 $ids = array('contribution' => $contributionId);
1811 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1814 return $updateResult;
1818 * Returns all contribution related object ids.
1820 * @param $contributionId
1824 public static function getComponentDetails($contributionId) {
1825 $componentDetails = $pledgePayment = array();
1826 if (!$contributionId) {
1827 return $componentDetails;
1831 SELECT c.id as contribution_id,
1832 c.contact_id as contact_id,
1833 c.contribution_recur_id,
1834 mp.membership_id as membership_id,
1835 m.membership_type_id as membership_type_id,
1836 pp.participant_id as participant_id,
1837 p.event_id as event_id,
1838 pgp.id as pledge_payment_id
1839 FROM civicrm_contribution c
1840 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1841 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1842 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1843 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1844 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1845 WHERE c.id = $contributionId";
1847 $dao = CRM_Core_DAO
::executeQuery($query);
1848 $componentDetails = array();
1850 while ($dao->fetch()) {
1851 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1852 $componentDetails['contact_id'] = $dao->contact_id
;
1853 if ($dao->event_id
) {
1854 $componentDetails['event'] = $dao->event_id
;
1856 if ($dao->participant_id
) {
1857 $componentDetails['participant'] = $dao->participant_id
;
1859 if ($dao->membership_id
) {
1860 if (!isset($componentDetails['membership'])) {
1861 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1863 $componentDetails['membership'][] = $dao->membership_id
;
1864 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1866 if ($dao->pledge_payment_id
) {
1867 $pledgePayment[] = $dao->pledge_payment_id
;
1869 if ($dao->contribution_recur_id
) {
1870 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1874 if ($pledgePayment) {
1875 $componentDetails['pledge_payment'] = $pledgePayment;
1878 return $componentDetails;
1882 * @param int $contactId
1883 * @param bool $includeSoftCredit
1885 * @return null|string
1887 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1892 $contactContributionsSQL = "
1893 SELECT contribution.id AS id
1894 FROM civicrm_contribution contribution
1895 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1897 $contactSoftCreditContributionsSQL = "
1898 SELECT contribution.id
1899 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1900 ON ( contribution.id = softContribution.contribution_id )
1901 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1902 $query = "SELECT count( x.id ) count FROM ( ";
1903 $query .= $contactContributionsSQL;
1905 if ($includeSoftCredit) {
1906 $query .= " UNION ";
1907 $query .= $contactSoftCreditContributionsSQL;
1912 return CRM_Core_DAO
::singleValueQuery($query);
1916 * Repeat a transaction as part of a recurring series.
1918 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
1919 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
1920 * subsequent call to the contribution.completetransaction api.
1922 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
1924 * @param CRM_Contribute_BAO_Contribution $contribution
1925 * @param array $input
1926 * @param array $contributionParams
1930 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
1931 if (!empty($contribution->id
)) {
1934 if (empty($contribution->id
)) {
1935 // Unclear why this would only be set for repeats.
1936 if (!empty($input['amount'])) {
1937 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
1939 $templateContribution = civicrm_api3('Contribution', 'getsingle', array(
1940 'contribution_recur_id' => $contributionParams['contribution_recur_id'],
1941 'options' => array('limit' => 1),
1943 $contributionParams['skipLineItem'] = TRUE;
1944 $contributionParams['status_id'] = 'Pending';
1945 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
1946 $contributionParams['contact_id'] = $templateContribution['contact_id'];
1947 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
1948 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
1949 $contribution->id
= $createContribution['id'];
1950 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
1951 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
1957 * Get individual id for onbehalf contribution.
1959 * @param int $contributionId
1961 * @param int $contributorId
1965 * containing organization id and individual id
1967 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1971 if (!$contributionId) {
1975 // fetch contributor id if null
1976 if (!$contributorId) {
1977 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1978 $contributionId, 'contact_id'
1982 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1983 $activityTypeId = array_search('Contribution', $activityTypeIds);
1985 if ($activityTypeId && $contributorId) {
1987 SELECT civicrm_activity_contact.contact_id
1988 FROM civicrm_activity_contact
1989 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1990 WHERE civicrm_activity.activity_type_id = %1
1991 AND civicrm_activity.source_record_id = %2
1992 AND civicrm_activity_contact.record_type_id = %3
1995 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1996 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1999 1 => array($activityTypeId, 'Integer'),
2000 2 => array($contributionId, 'Integer'),
2001 3 => array($sourceID, 'Integer'),
2004 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2006 // for on behalf contribution source is individual and contributor is organization
2007 if ($sourceContactId && $sourceContactId != $contributorId) {
2008 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2009 // get rel type id for employee of relation
2010 foreach ($relationshipTypeIds as $id => $typeVals) {
2011 if ($typeVals['name_a_b'] == 'Employee of') {
2012 $relationshipTypeId = $id;
2017 $rel = new CRM_Contact_DAO_Relationship();
2018 $rel->relationship_type_id
= $relationshipTypeId;
2019 $rel->contact_id_a
= $sourceContactId;
2020 $rel->contact_id_b
= $contributorId;
2021 if ($rel->find(TRUE)) {
2022 $ids['individual_id'] = $rel->contact_id_a
;
2023 $ids['organization_id'] = $rel->contact_id_b
;
2034 public static function getContributionDates() {
2035 $config = CRM_Core_Config
::singleton();
2036 $currentMonth = date('m');
2037 $currentDay = date('d');
2038 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2039 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2040 (int ) $config->fiscalYearStart
['d'] > $currentDay
2043 $year = date('Y') - 1;
2048 $year = array('Y' => $year);
2049 $yearDate = $config->fiscalYearStart
;
2050 $yearDate = array_merge($year, $yearDate);
2051 $yearDate = CRM_Utils_Date
::format($yearDate);
2053 $monthDate = date('Ym') . '01';
2059 'yearDate' => $yearDate,
2060 'monthDate' => $monthDate,
2065 * Load objects relations to contribution object.
2066 * Objects are stored in the $_relatedObjects property
2067 * In the first instance we are just moving functionality from BASEIpn -
2068 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2070 * Note that the unit test for the BaseIPN class tests this function
2072 * @param array $input
2073 * Input as delivered from Payment Processor.
2075 * Ids as Loaded by Payment Processor.
2076 * @param bool $loadAll
2077 * Load all related objects - even where id not passed in? (allows API to call this).
2082 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2084 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2085 if (empty($ids['contact']) && isset($this->contact_id
)) {
2086 $ids['contact'] = $this->contact_id
;
2089 if (empty($this->_component
)) {
2090 if (!empty($ids['event'])) {
2091 $this->_component
= 'event';
2094 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2098 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2099 // refactoring than anything else, and has unit test coverage.
2100 if (empty($this->financial_type_id
)) {
2104 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2109 if (!$paymentProcessorID && $this->contribution_page_id
) {
2110 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2111 $this->contribution_page_id
,
2114 if ($paymentProcessorID) {
2115 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2119 $ids['contributionType'] = $this->financial_type_id
;
2120 $ids['financialType'] = $this->financial_type_id
;
2123 'contact' => 'CRM_Contact_BAO_Contact',
2124 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2125 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2126 'financialType' => 'CRM_Financial_BAO_FinancialType',
2128 foreach ($entities as $entity => $bao) {
2129 if (!empty($ids[$entity])) {
2130 $this->_relatedObjects
[$entity] = new $bao();
2131 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2132 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2133 throw new CRM_Core_Exception($entity . ' could not be loaded');
2138 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2139 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2142 if (!empty($ids['pledge_payment'])) {
2143 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2144 if (empty($paymentID)) {
2147 $payment = new CRM_Pledge_BAO_PledgePayment();
2148 $payment->id
= $paymentID;
2149 if (!$payment->find(TRUE)) {
2150 throw new Exception("Could not find pledge payment record: " . $paymentID);
2152 $this->_relatedObjects
['pledge_payment'][] = $payment;
2156 if ($this->_component
== 'contribute') {
2157 // retrieve the other optional objects first so
2158 // stuff down the line can use this info and do things
2160 //in any case get the memberships associated with the contribution
2161 //because we now support multiple memberships w/ price set
2162 // see if there are any other memberships to be considered for same contribution.
2164 SELECT membership_id
2165 FROM civicrm_membership_payment
2166 WHERE contribution_id = %1 ";
2167 $params = array(1 => array($this->id
, 'Integer'));
2169 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2170 while ($dao->fetch()) {
2171 if ($dao->membership_id
) {
2172 if (!is_array($ids['membership'])) {
2173 $ids['membership'] = array();
2175 $ids['membership'][] = $dao->membership_id
;
2179 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2180 foreach ($ids['membership'] as $id) {
2182 $membership = new CRM_Member_BAO_Membership();
2183 $membership->id
= $id;
2184 if (!$membership->find(TRUE)) {
2185 throw new Exception("Could not find membership record: $id");
2187 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2188 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2189 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2190 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2191 $membership->free();
2197 // we are in event mode
2198 // make sure event exists and is valid
2199 $event = new CRM_Event_BAO_Event();
2200 $event->id
= $ids['event'];
2201 if ($ids['event'] &&
2204 throw new Exception("Could not find event: " . $ids['event']);
2207 $this->_relatedObjects
['event'] = &$event;
2209 $participant = new CRM_Event_BAO_Participant();
2210 $participant->id
= $ids['participant'];
2211 if ($ids['participant'] &&
2212 !$participant->find(TRUE)
2214 throw new Exception("Could not find participant: " . $ids['participant']);
2216 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2218 $this->_relatedObjects
['participant'] = &$participant;
2220 // get the payment processor id from event - this is inaccurate see CRM-16923
2221 // in future we should look at throwing an exception here rather than an dubious guess.
2222 if (!$paymentProcessorID) {
2223 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2224 if ($paymentProcessorID) {
2225 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2230 if ($paymentProcessorID) {
2231 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2232 $this->is_test ?
'test' : 'live'
2234 $ids['paymentProcessor'] = $paymentProcessorID;
2235 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2241 * Create array of message information - ie. return html version, txt version, to field
2243 * @param array $input
2244 * Incoming information.
2245 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2246 * just check presence of recur object but maintaining legacy approach
2249 * IDs of related objects.
2250 * @param array $values
2251 * Any values that may have already been compiled by calling process.
2252 * This is augmented by values 'gathered' by gatherMessageValues
2253 * @param bool $recur
2254 * @param bool $returnMessageText
2255 * Distinguishes between whether to send message or return.
2256 * message text. We are working towards this function ALWAYS returning message text & calling
2257 * function doing emails / pdfs with it
2263 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2264 $this->loadRelatedObjects($input, $ids);
2266 if (empty($this->_component
)) {
2267 $this->_component
= CRM_Utils_Array
::value('component', $input);
2270 //not really sure what params might be passed in but lets merge em into values
2271 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2272 $template = CRM_Core_Smarty
::singleton();
2273 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2274 //what does recur 'mean here - to do with payment processor return functionality but
2275 // what is the importance
2276 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2277 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2279 $entityID = $entity = NULL;
2280 if (isset($ids['contribution'])) {
2281 $entity = 'contribution';
2282 $entityID = $ids['contribution'];
2284 if (!empty($ids['membership'])) {
2285 //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
2286 // 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
2287 // line having loaded an array
2288 $ids['membership'] = (array) $ids['membership'];
2289 $entity = 'membership';
2290 $entityID = $ids['membership'][0];
2293 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity));
2294 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2295 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2297 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2298 //direct mode showing billing block, so use directIPN for temporary
2299 $template->assign('contributeMode', 'directIPN');
2302 // todo remove strtolower - check consistency
2303 if (strtolower($this->_component
) == 'event') {
2304 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2305 $values['event'] = array();
2307 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2309 //get location details
2310 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2311 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2313 $ufJoinParams = array(
2314 'entity_table' => 'civicrm_event',
2315 'entity_id' => $ids['event'],
2316 'module' => 'CiviEvent',
2319 list($custom_pre_id,
2321 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2323 $values['custom_pre_id'] = $custom_pre_id;
2324 $values['custom_post_id'] = $custom_post_ids;
2325 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
2326 //and cases involving status updation through ipn
2327 // whatever that means!
2328 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2329 // perhaps we should throw an e-notice if amount is set & force total_amount?
2330 if (!empty($input['amount'])) {
2331 $values['totalAmount'] = $input['amount'];
2334 if ($values['event']['is_email_confirm']) {
2335 $values['is_email_receipt'] = 1;
2337 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2338 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2342 $values['contribution_id'] = $this->id
;
2343 if (!empty($ids['related_contact'])) {
2344 $values['related_contact'] = $ids['related_contact'];
2345 if (isset($ids['onbehalf_dupe_alert'])) {
2346 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2348 $entityBlock = array(
2349 'contact_id' => $ids['contact'],
2350 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2351 'Home', 'id', 'name'
2354 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2355 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2358 if ($this->is_test
) {
2361 if (!empty($this->_relatedObjects
['membership'])) {
2362 foreach ($this->_relatedObjects
['membership'] as $membership) {
2363 if ($membership->id
) {
2364 $values['isMembership'] = TRUE;
2366 // need to set the membership values here
2367 $template->assign('membership_assign', 1);
2368 $template->assign('membership_name',
2369 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2371 $template->assign('mem_start_date', $membership->start_date
);
2372 $template->assign('mem_join_date', $membership->join_date
);
2373 $template->assign('mem_end_date', $membership->end_date
);
2374 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2375 $template->assign('mem_status', $membership_status);
2376 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2377 $template->assign('is_pay_later', 1);
2380 // if separate payment there are two contributions recorded and the
2381 // admin will need to send a receipt for each of them separately.
2382 // we dont link the two in the db (but can potentially infer it if needed)
2383 $template->assign('is_separate_payment', 0);
2385 if ($recur && $paymentObject) {
2386 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2387 $template->assign('cancelSubscriptionUrl', $url);
2388 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2389 $template->assign('updateSubscriptionBillingUrl', $url);
2390 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2391 $template->assign('updateSubscriptionUrl', $url);
2394 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2397 // otherwise if its about sending emails, continue sending without return, as we
2398 // don't want to exit the loop.
2403 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2409 * Gather values for contribution mail - this function has been created
2410 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2411 * Values related to the contribution in question are gathered
2413 * @param array $input
2414 * Input into function (probably from payment processor).
2415 * @param array $values
2417 * The set of ids related to the input.
2421 public function _gatherMessageValues($input, &$values, $ids = array()) {
2422 // set display address of contributor
2423 if ($this->address_id
) {
2424 $addressParams = array('id' => $this->address_id
);
2425 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2426 $addressDetails = array_values($addressDetails);
2427 $values['address'] = $addressDetails[0]['display'];
2429 if ($this->_component
== 'contribute') {
2430 //get soft contributions
2431 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2432 if (!empty($softContributions)) {
2433 $values['softContributions'] = $softContributions['soft_credit'];
2435 if (isset($this->contribution_page_id
)) {
2436 CRM_Contribute_BAO_ContributionPage
::setValues(
2437 $this->contribution_page_id
,
2440 if ($this->contribution_page_id
) {
2441 // CRM-8254 - override default currency if applicable
2442 $config = CRM_Core_Config
::singleton();
2443 $config->defaultCurrency
= CRM_Utils_Array
::value(
2446 $config->defaultCurrency
2450 // no contribution page -probably back office
2452 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2453 $values['is_email_receipt'] = 1;
2454 $values['title'] = 'Contribution';
2456 // set lineItem for contribution
2458 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2459 if (!empty($lineItem)) {
2460 $itemId = key($lineItem);
2461 foreach ($lineItem as &$eachItem) {
2462 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2463 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2464 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2465 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2468 $values['lineItem'][0] = $lineItem;
2469 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2473 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2477 // if this is onbehalf of contribution then set related contact
2478 if (!empty($relatedContact['individual_id'])) {
2479 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2484 $eventParams = array(
2485 'id' => $this->_relatedObjects
['event']->id
,
2487 $values['event'] = array();
2489 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2490 // add custom fields for event
2491 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2493 $eventCustomGroup = array();
2494 foreach ($eventGroupTree as $key => $group) {
2495 if ($key === 'info') {
2499 foreach ($group['fields'] as $k => $customField) {
2500 $groupLabel = $group['title'];
2501 if (!empty($customField['customValue'])) {
2502 foreach ($customField['customValue'] as $customFieldValues) {
2503 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2508 $values['event']['customGroup'] = $eventCustomGroup;
2510 //get participant details
2511 $participantParams = array(
2512 'id' => $this->_relatedObjects
['participant']->id
,
2515 $values['participant'] = array();
2517 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2518 // add custom fields for event
2519 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2520 $participantCustomGroup = array();
2521 foreach ($participantGroupTree as $key => $group) {
2522 if ($key === 'info') {
2526 foreach ($group['fields'] as $k => $customField) {
2527 $groupLabel = $group['title'];
2528 if (!empty($customField['customValue'])) {
2529 foreach ($customField['customValue'] as $customFieldValues) {
2530 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2535 $values['participant']['customGroup'] = $participantCustomGroup;
2537 //get location details
2538 $locationParams = array(
2539 'entity_id' => $this->_relatedObjects
['event']->id
,
2540 'entity_table' => 'civicrm_event',
2542 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2544 $ufJoinParams = array(
2545 'entity_table' => 'civicrm_event',
2546 'entity_id' => $ids['event'],
2547 'module' => 'CiviEvent',
2550 list($custom_pre_id,
2552 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2554 $values['custom_pre_id'] = $custom_pre_id;
2555 $values['custom_post_id'] = $custom_post_ids;
2557 // set lineItem for event contribution
2559 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2560 if (!empty($participantIds)) {
2561 foreach ($participantIds as $pIDs) {
2562 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2563 if (!CRM_Utils_System
::isNull($lineItem)) {
2564 $values['lineItem'][] = $lineItem;
2571 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2573 $customGroup = array();
2574 foreach ($groupTree as $key => $group) {
2575 if ($key === 'info') {
2579 foreach ($group['fields'] as $k => $customField) {
2580 $groupLabel = $group['title'];
2581 if (!empty($customField['customValue'])) {
2582 foreach ($customField['customValue'] as $customFieldValues) {
2583 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2588 $values['customGroup'] = $customGroup;
2594 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2595 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2596 * Note we send directly from this function in some cases because it is only partly refactored
2597 * Don't call this function directly as the signature will change
2601 * @param CRM_Core_SMARTY $template
2602 * @param bool $recur
2603 * @param bool $returnMessageText
2607 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2608 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2609 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2610 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2611 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2612 $template->assign('useForMember', TRUE);
2614 //assign honor information to receipt message
2615 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2617 if (isset($softRecord['soft_credit'])) {
2618 //if id of contribution page is present
2619 if (!empty($values['id'])) {
2620 $values['honor'] = array(
2621 'honor_profile_values' => array(),
2622 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2623 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2625 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2627 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2628 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2631 //offline contribution
2632 $softCreditTypes = $softCredits = array();
2633 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2634 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2635 $softCredits[$key] = array(
2636 'Name' => $softCredit['contact_name'],
2637 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2640 $template->assign('softCreditTypes', $softCreditTypes);
2641 $template->assign('softCredits', $softCredits);
2645 $dao = new CRM_Contribute_DAO_ContributionProduct();
2646 $dao->contribution_id
= $this->id
;
2647 if ($dao->find(TRUE)) {
2648 $premiumId = $dao->product_id
;
2649 $template->assign('option', $dao->product_option
);
2651 $productDAO = new CRM_Contribute_DAO_Product();
2652 $productDAO->id
= $premiumId;
2653 $productDAO->find(TRUE);
2654 $template->assign('selectPremium', TRUE);
2655 $template->assign('product_name', $productDAO->name
);
2656 $template->assign('price', $productDAO->price
);
2657 $template->assign('sku', $productDAO->sku
);
2659 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2660 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2661 if (empty($amount) && isset($this->total_amount
)) {
2662 $amount = $this->total_amount
;
2664 $template->assign('amount', $amount);
2665 // add the new contribution values
2666 if (strtolower($this->_component
) == 'contribute') {
2668 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2669 $softDAO->contribution_id
= $this->id
;
2670 if ($softDAO->find(TRUE)) {
2671 $template->assign('pcpBlock', TRUE);
2672 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2673 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2674 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2676 //assign the pcp page title for email subject
2677 $pcpDAO = new CRM_PCP_DAO_PCP();
2678 $pcpDAO->id
= $softDAO->pcp_id
;
2679 if ($pcpDAO->find(TRUE)) {
2680 $template->assign('title', $pcpDAO->title
);
2685 if ($this->financial_type_id
) {
2686 $values['financial_type_id'] = $this->financial_type_id
;
2689 $template->assign('trxn_id', $this->trxn_id
);
2690 $template->assign('receive_date',
2691 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2693 $template->assign('contributeMode', 'notify');
2694 $template->assign('action', $this->is_test ?
1024 : 1);
2695 $template->assign('receipt_text',
2696 CRM_Utils_Array
::value('receipt_text',
2700 $template->assign('is_monetary', 1);
2701 $template->assign('is_recur', (bool) $recur);
2702 $template->assign('currency', $this->currency
);
2703 $template->assign('address', CRM_Utils_Address
::format($input));
2704 if (!empty($values['customGroup'])) {
2705 $template->assign('customGroup', $values['customGroup']);
2707 if (!empty($values['softContributions'])) {
2708 $template->assign('softContributions', $values['softContributions']);
2710 if ($this->_component
== 'event') {
2711 $template->assign('title', $values['event']['title']);
2712 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2713 $viewRoles = array();
2714 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2715 $viewRoles[] = $participantRoles[$v];
2717 $values['event']['participant_role'] = implode(', ', $viewRoles);
2718 $template->assign('event', $values['event']);
2719 $template->assign('participant', $values['participant']);
2720 $template->assign('location', $values['location']);
2721 $template->assign('customPre', $values['custom_pre_id']);
2722 $template->assign('customPost', $values['custom_post_id']);
2725 if ($this->_relatedObjects
['participant']->is_test
) {
2729 $values['params'] = array();
2730 //to get email of primary participant.
2731 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2732 $primaryAmount[] = array(
2733 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2734 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2736 //build an array of cId/pId of participants
2737 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2738 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2739 //send receipt to additional participant if exists
2740 if (count($additionalIDs)) {
2741 $template->assign('isPrimary', 0);
2742 $template->assign('customProfile', NULL);
2743 //set additionalParticipant true
2744 $values['params']['additionalParticipant'] = TRUE;
2745 foreach ($additionalIDs as $pId => $cId) {
2747 //to change the status pending to completed
2748 $additional = new CRM_Event_DAO_Participant();
2749 $additional->id
= $pId;
2750 $additional->contact_id
= $cId;
2751 $additional->find(TRUE);
2752 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2753 $additional->status_id
= 1;
2754 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2755 //if additional participant dont have email
2757 if (!$additionalParticipantInfo) {
2758 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2760 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2761 $primaryAmount[] = array(
2762 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2763 'amount' => $additional->fee_amount
,
2765 $additional->save();
2766 $additional->free();
2767 $template->assign('amount', $amount);
2768 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2772 //build an array of custom profile and assigning it to template
2773 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2775 if (count($customProfile)) {
2776 $template->assign('customProfile', $customProfile);
2779 // for primary contact
2780 $values['params']['additionalParticipant'] = FALSE;
2781 $template->assign('isPrimary', 1);
2782 $template->assign('amount', $primaryAmount);
2783 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2784 if ($this->payment_instrument_id
) {
2785 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2786 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2788 // carry paylater, since we did not created billing,
2789 // so need to pull email from primary location, CRM-4395
2790 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2796 * Check whether payment processor supports
2797 * cancellation of contribution subscription
2799 * @param int $contributionId
2802 * @param bool $isNotCancelled
2806 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2807 $cacheKeyString = "$contributionId";
2808 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2810 static $supportsCancel = array();
2812 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2813 $supportsCancel[$cacheKeyString] = FALSE;
2814 $isCancelled = FALSE;
2816 if ($isNotCancelled) {
2817 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2820 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2821 if (!empty($paymentObject)) {
2822 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2825 return $supportsCancel[$cacheKeyString];
2829 * Check whether subscription is already cancelled.
2831 * @param int $contributionId
2835 * contribution status
2837 public static function isSubscriptionCancelled($contributionId) {
2839 SELECT cr.contribution_status_id
2840 FROM civicrm_contribution_recur cr
2841 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2842 WHERE con.id = %1 LIMIT 1";
2843 $params = array(1 => array($contributionId, 'Integer'));
2844 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2845 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2846 if ($status == 'Cancelled') {
2853 * Create all financial accounts entry.
2855 * @param array $params
2856 * Contribution object, line item array and params for trxn.
2859 * @param array $financialTrxnValues
2861 * @return null|object
2863 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2864 $skipRecords = $update = $return = $isRelatedId = FALSE;
2866 $additionalParticipantId = array();
2867 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2869 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2870 $entityId = $params['participant_id'];
2871 $entityTable = 'civicrm_participant';
2872 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2874 elseif (!empty($params['membership_id'])) {
2875 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2876 // are created off one contribution should be handled elsewhere
2877 $entityId = $params['membership_id'];
2878 $entityTable = 'civicrm_membership';
2881 $entityId = $params['contribution']->id
;
2882 $entityTable = 'civicrm_contribution';
2885 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2886 $isRelatedId = TRUE;
2889 $entityID[] = $entityId;
2890 if (!empty($additionalParticipantId)) {
2891 $entityID +
= $additionalParticipantId;
2893 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2894 if (empty($params['prevContribution'])) {
2901 $statusId = $params['contribution']->contribution_status_id
;
2902 // CRM-13964 partial payment
2903 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2904 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2906 $partialAmtPay = $params['partial_amount_pay'];
2907 $partialAmtTotal = $params['partial_payment_total'];
2909 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2910 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2911 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2912 $params['total_amount'] = $partialAmtPay;
2914 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2915 if (empty($balanceTrxnInfo['trxn_id'])) {
2916 // create new balance transaction record
2917 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2918 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2920 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2921 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2922 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2923 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2924 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2925 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2926 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2927 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2928 $balanceTrxnParams['status_id'] = $statusId;
2929 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2930 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2931 if (!empty($params['payment_processor'])) {
2932 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2934 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2938 // build line item array if its not set in $params
2939 if (empty($params['line_item']) ||
$additionalParticipantId) {
2940 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2943 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2944 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2946 $skipRecords = TRUE;
2947 $pendingStatus = array(
2948 array_search('Pending', $contributionStatuses),
2949 array_search('In Progress', $contributionStatuses),
2951 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2952 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2953 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2955 elseif (!empty($params['payment_processor'])) {
2956 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2958 elseif (!empty($params['payment_instrument_id'])) {
2959 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2962 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2963 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2964 $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);
2967 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2968 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2969 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2972 //build financial transaction params
2973 $trxnParams = array(
2974 'contribution_id' => $params['contribution']->id
,
2975 'to_financial_account_id' => $params['to_financial_account_id'],
2976 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2977 'total_amount' => $totalAmount,
2978 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2979 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2980 'currency' => $params['contribution']->currency
,
2981 'trxn_id' => $params['contribution']->trxn_id
,
2982 'status_id' => $statusId,
2983 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2984 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2987 if (!empty($params['payment_processor'])) {
2988 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2991 if (isset($fromFinancialAccountId)) {
2992 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2995 // consider external values passed for recording transaction entry
2996 if (!empty($financialTrxnValues)) {
2997 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3000 $params['trxnParams'] = $trxnParams;
3002 if (!empty($params['prevContribution'])) {
3003 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3004 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3005 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3006 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3007 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3009 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3010 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3011 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3013 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3014 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3017 //if financial type is changed
3018 if (!empty($params['financial_type_id']) &&
3019 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3021 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3022 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3023 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3024 if ($oldFinancialAccount != $newFinancialAccount) {
3025 $params['total_amount'] = 0;
3026 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3027 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3028 $params['prevContribution']->financial_type_id
, $relationTypeId);
3031 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3032 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3033 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3036 self
::updateFinancialAccounts($params, 'changeFinancialType');
3037 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3038 $params['financial_account_id'] = $newFinancialAccount;
3039 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3040 self
::updateFinancialAccounts($params);
3041 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3045 //Update contribution status
3046 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3047 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3048 if (!empty($params['contribution_status_id']) &&
3049 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3051 //Update Financial Records
3052 self
::updateFinancialAccounts($params, 'changedStatus');
3055 // change Payment Instrument for a Completed contribution
3056 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3057 // instrument is null and now new payment instrument is added along with the payment
3058 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3059 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3060 if (array_key_exists('payment_instrument_id', $params)) {
3061 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3062 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3063 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3065 //check if status is changed from Pending to Completed
3066 // do not update payment instrument changes for Pending to Completed
3067 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3068 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3070 // for all other statuses create new financial records
3071 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3072 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3073 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3076 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3077 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3078 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3080 // for any other payment instrument changes create new financial records
3081 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3082 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3083 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3085 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3086 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3088 // another special case when check number is changed, create new financial records
3089 // create financial trxn with negative amount
3090 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3091 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3092 // create financial trxn with positive amount
3093 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3094 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3095 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3099 //if Change contribution amount
3100 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3101 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3102 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3103 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3104 if (isset($totalAmount) &&
3105 $totalAmount != $params['prevContribution']->total_amount
3107 //Update Financial Records
3108 $params['trxnParams']['from_financial_account_id'] = NULL;
3109 self
::updateFinancialAccounts($params, 'changedAmount');
3114 // records finanical trxn and entity financial trxn
3115 // also make it available as return value
3116 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3117 $params['entity_id'] = $financialTxn->id
;
3120 // record line items and financial items
3121 if (empty($params['skipLineItem'])) {
3122 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3125 // create batch entry if batch_id is passed and
3126 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3127 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3128 $entityParams = array(
3129 'batch_id' => $params['batch_id'],
3130 'entity_table' => 'civicrm_financial_trxn',
3131 'entity_id' => $financialTxn->id
,
3133 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3136 // when a fee is charged
3137 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3138 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3141 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3142 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3144 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3145 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3146 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3148 unset($params['line_item']);
3154 * Update all financial accounts entry.
3156 * @param array $params
3157 * Contribution object, line item array and params for trxn.
3159 * @param string $context
3162 * @param null $skipTrxn
3165 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3166 $itemAmount = $trxnID = NULL;
3167 //get all the statuses
3168 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3169 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3170 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3171 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3172 && $context == 'changePaymentInstrument'
3176 if (($params['prevContribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus))
3177 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3178 && $context == 'changedStatus'
3182 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3183 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3185 if ($context == 'changedStatus') {
3186 //get all the statuses
3187 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3189 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3190 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3191 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3193 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3195 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3196 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3198 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3199 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3200 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3202 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3203 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3204 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3207 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3210 $itemAmount = $params['trxnParams']['total_amount'];
3212 elseif ($context == 'changePaymentInstrument') {
3213 if ($params['trxnParams']['total_amount'] < 0) {
3214 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3215 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3216 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3217 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3221 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3222 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3225 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3226 $params['entity_id'] = $trxn->id
;
3228 if ($context == 'changedStatus') {
3229 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3230 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3231 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3233 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3234 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3236 $entityParams = array(
3237 'entity_table' => 'civicrm_financial_item',
3238 'financial_trxn_id' => $trxn->id
,
3240 if (empty($params['line_item'])) {
3242 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3243 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3244 // & this can be removed
3247 foreach ($params['line_item'] as $fieldId => $fields) {
3248 foreach ($fields as $fieldValueId => $fieldValues) {
3250 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3251 2 => array($fieldValues['id'], 'Integer'),
3253 CRM_Core_DAO
::executeQuery($query, $fparams);
3255 1 => array($fieldValues['id'], 'Integer'),
3257 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3258 while ($financialItem->fetch()) {
3259 $entityParams['entity_id'] = $financialItem->id
;
3260 $entityParams['amount'] = $financialItem->amount
;
3261 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3268 if ($context != 'changePaymentInstrument') {
3269 $itemParams['entity_table'] = 'civicrm_line_item';
3270 $trxnIds['id'] = $params['entity_id'];
3271 foreach ($params['line_item'] as $fieldId => $fields) {
3272 foreach ($fields as $fieldValueId => $fieldValues) {
3273 $prevParams['entity_id'] = $fieldValues['id'];
3274 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3276 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3277 if ($params['contribution']->receive_date
) {
3278 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3281 $financialAccount = $prevfinancialItem->financial_account_id
;
3282 if (!empty($params['financial_account_id'])) {
3283 $financialAccount = $params['financial_account_id'];
3286 $currency = $params['prevContribution']->currency
;
3287 if ($params['contribution']->currency
) {
3288 $currency = $params['contribution']->currency
;
3291 if (!empty($params['is_quick_config'])) {
3292 $amount = $itemAmount;
3294 $amount = $params['total_amount'];
3298 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3299 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3303 $amount = $diff * $fieldValues['line_total'];
3306 $itemParams = array(
3307 'transaction_date' => $receiveDate,
3308 'contact_id' => $params['prevContribution']->contact_id
,
3309 'currency' => $currency,
3310 'amount' => $amount,
3311 'description' => $prevfinancialItem->description
,
3312 'status_id' => $prevfinancialItem->status_id
,
3313 'financial_account_id' => $financialAccount,
3314 'entity_table' => 'civicrm_line_item',
3315 'entity_id' => $fieldValues['id'],
3317 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3319 if ($fieldValues['tax_amount']) {
3320 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3321 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3322 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3323 $itemParams['description'] = $taxTerm;
3324 if ($fieldValues['financial_type_id']) {
3325 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3327 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3332 if ($context == 'changeFinancialType') {
3333 $params['skipLineItem'] = FALSE;
3334 foreach ($params['line_item'] as &$lineItems) {
3335 foreach ($lineItems as &$line) {
3336 $line['financial_type_id'] = $params['financial_type_id'];
3343 * Check status validation on update of a contribution.
3345 * @param array $values
3346 * Previous form values before submit.
3348 * @param array $fields
3349 * The input form values.
3351 * @param array $errors
3356 public static function checkStatusValidation($values, &$fields, &$errors) {
3357 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3358 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3359 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3363 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3364 $checkStatus = array(
3365 'Cancelled' => array('Completed', 'Refunded'),
3366 'Completed' => array('Cancelled', 'Refunded'),
3367 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3368 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3369 'Refunded' => array('Cancelled', 'Completed'),
3370 'Partially paid' => array('Completed'),
3373 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3374 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3375 1 => $contributionStatuses[$values['contribution_status_id']],
3376 2 => $contributionStatuses[$fields['contribution_status_id']],
3382 * Delete contribution of contact.
3386 * @param int $contactId
3390 public static function deleteContactContribution($contactId) {
3391 $contribution = new CRM_Contribute_DAO_Contribution();
3392 $contribution->contact_id
= $contactId;
3393 $contribution->find();
3394 while ($contribution->fetch()) {
3395 self
::deleteContribution($contribution->id
);
3400 * Get options for a given contribution field.
3401 * @see CRM_Core_DAO::buildOptions
3403 * @param string $fieldName
3404 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3405 * @param array $props whatever is known about this dao object.
3407 * @return array|bool
3409 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3410 $className = __CLASS__
;
3412 switch ($fieldName) {
3413 // This field is not part of this object but the api supports it
3414 case 'payment_processor':
3415 $className = 'CRM_Contribute_BAO_ContributionPage';
3416 // Filter results by contribution page
3417 if (!empty($props['contribution_page_id'])) {
3418 $page = civicrm_api('contribution_page', 'getsingle', array(
3420 'id' => ($props['contribution_page_id']),
3422 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3423 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3427 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3428 case 'honor_type_id':
3429 $className = 'CRM_Contribute_BAO_ContributionSoft';
3430 $fieldName = 'soft_credit_type_id';
3431 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3434 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3438 * Validate financial type.
3442 * @param int $financialTypeId
3443 * Financial Type id.
3445 * @param string $relationName
3447 * @return array|bool
3449 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3450 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3451 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3453 if (!$financialAccount) {
3454 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3461 * Function to record additional payment for partial and refund contributions.
3463 * @param int $contributionId
3464 * is the invoice contribution id (got created after processing participant payment).
3465 * @param array $trxnsData
3466 * to take user provided input of transaction details.
3467 * @param string $paymentType
3468 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3469 * @param int $participantId
3471 * @return null|object
3473 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3474 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3475 $getInfoOf['id'] = $contributionId;
3476 $defaults = array();
3477 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3479 if ($paymentType == 'owed') {
3480 // build params for recording financial trxn entry
3481 $params['contribution'] = $contributionDAO;
3482 $params = array_merge($defaults, $params);
3483 $params['skipLineItem'] = TRUE;
3484 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3485 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3486 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3487 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3490 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3491 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3492 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3494 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3495 if (!empty($trxnId)) {
3496 $trxnId = $trxnId['trxn_id'];
3498 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3499 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3502 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3503 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3504 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3508 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3509 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3510 FROM civicrm_financial_trxn ft
3511 LEFT JOIN civicrm_entity_financial_trxn eft
3512 ON (ft.id = eft.financial_trxn_id)
3513 WHERE eft.entity_table = 'civicrm_contribution'
3514 AND eft.entity_id = {$contributionId}
3515 AND ft.to_financial_account_id != {$toFinancialAccount}
3516 AND ft.status_id = {$statusId}
3518 $query = CRM_Core_DAO
::executeQuery($sql);
3520 $sumOfPayments = $query->sum_of_payments
;
3523 if ($contributionDAO->total_amount
== $sumOfPayments) {
3524 // update contribution status and
3525 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3526 $contributionDAO->contribution_status_id
= $statusId;
3527 $contributionDAO->cancel_date
= 'null';
3528 $contributionDAO->cancel_reason
= NULL;
3529 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3530 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3531 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3532 $contributionDAO->save();
3534 //Change status of financial record too
3535 $financialTrxn->status_id
= $statusId;
3536 $financialTrxn->save();
3538 // note : not using the self::add method,
3539 // the reason because it performs 'status change' related code execution for financial records
3540 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3541 // are coded below i.e. just updating financial_item status to 'Paid'
3543 if ($participantId) {
3544 // update participant status
3545 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3546 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3547 foreach ($ids as $val) {
3548 $participantUpdate['id'] = $val;
3549 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3550 CRM_Event_BAO_Participant
::add($participantUpdate);
3554 // update financial item statuses
3555 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3556 $paidStatus = array_search('Paid', $financialItemStatus);
3558 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3559 $sqlFinancialItemUpdate = "
3560 UPDATE civicrm_financial_item fi
3561 LEFT JOIN civicrm_entity_financial_trxn eft
3562 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3563 SET status_id = {$paidStatus}
3564 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3566 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3569 elseif ($paymentType == 'refund') {
3570 // build params for recording financial trxn entry
3571 $params['contribution'] = $contributionDAO;
3572 $params = array_merge($defaults, $params);
3573 $params['skipLineItem'] = TRUE;
3574 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3575 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3577 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3578 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3579 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3581 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3583 // note : not using the self::add method,
3584 // the reason because it performs 'status change' related code execution for financial records
3585 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3586 // are coded below i.e. just updating financial_item status to 'Paid'
3587 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3589 // add financial item entry
3590 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3591 $getLine['entity_id'] = $contributionDAO->id
;
3592 $getLine['entity_table'] = 'civicrm_contribution';
3593 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3594 if (!empty($lineItemId->id
)) {
3595 $addFinancialEntry = array(
3596 'transaction_date' => $financialTrxn->trxn_date
,
3597 'contact_id' => $contributionDAO->contact_id
,
3598 'amount' => $financialTrxn->total_amount
,
3599 'status_id' => array_search('Paid', $financialItemStatus),
3600 'entity_id' => $lineItemId->id
,
3601 'entity_table' => 'civicrm_line_item',
3603 $trxnIds['id'] = $financialTrxn->id
;
3604 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3606 if ($participantId) {
3607 // update participant status
3608 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3609 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3610 foreach ($ids as $val) {
3611 $participantUpdate['id'] = $val;
3612 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3613 CRM_Event_BAO_Participant
::add($participantUpdate);
3618 // activity creation
3619 if (!empty($financialTrxn)) {
3620 if ($participantId) {
3621 $inputParams['id'] = $participantId;
3624 $component = 'event';
3625 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3626 $entityObj = $entityObj[$participantId];
3628 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3630 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3632 return $financialTrxn;
3638 * @param $activityType
3640 * @param int $contributionId
3642 * @throws CRM_Core_Exception
3644 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3645 if ($component == 'event') {
3646 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3647 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3648 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3649 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3650 $targetCid = $entityObj->contact_id
;
3651 // source record id would be the contribution id
3652 $srcRecId = $contributionId;
3656 $activityParams = array(
3657 'source_contact_id' => $targetCid,
3658 'source_record_id' => $srcRecId,
3659 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3663 'subject' => $subject,
3664 'activity_date_time' => $date,
3665 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3669 'skipRecentView' => TRUE,
3672 // create activity with target contacts
3673 $session = CRM_Core_Session
::singleton();
3674 $id = $session->get('userID');
3676 $activityParams['source_contact_id'] = $id;
3677 $activityParams['target_contact_id'][] = $targetCid;
3679 CRM_Activity_BAO_Activity
::create($activityParams);
3683 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3687 * @param bool $getTrxnInfo
3688 * @param bool $usingLineTotal
3692 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3693 if ($component == 'event') {
3694 $entity = 'participant';
3695 $entityTable = 'civicrm_participant';
3696 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3698 if (!$contributionId) {
3699 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3700 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3701 $id = $primaryParticipantId;
3703 if (!$contributionId) {
3708 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3709 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3715 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3716 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3719 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3720 // for additional participants
3721 if ($entityTable == 'civicrm_participant') {
3722 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3724 foreach ($ids as $val) {
3725 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3729 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3733 $baseTrxnId = $total['trxn_id'];
3734 $total = $total['total_amount'];
3737 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3738 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3740 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3741 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3742 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3744 if ($paymentBalance == 0 && $contributionIsPayLater) {
3745 $paymentBalance = $total;
3748 $info['total'] = $total;
3749 $info['paid'] = $total - $paymentBalance;
3750 $info['balance'] = $paymentBalance;
3752 $info['component'] = $component;
3753 $info['payLater'] = $contributionIsPayLater;
3755 if ($getTrxnInfo && $baseTrxnId) {
3756 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3758 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3759 FROM civicrm_contribution con
3760 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3761 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3762 WHERE con.id = {$contributionId}
3765 // conditioned WHERE clause
3767 // if balance trxn exists don't include details of it in transaction info
3768 $sql .= " AND ft.id != {$baseTrxnId} ";
3770 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3772 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3773 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3774 while ($resultDAO->fetch()) {
3775 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3776 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3778 'total_amount' => $resultDAO->total_amount
,
3779 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3780 'payment_instrument' => $paidByLabel,
3781 'receive_date' => $resultDAO->trxn_date
,
3782 'trxn_id' => $resultDAO->trxn_id
,
3783 'status' => $statuses[$resultDAO->status_id
],
3785 if ($paidByName == 'Check') {
3786 $val['check_number'] = $resultDAO->check_number
;
3790 $info['transaction'] = $rows;
3796 * Get financial account id has 'Sales Tax Account is'
3797 * account relationship with financial type
3799 * @param int $financialTypeId
3801 * @return FinancialAccountId
3803 public static function getFinancialAccountId($financialTypeId) {
3804 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3805 $searchParams = array(
3806 'entity_table' => 'civicrm_financial_type',
3807 'entity_id' => $financialTypeId,
3808 'account_relationship' => $accountRel,
3811 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3813 return CRM_Utils_Array
::value('financial_account_id', $result);
3819 * @param array $params
3820 * @param bool $isLineItem
3824 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3825 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3827 // Update contribution.
3828 if (!empty($params['id'])) {
3829 $id = $params['id'];
3830 $values = $ids = array();
3831 $contrbutionParams = array('id' => $id);
3832 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3834 // To assign pervious finantial type on update of contribution
3835 if (!isset($params['financial_type_id'])) {
3836 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3838 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3839 // Assisn tax Amount on update of contrbution
3840 if (!empty($prevContributionValue->tax_amount
)) {
3841 $params['tax_amount'] = 'null';
3842 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3843 foreach ($params['line_item'] as $setID => $priceField) {
3844 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3845 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3852 // New Contrbution and update of contribution with tax rate financial type
3853 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3854 empty($params['skipLineItem']) && !$isLineItem
3856 $taxRateParams = $taxRates[$params['financial_type_id']];
3857 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3858 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3860 // Get Line Item on update of contribution
3861 if (isset($params['id'])) {
3862 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3865 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3867 foreach ($params['line_item'] as $setID => $priceField) {
3868 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3869 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3872 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3874 elseif (isset($params['api.line_item.create'])) {
3875 // Update total amount of contribution using lineItem
3876 $taxAmountArray = array();
3877 foreach ($params['api.line_item.create'] as $key => $value) {
3878 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3879 $taxRate = $taxRates[$value['financial_type_id']];
3880 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3881 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3884 $params['tax_amount'] = array_sum($taxAmountArray);
3885 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3888 // update line item of contrbution
3889 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3890 $taxRate = $taxRates[$params['financial_type_id']];
3891 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3892 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3899 * Check financial type validation on update of a contribution.
3901 * @param Integer $financialTypeId
3902 * Value of latest Financial Type.
3904 * @param Integer $contributionId
3907 * @param array $errors
3912 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3913 if (!empty($financialTypeId)) {
3914 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3915 if ($oldFinancialTypeId == $financialTypeId) {
3919 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3921 '1' => array($contributionId, 'Integer'),
3923 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3924 if ($result->N
> 1) {
3925 $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.');
3930 * Update related pledge payment payments.
3932 * This function has been refactored out of the back office contribution form and may
3933 * still overlap with other functions.
3935 * @param string $action
3936 * @param int $pledgePaymentID
3937 * @param int $contributionID
3938 * @param bool $adjustTotalAmount
3939 * @param float $total_amount
3940 * @param float $original_total_amount
3941 * @param int $contribution_status_id
3942 * @param int $original_contribution_status_id
3944 public static function updateRelatedPledge(
3950 $original_total_amount,
3951 $contribution_status_id,
3952 $original_contribution_status_id
3954 if (!$pledgePaymentID ||
$action & CRM_Core_Action
::ADD
&& !$contributionID) {
3958 if ($pledgePaymentID) {
3959 //store contribution id in payment record.
3960 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
3963 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3969 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3975 $updatePledgePaymentStatus = FALSE;
3977 // If either the status or the amount has changed we update the pledge status.
3978 if ($action & CRM_Core_Action
::ADD
) {
3979 $updatePledgePaymentStatus = TRUE;
3981 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
3982 ($original_total_amount != $total_amount))
3984 $updatePledgePaymentStatus = TRUE;
3987 if ($updatePledgePaymentStatus) {
3988 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
3989 array($pledgePaymentID),
3990 $contribution_status_id,
3999 * Compute the stats values
4001 * @param $stat either 'mode' or 'median'
4003 * @param $alias of civicrm_contribution
4005 public static function computeStats($stat, $sql, $alias = NULL) {
4006 $mode = $median = array();
4009 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4010 while ($modeDAO->fetch()) {
4011 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4012 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4021 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4022 foreach ($currencies as $currency => $val) {
4024 $where = "AND {$alias}.currency = '{$currency}'";
4025 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4029 $medianRow = floor($rowCount / 2);
4030 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4036 $medianValue = "SELECT {$alias}.total_amount as median
4038 ORDER BY median LIMIT {$medianRow},{$offset}";
4039 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4040 while ($medianValDAO->fetch()) {
4042 $midValue = $midValue +
$medianValDAO->median
;
4045 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4049 $midValue = $midValue / 2;
4050 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4061 * Complete an order.
4063 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4065 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4067 * Moving it out of the BaseIPN class is just the first step.
4069 * @param array $input
4071 * @param array $objects
4072 * @param CRM_Core_Transaction $transaction
4074 * @param CRM_Contribute_BAO_Contribution $contribution
4075 * @param bool $isRecurring
4076 * Duplication of param needs review. Only used by AuthorizeNetIPN
4077 * @param int $isFirstOrLastRecurringPayment
4078 * Deprecated param only used by AuthorizeNetIPN.
4080 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4081 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4082 // The previous details are used when calculating line items so keep it before any code that 'does something'
4083 if (!empty($contribution->id
)) {
4084 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4085 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4087 $inputContributionWhiteList = array(
4092 'payment_instrument_id',
4098 $contributionParams = array_merge(array(
4099 'contribution_status_id' => 'Completed',
4100 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4103 $participant = CRM_Utils_Array
::value('participant', $objects);
4104 $memberships = CRM_Utils_Array
::value('membership', $objects);
4105 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4106 if (!empty($recurContrib->id
)) {
4107 $contributionParams['contribution_recur_id'] = $recurContrib->id
;
4109 self
::repeatTransaction($contribution, $input, $contributionParams);
4111 if (is_numeric($memberships)) {
4112 $memberships = array($objects['membership']);
4115 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4118 if (isset($input['is_email_receipt'])) {
4119 $values['is_email_receipt'] = $input['is_email_receipt'];
4122 if ($input['component'] == 'contribute') {
4123 if ($contribution->contribution_page_id
) {
4124 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4125 $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
4127 elseif ($recurContrib && $recurContrib->id
) {
4128 $contributionParams['contribution_page_id'] = NULL;
4129 $values['amount'] = $recurContrib->amount
;
4130 $values['financial_type_id'] = $objects['contributionType']->id
;
4131 $values['title'] = $source = ts('Offline Recurring Contribution');
4132 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
4133 $values['receipt_from_name'] = $domainValues[0];
4134 $values['receipt_from_email'] = $domainValues[1];
4137 if (empty($contributionParams['receive_date']) && $changeDate) {
4138 $contributionParams['receive_date'] = $changeDate;
4141 if ($recurContrib && $recurContrib->id
&& !isset($input['is_email_receipt'])) {
4142 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4143 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4144 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4147 if (!empty($values['is_email_receipt'])) {
4148 $contributionParams['receipt_date'] = $changeDate;
4151 if (!empty($memberships)) {
4152 foreach ($memberships as $membershipTypeIdKey => $membership) {
4154 $membershipParams = array(
4155 'id' => $membership->id
,
4156 'contact_id' => $membership->contact_id
,
4157 'is_test' => $membership->is_test
,
4158 'membership_type_id' => $membership->membership_type_id
,
4161 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4162 $membershipParams['membership_type_id'],
4163 $membershipParams['is_test'],
4164 $membershipParams['id']
4167 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4168 // this picks up membership type changes during renewals
4170 SELECT membership_type_id
4171 FROM civicrm_membership_log
4172 WHERE membership_id={$membershipParams['id']}
4175 $dao = CRM_Core_DAO
::executeQuery($sql);
4176 if ($dao->fetch()) {
4177 if (!empty($dao->membership_type_id
)) {
4178 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4183 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4184 $membershipParams['membership_type_id'],
4185 $primaryContributionID
4187 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4188 if ($currentMembership) {
4190 * Fixed FOR CRM-4433
4191 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4192 * when Contribution mode is notify and membership is for renewal )
4194 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4196 // @todo - we should pass membership_type_id instead of null here but not
4197 // adding as not sure of testing
4198 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4199 $changeDate, NULL, $membershipParams['num_terms']
4202 $dates['join_date'] = $currentMembership['join_date'];
4205 //get the status for membership.
4206 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4208 $dates['join_date'],
4211 $membershipParams['membership_type_id'],
4215 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4216 //we might be renewing membership,
4217 //so make status override false.
4218 $membershipParams['is_override'] = FALSE;
4219 civicrm_api3('Membership', 'create', $membershipParams);
4221 //update related Memberships.
4222 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $membershipParams);
4228 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4229 $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id
));
4230 $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
4231 if ($eventDetail['is_email_confirm']) {
4232 // @todo this should be set by the function that sends the mail after sending.
4233 $contributionParams['receipt_date'] = $changeDate;
4235 $participantParams['id'] = $participant->id
;
4236 $participantParams['status_id'] = 'Registered';
4237 civicrm_api3('Participant', 'create', $participantParams);
4241 $contributionParams['id'] = $contribution->id
;
4243 civicrm_api3('Contribution', 'create', $contributionParams);
4245 // Add new soft credit against current $contribution.
4246 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4247 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4250 $paymentProcessorId = '';
4251 if (isset($objects['paymentProcessor'])) {
4252 if (is_array($objects['paymentProcessor'])) {
4253 $paymentProcessorId = $objects['paymentProcessor']['id'];
4256 $paymentProcessorId = $objects['paymentProcessor']->id
;
4260 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4261 'labelColumn' => 'name',
4264 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4265 $input['payment_processor'] = $paymentProcessorId;
4267 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4268 $input['total_amount'] = $input['amount'];
4269 $input['contribution'] = $contribution;
4270 $input['financial_type_id'] = $contribution->financial_type_id
;
4272 if (!empty($contribution->_relatedObjects
['participant'])) {
4273 $input['contribution_mode'] = 'participant';
4274 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4275 $input['skipLineItem'] = 1;
4277 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4278 $input['skipLineItem'] = TRUE;
4279 $input['contribution_mode'] = 'membership';
4281 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4282 // and subsequent payments. In this case the line items are created at
4283 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4284 // and since the contribution is saved prior to this line there is always a contribution-id,
4285 // however there is never a prevContribution (which appears to mean original contribution not previous
4286 // contribution - or preUpdateContributionObject most accurately)
4287 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4288 // to mean "are we updating an exisitng pending contribution"
4289 //I was able to make the unit test complete as fataling here doesn't prevent
4290 // the contribution being created - but activities would not be created or emails sent
4292 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4294 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4295 $transaction->commit();
4297 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution);
4299 // create an activity record
4300 if ($input['component'] == 'contribute') {
4302 $targetContactID = NULL;
4303 if (!empty($ids['related_contact'])) {
4304 $targetContactID = $contribution->contact_id
;
4305 $contribution->contact_id
= $ids['related_contact'];
4307 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4311 CRM_Activity_BAO_Activity
::addActivity($participant);
4314 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4315 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4316 if (!array_key_exists('is_email_receipt', $values) ||
4317 $values['is_email_receipt'] == 1
4319 self
::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
4320 CRM_Core_Error
::debug_log_message("Receipt sent");
4323 CRM_Core_Error
::debug_log_message("Success: Database updated");
4325 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4326 $isFirstOrLastRecurringPayment);
4331 * Send receipt from contribution.
4333 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4335 * Note that the compose message part has been moved to contribution
4336 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4338 * @param array $input
4339 * Incoming data from Payment processor.
4341 * Related object IDs.
4342 * @param CRM_Contribute_BAO_Contribution $contribution
4343 * @param array $values
4344 * Values related to objects that have already been loaded.
4345 * @param bool $recur
4346 * Is it part of a recurring contribution.
4347 * @param bool $returnMessageText
4348 * Should text be returned instead of sent. This.
4349 * is because the function is also used to generate pdfs
4353 public static function sendMail(&$input, &$ids, $contribution, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4354 $input['is_recur'] = $recur;
4355 // set receipt from e-mail and name in value
4356 if (!$returnMessageText) {
4357 $session = CRM_Core_Session
::singleton();
4358 $userID = $session->get('userID');
4359 if (!empty($userID)) {
4360 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4361 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4362 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4365 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);