3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
33 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
36 * Static field for all the contribution information that we can potentially import
40 static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 static $_exportableFields = NULL;
50 * Field for all the objects related to this contribution
51 * @var array of objects (e.g membership object, participant object)
53 public $_relatedObjects = array();
56 * Field for the component - either 'event' (participant) or 'contribute'
57 * (any item related to a contribution page e.g. membership, pledge, contribution)
58 * This is used for composing messages because they have dependency on the
59 * contribution_page or event page - although over time we may eliminate that
61 * @var string component or event
63 public $_component = NULL;
66 * Possibly obsolete variable.
68 * If you use it please explain why it is set in the create function here.
72 public $trxn_result_code;
77 * @return \CRM_Contribute_DAO_Contribution
81 public function __construct() {
82 parent
::__construct();
86 * Takes an associative array and creates a contribution object.
88 * the function extract all the params it needs to initialize the create a
89 * contribution object. the params array could contain additional unused name/value
92 * @param array $params
93 * (reference ) an assoc array of name/value pairs.
95 * The array that holds all the db ids.
97 * @return CRM_Contribute_BAO_Contribution|void
99 public static function add(&$params, $ids = array()) {
100 if (empty($params)) {
103 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
104 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
105 $duplicates = array();
106 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
107 $error = CRM_Core_Error
::singleton();
108 $d = implode(', ', $duplicates);
109 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
112 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
117 // first clean up all the money fields
118 $moneyFields = array(
122 'non_deductible_amount',
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
127 unset($moneyFields[0]);
130 foreach ($moneyFields as $field) {
131 if (isset($params[$field])) {
132 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
136 //set defaults in create mode
137 if (!$contributionID) {
138 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
140 self
::calculateMissingAmountParams($params, $contributionID);
142 if (!empty($params['payment_instrument_id'])) {
143 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
144 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
145 $params['check_number'] = 'null';
149 $setPrevContribution = TRUE;
150 // CRM-13964 partial payment
151 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
152 $partialAmtTotal = $params['partial_payment_total'];
153 $partialAmtPay = $params['partial_amount_pay'];
154 $params['total_amount'] = $partialAmtTotal;
155 if ($partialAmtPay < $partialAmtTotal) {
156 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
157 $params['is_pay_later'] = 0;
158 $setPrevContribution = FALSE;
161 if ($contributionID && $setPrevContribution) {
162 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
165 if ($contributionID) {
166 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
169 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
171 $contribution = new CRM_Contribute_BAO_Contribution();
172 $contribution->copyValues($params);
174 $contribution->id
= $contributionID;
176 if (empty($contribution->id
)) {
177 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
178 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
179 $config = CRM_Core_Config
::singleton();
180 $contribution->currency
= $config->defaultCurrency
;
184 $result = $contribution->save();
186 // Add financial_trxn details as part of fix for CRM-4724
187 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
188 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
190 //add Account details
191 $params['contribution'] = $contribution;
192 self
::recordFinancialAccounts($params);
194 // reset the group contact cache for this group
195 CRM_Contact_BAO_GroupContactCache
::remove();
197 if ($contributionID) {
198 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
201 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
208 * Get defaults for new entity.
211 public static function getDefaults() {
213 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
214 FALSE, FALSE, FALSE, 'AND is_default = 1')
216 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
221 * Given the list of params in the params array, fetch the object
222 * and store the values in the values array
224 * @param array $params
225 * Input parameters to find object.
226 * @param array $values
227 * Output values of the object.
229 * The array that holds all the db ids.
231 * @return CRM_Contribute_BAO_Contribution|null
232 * The found object or null
234 public static function getValues($params, &$values, &$ids) {
235 if (empty($params)) {
238 $contribution = new CRM_Contribute_BAO_Contribution();
240 $contribution->copyValues($params);
242 if ($contribution->find(TRUE)) {
243 $ids['contribution'] = $contribution->id
;
245 CRM_Core_DAO
::storeValues($contribution, $values);
247 return $contribution;
249 $null = NULL; // return by reference
254 * Calculate net_amount & fee_amount if they are not set.
256 * Net amount should be total - fee.
257 * This should only be called for new contributions.
259 * @param array $params
260 * Params for a new contribution before they are saved.
261 * @param int|null $contributionID
262 * Contribution ID if we are dealing with an update.
264 * @throws \CiviCRM_API3_Exception
266 public static function calculateMissingAmountParams(&$params, $contributionID) {
267 if (!$contributionID && !isset($params['fee_amount'])) {
268 if (isset($params['total_amount']) && isset($params['net_amount'])) {
269 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
272 $params['fee_amount'] = 0;
275 if (!isset($params['net_amount'])) {
276 if (!$contributionID) {
277 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
280 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
281 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
282 // net_amount may need adjusting.
283 $contribution = civicrm_api3('Contribution', 'getsingle', array(
284 'id' => $contributionID,
285 'return' => array('total_amount', 'net_amount'),
287 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
288 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
289 $params['net_amount'] = $totalAmount - $feeAmount;
297 * @param $billingLocationTypeID
301 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
302 $hasBillingField = FALSE;
303 $billingFields = array(
311 //build address array
312 $addressParams = array();
313 $addressParams['location_type_id'] = $billingLocationTypeID;
314 $addressParams['is_billing'] = 1;
316 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
317 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
318 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
319 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
321 foreach ($billingFields as $value) {
322 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
323 if (!empty($addressParams[$value])) {
324 $hasBillingField = TRUE;
327 return array($hasBillingField, $addressParams);
331 * Get address params ready to be passed to the payment processor.
333 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
334 * To create an address we need state_province_id.
336 * @param array $params
337 * @param int $billingLocationTypeID
341 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
342 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
343 foreach ($addressParams as $name => $field) {
344 if (substr($name, 0, 8) == 'billing_') {
345 $addressParams[substr($name, 9)] = $addressParams[$field];
348 return array($hasBillingField, $addressParams);
352 * Get the number of terms for this contribution for a given membership type
353 * based on querying the line item table and relevant price field values
354 * Note that any one contribution should only be able to have one line item relating to a particular membership
357 * @param int $membershipTypeID
359 * @param int $contributionID
363 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
364 $numTerms = CRM_Core_DAO
::singleValueQuery("
365 SELECT membership_num_terms FROM civicrm_line_item li
366 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
367 WHERE contribution_id = %1 AND membership_type_id = %2",
368 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
370 // default of 1 is precautionary
371 return empty($numTerms) ?
1 : $numTerms;
375 * Takes an associative array and creates a contribution object.
377 * @param array $params
378 * (reference ) an assoc array of name/value pairs.
380 * The array that holds all the db ids.
382 * @return CRM_Contribute_BAO_Contribution
384 public static function create(&$params, $ids = array()) {
385 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
386 foreach ($dateFields as $df) {
387 if (isset($params[$df])) {
388 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
392 $transaction = new CRM_Core_Transaction();
394 $contribution = self
::add($params, $ids);
396 if (is_a($contribution, 'CRM_Core_Error')) {
397 $transaction->rollback();
398 return $contribution;
401 $params['contribution_id'] = $contribution->id
;
403 if (!empty($params['custom']) &&
404 is_array($params['custom'])
406 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
409 $session = CRM_Core_Session
::singleton();
411 if (!empty($params['note'])) {
413 'entity_table' => 'civicrm_contribution',
414 'note' => $params['note'],
415 'entity_id' => $contribution->id
,
416 'contact_id' => $session->get('userID'),
417 'modified_date' => date('Ymd'),
419 if (!$noteParams['contact_id']) {
420 $noteParams['contact_id'] = $params['contact_id'];
422 CRM_Core_BAO_Note
::add($noteParams);
425 // make entry in batch entity batch table
426 if (!empty($params['batch_id'])) {
427 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
428 $titleFields = array(
434 $retrieveRequired = 0;
435 foreach ($titleFields as $titleField) {
436 if (!isset($contribution->$titleField)) {
437 $retrieveRequired = 1;
441 if ($retrieveRequired == 1) {
442 $contribution->find(TRUE);
446 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
448 $transaction->commit();
450 // check if activity record exist for this contribution, if
452 $activity = new CRM_Activity_DAO_Activity();
453 $activity->source_record_id
= $contribution->id
;
454 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
458 if (!$activity->find(TRUE)) {
459 if (empty($contribution->contact_id
)) {
460 $contribution->find(TRUE);
462 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
465 // CRM-13237 : if activity record found, update it with campaign id of contribution
466 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
469 // do not add to recent items for import, CRM-4399
470 if (empty($params['skipRecentView'])) {
471 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
472 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
474 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
475 $titleFields = array(
481 $retrieveRequired = 0;
482 foreach ($titleFields as $titleField) {
483 if (!isset($contribution->$titleField)) {
484 $retrieveRequired = 1;
488 if ($retrieveRequired == 1) {
489 $contribution->find(TRUE);
491 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
492 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
494 $recentOther = array();
495 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
496 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
497 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
501 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
502 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
503 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
507 // add the recently created Contribution
508 CRM_Utils_Recent
::add($title,
512 $contribution->contact_id
,
518 return $contribution;
522 * Get the values for pseudoconstants for name->value and reverse.
524 * @param array $defaults
525 * (reference) the default values, some of which need to be resolved.
526 * @param bool $reverse
527 * True if we want to resolve the values in the reverse direction (value -> name).
529 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
530 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
531 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
532 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
533 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
537 * Convert associative array names to values and vice-versa.
539 * This function is used by both the web form layer and the api. Note that
540 * the api needs the name => value conversion, also the view layer typically
541 * requires value => name conversion
543 * @param array $defaults
544 * @param string $property
545 * @param array $lookup
546 * @param bool $reverse
550 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
551 $id = $property . '_id';
553 $src = $reverse ?
$property : $id;
554 $dst = $reverse ?
$id : $property;
556 if (!array_key_exists($src, $defaults)) {
560 $look = $reverse ?
array_flip($lookup) : $lookup;
562 if (is_array($look)) {
563 if (!array_key_exists($defaults[$src], $look)) {
567 $defaults[$dst] = $look[$defaults[$src]];
572 * Retrieve DB object based on input parameters.
574 * It also stores all the retrieved values in the default array.
576 * @param array $params
577 * (reference ) an assoc array of name/value pairs.
578 * @param array $defaults
579 * (reference ) an assoc array to hold the name / value pairs.
580 * in a hierarchical manner
582 * (reference) the array that holds all the db ids.
584 * @return CRM_Contribute_BAO_Contribution
586 public static function retrieve(&$params, &$defaults, &$ids) {
587 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
588 return $contribution;
592 * Combine all the importable fields from the lower levels object.
594 * The ordering is important, since currently we do not have a weight
595 * scheme. Adding weight is super important and should be done in the
596 * next week or so, before this can be called complete.
598 * @param string $contactType
599 * @param bool $status
602 * array of importable Fields
604 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
605 if (!self
::$_importableFields) {
606 if (!self
::$_importableFields) {
607 self
::$_importableFields = array();
611 $fields = array('' => array('title' => ts('- do not import -')));
614 $fields = array('' => array('title' => ts('- Contribution Fields -')));
617 $note = CRM_Core_DAO_Note
::import();
618 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
619 unset($tmpFields['option_value']);
620 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
621 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
623 // Using new Dedupe rule.
625 'contact_type' => $contactType,
626 'used' => 'Unsupervised',
628 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
629 $tmpContactField = array();
630 if (is_array($fieldsArray)) {
631 foreach ($fieldsArray as $value) {
632 //skip if there is no dupe rule
633 if ($value == 'none') {
636 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
641 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
642 $tmpContactField[trim($value)] = $contactFields[trim($value)];
644 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
647 $title = $tmpContactField[trim($value)]['title'];
649 $tmpContactField[trim($value)]['title'] = $title;
653 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
654 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
655 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
656 $fields = array_merge($fields, $tmpContactField);
657 $fields = array_merge($fields, $tmpFields);
658 $fields = array_merge($fields, $note);
659 $fields = array_merge($fields, $optionFields);
660 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
661 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
662 self
::$_importableFields = $fields;
664 return self
::$_importableFields;
670 public static function &exportableFields() {
671 if (!self
::$_exportableFields) {
672 if (!self
::$_exportableFields) {
673 self
::$_exportableFields = array();
676 $impFields = CRM_Contribute_DAO_Contribution
::export();
677 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
678 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
679 $typeField = CRM_Financial_DAO_FinancialType
::export();
680 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
681 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
682 $contributionStatus = array(
683 'contribution_status' => array(
684 'title' => ts('Contribution Status'),
685 'name' => 'contribution_status',
686 'data_type' => CRM_Utils_Type
::T_STRING
,
690 $contributionPage = array(
691 'contribution_page' => array(
692 'title' => ts('Contribution Page'),
693 'name' => 'contribution_page',
694 'where' => 'civicrm_contribution_page.title',
695 'data_type' => CRM_Utils_Type
::T_STRING
,
699 $contributionNote = array(
700 'contribution_note' => array(
701 'title' => ts('Contribution Note'),
702 'name' => 'contribution_note',
703 'data_type' => CRM_Utils_Type
::T_TEXT
,
707 $contributionRecurId = array(
708 'contribution_recur_id' => array(
709 'title' => ts('Recurring Contributions ID'),
710 'name' => 'contribution_recur_id',
711 'where' => 'civicrm_contribution.contribution_recur_id',
712 'data_type' => CRM_Utils_Type
::T_INT
,
716 $extraFields = array(
717 'contribution_batch' => array(
718 'title' => ts('Batch Name'),
722 $softCreditFields = array(
723 'contribution_soft_credit_name' => array(
724 'name' => 'contribution_soft_credit_name',
725 'title' => 'Soft Credit For',
726 'where' => 'civicrm_contact_d.display_name',
727 'data_type' => CRM_Utils_Type
::T_STRING
,
729 'contribution_soft_credit_amount' => array(
730 'name' => 'contribution_soft_credit_amount',
731 'title' => 'Soft Credit Amount',
732 'where' => 'civicrm_contribution_soft.amount',
733 'data_type' => CRM_Utils_Type
::T_MONEY
,
735 'contribution_soft_credit_type' => array(
736 'name' => 'contribution_soft_credit_type',
737 'title' => 'Soft Credit Type',
738 'where' => 'contribution_softcredit_type.label',
739 'data_type' => CRM_Utils_Type
::T_STRING
,
741 'contribution_soft_credit_contribution_id' => array(
742 'name' => 'contribution_soft_credit_contribution_id',
743 'title' => 'Soft Credit For Contribution ID',
744 'where' => 'civicrm_contribution_soft.contribution_id',
745 'data_type' => CRM_Utils_Type
::T_INT
,
749 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
751 'contribution_product_id' => array(
752 'title' => ts('Premium'),
753 'name' => 'contribution_product_id',
754 'where' => 'civicrm_product.id',
755 'data_type' => CRM_Utils_Type
::T_INT
,
759 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
760 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums,
761 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
764 self
::$_exportableFields = $fields;
767 return self
::$_exportableFields;
771 * @param null $status
772 * @param null $startDate
773 * @param null $endDate
777 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
781 $where[] = 'contribution_status_id = 1';
785 $where[] = 'contribution_status_id = 3';
790 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
793 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
796 $whereCond = implode(' AND ', $where);
799 SELECT sum( total_amount ) as total_amount,
800 count( civicrm_contribution.id ) as total_count,
802 FROM civicrm_contribution
803 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
805 AND ( is_test = 0 OR is_test IS NULL )
806 AND contact.is_deleted = 0
810 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
813 while ($dao->fetch()) {
814 $count +
= $dao->total_count
;
815 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
819 'amount' => implode(', ', $amount),
827 * Delete the indirect records associated with this contribution first.
832 * $results no of deleted Contribution on success, false otherwise
834 public static function deleteContribution($id) {
835 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
837 $transaction = new CRM_Core_Transaction();
840 //delete activity record
842 'source_record_id' => $id,
843 // activity type id for contribution
844 'activity_type_id' => 6,
847 CRM_Activity_BAO_Activity
::deleteActivity($params);
849 //delete billing address if exists for this contribution.
850 self
::deleteAddress($id);
852 //update pledge and pledge payment, CRM-3961
853 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
855 // remove entry from civicrm_price_set_entity, CRM-5095
856 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
857 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
859 // cleanup line items.
860 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
862 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
863 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
865 if ($participantId) {
866 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
869 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
873 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
874 $noteId = key($note);
876 CRM_Core_BAO_Note
::del($noteId, FALSE);
879 $dao = new CRM_Contribute_DAO_Contribution();
882 $results = $dao->delete();
884 $transaction->commit();
886 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
888 // delete the recently created Contribution
889 $contributionRecent = array(
891 'type' => 'Contribution',
893 CRM_Utils_Recent
::del($contributionRecent);
899 * React to a financial transaction (payment) failure.
901 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
902 * payments is important for forensic and outreach reasons.
904 * @param int $contributionID
905 * @param string $message
907 public static function failPayment($contributionID, $contactID, $message) {
908 civicrm_api3('activity', 'create', array(
909 'activity_type_id' => 'Failed Payment',
910 'details' => $message,
911 'subject' => ts('Payment failed at payment processor'),
912 'source_record_id' => $contributionID,
913 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
919 * Check if there is a contribution with the same trxn_id or invoice_id.
921 * @param array $input
922 * An assoc array of name/value pairs.
923 * @param array $duplicates
924 * (reference) store ids of duplicate contribs.
928 * true if duplicate, false otherwise
930 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
932 $id = CRM_Utils_Array
::value('id', $input);
934 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
935 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
941 $clause[] = "trxn_id = %1";
942 $input[1] = array($trxn_id, 'String');
946 $clause[] = "invoice_id = %2";
947 $input[2] = array($invoice_id, 'String');
950 if (empty($clause)) {
954 $clause = implode(' OR ', $clause);
956 $clause = "( $clause ) AND id != %3";
957 $input[3] = array($id, 'Integer');
960 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
961 $dao = CRM_Core_DAO
::executeQuery($query, $input);
963 while ($dao->fetch()) {
964 $duplicates[] = $dao->id
;
971 * Takes an associative array and creates a contribution_product object.
973 * the function extract all the params it needs to initialize the create a
974 * contribution_product object. the params array could contain additional unused name/value
977 * @param array $params
978 * (reference) an assoc array of name/value pairs.
980 * @return CRM_Contribute_DAO_ContributionProduct
982 public static function addPremium(&$params) {
983 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
984 $contributionProduct->copyValues($params);
985 return $contributionProduct->save();
989 * Get list of contribution fields for profile.
990 * For now we only allow custom contribution fields to be in
993 * @param bool $addExtraFields
994 * True if special fields needs to be added.
997 * the list of contribution fields
999 public static function getContributionFields($addExtraFields = TRUE) {
1000 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1001 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1003 if ($addExtraFields) {
1004 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1007 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1009 foreach ($contributionFields as $key => $var) {
1010 if ($key == 'contribution_contact_id') {
1013 elseif ($key == 'contribution_campaign_id') {
1014 $var['title'] = ts('Campaign');
1016 $fields[$key] = $var;
1019 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1024 * Add extra fields specific to contribution.
1026 public static function getSpecialContributionFields() {
1027 $extraFields = array(
1028 'contribution_soft_credit_name' => array(
1029 'name' => 'contribution_soft_credit_name',
1030 'title' => 'Soft Credit Name',
1031 'headerPattern' => '/^soft_credit_name$/i',
1032 'where' => 'civicrm_contact_d.display_name',
1034 'contribution_soft_credit_email' => array(
1035 'name' => 'contribution_soft_credit_email',
1036 'title' => 'Soft Credit Email',
1037 'headerPattern' => '/^soft_credit_email$/i',
1038 'where' => 'soft_email.email',
1040 'contribution_soft_credit_phone' => array(
1041 'name' => 'contribution_soft_credit_phone',
1042 'title' => 'Soft Credit Phone',
1043 'headerPattern' => '/^soft_credit_phone$/i',
1044 'where' => 'soft_phone.phone',
1046 'contribution_soft_credit_contact_id' => array(
1047 'name' => 'contribution_soft_credit_contact_id',
1048 'title' => 'Soft Credit Contact ID',
1049 'headerPattern' => '/^soft_credit_contact_id$/i',
1050 'where' => 'civicrm_contribution_soft.contact_id',
1054 return $extraFields;
1058 * @param int $pageID
1062 public static function getCurrentandGoalAmount($pageID) {
1064 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1065 FROM civicrm_contribution_page p,
1066 civicrm_contribution c
1067 WHERE p.id = c.contribution_page_id
1069 AND c.cancel_date is null
1073 $config = CRM_Core_Config
::singleton();
1074 $params = array(1 => array($pageID, 'Integer'));
1075 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1077 if ($dao->fetch()) {
1078 return array($dao->goal
, $dao->total
);
1081 return array(NULL, NULL);
1086 * Get list of contribution In Honor of contact Ids.
1088 * @param int $honorId
1089 * In Honor of Contact ID.
1092 * list of contribution fields
1094 public static function getHonorContacts($honorId) {
1096 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1097 $honorDAO->contact_id
= $honorId;
1100 $type = CRM_Contribute_PseudoConstant
::financialType();
1102 while ($honorDAO->fetch()) {
1103 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1104 $contributionDAO->id
= $honorDAO->contribution_id
;
1106 if ($contributionDAO->find(TRUE)) {
1107 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1108 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1109 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1110 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1111 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1112 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1113 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1114 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1115 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1123 * Get the sort name of a contact for a particular contribution.
1126 * Id of the contribution.
1128 * @return null|string
1129 * sort name of the contact if found
1131 public static function sortName($id) {
1132 $id = CRM_Utils_Type
::escape($id, 'Integer');
1135 SELECT civicrm_contact.sort_name
1136 FROM civicrm_contribution, civicrm_contact
1137 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1138 AND civicrm_contribution.id = {$id}
1140 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1144 * @param int $contactID
1148 public static function annual($contactID) {
1149 if (is_array($contactID)) {
1150 $contactIDs = implode(',', $contactID);
1153 $contactIDs = $contactID;
1156 $config = CRM_Core_Config
::singleton();
1157 $startDate = $endDate = NULL;
1159 $currentMonth = date('m');
1160 $currentDay = date('d');
1161 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1162 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1163 (int ) $config->fiscalYearStart
['d'] > $currentDay
1166 $year = date('Y') - 1;
1171 $nextYear = $year +
1;
1173 if ($config->fiscalYearStart
) {
1174 if ($config->fiscalYearStart
['M'] < 10) {
1175 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1177 if ($config->fiscalYearStart
['d'] < 10) {
1178 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1180 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1185 $startDate = "$year$monthDay";
1186 $endDate = "$nextYear$monthDay";
1189 SELECT count(*) as count,
1190 sum(total_amount) as amount,
1191 avg(total_amount) as average,
1193 FROM civicrm_contribution b
1194 WHERE b.contact_id IN ( $contactIDs )
1195 AND b.contribution_status_id = 1
1197 AND b.receive_date >= $startDate
1198 AND b.receive_date < $endDate
1201 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1203 $amount = $average = array();
1204 while ($dao->fetch()) {
1205 if ($dao->count
> 0 && $dao->amount
> 0) {
1206 $count +
= $dao->count
;
1207 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1208 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1214 implode(', ', $amount),
1215 implode(', ', $average),
1218 return array(0, 0, 0);
1222 * Check if there is a contribution with the params passed in.
1224 * Used for trxn_id,invoice_id and contribution_id
1226 * @param array $params
1227 * An assoc array of name/value pairs.
1230 * contribution id if success else NULL
1232 public static function checkDuplicateIds($params) {
1233 $dao = new CRM_Contribute_DAO_Contribution();
1237 foreach ($params as $k => $v) {
1239 $clause[] = "$k = '$v'";
1242 $clause = implode(' AND ', $clause);
1243 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1244 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1246 while ($dao->fetch()) {
1254 * Get the contribution details for component export.
1256 * @param int $exportMode
1258 * @param string $componentIds
1264 public static function getContributionDetails($exportMode, $componentIds) {
1265 $paymentDetails = array();
1266 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1268 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1269 $componentSelect = " civicrm_participant_payment.participant_id id";
1270 $additionalClause = "
1271 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1272 AND civicrm_participant_payment.participant_id {$componentClause} )
1275 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1276 $componentSelect = " civicrm_membership_payment.membership_id id";
1277 $additionalClause = "
1278 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1279 AND civicrm_membership_payment.membership_id {$componentClause} )
1282 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1283 $componentSelect = " civicrm_pledge_payment.id id";
1284 $additionalClause = "
1285 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1286 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1290 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1291 trxn_id, {$componentSelect}
1292 FROM civicrm_contribution
1293 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1294 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1295 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1296 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1297 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1298 AND option_group_contribution_status.id = contribution_status.option_group_id )
1302 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1304 while ($dao->fetch()) {
1305 $paymentDetails[$dao->id
] = array(
1306 'total_amount' => $dao->total_amount
,
1307 'contribution_status' => $dao->status
,
1308 'receive_date' => $dao->receive_date
,
1309 'pay_instru' => $dao->payment_instrument
,
1310 'trxn_id' => $dao->trxn_id
,
1314 return $paymentDetails;
1318 * Create address associated with contribution record.
1320 * As long as there is one or more billing field in the parameters we will create the address.
1322 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1325 * @param array $params
1326 * @param int $billingLocationTypeID
1331 public static function createAddress($params, $billingLocationTypeID) {
1332 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1333 if ($hasBillingField) {
1334 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1335 return $address->id
;
1342 * Delete billing address record related contribution.
1344 * @param int $contributionId
1345 * @param int $contactId
1347 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1349 $contactJoin = NULL;
1351 if ($contributionId) {
1352 $clauses[] = "cc.id = {$contributionId}";
1356 $clauses[] = "cco.id = {$contactId}";
1357 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1360 if (empty($clauses)) {
1361 CRM_Core_Error
::fatal();
1364 $condition = implode(' OR ', $clauses);
1368 FROM civicrm_address ca
1369 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1373 $dao = CRM_Core_DAO
::executeQuery($query);
1375 while ($dao->fetch()) {
1376 $params = array('id' => $dao->id
);
1377 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1382 * This function check online pending contribution associated w/
1383 * Online Event Registration or Online Membership signup.
1385 * @param int $componentId
1386 * Participant/membership id.
1387 * @param string $componentName
1391 * pending contribution id.
1393 public static function checkOnlinePendingContribution($componentId, $componentName) {
1394 $contributionId = NULL;
1395 if (!$componentId ||
1396 !in_array($componentName, array('Event', 'Membership'))
1398 return $contributionId;
1401 if ($componentName == 'Event') {
1402 $idName = 'participant_id';
1403 $componentTable = 'civicrm_participant';
1404 $paymentTable = 'civicrm_participant_payment';
1405 $source = ts('Online Event Registration');
1408 if ($componentName == 'Membership') {
1409 $idName = 'membership_id';
1410 $componentTable = 'civicrm_membership';
1411 $paymentTable = 'civicrm_membership_payment';
1412 $source = ts('Online Contribution');
1415 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1418 SELECT component.id as {$idName},
1419 componentPayment.contribution_id as contribution_id,
1420 contribution.source source,
1421 contribution.contribution_status_id as contribution_status_id,
1422 contribution.is_pay_later as is_pay_later
1423 FROM $componentTable component
1424 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1425 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1426 WHERE component.id = {$componentId}";
1428 $dao = CRM_Core_DAO
::executeQuery($query);
1430 while ($dao->fetch()) {
1431 if ($dao->contribution_id
&&
1432 $dao->is_pay_later
&&
1433 $dao->contribution_status_id
== $pendingStatusId &&
1434 strpos($dao->source
, $source) !== FALSE
1436 $contributionId = $dao->contribution_id
;
1441 return $contributionId;
1445 * Update contribution as well as related objects.
1447 * This function by-passes hooks - to address this - don't use this function.
1451 * Use api contribute.completetransaction
1452 * For failures use failPayment (preferably exposing by api in the process).
1454 * @param array $params
1455 * @param bool $processContributionObject
1458 * @throws \Exception
1460 public static function transitionComponents($params, $processContributionObject = FALSE) {
1461 // get minimum required values.
1462 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1463 $componentId = CRM_Utils_Array
::value('component_id', $params);
1464 $componentName = CRM_Utils_Array
::value('componentName', $params);
1465 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1466 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1468 // if we already processed contribution object pass previous status id.
1469 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1471 $updateResult = array();
1473 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1475 // we process only ( Completed, Cancelled, or Failed ) contributions.
1476 if (!$contributionId ||
1477 !in_array($contributionStatusId, array(
1478 array_search('Completed', $contributionStatuses),
1479 array_search('Cancelled', $contributionStatuses),
1480 array_search('Failed', $contributionStatuses),
1483 return $updateResult;
1486 if (!$componentName ||
!$componentId) {
1487 // get the related component details.
1488 $componentDetails = self
::getComponentDetails($contributionId);
1491 $componentDetails['contact_id'] = $contactId;
1492 $componentDetails['component'] = $componentName;
1494 if ($componentName == 'event') {
1495 $componentDetails['participant'] = $componentId;
1498 $componentDetails['membership'] = $componentId;
1502 if (!empty($componentDetails['contact_id'])) {
1503 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1509 // do check for required ids.
1510 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1511 return $updateResult;
1514 //now we are ready w/ required ids, start processing.
1516 $baseIPN = new CRM_Core_Payment_BaseIPN();
1518 $input = $ids = $objects = array();
1520 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1521 $ids['contribution'] = $contributionId;
1522 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1523 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1524 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1525 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1526 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1527 $ids['contributionRecur'] = NULL;
1528 $ids['contributionPage'] = NULL;
1530 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1531 CRM_Core_Error
::fatal();
1534 $memberships = &$objects['membership'];
1535 $participant = &$objects['participant'];
1536 $pledgePayment = &$objects['pledge_payment'];
1537 $contribution = &$objects['contribution'];
1539 if ($pledgePayment) {
1540 $pledgePaymentIDs = array();
1541 foreach ($pledgePayment as $key => $object) {
1542 $pledgePaymentIDs[] = $object->id
;
1544 $pledgeID = $pledgePayment[0]->pledge_id
;
1547 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1550 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1551 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1556 // we might want to process contribution object.
1557 $processContribution = FALSE;
1558 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1559 if (is_array($memberships)) {
1560 foreach ($memberships as $membership) {
1562 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1563 $membership->save();
1565 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1566 if ($processContributionObject) {
1567 $processContribution = TRUE;
1574 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1575 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1577 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1578 if ($processContributionObject) {
1579 $processContribution = TRUE;
1583 if ($pledgePayment) {
1584 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1586 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1587 if ($processContributionObject) {
1588 $processContribution = TRUE;
1592 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1593 if (is_array($memberships)) {
1594 foreach ($memberships as $membership) {
1596 $membership->status_id
= array_search('Expired', $membershipStatuses);
1597 $membership->save();
1599 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1600 if ($processContributionObject) {
1601 $processContribution = TRUE;
1607 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1608 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1610 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1611 if ($processContributionObject) {
1612 $processContribution = TRUE;
1616 if ($pledgePayment) {
1617 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1619 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1620 if ($processContributionObject) {
1621 $processContribution = TRUE;
1625 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1627 // only pending contribution related object processed.
1628 if ($previousContriStatusId &&
1629 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1631 // this is case when we already processed contribution object.
1632 return $updateResult;
1634 elseif (!$previousContriStatusId &&
1635 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1637 // this is case when we are going to process contribution object later.
1638 return $updateResult;
1641 if (is_array($memberships)) {
1642 foreach ($memberships as $membership) {
1647 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1648 $membership->membership_type_id
,
1649 $membership->is_test
, $membership->id
1652 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1653 // this picks up membership type changes during renewals
1655 SELECT membership_type_id
1656 FROM civicrm_membership_log
1657 WHERE membership_id=$membership->id
1660 $dao = new CRM_Core_DAO();
1662 if ($dao->fetch()) {
1663 if (!empty($dao->membership_type_id
)) {
1664 $membership->membership_type_id
= $dao->membership_type_id
;
1665 $membership->save();
1668 // else fall back to using current membership type
1671 // Figure out number of terms
1673 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1674 foreach ($lineitems as $lineitem) {
1675 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1676 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1678 // in case membership_num_terms comes through as null or zero
1679 $numterms = $numterms >= 1 ?
$numterms : 1;
1684 // CRM-15735-to update the membership status as per the contribution receive date
1686 if (!empty($params['receive_date'])) {
1687 $joinDate = $params['receive_date'];
1688 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1689 $membership->end_date
,
1690 $membership->join_date
,
1691 $params['receive_date'],
1693 $membership->membership_type_id
,
1696 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1697 $membership->save();
1700 if ($currentMembership) {
1701 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1702 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1703 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1706 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1709 //get the status for membership.
1710 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1712 $dates['join_date'],
1715 $membership->membership_type_id
,
1719 $formattedParams = array(
1720 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1721 array_search('Current', $membershipStatuses)
1723 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1724 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1725 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1728 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1730 $membership->copyValues($formattedParams);
1731 $membership->save();
1733 //updating the membership log
1734 $membershipLog = array();
1735 $membershipLog = $formattedParams;
1736 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1737 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1739 $membershipLog['start_date'] = $logStartDate;
1740 $membershipLog['membership_id'] = $membership->id
;
1741 $membershipLog['modified_id'] = $membership->contact_id
;
1742 $membershipLog['modified_date'] = date('Ymd');
1743 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1745 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1747 //update related Memberships.
1748 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1750 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1753 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1754 if ($processContributionObject) {
1755 $processContribution = TRUE;
1758 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1764 $updatedStatusId = array_search('Registered', $participantStatuses);
1765 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1767 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1768 if ($processContributionObject) {
1769 $processContribution = TRUE;
1773 if ($pledgePayment) {
1774 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1776 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1777 if ($processContributionObject) {
1778 $processContribution = TRUE;
1783 // process contribution object.
1784 if ($processContribution) {
1785 $contributionParams = array();
1792 'payment_instrument_id',
1795 'financial_type_id',
1796 'contribution_status_id',
1797 'non_deductible_amount',
1801 foreach ($fields as $field) {
1802 if (empty($params[$field])) {
1805 $contributionParams[$field] = $params[$field];
1808 $ids = array('contribution' => $contributionId);
1809 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1812 return $updateResult;
1816 * Returns all contribution related object ids.
1818 * @param $contributionId
1822 public static function getComponentDetails($contributionId) {
1823 $componentDetails = $pledgePayment = array();
1824 if (!$contributionId) {
1825 return $componentDetails;
1829 SELECT c.id as contribution_id,
1830 c.contact_id as contact_id,
1831 c.contribution_recur_id,
1832 mp.membership_id as membership_id,
1833 m.membership_type_id as membership_type_id,
1834 pp.participant_id as participant_id,
1835 p.event_id as event_id,
1836 pgp.id as pledge_payment_id
1837 FROM civicrm_contribution c
1838 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1839 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1840 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1841 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1842 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1843 WHERE c.id = $contributionId";
1845 $dao = CRM_Core_DAO
::executeQuery($query);
1846 $componentDetails = array();
1848 while ($dao->fetch()) {
1849 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1850 $componentDetails['contact_id'] = $dao->contact_id
;
1851 if ($dao->event_id
) {
1852 $componentDetails['event'] = $dao->event_id
;
1854 if ($dao->participant_id
) {
1855 $componentDetails['participant'] = $dao->participant_id
;
1857 if ($dao->membership_id
) {
1858 if (!isset($componentDetails['membership'])) {
1859 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1861 $componentDetails['membership'][] = $dao->membership_id
;
1862 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1864 if ($dao->pledge_payment_id
) {
1865 $pledgePayment[] = $dao->pledge_payment_id
;
1867 if ($dao->contribution_recur_id
) {
1868 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1872 if ($pledgePayment) {
1873 $componentDetails['pledge_payment'] = $pledgePayment;
1876 return $componentDetails;
1880 * @param int $contactId
1881 * @param bool $includeSoftCredit
1883 * @return null|string
1885 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1889 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1891 $contactContributionsSQL = "
1892 SELECT contribution.id AS id
1893 FROM civicrm_contribution contribution
1894 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution'
1895 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
1896 AND contribution.financial_type_id IN (" . implode(',' , array_keys($financialTypes)) . ")
1897 AND i.financial_type_id IN (" . implode(',' , array_keys($financialTypes)) . ") ";
1899 $contactSoftCreditContributionsSQL = "
1900 SELECT contribution.id
1901 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1902 ON ( contribution.id = softContribution.contribution_id )
1903 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1904 $query = "SELECT count( x.id ) count FROM ( ";
1905 $query .= $contactContributionsSQL;
1907 if ($includeSoftCredit) {
1908 $query .= " UNION ";
1909 $query .= $contactSoftCreditContributionsSQL;
1914 return CRM_Core_DAO
::singleValueQuery($query);
1918 * Repeat a transaction as part of a recurring series.
1920 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
1921 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
1922 * subsequent call to the contribution.completetransaction api.
1924 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
1926 * @param CRM_Contribute_BAO_Contribution $contribution
1927 * @param array $input
1928 * @param array $contributionParams
1932 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
1933 if (!empty($contribution->id
)) {
1936 if (empty($contribution->id
)) {
1937 // Unclear why this would only be set for repeats.
1938 if (!empty($input['amount'])) {
1939 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
1941 $templateContribution = civicrm_api3('Contribution', 'getsingle', array(
1942 'contribution_recur_id' => $contributionParams['contribution_recur_id'],
1943 'options' => array('limit' => 1),
1945 $contributionParams['skipLineItem'] = TRUE;
1946 $contributionParams['status_id'] = 'Pending';
1947 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
1948 $contributionParams['contact_id'] = $templateContribution['contact_id'];
1949 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
1950 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
1951 $contribution->id
= $createContribution['id'];
1952 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
1953 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
1959 * Get individual id for onbehalf contribution.
1961 * @param int $contributionId
1963 * @param int $contributorId
1967 * containing organization id and individual id
1969 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1973 if (!$contributionId) {
1977 // fetch contributor id if null
1978 if (!$contributorId) {
1979 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1980 $contributionId, 'contact_id'
1984 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1985 $activityTypeId = array_search('Contribution', $activityTypeIds);
1987 if ($activityTypeId && $contributorId) {
1989 SELECT civicrm_activity_contact.contact_id
1990 FROM civicrm_activity_contact
1991 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1992 WHERE civicrm_activity.activity_type_id = %1
1993 AND civicrm_activity.source_record_id = %2
1994 AND civicrm_activity_contact.record_type_id = %3
1997 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1998 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2001 1 => array($activityTypeId, 'Integer'),
2002 2 => array($contributionId, 'Integer'),
2003 3 => array($sourceID, 'Integer'),
2006 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2008 // for on behalf contribution source is individual and contributor is organization
2009 if ($sourceContactId && $sourceContactId != $contributorId) {
2010 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2011 // get rel type id for employee of relation
2012 foreach ($relationshipTypeIds as $id => $typeVals) {
2013 if ($typeVals['name_a_b'] == 'Employee of') {
2014 $relationshipTypeId = $id;
2019 $rel = new CRM_Contact_DAO_Relationship();
2020 $rel->relationship_type_id
= $relationshipTypeId;
2021 $rel->contact_id_a
= $sourceContactId;
2022 $rel->contact_id_b
= $contributorId;
2023 if ($rel->find(TRUE)) {
2024 $ids['individual_id'] = $rel->contact_id_a
;
2025 $ids['organization_id'] = $rel->contact_id_b
;
2036 public static function getContributionDates() {
2037 $config = CRM_Core_Config
::singleton();
2038 $currentMonth = date('m');
2039 $currentDay = date('d');
2040 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2041 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2042 (int ) $config->fiscalYearStart
['d'] > $currentDay
2045 $year = date('Y') - 1;
2050 $year = array('Y' => $year);
2051 $yearDate = $config->fiscalYearStart
;
2052 $yearDate = array_merge($year, $yearDate);
2053 $yearDate = CRM_Utils_Date
::format($yearDate);
2055 $monthDate = date('Ym') . '01';
2061 'yearDate' => $yearDate,
2062 'monthDate' => $monthDate,
2067 * Load objects relations to contribution object.
2068 * Objects are stored in the $_relatedObjects property
2069 * In the first instance we are just moving functionality from BASEIpn -
2070 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2072 * Note that the unit test for the BaseIPN class tests this function
2074 * @param array $input
2075 * Input as delivered from Payment Processor.
2077 * Ids as Loaded by Payment Processor.
2078 * @param bool $loadAll
2079 * Load all related objects - even where id not passed in? (allows API to call this).
2084 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2086 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2087 if (empty($ids['contact']) && isset($this->contact_id
)) {
2088 $ids['contact'] = $this->contact_id
;
2091 if (empty($this->_component
)) {
2092 if (!empty($ids['event'])) {
2093 $this->_component
= 'event';
2096 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2100 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2101 // refactoring than anything else, and has unit test coverage.
2102 if (empty($this->financial_type_id
)) {
2106 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2111 if (!$paymentProcessorID && $this->contribution_page_id
) {
2112 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2113 $this->contribution_page_id
,
2116 if ($paymentProcessorID) {
2117 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2121 $ids['contributionType'] = $this->financial_type_id
;
2122 $ids['financialType'] = $this->financial_type_id
;
2125 'contact' => 'CRM_Contact_BAO_Contact',
2126 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2127 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2128 'financialType' => 'CRM_Financial_BAO_FinancialType',
2130 foreach ($entities as $entity => $bao) {
2131 if (!empty($ids[$entity])) {
2132 $this->_relatedObjects
[$entity] = new $bao();
2133 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2134 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2135 throw new CRM_Core_Exception($entity . ' could not be loaded');
2140 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2141 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2144 if (!empty($ids['pledge_payment'])) {
2145 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2146 if (empty($paymentID)) {
2149 $payment = new CRM_Pledge_BAO_PledgePayment();
2150 $payment->id
= $paymentID;
2151 if (!$payment->find(TRUE)) {
2152 throw new Exception("Could not find pledge payment record: " . $paymentID);
2154 $this->_relatedObjects
['pledge_payment'][] = $payment;
2158 if ($this->_component
== 'contribute') {
2159 // retrieve the other optional objects first so
2160 // stuff down the line can use this info and do things
2162 //in any case get the memberships associated with the contribution
2163 //because we now support multiple memberships w/ price set
2164 // see if there are any other memberships to be considered for same contribution.
2166 SELECT membership_id
2167 FROM civicrm_membership_payment
2168 WHERE contribution_id = %1 ";
2169 $params = array(1 => array($this->id
, 'Integer'));
2171 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2172 while ($dao->fetch()) {
2173 if ($dao->membership_id
) {
2174 if (!is_array($ids['membership'])) {
2175 $ids['membership'] = array();
2177 $ids['membership'][] = $dao->membership_id
;
2181 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2182 foreach ($ids['membership'] as $id) {
2184 $membership = new CRM_Member_BAO_Membership();
2185 $membership->id
= $id;
2186 if (!$membership->find(TRUE)) {
2187 throw new Exception("Could not find membership record: $id");
2189 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2190 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2191 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2192 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2193 $membership->free();
2199 // we are in event mode
2200 // make sure event exists and is valid
2201 $event = new CRM_Event_BAO_Event();
2202 $event->id
= $ids['event'];
2203 if ($ids['event'] &&
2206 throw new Exception("Could not find event: " . $ids['event']);
2209 $this->_relatedObjects
['event'] = &$event;
2211 $participant = new CRM_Event_BAO_Participant();
2212 $participant->id
= $ids['participant'];
2213 if ($ids['participant'] &&
2214 !$participant->find(TRUE)
2216 throw new Exception("Could not find participant: " . $ids['participant']);
2218 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2220 $this->_relatedObjects
['participant'] = &$participant;
2222 // get the payment processor id from event - this is inaccurate see CRM-16923
2223 // in future we should look at throwing an exception here rather than an dubious guess.
2224 if (!$paymentProcessorID) {
2225 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2226 if ($paymentProcessorID) {
2227 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2232 if ($paymentProcessorID) {
2233 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2234 $this->is_test ?
'test' : 'live'
2236 $ids['paymentProcessor'] = $paymentProcessorID;
2237 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2243 * Create array of message information - ie. return html version, txt version, to field
2245 * @param array $input
2246 * Incoming information.
2247 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2248 * just check presence of recur object but maintaining legacy approach
2251 * IDs of related objects.
2252 * @param array $values
2253 * Any values that may have already been compiled by calling process.
2254 * This is augmented by values 'gathered' by gatherMessageValues
2255 * @param bool $recur
2256 * @param bool $returnMessageText
2257 * Distinguishes between whether to send message or return.
2258 * message text. We are working towards this function ALWAYS returning message text & calling
2259 * function doing emails / pdfs with it
2265 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2266 $this->loadRelatedObjects($input, $ids);
2268 if (empty($this->_component
)) {
2269 $this->_component
= CRM_Utils_Array
::value('component', $input);
2272 //not really sure what params might be passed in but lets merge em into values
2273 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2274 $template = CRM_Core_Smarty
::singleton();
2275 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2276 //what does recur 'mean here - to do with payment processor return functionality but
2277 // what is the importance
2278 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2279 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2281 $entityID = $entity = NULL;
2282 if (isset($ids['contribution'])) {
2283 $entity = 'contribution';
2284 $entityID = $ids['contribution'];
2286 if (!empty($ids['membership'])) {
2287 //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
2288 // 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
2289 // line having loaded an array
2290 $ids['membership'] = (array) $ids['membership'];
2291 $entity = 'membership';
2292 $entityID = $ids['membership'][0];
2295 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity));
2296 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2297 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2299 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2300 //direct mode showing billing block, so use directIPN for temporary
2301 $template->assign('contributeMode', 'directIPN');
2304 // todo remove strtolower - check consistency
2305 if (strtolower($this->_component
) == 'event') {
2306 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2307 $values['event'] = array();
2309 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2311 //get location details
2312 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2313 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2315 $ufJoinParams = array(
2316 'entity_table' => 'civicrm_event',
2317 'entity_id' => $ids['event'],
2318 'module' => 'CiviEvent',
2321 list($custom_pre_id,
2323 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2325 $values['custom_pre_id'] = $custom_pre_id;
2326 $values['custom_post_id'] = $custom_post_ids;
2327 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
2328 //and cases involving status updation through ipn
2329 // whatever that means!
2330 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2331 // perhaps we should throw an e-notice if amount is set & force total_amount?
2332 if (!empty($input['amount'])) {
2333 $values['totalAmount'] = $input['amount'];
2336 if ($values['event']['is_email_confirm']) {
2337 $values['is_email_receipt'] = 1;
2339 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2340 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2344 $values['contribution_id'] = $this->id
;
2345 if (!empty($ids['related_contact'])) {
2346 $values['related_contact'] = $ids['related_contact'];
2347 if (isset($ids['onbehalf_dupe_alert'])) {
2348 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2350 $entityBlock = array(
2351 'contact_id' => $ids['contact'],
2352 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2353 'Home', 'id', 'name'
2356 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2357 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2360 if ($this->is_test
) {
2363 if (!empty($this->_relatedObjects
['membership'])) {
2364 foreach ($this->_relatedObjects
['membership'] as $membership) {
2365 if ($membership->id
) {
2366 $values['isMembership'] = TRUE;
2368 // need to set the membership values here
2369 $template->assign('membership_assign', 1);
2370 $template->assign('membership_name',
2371 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2373 $template->assign('mem_start_date', $membership->start_date
);
2374 $template->assign('mem_join_date', $membership->join_date
);
2375 $template->assign('mem_end_date', $membership->end_date
);
2376 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2377 $template->assign('mem_status', $membership_status);
2378 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2379 $template->assign('is_pay_later', 1);
2382 // if separate payment there are two contributions recorded and the
2383 // admin will need to send a receipt for each of them separately.
2384 // we dont link the two in the db (but can potentially infer it if needed)
2385 $template->assign('is_separate_payment', 0);
2387 if ($recur && $paymentObject) {
2388 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2389 $template->assign('cancelSubscriptionUrl', $url);
2390 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2391 $template->assign('updateSubscriptionBillingUrl', $url);
2392 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2393 $template->assign('updateSubscriptionUrl', $url);
2396 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2399 // otherwise if its about sending emails, continue sending without return, as we
2400 // don't want to exit the loop.
2405 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2411 * Gather values for contribution mail - this function has been created
2412 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2413 * Values related to the contribution in question are gathered
2415 * @param array $input
2416 * Input into function (probably from payment processor).
2417 * @param array $values
2419 * The set of ids related to the input.
2423 public function _gatherMessageValues($input, &$values, $ids = array()) {
2424 // set display address of contributor
2425 if ($this->address_id
) {
2426 $addressParams = array('id' => $this->address_id
);
2427 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2428 $addressDetails = array_values($addressDetails);
2429 $values['address'] = $addressDetails[0]['display'];
2431 if ($this->_component
== 'contribute') {
2432 //get soft contributions
2433 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2434 if (!empty($softContributions)) {
2435 $values['softContributions'] = $softContributions['soft_credit'];
2437 if (isset($this->contribution_page_id
)) {
2438 CRM_Contribute_BAO_ContributionPage
::setValues(
2439 $this->contribution_page_id
,
2442 if ($this->contribution_page_id
) {
2443 // CRM-8254 - override default currency if applicable
2444 $config = CRM_Core_Config
::singleton();
2445 $config->defaultCurrency
= CRM_Utils_Array
::value(
2448 $config->defaultCurrency
2452 // no contribution page -probably back office
2454 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2455 $values['is_email_receipt'] = 1;
2456 $values['title'] = 'Contribution';
2458 // set lineItem for contribution
2460 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2461 if (!empty($lineItem)) {
2462 $itemId = key($lineItem);
2463 foreach ($lineItem as &$eachItem) {
2464 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2465 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2466 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2467 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2470 $values['lineItem'][0] = $lineItem;
2471 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2475 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2479 // if this is onbehalf of contribution then set related contact
2480 if (!empty($relatedContact['individual_id'])) {
2481 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2486 $eventParams = array(
2487 'id' => $this->_relatedObjects
['event']->id
,
2489 $values['event'] = array();
2491 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2492 // add custom fields for event
2493 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2495 $eventCustomGroup = array();
2496 foreach ($eventGroupTree as $key => $group) {
2497 if ($key === 'info') {
2501 foreach ($group['fields'] as $k => $customField) {
2502 $groupLabel = $group['title'];
2503 if (!empty($customField['customValue'])) {
2504 foreach ($customField['customValue'] as $customFieldValues) {
2505 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2510 $values['event']['customGroup'] = $eventCustomGroup;
2512 //get participant details
2513 $participantParams = array(
2514 'id' => $this->_relatedObjects
['participant']->id
,
2517 $values['participant'] = array();
2519 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2520 // add custom fields for event
2521 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2522 $participantCustomGroup = array();
2523 foreach ($participantGroupTree as $key => $group) {
2524 if ($key === 'info') {
2528 foreach ($group['fields'] as $k => $customField) {
2529 $groupLabel = $group['title'];
2530 if (!empty($customField['customValue'])) {
2531 foreach ($customField['customValue'] as $customFieldValues) {
2532 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2537 $values['participant']['customGroup'] = $participantCustomGroup;
2539 //get location details
2540 $locationParams = array(
2541 'entity_id' => $this->_relatedObjects
['event']->id
,
2542 'entity_table' => 'civicrm_event',
2544 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2546 $ufJoinParams = array(
2547 'entity_table' => 'civicrm_event',
2548 'entity_id' => $ids['event'],
2549 'module' => 'CiviEvent',
2552 list($custom_pre_id,
2554 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2556 $values['custom_pre_id'] = $custom_pre_id;
2557 $values['custom_post_id'] = $custom_post_ids;
2559 // set lineItem for event contribution
2561 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2562 if (!empty($participantIds)) {
2563 foreach ($participantIds as $pIDs) {
2564 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2565 if (!CRM_Utils_System
::isNull($lineItem)) {
2566 $values['lineItem'][] = $lineItem;
2573 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2575 $customGroup = array();
2576 foreach ($groupTree as $key => $group) {
2577 if ($key === 'info') {
2581 foreach ($group['fields'] as $k => $customField) {
2582 $groupLabel = $group['title'];
2583 if (!empty($customField['customValue'])) {
2584 foreach ($customField['customValue'] as $customFieldValues) {
2585 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2590 $values['customGroup'] = $customGroup;
2596 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2597 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2598 * Note we send directly from this function in some cases because it is only partly refactored
2599 * Don't call this function directly as the signature will change
2603 * @param CRM_Core_SMARTY $template
2604 * @param bool $recur
2605 * @param bool $returnMessageText
2609 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2610 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2611 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2612 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2613 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2614 $template->assign('useForMember', TRUE);
2616 //assign honor information to receipt message
2617 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2619 if (isset($softRecord['soft_credit'])) {
2620 //if id of contribution page is present
2621 if (!empty($values['id'])) {
2622 $values['honor'] = array(
2623 'honor_profile_values' => array(),
2624 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2625 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2627 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2629 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2630 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2633 //offline contribution
2634 $softCreditTypes = $softCredits = array();
2635 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2636 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2637 $softCredits[$key] = array(
2638 'Name' => $softCredit['contact_name'],
2639 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2642 $template->assign('softCreditTypes', $softCreditTypes);
2643 $template->assign('softCredits', $softCredits);
2647 $dao = new CRM_Contribute_DAO_ContributionProduct();
2648 $dao->contribution_id
= $this->id
;
2649 if ($dao->find(TRUE)) {
2650 $premiumId = $dao->product_id
;
2651 $template->assign('option', $dao->product_option
);
2653 $productDAO = new CRM_Contribute_DAO_Product();
2654 $productDAO->id
= $premiumId;
2655 $productDAO->find(TRUE);
2656 $template->assign('selectPremium', TRUE);
2657 $template->assign('product_name', $productDAO->name
);
2658 $template->assign('price', $productDAO->price
);
2659 $template->assign('sku', $productDAO->sku
);
2661 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2662 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2663 if (empty($amount) && isset($this->total_amount
)) {
2664 $amount = $this->total_amount
;
2666 $template->assign('amount', $amount);
2667 // add the new contribution values
2668 if (strtolower($this->_component
) == 'contribute') {
2670 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2671 $softDAO->contribution_id
= $this->id
;
2672 if ($softDAO->find(TRUE)) {
2673 $template->assign('pcpBlock', TRUE);
2674 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2675 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2676 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2678 //assign the pcp page title for email subject
2679 $pcpDAO = new CRM_PCP_DAO_PCP();
2680 $pcpDAO->id
= $softDAO->pcp_id
;
2681 if ($pcpDAO->find(TRUE)) {
2682 $template->assign('title', $pcpDAO->title
);
2687 if ($this->financial_type_id
) {
2688 $values['financial_type_id'] = $this->financial_type_id
;
2691 $template->assign('trxn_id', $this->trxn_id
);
2692 $template->assign('receive_date',
2693 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2695 $template->assign('contributeMode', 'notify');
2696 $template->assign('action', $this->is_test ?
1024 : 1);
2697 $template->assign('receipt_text',
2698 CRM_Utils_Array
::value('receipt_text',
2702 $template->assign('is_monetary', 1);
2703 $template->assign('is_recur', (bool) $recur);
2704 $template->assign('currency', $this->currency
);
2705 $template->assign('address', CRM_Utils_Address
::format($input));
2706 if (!empty($values['customGroup'])) {
2707 $template->assign('customGroup', $values['customGroup']);
2709 if (!empty($values['softContributions'])) {
2710 $template->assign('softContributions', $values['softContributions']);
2712 if ($this->_component
== 'event') {
2713 $template->assign('title', $values['event']['title']);
2714 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2715 $viewRoles = array();
2716 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2717 $viewRoles[] = $participantRoles[$v];
2719 $values['event']['participant_role'] = implode(', ', $viewRoles);
2720 $template->assign('event', $values['event']);
2721 $template->assign('participant', $values['participant']);
2722 $template->assign('location', $values['location']);
2723 $template->assign('customPre', $values['custom_pre_id']);
2724 $template->assign('customPost', $values['custom_post_id']);
2727 if ($this->_relatedObjects
['participant']->is_test
) {
2731 $values['params'] = array();
2732 //to get email of primary participant.
2733 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2734 $primaryAmount[] = array(
2735 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2736 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2738 //build an array of cId/pId of participants
2739 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2740 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2741 //send receipt to additional participant if exists
2742 if (count($additionalIDs)) {
2743 $template->assign('isPrimary', 0);
2744 $template->assign('customProfile', NULL);
2745 //set additionalParticipant true
2746 $values['params']['additionalParticipant'] = TRUE;
2747 foreach ($additionalIDs as $pId => $cId) {
2749 //to change the status pending to completed
2750 $additional = new CRM_Event_DAO_Participant();
2751 $additional->id
= $pId;
2752 $additional->contact_id
= $cId;
2753 $additional->find(TRUE);
2754 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2755 $additional->status_id
= 1;
2756 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2757 //if additional participant dont have email
2759 if (!$additionalParticipantInfo) {
2760 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2762 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2763 $primaryAmount[] = array(
2764 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2765 'amount' => $additional->fee_amount
,
2767 $additional->save();
2768 $additional->free();
2769 $template->assign('amount', $amount);
2770 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2774 //build an array of custom profile and assigning it to template
2775 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2777 if (count($customProfile)) {
2778 $template->assign('customProfile', $customProfile);
2781 // for primary contact
2782 $values['params']['additionalParticipant'] = FALSE;
2783 $template->assign('isPrimary', 1);
2784 $template->assign('amount', $primaryAmount);
2785 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2786 if ($this->payment_instrument_id
) {
2787 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2788 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2790 // carry paylater, since we did not created billing,
2791 // so need to pull email from primary location, CRM-4395
2792 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2798 * Check whether payment processor supports
2799 * cancellation of contribution subscription
2801 * @param int $contributionId
2804 * @param bool $isNotCancelled
2808 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2809 $cacheKeyString = "$contributionId";
2810 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2812 static $supportsCancel = array();
2814 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2815 $supportsCancel[$cacheKeyString] = FALSE;
2816 $isCancelled = FALSE;
2818 if ($isNotCancelled) {
2819 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2822 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2823 if (!empty($paymentObject)) {
2824 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2827 return $supportsCancel[$cacheKeyString];
2831 * Check whether subscription is already cancelled.
2833 * @param int $contributionId
2837 * contribution status
2839 public static function isSubscriptionCancelled($contributionId) {
2841 SELECT cr.contribution_status_id
2842 FROM civicrm_contribution_recur cr
2843 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2844 WHERE con.id = %1 LIMIT 1";
2845 $params = array(1 => array($contributionId, 'Integer'));
2846 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2847 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2848 if ($status == 'Cancelled') {
2855 * Create all financial accounts entry.
2857 * @param array $params
2858 * Contribution object, line item array and params for trxn.
2861 * @param array $financialTrxnValues
2863 * @return null|object
2865 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2866 $skipRecords = $update = $return = $isRelatedId = FALSE;
2868 $additionalParticipantId = array();
2869 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2871 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2872 $entityId = $params['participant_id'];
2873 $entityTable = 'civicrm_participant';
2874 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2876 elseif (!empty($params['membership_id'])) {
2877 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2878 // are created off one contribution should be handled elsewhere
2879 $entityId = $params['membership_id'];
2880 $entityTable = 'civicrm_membership';
2883 $entityId = $params['contribution']->id
;
2884 $entityTable = 'civicrm_contribution';
2887 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2888 $isRelatedId = TRUE;
2891 $entityID[] = $entityId;
2892 if (!empty($additionalParticipantId)) {
2893 $entityID +
= $additionalParticipantId;
2895 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2896 if (empty($params['prevContribution'])) {
2903 $statusId = $params['contribution']->contribution_status_id
;
2904 // CRM-13964 partial payment
2905 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2906 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2908 $partialAmtPay = $params['partial_amount_pay'];
2909 $partialAmtTotal = $params['partial_payment_total'];
2911 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2912 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2913 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2914 $params['total_amount'] = $partialAmtPay;
2916 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2917 if (empty($balanceTrxnInfo['trxn_id'])) {
2918 // create new balance transaction record
2919 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2920 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2922 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2923 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2924 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2925 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2926 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2927 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2928 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2929 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2930 $balanceTrxnParams['status_id'] = $statusId;
2931 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2932 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2933 if (!empty($params['payment_processor'])) {
2934 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2936 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2940 // build line item array if its not set in $params
2941 if (empty($params['line_item']) ||
$additionalParticipantId) {
2942 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2945 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2946 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2948 $skipRecords = TRUE;
2949 $pendingStatus = array(
2950 array_search('Pending', $contributionStatuses),
2951 array_search('In Progress', $contributionStatuses),
2953 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2954 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2955 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2957 elseif (!empty($params['payment_processor'])) {
2958 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2960 elseif (!empty($params['payment_instrument_id'])) {
2961 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2964 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2965 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2966 $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);
2969 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2970 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2971 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2974 //build financial transaction params
2975 $trxnParams = array(
2976 'contribution_id' => $params['contribution']->id
,
2977 'to_financial_account_id' => $params['to_financial_account_id'],
2978 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2979 'total_amount' => $totalAmount,
2980 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2981 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2982 'currency' => $params['contribution']->currency
,
2983 'trxn_id' => $params['contribution']->trxn_id
,
2984 'status_id' => $statusId,
2985 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2986 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2989 if (!empty($params['payment_processor'])) {
2990 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2993 if (isset($fromFinancialAccountId)) {
2994 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2997 // consider external values passed for recording transaction entry
2998 if (!empty($financialTrxnValues)) {
2999 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3002 $params['trxnParams'] = $trxnParams;
3004 if (!empty($params['prevContribution'])) {
3005 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3006 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3007 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3008 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3009 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3011 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3012 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3013 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3015 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3016 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3019 //if financial type is changed
3020 if (!empty($params['financial_type_id']) &&
3021 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3023 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3024 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3025 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3026 if ($oldFinancialAccount != $newFinancialAccount) {
3027 $params['total_amount'] = 0;
3028 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3029 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3030 $params['prevContribution']->financial_type_id
, $relationTypeId);
3033 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3034 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3035 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3038 self
::updateFinancialAccounts($params, 'changeFinancialType');
3039 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3040 $params['financial_account_id'] = $newFinancialAccount;
3041 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3042 self
::updateFinancialAccounts($params);
3043 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3047 //Update contribution status
3048 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3049 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3050 if (!empty($params['contribution_status_id']) &&
3051 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3053 //Update Financial Records
3054 self
::updateFinancialAccounts($params, 'changedStatus');
3057 // change Payment Instrument for a Completed contribution
3058 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3059 // instrument is null and now new payment instrument is added along with the payment
3060 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3061 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3062 if (array_key_exists('payment_instrument_id', $params)) {
3063 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3064 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3065 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3067 //check if status is changed from Pending to Completed
3068 // do not update payment instrument changes for Pending to Completed
3069 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3070 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3072 // for all other statuses create new financial records
3073 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3074 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3075 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3078 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3079 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3080 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3082 // for any other payment instrument changes create new financial records
3083 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3084 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3085 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3087 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3088 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3090 // another special case when check number is changed, create new financial records
3091 // create financial trxn with negative amount
3092 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3093 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3094 // create financial trxn with positive amount
3095 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3096 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3097 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3101 //if Change contribution amount
3102 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3103 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3104 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3105 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3106 if (isset($totalAmount) &&
3107 $totalAmount != $params['prevContribution']->total_amount
3109 //Update Financial Records
3110 $params['trxnParams']['from_financial_account_id'] = NULL;
3111 self
::updateFinancialAccounts($params, 'changedAmount');
3116 // records finanical trxn and entity financial trxn
3117 // also make it available as return value
3118 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3119 $params['entity_id'] = $financialTxn->id
;
3122 // record line items and financial items
3123 if (empty($params['skipLineItem'])) {
3124 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3127 // create batch entry if batch_id is passed and
3128 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3129 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3130 $entityParams = array(
3131 'batch_id' => $params['batch_id'],
3132 'entity_table' => 'civicrm_financial_trxn',
3133 'entity_id' => $financialTxn->id
,
3135 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3138 // when a fee is charged
3139 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3140 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3143 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3144 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3146 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3147 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3148 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3150 unset($params['line_item']);
3156 * Update all financial accounts entry.
3158 * @param array $params
3159 * Contribution object, line item array and params for trxn.
3161 * @param string $context
3164 * @param null $skipTrxn
3167 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3168 $itemAmount = $trxnID = NULL;
3169 //get all the statuses
3170 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3171 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3172 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3173 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3174 && $context == 'changePaymentInstrument'
3178 if (($params['prevContribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus))
3179 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3180 && $context == 'changedStatus'
3184 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3185 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3187 if ($context == 'changedStatus') {
3188 //get all the statuses
3189 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3191 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3192 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3193 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3195 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3197 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3198 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3200 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3201 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3202 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3204 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3205 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3206 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3209 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3212 $itemAmount = $params['trxnParams']['total_amount'];
3214 elseif ($context == 'changePaymentInstrument') {
3215 if ($params['trxnParams']['total_amount'] < 0) {
3216 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3217 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3218 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3219 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3223 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3224 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3227 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3228 $params['entity_id'] = $trxn->id
;
3230 if ($context == 'changedStatus') {
3231 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3232 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3233 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3235 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3236 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3238 $entityParams = array(
3239 'entity_table' => 'civicrm_financial_item',
3240 'financial_trxn_id' => $trxn->id
,
3242 if (empty($params['line_item'])) {
3244 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3245 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3246 // & this can be removed
3249 foreach ($params['line_item'] as $fieldId => $fields) {
3250 foreach ($fields as $fieldValueId => $fieldValues) {
3252 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3253 2 => array($fieldValues['id'], 'Integer'),
3255 CRM_Core_DAO
::executeQuery($query, $fparams);
3257 1 => array($fieldValues['id'], 'Integer'),
3259 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3260 while ($financialItem->fetch()) {
3261 $entityParams['entity_id'] = $financialItem->id
;
3262 $entityParams['amount'] = $financialItem->amount
;
3263 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3270 if ($context != 'changePaymentInstrument') {
3271 $itemParams['entity_table'] = 'civicrm_line_item';
3272 $trxnIds['id'] = $params['entity_id'];
3273 foreach ($params['line_item'] as $fieldId => $fields) {
3274 foreach ($fields as $fieldValueId => $fieldValues) {
3275 $prevParams['entity_id'] = $fieldValues['id'];
3276 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3278 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3279 if ($params['contribution']->receive_date
) {
3280 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3283 $financialAccount = $prevfinancialItem->financial_account_id
;
3284 if (!empty($params['financial_account_id'])) {
3285 $financialAccount = $params['financial_account_id'];
3288 $currency = $params['prevContribution']->currency
;
3289 if ($params['contribution']->currency
) {
3290 $currency = $params['contribution']->currency
;
3293 if (!empty($params['is_quick_config'])) {
3294 $amount = $itemAmount;
3296 $amount = $params['total_amount'];
3300 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3301 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3305 $amount = $diff * $fieldValues['line_total'];
3308 $itemParams = array(
3309 'transaction_date' => $receiveDate,
3310 'contact_id' => $params['prevContribution']->contact_id
,
3311 'currency' => $currency,
3312 'amount' => $amount,
3313 'description' => $prevfinancialItem->description
,
3314 'status_id' => $prevfinancialItem->status_id
,
3315 'financial_account_id' => $financialAccount,
3316 'entity_table' => 'civicrm_line_item',
3317 'entity_id' => $fieldValues['id'],
3319 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3321 if ($fieldValues['tax_amount']) {
3322 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3323 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3324 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3325 $itemParams['description'] = $taxTerm;
3326 if ($fieldValues['financial_type_id']) {
3327 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3329 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3334 if ($context == 'changeFinancialType') {
3335 $params['skipLineItem'] = FALSE;
3336 foreach ($params['line_item'] as &$lineItems) {
3337 foreach ($lineItems as &$line) {
3338 $line['financial_type_id'] = $params['financial_type_id'];
3345 * Check status validation on update of a contribution.
3347 * @param array $values
3348 * Previous form values before submit.
3350 * @param array $fields
3351 * The input form values.
3353 * @param array $errors
3358 public static function checkStatusValidation($values, &$fields, &$errors) {
3359 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3360 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3361 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3365 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3366 $checkStatus = array(
3367 'Cancelled' => array('Completed', 'Refunded'),
3368 'Completed' => array('Cancelled', 'Refunded'),
3369 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3370 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3371 'Refunded' => array('Cancelled', 'Completed'),
3372 'Partially paid' => array('Completed'),
3375 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3376 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3377 1 => $contributionStatuses[$values['contribution_status_id']],
3378 2 => $contributionStatuses[$fields['contribution_status_id']],
3384 * Delete contribution of contact.
3388 * @param int $contactId
3392 public static function deleteContactContribution($contactId) {
3393 $contribution = new CRM_Contribute_DAO_Contribution();
3394 $contribution->contact_id
= $contactId;
3395 $contribution->find();
3396 while ($contribution->fetch()) {
3397 self
::deleteContribution($contribution->id
);
3402 * Get options for a given contribution field.
3403 * @see CRM_Core_DAO::buildOptions
3405 * @param string $fieldName
3406 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3407 * @param array $props whatever is known about this dao object.
3409 * @return array|bool
3411 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3412 $className = __CLASS__
;
3414 switch ($fieldName) {
3415 // This field is not part of this object but the api supports it
3416 case 'payment_processor':
3417 $className = 'CRM_Contribute_BAO_ContributionPage';
3418 // Filter results by contribution page
3419 if (!empty($props['contribution_page_id'])) {
3420 $page = civicrm_api('contribution_page', 'getsingle', array(
3422 'id' => ($props['contribution_page_id']),
3424 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3425 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3429 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3430 case 'honor_type_id':
3431 $className = 'CRM_Contribute_BAO_ContributionSoft';
3432 $fieldName = 'soft_credit_type_id';
3433 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3436 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3440 * Validate financial type.
3444 * @param int $financialTypeId
3445 * Financial Type id.
3447 * @param string $relationName
3449 * @return array|bool
3451 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3452 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3453 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3455 if (!$financialAccount) {
3456 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3463 * Function to record additional payment for partial and refund contributions.
3465 * @param int $contributionId
3466 * is the invoice contribution id (got created after processing participant payment).
3467 * @param array $trxnsData
3468 * to take user provided input of transaction details.
3469 * @param string $paymentType
3470 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3471 * @param int $participantId
3473 * @return null|object
3475 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3476 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3477 $getInfoOf['id'] = $contributionId;
3478 $defaults = array();
3479 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3481 if ($paymentType == 'owed') {
3482 // build params for recording financial trxn entry
3483 $params['contribution'] = $contributionDAO;
3484 $params = array_merge($defaults, $params);
3485 $params['skipLineItem'] = TRUE;
3486 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3487 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3488 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3489 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3492 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3493 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3494 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3496 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3497 if (!empty($trxnId)) {
3498 $trxnId = $trxnId['trxn_id'];
3500 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3501 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3504 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3505 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3506 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3510 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3511 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3512 FROM civicrm_financial_trxn ft
3513 LEFT JOIN civicrm_entity_financial_trxn eft
3514 ON (ft.id = eft.financial_trxn_id)
3515 WHERE eft.entity_table = 'civicrm_contribution'
3516 AND eft.entity_id = {$contributionId}
3517 AND ft.to_financial_account_id != {$toFinancialAccount}
3518 AND ft.status_id = {$statusId}
3520 $query = CRM_Core_DAO
::executeQuery($sql);
3522 $sumOfPayments = $query->sum_of_payments
;
3525 if ($contributionDAO->total_amount
== $sumOfPayments) {
3526 // update contribution status and
3527 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3528 $contributionDAO->contribution_status_id
= $statusId;
3529 $contributionDAO->cancel_date
= 'null';
3530 $contributionDAO->cancel_reason
= NULL;
3531 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3532 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3533 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3534 $contributionDAO->save();
3536 //Change status of financial record too
3537 $financialTrxn->status_id
= $statusId;
3538 $financialTrxn->save();
3540 // note : not using the self::add method,
3541 // the reason because it performs 'status change' related code execution for financial records
3542 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3543 // are coded below i.e. just updating financial_item status to 'Paid'
3545 if ($participantId) {
3546 // update participant status
3547 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3548 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3549 foreach ($ids as $val) {
3550 $participantUpdate['id'] = $val;
3551 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3552 CRM_Event_BAO_Participant
::add($participantUpdate);
3556 // update financial item statuses
3557 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3558 $paidStatus = array_search('Paid', $financialItemStatus);
3560 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3561 $sqlFinancialItemUpdate = "
3562 UPDATE civicrm_financial_item fi
3563 LEFT JOIN civicrm_entity_financial_trxn eft
3564 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3565 SET status_id = {$paidStatus}
3566 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3568 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3571 elseif ($paymentType == 'refund') {
3572 // build params for recording financial trxn entry
3573 $params['contribution'] = $contributionDAO;
3574 $params = array_merge($defaults, $params);
3575 $params['skipLineItem'] = TRUE;
3576 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3577 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3579 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3580 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3581 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3583 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3585 // note : not using the self::add method,
3586 // the reason because it performs 'status change' related code execution for financial records
3587 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3588 // are coded below i.e. just updating financial_item status to 'Paid'
3589 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3591 // add financial item entry
3592 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3593 $getLine['entity_id'] = $contributionDAO->id
;
3594 $getLine['entity_table'] = 'civicrm_contribution';
3595 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3596 if (!empty($lineItemId->id
)) {
3597 $addFinancialEntry = array(
3598 'transaction_date' => $financialTrxn->trxn_date
,
3599 'contact_id' => $contributionDAO->contact_id
,
3600 'amount' => $financialTrxn->total_amount
,
3601 'status_id' => array_search('Paid', $financialItemStatus),
3602 'entity_id' => $lineItemId->id
,
3603 'entity_table' => 'civicrm_line_item',
3605 $trxnIds['id'] = $financialTrxn->id
;
3606 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3608 if ($participantId) {
3609 // update participant status
3610 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3611 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3612 foreach ($ids as $val) {
3613 $participantUpdate['id'] = $val;
3614 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3615 CRM_Event_BAO_Participant
::add($participantUpdate);
3620 // activity creation
3621 if (!empty($financialTrxn)) {
3622 if ($participantId) {
3623 $inputParams['id'] = $participantId;
3626 $component = 'event';
3627 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3628 $entityObj = $entityObj[$participantId];
3630 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3632 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3634 return $financialTrxn;
3640 * @param $activityType
3642 * @param int $contributionId
3644 * @throws CRM_Core_Exception
3646 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3647 if ($component == 'event') {
3648 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3649 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3650 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3651 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3652 $targetCid = $entityObj->contact_id
;
3653 // source record id would be the contribution id
3654 $srcRecId = $contributionId;
3658 $activityParams = array(
3659 'source_contact_id' => $targetCid,
3660 'source_record_id' => $srcRecId,
3661 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3665 'subject' => $subject,
3666 'activity_date_time' => $date,
3667 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3671 'skipRecentView' => TRUE,
3674 // create activity with target contacts
3675 $session = CRM_Core_Session
::singleton();
3676 $id = $session->get('userID');
3678 $activityParams['source_contact_id'] = $id;
3679 $activityParams['target_contact_id'][] = $targetCid;
3681 CRM_Activity_BAO_Activity
::create($activityParams);
3685 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3689 * @param bool $getTrxnInfo
3690 * @param bool $usingLineTotal
3694 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3695 if ($component == 'event') {
3696 $entity = 'participant';
3697 $entityTable = 'civicrm_participant';
3698 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3700 if (!$contributionId) {
3701 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3702 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3703 $id = $primaryParticipantId;
3705 if (!$contributionId) {
3710 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3711 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3717 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3718 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3721 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3722 // for additional participants
3723 if ($entityTable == 'civicrm_participant') {
3724 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3726 foreach ($ids as $val) {
3727 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3731 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3735 $baseTrxnId = $total['trxn_id'];
3736 $total = $total['total_amount'];
3739 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3740 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3742 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3743 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3744 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3746 if ($paymentBalance == 0 && $contributionIsPayLater) {
3747 $paymentBalance = $total;
3750 $info['total'] = $total;
3751 $info['paid'] = $total - $paymentBalance;
3752 $info['balance'] = $paymentBalance;
3754 $info['component'] = $component;
3755 $info['payLater'] = $contributionIsPayLater;
3757 if ($getTrxnInfo && $baseTrxnId) {
3758 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3760 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3761 FROM civicrm_contribution con
3762 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3763 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3764 WHERE con.id = {$contributionId}
3767 // conditioned WHERE clause
3769 // if balance trxn exists don't include details of it in transaction info
3770 $sql .= " AND ft.id != {$baseTrxnId} ";
3772 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3774 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3775 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3776 while ($resultDAO->fetch()) {
3777 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3778 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3780 'total_amount' => $resultDAO->total_amount
,
3781 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3782 'payment_instrument' => $paidByLabel,
3783 'receive_date' => $resultDAO->trxn_date
,
3784 'trxn_id' => $resultDAO->trxn_id
,
3785 'status' => $statuses[$resultDAO->status_id
],
3787 if ($paidByName == 'Check') {
3788 $val['check_number'] = $resultDAO->check_number
;
3792 $info['transaction'] = $rows;
3798 * Get financial account id has 'Sales Tax Account is'
3799 * account relationship with financial type
3801 * @param int $financialTypeId
3803 * @return FinancialAccountId
3805 public static function getFinancialAccountId($financialTypeId) {
3806 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3807 $searchParams = array(
3808 'entity_table' => 'civicrm_financial_type',
3809 'entity_id' => $financialTypeId,
3810 'account_relationship' => $accountRel,
3813 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3815 return CRM_Utils_Array
::value('financial_account_id', $result);
3821 * @param array $params
3822 * @param bool $isLineItem
3826 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3827 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3829 // Update contribution.
3830 if (!empty($params['id'])) {
3831 $id = $params['id'];
3832 $values = $ids = array();
3833 $contrbutionParams = array('id' => $id);
3834 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3836 // To assign pervious finantial type on update of contribution
3837 if (!isset($params['financial_type_id'])) {
3838 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3840 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3841 // Assisn tax Amount on update of contrbution
3842 if (!empty($prevContributionValue->tax_amount
)) {
3843 $params['tax_amount'] = 'null';
3844 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3845 foreach ($params['line_item'] as $setID => $priceField) {
3846 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3847 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3854 // New Contrbution and update of contribution with tax rate financial type
3855 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3856 empty($params['skipLineItem']) && !$isLineItem
3858 $taxRateParams = $taxRates[$params['financial_type_id']];
3859 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3860 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3862 // Get Line Item on update of contribution
3863 if (isset($params['id'])) {
3864 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3867 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3869 foreach ($params['line_item'] as $setID => $priceField) {
3870 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3871 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3874 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3876 elseif (isset($params['api.line_item.create'])) {
3877 // Update total amount of contribution using lineItem
3878 $taxAmountArray = array();
3879 foreach ($params['api.line_item.create'] as $key => $value) {
3880 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3881 $taxRate = $taxRates[$value['financial_type_id']];
3882 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3883 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3886 $params['tax_amount'] = array_sum($taxAmountArray);
3887 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3890 // update line item of contrbution
3891 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3892 $taxRate = $taxRates[$params['financial_type_id']];
3893 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3894 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3901 * Check financial type validation on update of a contribution.
3903 * @param Integer $financialTypeId
3904 * Value of latest Financial Type.
3906 * @param Integer $contributionId
3909 * @param array $errors
3914 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3915 if (!empty($financialTypeId)) {
3916 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3917 if ($oldFinancialTypeId == $financialTypeId) {
3921 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3923 '1' => array($contributionId, 'Integer'),
3925 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3926 if ($result->N
> 1) {
3927 $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.');
3932 * Update related pledge payment payments.
3934 * This function has been refactored out of the back office contribution form and may
3935 * still overlap with other functions.
3937 * @param string $action
3938 * @param int $pledgePaymentID
3939 * @param int $contributionID
3940 * @param bool $adjustTotalAmount
3941 * @param float $total_amount
3942 * @param float $original_total_amount
3943 * @param int $contribution_status_id
3944 * @param int $original_contribution_status_id
3946 public static function updateRelatedPledge(
3952 $original_total_amount,
3953 $contribution_status_id,
3954 $original_contribution_status_id
3956 if (!$pledgePaymentID ||
$action & CRM_Core_Action
::ADD
&& !$contributionID) {
3960 if ($pledgePaymentID) {
3961 //store contribution id in payment record.
3962 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
3965 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3971 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3977 $updatePledgePaymentStatus = FALSE;
3979 // If either the status or the amount has changed we update the pledge status.
3980 if ($action & CRM_Core_Action
::ADD
) {
3981 $updatePledgePaymentStatus = TRUE;
3983 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
3984 ($original_total_amount != $total_amount))
3986 $updatePledgePaymentStatus = TRUE;
3989 if ($updatePledgePaymentStatus) {
3990 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
3991 array($pledgePaymentID),
3992 $contribution_status_id,
4001 * Compute the stats values
4003 * @param $stat either 'mode' or 'median'
4005 * @param $alias of civicrm_contribution
4007 public static function computeStats($stat, $sql, $alias = NULL) {
4008 $mode = $median = array();
4011 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4012 while ($modeDAO->fetch()) {
4013 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4014 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4023 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4024 foreach ($currencies as $currency => $val) {
4026 $where = "AND {$alias}.currency = '{$currency}'";
4027 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4031 $medianRow = floor($rowCount / 2);
4032 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4038 $medianValue = "SELECT {$alias}.total_amount as median
4040 ORDER BY median LIMIT {$medianRow},{$offset}";
4041 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4042 while ($medianValDAO->fetch()) {
4044 $midValue = $midValue +
$medianValDAO->median
;
4047 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4051 $midValue = $midValue / 2;
4052 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4063 * Complete an order.
4065 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4067 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4069 * Moving it out of the BaseIPN class is just the first step.
4071 * @param array $input
4073 * @param array $objects
4074 * @param CRM_Core_Transaction $transaction
4076 * @param CRM_Contribute_BAO_Contribution $contribution
4077 * @param bool $isRecurring
4078 * Duplication of param needs review. Only used by AuthorizeNetIPN
4079 * @param int $isFirstOrLastRecurringPayment
4080 * Deprecated param only used by AuthorizeNetIPN.
4082 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4083 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4084 // The previous details are used when calculating line items so keep it before any code that 'does something'
4085 if (!empty($contribution->id
)) {
4086 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4087 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4089 $inputContributionWhiteList = array(
4094 'payment_instrument_id',
4100 $contributionParams = array_merge(array(
4101 'contribution_status_id' => 'Completed',
4102 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4105 $participant = CRM_Utils_Array
::value('participant', $objects);
4106 $memberships = CRM_Utils_Array
::value('membership', $objects);
4107 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4108 if (!empty($recurContrib->id
)) {
4109 $contributionParams['contribution_recur_id'] = $recurContrib->id
;
4111 self
::repeatTransaction($contribution, $input, $contributionParams);
4113 if (is_numeric($memberships)) {
4114 $memberships = array($objects['membership']);
4117 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4120 if (isset($input['is_email_receipt'])) {
4121 $values['is_email_receipt'] = $input['is_email_receipt'];
4124 if ($input['component'] == 'contribute') {
4125 if ($contribution->contribution_page_id
) {
4126 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4127 $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
4129 elseif ($recurContrib && $recurContrib->id
) {
4130 $contributionParams['contribution_page_id'] = NULL;
4131 $values['amount'] = $recurContrib->amount
;
4132 $values['financial_type_id'] = $objects['contributionType']->id
;
4133 $values['title'] = $source = ts('Offline Recurring Contribution');
4134 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
4135 $values['receipt_from_name'] = $domainValues[0];
4136 $values['receipt_from_email'] = $domainValues[1];
4139 if (empty($contributionParams['receive_date']) && $changeDate) {
4140 $contributionParams['receive_date'] = $changeDate;
4143 if ($recurContrib && $recurContrib->id
&& !isset($input['is_email_receipt'])) {
4144 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4145 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4146 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4149 if (!empty($values['is_email_receipt'])) {
4150 $contributionParams['receipt_date'] = $changeDate;
4153 if (!empty($memberships)) {
4154 foreach ($memberships as $membershipTypeIdKey => $membership) {
4156 $membershipParams = array(
4157 'id' => $membership->id
,
4158 'contact_id' => $membership->contact_id
,
4159 'is_test' => $membership->is_test
,
4160 'membership_type_id' => $membership->membership_type_id
,
4163 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4164 $membershipParams['membership_type_id'],
4165 $membershipParams['is_test'],
4166 $membershipParams['id']
4169 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4170 // this picks up membership type changes during renewals
4172 SELECT membership_type_id
4173 FROM civicrm_membership_log
4174 WHERE membership_id={$membershipParams['id']}
4177 $dao = CRM_Core_DAO
::executeQuery($sql);
4178 if ($dao->fetch()) {
4179 if (!empty($dao->membership_type_id
)) {
4180 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4185 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4186 $membershipParams['membership_type_id'],
4187 $primaryContributionID
4189 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4190 if ($currentMembership) {
4192 * Fixed FOR CRM-4433
4193 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4194 * when Contribution mode is notify and membership is for renewal )
4196 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4198 // @todo - we should pass membership_type_id instead of null here but not
4199 // adding as not sure of testing
4200 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4201 $changeDate, NULL, $membershipParams['num_terms']
4204 $dates['join_date'] = $currentMembership['join_date'];
4207 //get the status for membership.
4208 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4210 $dates['join_date'],
4213 $membershipParams['membership_type_id'],
4217 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4218 //we might be renewing membership,
4219 //so make status override false.
4220 $membershipParams['is_override'] = FALSE;
4221 civicrm_api3('Membership', 'create', $membershipParams);
4223 //update related Memberships.
4224 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $membershipParams);
4230 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4231 $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id
));
4232 $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
4233 if ($eventDetail['is_email_confirm']) {
4234 // @todo this should be set by the function that sends the mail after sending.
4235 $contributionParams['receipt_date'] = $changeDate;
4237 $participantParams['id'] = $participant->id
;
4238 $participantParams['status_id'] = 'Registered';
4239 civicrm_api3('Participant', 'create', $participantParams);
4243 $contributionParams['id'] = $contribution->id
;
4245 civicrm_api3('Contribution', 'create', $contributionParams);
4247 // Add new soft credit against current $contribution.
4248 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4249 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4252 $paymentProcessorId = '';
4253 if (isset($objects['paymentProcessor'])) {
4254 if (is_array($objects['paymentProcessor'])) {
4255 $paymentProcessorId = $objects['paymentProcessor']['id'];
4258 $paymentProcessorId = $objects['paymentProcessor']->id
;
4262 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4263 'labelColumn' => 'name',
4266 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4267 $input['payment_processor'] = $paymentProcessorId;
4269 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4270 $input['total_amount'] = $input['amount'];
4271 $input['contribution'] = $contribution;
4272 $input['financial_type_id'] = $contribution->financial_type_id
;
4274 if (!empty($contribution->_relatedObjects
['participant'])) {
4275 $input['contribution_mode'] = 'participant';
4276 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4277 $input['skipLineItem'] = 1;
4279 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4280 $input['skipLineItem'] = TRUE;
4281 $input['contribution_mode'] = 'membership';
4283 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4284 // and subsequent payments. In this case the line items are created at
4285 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4286 // and since the contribution is saved prior to this line there is always a contribution-id,
4287 // however there is never a prevContribution (which appears to mean original contribution not previous
4288 // contribution - or preUpdateContributionObject most accurately)
4289 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4290 // to mean "are we updating an exisitng pending contribution"
4291 //I was able to make the unit test complete as fataling here doesn't prevent
4292 // the contribution being created - but activities would not be created or emails sent
4294 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4296 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4297 $transaction->commit();
4299 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution);
4301 // create an activity record
4302 if ($input['component'] == 'contribute') {
4304 $targetContactID = NULL;
4305 if (!empty($ids['related_contact'])) {
4306 $targetContactID = $contribution->contact_id
;
4307 $contribution->contact_id
= $ids['related_contact'];
4309 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4313 CRM_Activity_BAO_Activity
::addActivity($participant);
4316 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4317 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4318 if (!array_key_exists('is_email_receipt', $values) ||
4319 $values['is_email_receipt'] == 1
4321 self
::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
4322 CRM_Core_Error
::debug_log_message("Receipt sent");
4325 CRM_Core_Error
::debug_log_message("Success: Database updated");
4327 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4328 $isFirstOrLastRecurringPayment);
4333 * Send receipt from contribution.
4335 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4337 * Note that the compose message part has been moved to contribution
4338 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4340 * @param array $input
4341 * Incoming data from Payment processor.
4343 * Related object IDs.
4344 * @param CRM_Contribute_BAO_Contribution $contribution
4345 * @param array $values
4346 * Values related to objects that have already been loaded.
4347 * @param bool $recur
4348 * Is it part of a recurring contribution.
4349 * @param bool $returnMessageText
4350 * Should text be returned instead of sent. This.
4351 * is because the function is also used to generate pdfs
4355 public static function sendMail(&$input, &$ids, $contribution, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4356 $input['is_recur'] = $recur;
4357 // set receipt from e-mail and name in value
4358 if (!$returnMessageText) {
4359 $session = CRM_Core_Session
::singleton();
4360 $userID = $session->get('userID');
4361 if (!empty($userID)) {
4362 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4363 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4364 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4367 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);