3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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());
139 self
::calculateMissingAmountParams($params);
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;
162 if ($contributionID) {
163 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
166 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
168 $contribution = new CRM_Contribute_BAO_Contribution();
169 $contribution->copyValues($params);
171 $contribution->id
= $contributionID;
173 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
174 $config = CRM_Core_Config
::singleton();
175 $contribution->currency
= $config->defaultCurrency
;
178 if ($contributionID && $setPrevContribution) {
179 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
182 $result = $contribution->save();
184 // Add financial_trxn details as part of fix for CRM-4724
185 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
186 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
188 //add Account details
189 $params['contribution'] = $contribution;
190 self
::recordFinancialAccounts($params);
192 // reset the group contact cache for this group
193 CRM_Contact_BAO_GroupContactCache
::remove();
195 if ($contributionID) {
196 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
199 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
206 * Get defaults for new entity.
209 public static function getDefaults() {
211 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
212 FALSE, FALSE, FALSE, 'AND is_default = 1')
214 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
219 * Given the list of params in the params array, fetch the object
220 * and store the values in the values array
222 * @param array $params
223 * Input parameters to find object.
224 * @param array $values
225 * Output values of the object.
227 * The array that holds all the db ids.
229 * @return CRM_Contribute_BAO_Contribution|null
230 * The found object or null
232 public static function getValues($params, &$values, &$ids) {
233 if (empty($params)) {
236 $contribution = new CRM_Contribute_BAO_Contribution();
238 $contribution->copyValues($params);
240 if ($contribution->find(TRUE)) {
241 $ids['contribution'] = $contribution->id
;
243 CRM_Core_DAO
::storeValues($contribution, $values);
245 return $contribution;
247 $null = NULL; // return by reference
252 * Calculate net_amount & fee_amount if they are not set.
254 * Net amount should be total - fee.
255 * This should only be called for new contributions.
257 * @param array $params
258 * Params for a new contribution before they are saved.
260 public static function calculateMissingAmountParams(&$params) {
261 if (!isset($params['fee_amount'])) {
262 if (isset($params['total_amount']) && isset($params['net_amount'])) {
263 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
266 $params['fee_amount'] = 0;
269 if (!isset($params['net_amount'])) {
270 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
276 * @param $billingLocationTypeID
280 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
281 $hasBillingField = FALSE;
282 $billingFields = array(
290 //build address array
291 $addressParams = array();
292 $addressParams['location_type_id'] = $billingLocationTypeID;
293 $addressParams['is_billing'] = 1;
295 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
296 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
297 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
298 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
300 foreach ($billingFields as $value) {
301 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
302 if (!empty($addressParams[$value])) {
303 $hasBillingField = TRUE;
306 return array($hasBillingField, $addressParams);
310 * Get address params ready to be passed to the payment processor.
312 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
313 * To create an address we need state_province_id.
315 * @param array $params
316 * @param int $billingLocationTypeID
320 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
321 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
322 foreach ($addressParams as $name => $field) {
323 if (substr($name, 0, 8) == 'billing_') {
324 $addressParams[substr($name, 9)] = $addressParams[$field];
327 return array($hasBillingField, $addressParams);
331 * Get the number of terms for this contribution for a given membership type
332 * based on querying the line item table and relevant price field values
333 * Note that any one contribution should only be able to have one line item relating to a particular membership
336 * @param int $membershipTypeID
338 * @param int $contributionID
342 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
343 $numTerms = CRM_Core_DAO
::singleValueQuery("
344 SELECT membership_num_terms FROM civicrm_line_item li
345 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
346 WHERE contribution_id = %1 AND membership_type_id = %2",
347 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
349 // default of 1 is precautionary
350 return empty($numTerms) ?
1 : $numTerms;
354 * Takes an associative array and creates a contribution object.
356 * @param array $params
357 * (reference ) an assoc array of name/value pairs.
359 * The array that holds all the db ids.
361 * @return CRM_Contribute_BAO_Contribution
363 public static function create(&$params, $ids = array()) {
364 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
365 foreach ($dateFields as $df) {
366 if (isset($params[$df])) {
367 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
371 $transaction = new CRM_Core_Transaction();
373 $contribution = self
::add($params, $ids);
375 if (is_a($contribution, 'CRM_Core_Error')) {
376 $transaction->rollback();
377 return $contribution;
380 $params['contribution_id'] = $contribution->id
;
382 if (!empty($params['custom']) &&
383 is_array($params['custom'])
385 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
388 $session = CRM_Core_Session
::singleton();
390 if (!empty($params['note'])) {
392 'entity_table' => 'civicrm_contribution',
393 'note' => $params['note'],
394 'entity_id' => $contribution->id
,
395 'contact_id' => $session->get('userID'),
396 'modified_date' => date('Ymd'),
398 if (!$noteParams['contact_id']) {
399 $noteParams['contact_id'] = $params['contact_id'];
401 CRM_Core_BAO_Note
::add($noteParams);
404 // make entry in batch entity batch table
405 if (!empty($params['batch_id'])) {
406 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
407 $titleFields = array(
413 $retrieveRequired = 0;
414 foreach ($titleFields as $titleField) {
415 if (!isset($contribution->$titleField)) {
416 $retrieveRequired = 1;
420 if ($retrieveRequired == 1) {
421 $contribution->find(TRUE);
425 // Handle soft credit and / or link to personal campaign page
426 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
428 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
430 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
431 $softParams = array();
432 $softParams['id'] = $pcpId ?
$pcpId : NULL;
433 $softParams['contribution_id'] = $contribution->id
;
434 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
435 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
436 $pcp['pcp_made_through_id'], 'contact_id'
438 $softParams['currency'] = $contribution->currency
;
439 $softParams['amount'] = $contribution->total_amount
;
440 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
441 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
442 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
443 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
444 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($softParams);
445 //Send notification to owner for PCP
446 if ($contributionSoft->pcp_id
&& empty($pcpId)) {
447 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
450 //Delete PCP against this contribution and create new on submitted PCP information
451 elseif (array_key_exists('pcp', $params) && $pcpId) {
452 $deleteParams = array('id' => $pcpId);
453 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
455 if (isset($params['soft_credit'])) {
456 $softParams = $params['soft_credit'];
457 foreach ($softParams as $softParam) {
458 if (!empty($softIDs)) {
459 $key = key($softIDs);
460 $softParam['id'] = $softIDs[$key];
461 unset($softIDs[$key]);
463 $softParam['contribution_id'] = $contribution->id
;
464 $softParam['currency'] = $contribution->currency
;
465 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
466 if (empty($softParam['amount'])) {
467 $softParam['amount'] = $contribution->total_amount
;
469 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
472 if (!empty($softIDs)) {
473 foreach ($softIDs as $softID) {
474 if (!in_array($softID, $params['soft_credit_ids'])) {
475 $deleteParams = array('id' => $softID);
476 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
482 $transaction->commit();
484 // check if activity record exist for this contribution, if
486 $activity = new CRM_Activity_DAO_Activity();
487 $activity->source_record_id
= $contribution->id
;
488 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
492 if (!$activity->find(TRUE)) {
493 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
496 // CRM-13237 : if activity record found, update it with campaign id of contribution
497 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
500 // do not add to recent items for import, CRM-4399
501 if (empty($params['skipRecentView'])) {
502 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
503 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
505 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
506 $titleFields = array(
512 $retrieveRequired = 0;
513 foreach ($titleFields as $titleField) {
514 if (!isset($contribution->$titleField)) {
515 $retrieveRequired = 1;
519 if ($retrieveRequired == 1) {
520 $contribution->find(TRUE);
522 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
523 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
525 $recentOther = array();
526 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
527 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
528 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
532 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
533 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
534 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
538 // add the recently created Contribution
539 CRM_Utils_Recent
::add($title,
543 $contribution->contact_id
,
549 return $contribution;
553 * Get the values for pseudoconstants for name->value and reverse.
555 * @param array $defaults
556 * (reference) the default values, some of which need to be resolved.
557 * @param bool $reverse
558 * True if we want to resolve the values in the reverse direction (value -> name).
560 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
561 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
562 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
563 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
564 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
568 * Convert associative array names to values and vice-versa.
570 * This function is used by both the web form layer and the api. Note that
571 * the api needs the name => value conversion, also the view layer typically
572 * requires value => name conversion
574 * @param array $defaults
575 * @param string $property
576 * @param array $lookup
577 * @param bool $reverse
581 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
582 $id = $property . '_id';
584 $src = $reverse ?
$property : $id;
585 $dst = $reverse ?
$id : $property;
587 if (!array_key_exists($src, $defaults)) {
591 $look = $reverse ?
array_flip($lookup) : $lookup;
593 if (is_array($look)) {
594 if (!array_key_exists($defaults[$src], $look)) {
598 $defaults[$dst] = $look[$defaults[$src]];
603 * Retrieve DB object based on input parameters.
605 * It also stores all the retrieved values in the default array.
607 * @param array $params
608 * (reference ) an assoc array of name/value pairs.
609 * @param array $defaults
610 * (reference ) an assoc array to hold the name / value pairs.
611 * in a hierarchical manner
613 * (reference) the array that holds all the db ids.
615 * @return CRM_Contribute_BAO_Contribution
617 public static function retrieve(&$params, &$defaults, &$ids) {
618 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
619 return $contribution;
623 * Combine all the importable fields from the lower levels object.
625 * The ordering is important, since currently we do not have a weight
626 * scheme. Adding weight is super important and should be done in the
627 * next week or so, before this can be called complete.
629 * @param string $contactType
630 * @param bool $status
633 * array of importable Fields
635 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
636 if (!self
::$_importableFields) {
637 if (!self
::$_importableFields) {
638 self
::$_importableFields = array();
642 $fields = array('' => array('title' => ts('- do not import -')));
645 $fields = array('' => array('title' => ts('- Contribution Fields -')));
648 $note = CRM_Core_DAO_Note
::import();
649 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
650 unset($tmpFields['option_value']);
651 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
652 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
654 // Using new Dedupe rule.
656 'contact_type' => $contactType,
657 'used' => 'Unsupervised',
659 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
660 $tmpContactField = array();
661 if (is_array($fieldsArray)) {
662 foreach ($fieldsArray as $value) {
663 //skip if there is no dupe rule
664 if ($value == 'none') {
667 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
672 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
673 $tmpContactField[trim($value)] = $contactFields[trim($value)];
675 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
678 $title = $tmpContactField[trim($value)]['title'];
680 $tmpContactField[trim($value)]['title'] = $title;
684 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
685 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
686 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
687 $fields = array_merge($fields, $tmpContactField);
688 $fields = array_merge($fields, $tmpFields);
689 $fields = array_merge($fields, $note);
690 $fields = array_merge($fields, $optionFields);
691 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
692 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
693 self
::$_importableFields = $fields;
695 return self
::$_importableFields;
701 public static function &exportableFields() {
702 if (!self
::$_exportableFields) {
703 if (!self
::$_exportableFields) {
704 self
::$_exportableFields = array();
707 $impFields = CRM_Contribute_DAO_Contribution
::export();
708 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
709 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
710 $typeField = CRM_Financial_DAO_FinancialType
::export();
711 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
712 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
713 $contributionStatus = array(
714 'contribution_status' => array(
715 'title' => ts('Contribution Status'),
716 'name' => 'contribution_status',
717 'data_type' => CRM_Utils_Type
::T_STRING
,
721 $contributionPage = array(
722 'contribution_page' => array(
723 'title' => ts('Contribution Page'),
724 'name' => 'contribution_page',
725 'where' => 'civicrm_contribution_page.title',
726 'data_type' => CRM_Utils_Type
::T_STRING
,
730 $contributionNote = array(
731 'contribution_note' => array(
732 'title' => ts('Contribution Note'),
733 'name' => 'contribution_note',
734 'data_type' => CRM_Utils_Type
::T_TEXT
,
738 $contributionRecurId = array(
739 'contribution_recur_id' => array(
740 'title' => ts('Recurring Contributions ID'),
741 'name' => 'contribution_recur_id',
742 'where' => 'civicrm_contribution.contribution_recur_id',
743 'data_type' => CRM_Utils_Type
::T_INT
,
747 $extraFields = array(
748 'contribution_batch' => array(
749 'title' => ts('Batch Name'),
753 $softCreditFields = array(
754 'contribution_soft_credit_name' => array(
755 'name' => 'contribution_soft_credit_name',
756 'title' => 'Soft Credit For',
757 'where' => 'civicrm_contact_d.display_name',
758 'data_type' => CRM_Utils_Type
::T_STRING
,
760 'contribution_soft_credit_amount' => array(
761 'name' => 'contribution_soft_credit_amount',
762 'title' => 'Soft Credit Amount',
763 'where' => 'civicrm_contribution_soft.amount',
764 'data_type' => CRM_Utils_Type
::T_MONEY
,
766 'contribution_soft_credit_type' => array(
767 'name' => 'contribution_soft_credit_type',
768 'title' => 'Soft Credit Type',
769 'where' => 'contribution_softcredit_type.label',
770 'data_type' => CRM_Utils_Type
::T_STRING
,
772 'contribution_soft_credit_contribution_id' => array(
773 'name' => 'contribution_soft_credit_contribution_id',
774 'title' => 'Soft Credit For Contribution ID',
775 'where' => 'civicrm_contribution_soft.contribution_id',
776 'data_type' => CRM_Utils_Type
::T_INT
,
780 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
782 'contribution_product_id' => array(
783 'title' => ts('Premium'),
784 'name' => 'contribution_product_id',
785 'where' => 'civicrm_product.id',
786 'data_type' => CRM_Utils_Type
::T_INT
,
790 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
791 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums,
792 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
795 self
::$_exportableFields = $fields;
798 return self
::$_exportableFields;
802 * @param null $status
803 * @param null $startDate
804 * @param null $endDate
808 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
812 $where[] = 'contribution_status_id = 1';
816 $where[] = 'contribution_status_id = 3';
821 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
824 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
827 $whereCond = implode(' AND ', $where);
830 SELECT sum( total_amount ) as total_amount,
831 count( civicrm_contribution.id ) as total_count,
833 FROM civicrm_contribution
834 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
836 AND ( is_test = 0 OR is_test IS NULL )
837 AND contact.is_deleted = 0
841 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
844 while ($dao->fetch()) {
845 $count +
= $dao->total_count
;
846 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
850 'amount' => implode(', ', $amount),
858 * Delete the indirect records associated with this contribution first.
863 * $results no of deleted Contribution on success, false otherwise
865 public static function deleteContribution($id) {
866 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
868 $transaction = new CRM_Core_Transaction();
871 //delete activity record
873 'source_record_id' => $id,
874 // activity type id for contribution
875 'activity_type_id' => 6,
878 CRM_Activity_BAO_Activity
::deleteActivity($params);
880 //delete billing address if exists for this contribution.
881 self
::deleteAddress($id);
883 //update pledge and pledge payment, CRM-3961
884 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
886 // remove entry from civicrm_price_set_entity, CRM-5095
887 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
888 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
890 // cleanup line items.
891 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
893 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
894 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
896 if ($participantId) {
897 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
900 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
904 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
905 $noteId = key($note);
907 CRM_Core_BAO_Note
::del($noteId, FALSE);
910 $dao = new CRM_Contribute_DAO_Contribution();
913 $results = $dao->delete();
915 $transaction->commit();
917 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
919 // delete the recently created Contribution
920 $contributionRecent = array(
922 'type' => 'Contribution',
924 CRM_Utils_Recent
::del($contributionRecent);
930 * React to a financial transaction (payment) failure.
932 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
933 * payments is important for forensic and outreach reasons.
935 * @param int $contributionID
936 * @param string $message
938 public static function failPayment($contributionID, $contactID, $message) {
939 civicrm_api3('activity', 'create', array(
940 'activity_type_id' => 'Failed Payment',
941 'details' => $message,
942 'subject' => ts('Payment failed at payment processor'),
943 'source_record_id' => $contributionID,
944 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
950 * Check if there is a contribution with the same trxn_id or invoice_id.
952 * @param array $input
953 * An assoc array of name/value pairs.
954 * @param array $duplicates
955 * (reference) store ids of duplicate contribs.
959 * true if duplicate, false otherwise
961 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
963 $id = CRM_Utils_Array
::value('id', $input);
965 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
966 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
972 $clause[] = "trxn_id = %1";
973 $input[1] = array($trxn_id, 'String');
977 $clause[] = "invoice_id = %2";
978 $input[2] = array($invoice_id, 'String');
981 if (empty($clause)) {
985 $clause = implode(' OR ', $clause);
987 $clause = "( $clause ) AND id != %3";
988 $input[3] = array($id, 'Integer');
991 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
992 $dao = CRM_Core_DAO
::executeQuery($query, $input);
994 while ($dao->fetch()) {
995 $duplicates[] = $dao->id
;
1002 * Takes an associative array and creates a contribution_product object.
1004 * the function extract all the params it needs to initialize the create a
1005 * contribution_product object. the params array could contain additional unused name/value
1008 * @param array $params
1009 * (reference) an assoc array of name/value pairs.
1011 * @return CRM_Contribute_DAO_ContributionProduct
1013 public static function addPremium(&$params) {
1014 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1015 $contributionProduct->copyValues($params);
1016 return $contributionProduct->save();
1020 * Get list of contribution fields for profile.
1021 * For now we only allow custom contribution fields to be in
1024 * @param bool $addExtraFields
1025 * True if special fields needs to be added.
1028 * the list of contribution fields
1030 public static function getContributionFields($addExtraFields = TRUE) {
1031 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1032 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1034 if ($addExtraFields) {
1035 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1038 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1040 foreach ($contributionFields as $key => $var) {
1041 if ($key == 'contribution_contact_id') {
1044 elseif ($key == 'contribution_campaign_id') {
1045 $var['title'] = ts('Campaign');
1047 $fields[$key] = $var;
1050 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1055 * Add extra fields specific to contribution.
1057 public static function getSpecialContributionFields() {
1058 $extraFields = array(
1059 'contribution_soft_credit_name' => array(
1060 'name' => 'contribution_soft_credit_name',
1061 'title' => 'Soft Credit Name',
1062 'headerPattern' => '/^soft_credit_name$/i',
1063 'where' => 'civicrm_contact_d.display_name',
1065 'contribution_soft_credit_email' => array(
1066 'name' => 'contribution_soft_credit_email',
1067 'title' => 'Soft Credit Email',
1068 'headerPattern' => '/^soft_credit_email$/i',
1069 'where' => 'soft_email.email',
1071 'contribution_soft_credit_phone' => array(
1072 'name' => 'contribution_soft_credit_phone',
1073 'title' => 'Soft Credit Phone',
1074 'headerPattern' => '/^soft_credit_phone$/i',
1075 'where' => 'soft_phone.phone',
1077 'contribution_soft_credit_contact_id' => array(
1078 'name' => 'contribution_soft_credit_contact_id',
1079 'title' => 'Soft Credit Contact ID',
1080 'headerPattern' => '/^soft_credit_contact_id$/i',
1081 'where' => 'civicrm_contribution_soft.contact_id',
1085 return $extraFields;
1089 * @param int $pageID
1093 public static function getCurrentandGoalAmount($pageID) {
1095 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1096 FROM civicrm_contribution_page p,
1097 civicrm_contribution c
1098 WHERE p.id = c.contribution_page_id
1100 AND c.cancel_date is null
1104 $config = CRM_Core_Config
::singleton();
1105 $params = array(1 => array($pageID, 'Integer'));
1106 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1108 if ($dao->fetch()) {
1109 return array($dao->goal
, $dao->total
);
1112 return array(NULL, NULL);
1117 * Get list of contribution In Honor of contact Ids.
1119 * @param int $honorId
1120 * In Honor of Contact ID.
1123 * list of contribution fields
1125 public static function getHonorContacts($honorId) {
1127 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1128 $honorDAO->contact_id
= $honorId;
1131 $type = CRM_Contribute_PseudoConstant
::financialType();
1133 while ($honorDAO->fetch()) {
1134 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1135 $contributionDAO->id
= $honorDAO->contribution_id
;
1137 if ($contributionDAO->find(TRUE)) {
1138 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1139 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1140 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1141 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1142 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1143 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1144 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1145 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1146 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1154 * Get the sort name of a contact for a particular contribution.
1157 * Id of the contribution.
1159 * @return null|string
1160 * sort name of the contact if found
1162 public static function sortName($id) {
1163 $id = CRM_Utils_Type
::escape($id, 'Integer');
1166 SELECT civicrm_contact.sort_name
1167 FROM civicrm_contribution, civicrm_contact
1168 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1169 AND civicrm_contribution.id = {$id}
1171 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1175 * @param int $contactID
1179 public static function annual($contactID) {
1180 if (is_array($contactID)) {
1181 $contactIDs = implode(',', $contactID);
1184 $contactIDs = $contactID;
1187 $config = CRM_Core_Config
::singleton();
1188 $startDate = $endDate = NULL;
1190 $currentMonth = date('m');
1191 $currentDay = date('d');
1192 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1193 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1194 (int ) $config->fiscalYearStart
['d'] > $currentDay
1197 $year = date('Y') - 1;
1202 $nextYear = $year +
1;
1204 if ($config->fiscalYearStart
) {
1205 if ($config->fiscalYearStart
['M'] < 10) {
1206 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1208 if ($config->fiscalYearStart
['d'] < 10) {
1209 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1211 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1216 $startDate = "$year$monthDay";
1217 $endDate = "$nextYear$monthDay";
1220 SELECT count(*) as count,
1221 sum(total_amount) as amount,
1222 avg(total_amount) as average,
1224 FROM civicrm_contribution b
1225 WHERE b.contact_id IN ( $contactIDs )
1226 AND b.contribution_status_id = 1
1228 AND b.receive_date >= $startDate
1229 AND b.receive_date < $endDate
1232 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1234 $amount = $average = array();
1235 while ($dao->fetch()) {
1236 if ($dao->count
> 0 && $dao->amount
> 0) {
1237 $count +
= $dao->count
;
1238 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1239 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1245 implode(', ', $amount),
1246 implode(', ', $average),
1249 return array(0, 0, 0);
1253 * Check if there is a contribution with the params passed in.
1255 * Used for trxn_id,invoice_id and contribution_id
1257 * @param array $params
1258 * An assoc array of name/value pairs.
1261 * contribution id if success else NULL
1263 public static function checkDuplicateIds($params) {
1264 $dao = new CRM_Contribute_DAO_Contribution();
1268 foreach ($params as $k => $v) {
1270 $clause[] = "$k = '$v'";
1273 $clause = implode(' AND ', $clause);
1274 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1275 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1277 while ($dao->fetch()) {
1285 * Get the contribution details for component export.
1287 * @param int $exportMode
1289 * @param string $componentIds
1295 public static function getContributionDetails($exportMode, $componentIds) {
1296 $paymentDetails = array();
1297 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1299 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1300 $componentSelect = " civicrm_participant_payment.participant_id id";
1301 $additionalClause = "
1302 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1303 AND civicrm_participant_payment.participant_id {$componentClause} )
1306 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1307 $componentSelect = " civicrm_membership_payment.membership_id id";
1308 $additionalClause = "
1309 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1310 AND civicrm_membership_payment.membership_id {$componentClause} )
1313 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1314 $componentSelect = " civicrm_pledge_payment.id id";
1315 $additionalClause = "
1316 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1317 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1321 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1322 trxn_id, {$componentSelect}
1323 FROM civicrm_contribution
1324 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1325 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1326 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1327 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1328 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1329 AND option_group_contribution_status.id = contribution_status.option_group_id )
1333 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1335 while ($dao->fetch()) {
1336 $paymentDetails[$dao->id
] = array(
1337 'total_amount' => $dao->total_amount
,
1338 'contribution_status' => $dao->status
,
1339 'receive_date' => $dao->receive_date
,
1340 'pay_instru' => $dao->payment_instrument
,
1341 'trxn_id' => $dao->trxn_id
,
1345 return $paymentDetails;
1349 * Create address associated with contribution record.
1351 * As long as there is one or more billing field in the parameters we will create the address.
1353 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1356 * @param array $params
1357 * @param int $billingLocationTypeID
1362 public static function createAddress($params, $billingLocationTypeID) {
1363 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1364 if ($hasBillingField) {
1365 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1366 return $address->id
;
1373 * Delete billing address record related contribution.
1375 * @param int $contributionId
1376 * @param int $contactId
1378 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1380 $contactJoin = NULL;
1382 if ($contributionId) {
1383 $clauses[] = "cc.id = {$contributionId}";
1387 $clauses[] = "cco.id = {$contactId}";
1388 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1391 if (empty($clauses)) {
1392 CRM_Core_Error
::fatal();
1395 $condition = implode(' OR ', $clauses);
1399 FROM civicrm_address ca
1400 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1404 $dao = CRM_Core_DAO
::executeQuery($query);
1406 while ($dao->fetch()) {
1407 $params = array('id' => $dao->id
);
1408 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1413 * This function check online pending contribution associated w/
1414 * Online Event Registration or Online Membership signup.
1416 * @param int $componentId
1417 * Participant/membership id.
1418 * @param string $componentName
1422 * pending contribution id.
1424 public static function checkOnlinePendingContribution($componentId, $componentName) {
1425 $contributionId = NULL;
1426 if (!$componentId ||
1427 !in_array($componentName, array('Event', 'Membership'))
1429 return $contributionId;
1432 if ($componentName == 'Event') {
1433 $idName = 'participant_id';
1434 $componentTable = 'civicrm_participant';
1435 $paymentTable = 'civicrm_participant_payment';
1436 $source = ts('Online Event Registration');
1439 if ($componentName == 'Membership') {
1440 $idName = 'membership_id';
1441 $componentTable = 'civicrm_membership';
1442 $paymentTable = 'civicrm_membership_payment';
1443 $source = ts('Online Contribution');
1446 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1449 SELECT component.id as {$idName},
1450 componentPayment.contribution_id as contribution_id,
1451 contribution.source source,
1452 contribution.contribution_status_id as contribution_status_id,
1453 contribution.is_pay_later as is_pay_later
1454 FROM $componentTable component
1455 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1456 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1457 WHERE component.id = {$componentId}";
1459 $dao = CRM_Core_DAO
::executeQuery($query);
1461 while ($dao->fetch()) {
1462 if ($dao->contribution_id
&&
1463 $dao->is_pay_later
&&
1464 $dao->contribution_status_id
== $pendingStatusId &&
1465 strpos($dao->source
, $source) !== FALSE
1467 $contributionId = $dao->contribution_id
;
1472 return $contributionId;
1476 * Update contribution as well as related objects.
1478 * @param array $params
1479 * @param bool $processContributionObject
1482 * @throws \Exception
1484 public static function transitionComponents($params, $processContributionObject = FALSE) {
1485 // get minimum required values.
1486 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1487 $componentId = CRM_Utils_Array
::value('component_id', $params);
1488 $componentName = CRM_Utils_Array
::value('componentName', $params);
1489 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1490 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1492 // if we already processed contribution object pass previous status id.
1493 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1495 $updateResult = array();
1497 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1499 // we process only ( Completed, Cancelled, or Failed ) contributions.
1500 if (!$contributionId ||
1501 !in_array($contributionStatusId, array(
1502 array_search('Completed', $contributionStatuses),
1503 array_search('Cancelled', $contributionStatuses),
1504 array_search('Failed', $contributionStatuses),
1507 return $updateResult;
1510 if (!$componentName ||
!$componentId) {
1511 // get the related component details.
1512 $componentDetails = self
::getComponentDetails($contributionId);
1515 $componentDetails['contact_id'] = $contactId;
1516 $componentDetails['component'] = $componentName;
1518 if ($componentName == 'event') {
1519 $componentDetails['participant'] = $componentId;
1522 $componentDetails['membership'] = $componentId;
1526 if (!empty($componentDetails['contact_id'])) {
1527 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1533 // do check for required ids.
1534 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1535 return $updateResult;
1538 //now we are ready w/ required ids, start processing.
1540 $baseIPN = new CRM_Core_Payment_BaseIPN();
1542 $input = $ids = $objects = array();
1544 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1545 $ids['contribution'] = $contributionId;
1546 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1547 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1548 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1549 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1550 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1551 $ids['contributionRecur'] = NULL;
1552 $ids['contributionPage'] = NULL;
1554 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1555 CRM_Core_Error
::fatal();
1558 $memberships = &$objects['membership'];
1559 $participant = &$objects['participant'];
1560 $pledgePayment = &$objects['pledge_payment'];
1561 $contribution = &$objects['contribution'];
1563 if ($pledgePayment) {
1564 $pledgePaymentIDs = array();
1565 foreach ($pledgePayment as $key => $object) {
1566 $pledgePaymentIDs[] = $object->id
;
1568 $pledgeID = $pledgePayment[0]->pledge_id
;
1571 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1574 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1575 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1580 // we might want to process contribution object.
1581 $processContribution = FALSE;
1582 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1583 if (is_array($memberships)) {
1584 foreach ($memberships as $membership) {
1586 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1587 $membership->save();
1589 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1590 if ($processContributionObject) {
1591 $processContribution = TRUE;
1598 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1599 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1601 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1602 if ($processContributionObject) {
1603 $processContribution = TRUE;
1607 if ($pledgePayment) {
1608 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1610 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1611 if ($processContributionObject) {
1612 $processContribution = TRUE;
1616 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1617 if (is_array($memberships)) {
1618 foreach ($memberships as $membership) {
1620 $membership->status_id
= array_search('Expired', $membershipStatuses);
1621 $membership->save();
1623 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1624 if ($processContributionObject) {
1625 $processContribution = TRUE;
1631 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1632 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1634 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1635 if ($processContributionObject) {
1636 $processContribution = TRUE;
1640 if ($pledgePayment) {
1641 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1643 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1644 if ($processContributionObject) {
1645 $processContribution = TRUE;
1649 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1651 // only pending contribution related object processed.
1652 if ($previousContriStatusId &&
1653 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1655 // this is case when we already processed contribution object.
1656 return $updateResult;
1658 elseif (!$previousContriStatusId &&
1659 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1661 // this is case when we are going to process contribution object later.
1662 return $updateResult;
1665 if (is_array($memberships)) {
1666 foreach ($memberships as $membership) {
1671 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1672 $membership->membership_type_id
,
1673 $membership->is_test
, $membership->id
1676 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1677 // this picks up membership type changes during renewals
1679 SELECT membership_type_id
1680 FROM civicrm_membership_log
1681 WHERE membership_id=$membership->id
1684 $dao = new CRM_Core_DAO();
1686 if ($dao->fetch()) {
1687 if (!empty($dao->membership_type_id
)) {
1688 $membership->membership_type_id
= $dao->membership_type_id
;
1689 $membership->save();
1692 // else fall back to using current membership type
1695 // Figure out number of terms
1697 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1698 foreach ($lineitems as $lineitem) {
1699 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1700 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1702 // in case membership_num_terms comes through as null or zero
1703 $numterms = $numterms >= 1 ?
$numterms : 1;
1708 // CRM-15735-to update the membership status as per the contribution receive date
1710 if (!empty($params['receive_date'])) {
1711 $joinDate = $params['receive_date'];
1712 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1713 $membership->end_date
,
1714 $membership->join_date
,
1715 $params['receive_date'],
1717 $membership->membership_type_id
,
1720 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1721 $membership->save();
1724 if ($currentMembership) {
1725 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1726 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1727 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1730 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1733 //get the status for membership.
1734 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1736 $dates['join_date'],
1739 $membership->membership_type_id
,
1743 $formattedParams = array(
1744 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1745 array_search('Current', $membershipStatuses)
1747 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1748 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1749 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1752 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1754 $membership->copyValues($formattedParams);
1755 $membership->save();
1757 //updating the membership log
1758 $membershipLog = array();
1759 $membershipLog = $formattedParams;
1760 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1761 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1763 $membershipLog['start_date'] = $logStartDate;
1764 $membershipLog['membership_id'] = $membership->id
;
1765 $membershipLog['modified_id'] = $membership->contact_id
;
1766 $membershipLog['modified_date'] = date('Ymd');
1767 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1769 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1771 //update related Memberships.
1772 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1774 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1777 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1778 if ($processContributionObject) {
1779 $processContribution = TRUE;
1782 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1788 $updatedStatusId = array_search('Registered', $participantStatuses);
1789 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1791 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1792 if ($processContributionObject) {
1793 $processContribution = TRUE;
1797 if ($pledgePayment) {
1798 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1800 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1801 if ($processContributionObject) {
1802 $processContribution = TRUE;
1807 // process contribution object.
1808 if ($processContribution) {
1809 $contributionParams = array();
1816 'payment_instrument_id',
1819 'financial_type_id',
1820 'contribution_status_id',
1821 'non_deductible_amount',
1825 foreach ($fields as $field) {
1826 if (empty($params[$field])) {
1829 $contributionParams[$field] = $params[$field];
1832 $ids = array('contribution' => $contributionId);
1833 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1836 return $updateResult;
1840 * Returns all contribution related object ids.
1842 * @param $contributionId
1846 public static function getComponentDetails($contributionId) {
1847 $componentDetails = $pledgePayment = array();
1848 if (!$contributionId) {
1849 return $componentDetails;
1853 SELECT c.id as contribution_id,
1854 c.contact_id as contact_id,
1855 c.contribution_recur_id,
1856 mp.membership_id as membership_id,
1857 m.membership_type_id as membership_type_id,
1858 pp.participant_id as participant_id,
1859 p.event_id as event_id,
1860 pgp.id as pledge_payment_id
1861 FROM civicrm_contribution c
1862 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1863 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1864 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1865 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1866 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1867 WHERE c.id = $contributionId";
1869 $dao = CRM_Core_DAO
::executeQuery($query);
1870 $componentDetails = array();
1872 while ($dao->fetch()) {
1873 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1874 $componentDetails['contact_id'] = $dao->contact_id
;
1875 if ($dao->event_id
) {
1876 $componentDetails['event'] = $dao->event_id
;
1878 if ($dao->participant_id
) {
1879 $componentDetails['participant'] = $dao->participant_id
;
1881 if ($dao->membership_id
) {
1882 if (!isset($componentDetails['membership'])) {
1883 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1885 $componentDetails['membership'][] = $dao->membership_id
;
1886 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1888 if ($dao->pledge_payment_id
) {
1889 $pledgePayment[] = $dao->pledge_payment_id
;
1891 if ($dao->contribution_recur_id
) {
1892 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1896 if ($pledgePayment) {
1897 $componentDetails['pledge_payment'] = $pledgePayment;
1900 return $componentDetails;
1904 * @param int $contactId
1905 * @param bool $includeSoftCredit
1907 * @return null|string
1909 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1914 $contactContributionsSQL = "
1915 SELECT contribution.id AS id
1916 FROM civicrm_contribution contribution
1917 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1919 $contactSoftCreditContributionsSQL = "
1920 SELECT contribution.id
1921 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1922 ON ( contribution.id = softContribution.contribution_id )
1923 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1924 $query = "SELECT count( x.id ) count FROM ( ";
1925 $query .= $contactContributionsSQL;
1927 if ($includeSoftCredit) {
1928 $query .= " UNION ";
1929 $query .= $contactSoftCreditContributionsSQL;
1934 return CRM_Core_DAO
::singleValueQuery($query);
1938 * Get individual id for onbehalf contribution.
1940 * @param int $contributionId
1942 * @param int $contributorId
1946 * containing organization id and individual id
1948 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1952 if (!$contributionId) {
1956 // fetch contributor id if null
1957 if (!$contributorId) {
1958 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1959 $contributionId, 'contact_id'
1963 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1964 $activityTypeId = array_search('Contribution', $activityTypeIds);
1966 if ($activityTypeId && $contributorId) {
1968 SELECT civicrm_activity_contact.contact_id
1969 FROM civicrm_activity_contact
1970 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1971 WHERE civicrm_activity.activity_type_id = %1
1972 AND civicrm_activity.source_record_id = %2
1973 AND civicrm_activity_contact.record_type_id = %3
1976 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1977 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1980 1 => array($activityTypeId, 'Integer'),
1981 2 => array($contributionId, 'Integer'),
1982 3 => array($sourceID, 'Integer'),
1985 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1987 // for on behalf contribution source is individual and contributor is organization
1988 if ($sourceContactId && $sourceContactId != $contributorId) {
1989 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1990 // get rel type id for employee of relation
1991 foreach ($relationshipTypeIds as $id => $typeVals) {
1992 if ($typeVals['name_a_b'] == 'Employee of') {
1993 $relationshipTypeId = $id;
1998 $rel = new CRM_Contact_DAO_Relationship();
1999 $rel->relationship_type_id
= $relationshipTypeId;
2000 $rel->contact_id_a
= $sourceContactId;
2001 $rel->contact_id_b
= $contributorId;
2002 if ($rel->find(TRUE)) {
2003 $ids['individual_id'] = $rel->contact_id_a
;
2004 $ids['organization_id'] = $rel->contact_id_b
;
2015 public static function getContributionDates() {
2016 $config = CRM_Core_Config
::singleton();
2017 $currentMonth = date('m');
2018 $currentDay = date('d');
2019 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2020 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2021 (int ) $config->fiscalYearStart
['d'] > $currentDay
2024 $year = date('Y') - 1;
2029 $year = array('Y' => $year);
2030 $yearDate = $config->fiscalYearStart
;
2031 $yearDate = array_merge($year, $yearDate);
2032 $yearDate = CRM_Utils_Date
::format($yearDate);
2034 $monthDate = date('Ym') . '01';
2040 'yearDate' => $yearDate,
2041 'monthDate' => $monthDate,
2046 * Load objects relations to contribution object.
2047 * Objects are stored in the $_relatedObjects property
2048 * In the first instance we are just moving functionality from BASEIpn -
2049 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2051 * Note that the unit test for the BaseIPN class tests this function
2053 * @param array $input
2054 * Input as delivered from Payment Processor.
2056 * Ids as Loaded by Payment Processor.
2057 * @param bool $required
2058 * Is Payment processor / contribution page required.
2059 * @param bool $loadAll
2060 * Load all related objects - even where id not passed in? (allows API to call this).
2065 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
2067 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2068 if (empty($ids['contact']) && isset($this->contact_id
)) {
2069 $ids['contact'] = $this->contact_id
;
2072 if (empty($this->_component
)) {
2073 if (!empty($ids['event'])) {
2074 $this->_component
= 'event';
2077 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2080 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
2081 $contributionType = new CRM_Financial_BAO_FinancialType();
2082 $contributionType->id
= $this->financial_type_id
;
2083 $contributionType->find(TRUE);
2085 if (!empty($ids['contact'])) {
2086 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
2087 $this->_relatedObjects
['contact']->id
= $ids['contact'];
2088 $this->_relatedObjects
['contact']->find(TRUE);
2090 $this->_relatedObjects
['contributionType'] = $contributionType;
2092 if ($this->_component
== 'contribute') {
2093 // retrieve the other optional objects first so
2094 // stuff down the line can use this info and do things
2096 //in any case get the memberships associated with the contribution
2097 //because we now support multiple memberships w/ price set
2098 // see if there are any other memberships to be considered for same contribution.
2100 SELECT membership_id
2101 FROM civicrm_membership_payment
2102 WHERE contribution_id = %1 ";
2103 $params = array(1 => array($this->id
, 'Integer'));
2105 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2106 while ($dao->fetch()) {
2107 if ($dao->membership_id
) {
2108 if (!is_array($ids['membership'])) {
2109 $ids['membership'] = array();
2111 $ids['membership'][] = $dao->membership_id
;
2115 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2116 foreach ($ids['membership'] as $id) {
2118 $membership = new CRM_Member_BAO_Membership();
2119 $membership->id
= $id;
2120 if (!$membership->find(TRUE)) {
2121 throw new Exception("Could not find membership record: $id");
2123 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2124 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2125 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2126 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2127 $membership->free();
2132 if (!empty($ids['pledge_payment'])) {
2134 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2135 if (empty($paymentID)) {
2138 $payment = new CRM_Pledge_BAO_PledgePayment();
2139 $payment->id
= $paymentID;
2140 if (!$payment->find(TRUE)) {
2141 throw new Exception("Could not find pledge payment record: " . $paymentID);
2143 $this->_relatedObjects
['pledge_payment'][] = $payment;
2147 if (!empty($ids['contributionRecur'])) {
2148 $recur = new CRM_Contribute_BAO_ContributionRecur();
2149 $recur->id
= $ids['contributionRecur'];
2150 if (!$recur->find(TRUE)) {
2151 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2153 $this->_relatedObjects
['contributionRecur'] = &$recur;
2154 //get payment processor id from recur object.
2155 $paymentProcessorID = $recur->payment_processor_id
;
2157 //for normal contribution get the payment processor id.
2158 if (!$paymentProcessorID) {
2159 if ($this->contribution_page_id
) {
2160 // get the payment processor id from contribution page
2161 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2162 $this->contribution_page_id
,
2166 //fail to load payment processor id.
2167 elseif (empty($ids['pledge_payment'])) {
2168 $loadObjectSuccess = TRUE;
2170 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2172 return $loadObjectSuccess;
2177 // we are in event mode
2178 // make sure event exists and is valid
2179 $event = new CRM_Event_BAO_Event();
2180 $event->id
= $ids['event'];
2181 if ($ids['event'] &&
2184 throw new Exception("Could not find event: " . $ids['event']);
2187 $this->_relatedObjects
['event'] = &$event;
2189 $participant = new CRM_Event_BAO_Participant();
2190 $participant->id
= $ids['participant'];
2191 if ($ids['participant'] &&
2192 !$participant->find(TRUE)
2194 throw new Exception("Could not find participant: " . $ids['participant']);
2196 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2198 $this->_relatedObjects
['participant'] = &$participant;
2200 if (!$paymentProcessorID) {
2201 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2205 if ($paymentProcessorID) {
2206 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2207 $this->is_test ?
'test' : 'live'
2209 $ids['paymentProcessor'] = $paymentProcessorID;
2210 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2212 elseif ($required) {
2213 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2220 * Create array of message information - ie. return html version, txt version, to field
2222 * @param array $input
2223 * Incoming information.
2224 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2225 * just check presence of recur object but maintaining legacy approach
2228 * IDs of related objects.
2229 * @param array $values
2230 * Any values that may have already been compiled by calling process.
2231 * This is augmented by values 'gathered' by gatherMessageValues
2232 * @param bool $recur
2233 * @param bool $returnMessageText
2234 * Distinguishes between whether to send message or return.
2235 * message text. We are working towards this function ALWAYS returning message text & calling
2236 * function doing emails / pdfs with it
2242 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2243 if (empty($this->_relatedObjects
)) {
2244 $this->loadRelatedObjects($input, $ids);
2246 if (empty($this->_component
)) {
2247 $this->_component
= CRM_Utils_Array
::value('component', $input);
2250 //not really sure what params might be passed in but lets merge em into values
2251 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2252 $template = CRM_Core_Smarty
::singleton();
2253 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2254 //what does recur 'mean here - to do with payment processor return functionality but
2255 // what is the importance
2256 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2257 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2259 $entityID = $entity = NULL;
2260 if (isset($ids['contribution'])) {
2261 $entity = 'contribution';
2262 $entityID = $ids['contribution'];
2264 if (!empty($ids['membership'])) {
2265 //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
2266 // 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
2267 // line having loaded an array
2268 $ids['membership'] = (array) $ids['membership'];
2269 $entity = 'membership';
2270 $entityID = $ids['membership'][0];
2273 $url = $paymentObject->subscriptionURL($entityID, $entity);
2274 $template->assign('cancelSubscriptionUrl', $url);
2276 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2277 $template->assign('updateSubscriptionBillingUrl', $url);
2279 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2280 $template->assign('updateSubscriptionUrl', $url);
2282 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2283 //direct mode showing billing block, so use directIPN for temporary
2284 $template->assign('contributeMode', 'directIPN');
2287 // todo remove strtolower - check consistency
2288 if (strtolower($this->_component
) == 'event') {
2289 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2290 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2294 $values['contribution_id'] = $this->id
;
2295 if (!empty($ids['related_contact'])) {
2296 $values['related_contact'] = $ids['related_contact'];
2297 if (isset($ids['onbehalf_dupe_alert'])) {
2298 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2300 $entityBlock = array(
2301 'contact_id' => $ids['contact'],
2302 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2303 'Home', 'id', 'name'
2306 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2307 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2310 if ($this->is_test
) {
2313 if (!empty($this->_relatedObjects
['membership'])) {
2314 foreach ($this->_relatedObjects
['membership'] as $membership) {
2315 if ($membership->id
) {
2316 $values['isMembership'] = TRUE;
2318 // need to set the membership values here
2319 $template->assign('membership_assign', 1);
2320 $template->assign('membership_name',
2321 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2323 $template->assign('mem_start_date', $membership->start_date
);
2324 $template->assign('mem_join_date', $membership->join_date
);
2325 $template->assign('mem_end_date', $membership->end_date
);
2326 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2327 $template->assign('mem_status', $membership_status);
2328 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2329 $template->assign('is_pay_later', 1);
2332 // if separate payment there are two contributions recorded and the
2333 // admin will need to send a receipt for each of them separately.
2334 // we dont link the two in the db (but can potentially infer it if needed)
2335 $template->assign('is_separate_payment', 0);
2337 if ($recur && $paymentObject) {
2338 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2339 $template->assign('cancelSubscriptionUrl', $url);
2340 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2341 $template->assign('updateSubscriptionBillingUrl', $url);
2342 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2343 $template->assign('updateSubscriptionUrl', $url);
2346 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2349 // otherwise if its about sending emails, continue sending without return, as we
2350 // don't want to exit the loop.
2355 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2361 * Gather values for contribution mail - this function has been created
2362 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2363 * Values related to the contribution in question are gathered
2365 * @param array $input
2366 * Input into function (probably from payment processor).
2367 * @param array $values
2369 * The set of ids related to the input.
2373 public function _gatherMessageValues($input, &$values, $ids = array()) {
2374 // set display address of contributor
2375 if ($this->address_id
) {
2376 $addressParams = array('id' => $this->address_id
);
2377 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2378 $addressDetails = array_values($addressDetails);
2379 $values['address'] = $addressDetails[0]['display'];
2381 if ($this->_component
== 'contribute') {
2382 if (isset($this->contribution_page_id
)) {
2383 CRM_Contribute_BAO_ContributionPage
::setValues(
2384 $this->contribution_page_id
,
2387 if ($this->contribution_page_id
) {
2388 // CRM-8254 - override default currency if applicable
2389 $config = CRM_Core_Config
::singleton();
2390 $config->defaultCurrency
= CRM_Utils_Array
::value(
2393 $config->defaultCurrency
2397 // no contribution page -probably back office
2399 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2400 $values['is_email_receipt'] = 1;
2401 $values['title'] = 'Contribution';
2403 // set lineItem for contribution
2405 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2406 if (!empty($lineItem)) {
2407 $itemId = key($lineItem);
2408 foreach ($lineItem as &$eachItem) {
2409 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2410 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2411 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2412 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2415 $values['lineItem'][0] = $lineItem;
2416 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2420 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2424 // if this is onbehalf of contribution then set related contact
2425 if (!empty($relatedContact['individual_id'])) {
2426 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2431 $eventParams = array(
2432 'id' => $this->_relatedObjects
['event']->id
,
2434 $values['event'] = array();
2436 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2438 //get location details
2439 $locationParams = array(
2440 'entity_id' => $this->_relatedObjects
['event']->id
,
2441 'entity_table' => 'civicrm_event',
2443 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2445 $ufJoinParams = array(
2446 'entity_table' => 'civicrm_event',
2447 'entity_id' => $ids['event'],
2448 'module' => 'CiviEvent',
2451 list($custom_pre_id,
2453 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2455 $values['custom_pre_id'] = $custom_pre_id;
2456 $values['custom_post_id'] = $custom_post_ids;
2458 // set lineItem for event contribution
2460 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2461 if (!empty($participantIds)) {
2462 foreach ($participantIds as $pIDs) {
2463 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2464 if (!CRM_Utils_System
::isNull($lineItem)) {
2465 $values['lineItem'][] = $lineItem;
2476 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2477 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2478 * Note we send directly from this function in some cases because it is only partly refactored
2479 * Don't call this function directly as the signature will change
2483 * @param CRM_Core_SMARTY $template
2484 * @param bool $recur
2485 * @param bool $returnMessageText
2489 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2490 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2491 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2492 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2493 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2494 $template->assign('useForMember', TRUE);
2496 //assign honor information to receipt message
2497 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2499 if (isset($softRecord['soft_credit'])) {
2500 //if id of contribution page is present
2501 if (!empty($values['id'])) {
2502 $values['honor'] = array(
2503 'honor_profile_values' => array(),
2504 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2505 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2507 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2509 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2510 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2513 //offline contribution
2514 $softCreditTypes = $softCredits = array();
2515 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2516 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2517 $softCredits[$key] = array(
2518 'Name' => $softCredit['contact_name'],
2519 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2522 $template->assign('softCreditTypes', $softCreditTypes);
2523 $template->assign('softCredits', $softCredits);
2527 $dao = new CRM_Contribute_DAO_ContributionProduct();
2528 $dao->contribution_id
= $this->id
;
2529 if ($dao->find(TRUE)) {
2530 $premiumId = $dao->product_id
;
2531 $template->assign('option', $dao->product_option
);
2533 $productDAO = new CRM_Contribute_DAO_Product();
2534 $productDAO->id
= $premiumId;
2535 $productDAO->find(TRUE);
2536 $template->assign('selectPremium', TRUE);
2537 $template->assign('product_name', $productDAO->name
);
2538 $template->assign('price', $productDAO->price
);
2539 $template->assign('sku', $productDAO->sku
);
2541 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2542 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2543 if (empty($amount) && isset($this->total_amount
)) {
2544 $amount = $this->total_amount
;
2546 $template->assign('amount', $amount);
2547 // add the new contribution values
2548 if (strtolower($this->_component
) == 'contribute') {
2550 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2551 $softDAO->contribution_id
= $this->id
;
2552 if ($softDAO->find(TRUE)) {
2553 $template->assign('pcpBlock', TRUE);
2554 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2555 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2556 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2558 //assign the pcp page title for email subject
2559 $pcpDAO = new CRM_PCP_DAO_PCP();
2560 $pcpDAO->id
= $softDAO->pcp_id
;
2561 if ($pcpDAO->find(TRUE)) {
2562 $template->assign('title', $pcpDAO->title
);
2567 if ($this->financial_type_id
) {
2568 $values['financial_type_id'] = $this->financial_type_id
;
2571 $template->assign('trxn_id', $this->trxn_id
);
2572 $template->assign('receive_date',
2573 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2575 $template->assign('contributeMode', 'notify');
2576 $template->assign('action', $this->is_test ?
1024 : 1);
2577 $template->assign('receipt_text',
2578 CRM_Utils_Array
::value('receipt_text',
2582 $template->assign('is_monetary', 1);
2583 $template->assign('is_recur', (bool) $recur);
2584 $template->assign('currency', $this->currency
);
2585 $template->assign('address', CRM_Utils_Address
::format($input));
2586 if ($this->_component
== 'event') {
2587 $template->assign('title', $values['event']['title']);
2588 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2589 $viewRoles = array();
2590 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2591 $viewRoles[] = $participantRoles[$v];
2593 $values['event']['participant_role'] = implode(', ', $viewRoles);
2594 $template->assign('event', $values['event']);
2595 $template->assign('location', $values['location']);
2596 $template->assign('customPre', $values['custom_pre_id']);
2597 $template->assign('customPost', $values['custom_post_id']);
2600 if ($this->_relatedObjects
['participant']->is_test
) {
2604 $values['params'] = array();
2605 //to get email of primary participant.
2606 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2607 $primaryAmount[] = array(
2608 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2609 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2611 //build an array of cId/pId of participants
2612 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2613 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2614 //send receipt to additional participant if exists
2615 if (count($additionalIDs)) {
2616 $template->assign('isPrimary', 0);
2617 $template->assign('customProfile', NULL);
2618 //set additionalParticipant true
2619 $values['params']['additionalParticipant'] = TRUE;
2620 foreach ($additionalIDs as $pId => $cId) {
2622 //to change the status pending to completed
2623 $additional = new CRM_Event_DAO_Participant();
2624 $additional->id
= $pId;
2625 $additional->contact_id
= $cId;
2626 $additional->find(TRUE);
2627 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2628 $additional->status_id
= 1;
2629 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2630 //if additional participant dont have email
2632 if (!$additionalParticipantInfo) {
2633 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2635 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2636 $primaryAmount[] = array(
2637 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2638 'amount' => $additional->fee_amount
,
2640 $additional->save();
2641 $additional->free();
2642 $template->assign('amount', $amount);
2643 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2647 //build an array of custom profile and assigning it to template
2648 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2650 if (count($customProfile)) {
2651 $template->assign('customProfile', $customProfile);
2654 // for primary contact
2655 $values['params']['additionalParticipant'] = FALSE;
2656 $template->assign('isPrimary', 1);
2657 $template->assign('amount', $primaryAmount);
2658 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2659 if ($this->payment_instrument_id
) {
2660 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2661 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2663 // carry paylater, since we did not created billing,
2664 // so need to pull email from primary location, CRM-4395
2665 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2671 * Check whether payment processor supports
2672 * cancellation of contribution subscription
2674 * @param int $contributionId
2677 * @param bool $isNotCancelled
2681 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2682 $cacheKeyString = "$contributionId";
2683 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2685 static $supportsCancel = array();
2687 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2688 $supportsCancel[$cacheKeyString] = FALSE;
2689 $isCancelled = FALSE;
2691 if ($isNotCancelled) {
2692 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2695 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2696 if (!empty($paymentObject)) {
2697 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2700 return $supportsCancel[$cacheKeyString];
2704 * Check whether subscription is already cancelled.
2706 * @param int $contributionId
2710 * contribution status
2712 public static function isSubscriptionCancelled($contributionId) {
2714 SELECT cr.contribution_status_id
2715 FROM civicrm_contribution_recur cr
2716 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2717 WHERE con.id = %1 LIMIT 1";
2718 $params = array(1 => array($contributionId, 'Integer'));
2719 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2720 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2721 if ($status == 'Cancelled') {
2728 * Create all financial accounts entry.
2730 * @param array $params
2731 * Contribution object, line item array and params for trxn.
2734 * @param array $financialTrxnValues
2736 * @return null|object
2738 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2739 $skipRecords = $update = $return = $isRelatedId = FALSE;
2741 $additionalParticipantId = array();
2742 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2744 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2745 $entityId = $params['participant_id'];
2746 $entityTable = 'civicrm_participant';
2747 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2749 elseif (!empty($params['membership_id'])) {
2750 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2751 // are created off one contribution should be handled elsewhere
2752 $entityId = $params['membership_id'];
2753 $entityTable = 'civicrm_membership';
2756 $entityId = $params['contribution']->id
;
2757 $entityTable = 'civicrm_contribution';
2760 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2761 $isRelatedId = TRUE;
2764 $entityID[] = $entityId;
2765 if (!empty($additionalParticipantId)) {
2766 $entityID +
= $additionalParticipantId;
2768 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2769 if (empty($params['prevContribution'])) {
2776 $statusId = $params['contribution']->contribution_status_id
;
2777 // CRM-13964 partial payment
2778 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2779 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2781 $partialAmtPay = $params['partial_amount_pay'];
2782 $partialAmtTotal = $params['partial_payment_total'];
2784 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2785 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2786 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2787 $params['total_amount'] = $partialAmtPay;
2789 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2790 if (empty($balanceTrxnInfo['trxn_id'])) {
2791 // create new balance transaction record
2792 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2793 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2795 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2796 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2797 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2798 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2799 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2800 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2801 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2802 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2803 $balanceTrxnParams['status_id'] = $statusId;
2804 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2805 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2806 if (!empty($params['payment_processor'])) {
2807 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2809 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2813 // build line item array if its not set in $params
2814 if (empty($params['line_item']) ||
$additionalParticipantId) {
2815 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2818 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2819 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2821 $skipRecords = TRUE;
2822 $pendingStatus = array(
2823 array_search('Pending', $contributionStatuses),
2824 array_search('In Progress', $contributionStatuses),
2826 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2827 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2828 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2830 elseif (!empty($params['payment_processor'])) {
2831 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2833 elseif (!empty($params['payment_instrument_id'])) {
2834 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2837 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2838 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2839 $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);
2842 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2843 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2844 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2847 //build financial transaction params
2848 $trxnParams = array(
2849 'contribution_id' => $params['contribution']->id
,
2850 'to_financial_account_id' => $params['to_financial_account_id'],
2851 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2852 'total_amount' => $totalAmount,
2853 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2854 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2855 'currency' => $params['contribution']->currency
,
2856 'trxn_id' => $params['contribution']->trxn_id
,
2857 'status_id' => $statusId,
2858 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2859 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2862 if (!empty($params['payment_processor'])) {
2863 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2866 if (isset($fromFinancialAccountId)) {
2867 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2870 // consider external values passed for recording transaction entry
2871 if (!empty($financialTrxnValues)) {
2872 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2875 $params['trxnParams'] = $trxnParams;
2877 if (!empty($params['prevContribution'])) {
2878 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2879 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2880 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2881 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2882 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2884 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2885 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2886 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2888 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2889 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2892 //if financial type is changed
2893 if (!empty($params['financial_type_id']) &&
2894 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2896 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2897 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2898 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2899 if ($oldFinancialAccount != $newFinancialAccount) {
2900 $params['total_amount'] = 0;
2901 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2902 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2903 $params['prevContribution']->financial_type_id
, $relationTypeId);
2906 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2907 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2908 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2911 self
::updateFinancialAccounts($params, 'changeFinancialType');
2912 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2913 $params['financial_account_id'] = $newFinancialAccount;
2914 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2915 self
::updateFinancialAccounts($params);
2916 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2920 //Update contribution status
2921 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2922 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2923 if (!empty($params['contribution_status_id']) &&
2924 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2926 //Update Financial Records
2927 self
::updateFinancialAccounts($params, 'changedStatus');
2930 // change Payment Instrument for a Completed contribution
2931 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2932 // instrument is null and now new payment instrument is added along with the payment
2933 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2934 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2935 if (array_key_exists('payment_instrument_id', $params)) {
2936 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2937 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2938 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2940 //check if status is changed from Pending to Completed
2941 // do not update payment instrument changes for Pending to Completed
2942 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2943 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2945 // for all other statuses create new financial records
2946 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2947 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2948 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2951 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2952 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2953 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2955 // for any other payment instrument changes create new financial records
2956 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2957 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2958 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2960 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2961 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2963 // another special case when check number is changed, create new financial records
2964 // create financial trxn with negative amount
2965 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2966 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2967 // create financial trxn with positive amount
2968 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2969 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2970 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2974 //if Change contribution amount
2975 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2976 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2977 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2978 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2979 if (isset($totalAmount) &&
2980 $totalAmount != $params['prevContribution']->total_amount
2982 //Update Financial Records
2983 $params['trxnParams']['from_financial_account_id'] = NULL;
2984 self
::updateFinancialAccounts($params, 'changedAmount');
2989 // records finanical trxn and entity financial trxn
2990 // also make it available as return value
2991 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2992 $params['entity_id'] = $financialTxn->id
;
2995 // record line items and financial items
2996 if (empty($params['skipLineItem'])) {
2997 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3000 // create batch entry if batch_id is passed and
3001 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3002 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3003 $entityParams = array(
3004 'batch_id' => $params['batch_id'],
3005 'entity_table' => 'civicrm_financial_trxn',
3006 'entity_id' => $financialTxn->id
,
3008 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3011 // when a fee is charged
3012 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3013 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3016 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3017 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3019 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3020 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3021 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3023 unset($params['line_item']);
3029 * Update all financial accounts entry.
3031 * @param array $params
3032 * Contribution object, line item array and params for trxn.
3034 * @param string $context
3037 * @param null $skipTrxn
3040 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3041 $itemAmount = $trxnID = NULL;
3042 //get all the statuses
3043 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3044 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3045 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3046 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3047 && $context == 'changePaymentInstrument'
3051 if (($params['prevContribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus))
3052 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3053 && $context == 'changedStatus'
3057 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3058 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3060 if ($context == 'changedStatus') {
3061 //get all the statuses
3062 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3064 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3065 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3066 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3068 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3070 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3071 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3073 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3074 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3075 $params['trxnParams']['to_financial_account_id'] = NULL;
3076 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3078 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3079 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3080 $financialTypeID, $relationTypeId);
3082 $itemAmount = $params['trxnParams']['total_amount'];
3084 elseif ($context == 'changePaymentInstrument') {
3085 if ($params['trxnParams']['total_amount'] < 0) {
3086 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3087 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3088 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3089 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3093 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3094 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3097 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3098 $params['entity_id'] = $trxn->id
;
3100 if ($context == 'changedStatus') {
3101 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3102 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3103 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3105 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3106 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3108 $entityParams = array(
3109 'entity_table' => 'civicrm_financial_item',
3110 'financial_trxn_id' => $trxn->id
,
3112 if (empty($params['line_item'])) {
3114 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3115 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3116 // & this can be removed
3119 foreach ($params['line_item'] as $fieldId => $fields) {
3120 foreach ($fields as $fieldValueId => $fieldValues) {
3122 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3123 2 => array($fieldValues['id'], 'Integer'),
3125 CRM_Core_DAO
::executeQuery($query, $fparams);
3127 1 => array($fieldValues['id'], 'Integer'),
3129 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3130 while ($financialItem->fetch()) {
3131 $entityParams['entity_id'] = $financialItem->id
;
3132 $entityParams['amount'] = $financialItem->amount
;
3133 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3140 if ($context != 'changePaymentInstrument') {
3141 $itemParams['entity_table'] = 'civicrm_line_item';
3142 $trxnIds['id'] = $params['entity_id'];
3143 foreach ($params['line_item'] as $fieldId => $fields) {
3144 foreach ($fields as $fieldValueId => $fieldValues) {
3145 $prevParams['entity_id'] = $fieldValues['id'];
3146 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3148 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3149 if ($params['contribution']->receive_date
) {
3150 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3153 $financialAccount = $prevfinancialItem->financial_account_id
;
3154 if (!empty($params['financial_account_id'])) {
3155 $financialAccount = $params['financial_account_id'];
3158 $currency = $params['prevContribution']->currency
;
3159 if ($params['contribution']->currency
) {
3160 $currency = $params['contribution']->currency
;
3163 if (!empty($params['is_quick_config'])) {
3164 $amount = $itemAmount;
3166 $amount = $params['total_amount'];
3170 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3171 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3175 $amount = $diff * $fieldValues['line_total'];
3178 $itemParams = array(
3179 'transaction_date' => $receiveDate,
3180 'contact_id' => $params['prevContribution']->contact_id
,
3181 'currency' => $currency,
3182 'amount' => $amount,
3183 'description' => $prevfinancialItem->description
,
3184 'status_id' => $prevfinancialItem->status_id
,
3185 'financial_account_id' => $financialAccount,
3186 'entity_table' => 'civicrm_line_item',
3187 'entity_id' => $fieldValues['id'],
3189 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3191 if ($fieldValues['tax_amount']) {
3192 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3193 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3194 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3195 $itemParams['description'] = $taxTerm;
3196 if ($fieldValues['financial_type_id']) {
3197 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3199 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3204 if ($context == 'changeFinancialType') {
3205 $params['skipLineItem'] = FALSE;
3206 foreach ($params['line_item'] as &$lineItems) {
3207 foreach ($lineItems as &$line) {
3208 $line['financial_type_id'] = $params['financial_type_id'];
3215 * Check status validation on update of a contribution.
3217 * @param array $values
3218 * Previous form values before submit.
3220 * @param array $fields
3221 * The input form values.
3223 * @param array $errors
3228 public static function checkStatusValidation($values, &$fields, &$errors) {
3229 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3230 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3231 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3235 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3236 $checkStatus = array(
3237 'Cancelled' => array('Completed', 'Refunded'),
3238 'Completed' => array('Cancelled', 'Refunded'),
3239 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3240 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3241 'Refunded' => array('Cancelled', 'Completed'),
3242 'Partially paid' => array('Completed'),
3245 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3246 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3247 1 => $contributionStatuses[$values['contribution_status_id']],
3248 2 => $contributionStatuses[$fields['contribution_status_id']],
3254 * Delete contribution of contact.
3258 * @param int $contactId
3262 public static function deleteContactContribution($contactId) {
3263 $contribution = new CRM_Contribute_DAO_Contribution();
3264 $contribution->contact_id
= $contactId;
3265 $contribution->find();
3266 while ($contribution->fetch()) {
3267 self
::deleteContribution($contribution->id
);
3272 * Get options for a given contribution field.
3273 * @see CRM_Core_DAO::buildOptions
3275 * @param string $fieldName
3276 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3277 * @param array $props whatever is known about this dao object.
3279 * @return array|bool
3281 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3282 $className = __CLASS__
;
3284 switch ($fieldName) {
3285 // This field is not part of this object but the api supports it
3286 case 'payment_processor':
3287 $className = 'CRM_Contribute_BAO_ContributionPage';
3288 // Filter results by contribution page
3289 if (!empty($props['contribution_page_id'])) {
3290 $page = civicrm_api('contribution_page', 'getsingle', array(
3292 'id' => ($props['contribution_page_id']),
3294 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3295 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3299 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3300 case 'honor_type_id':
3301 $className = 'CRM_Contribute_BAO_ContributionSoft';
3302 $fieldName = 'soft_credit_type_id';
3303 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3306 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3310 * Validate financial type.
3314 * @param int $financialTypeId
3315 * Financial Type id.
3317 * @param string $relationName
3319 * @return array|bool
3321 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3322 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3323 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3325 if (!$financialAccount) {
3326 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3333 * Function to record additional payment for partial and refund contributions.
3335 * @param int $contributionId
3336 * is the invoice contribution id (got created after processing participant payment).
3337 * @param array $trxnsData
3338 * to take user provided input of transaction details.
3339 * @param string $paymentType
3340 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3341 * @param int $participantId
3343 * @return null|object
3345 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3346 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3347 $getInfoOf['id'] = $contributionId;
3348 $defaults = array();
3349 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3351 if ($paymentType == 'owed') {
3352 // build params for recording financial trxn entry
3353 $params['contribution'] = $contributionDAO;
3354 $params = array_merge($defaults, $params);
3355 $params['skipLineItem'] = TRUE;
3356 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3357 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3358 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3359 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3362 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3363 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3364 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3366 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3367 if (!empty($trxnId)) {
3368 $trxnId = $trxnId['trxn_id'];
3370 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3371 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3374 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3375 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3376 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3380 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3381 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3382 FROM civicrm_financial_trxn ft
3383 LEFT JOIN civicrm_entity_financial_trxn eft
3384 ON (ft.id = eft.financial_trxn_id)
3385 WHERE eft.entity_table = 'civicrm_contribution'
3386 AND eft.entity_id = {$contributionId}
3387 AND ft.to_financial_account_id != {$toFinancialAccount}
3388 AND ft.status_id = {$statusId}
3390 $query = CRM_Core_DAO
::executeQuery($sql);
3392 $sumOfPayments = $query->sum_of_payments
;
3395 if ($contributionDAO->total_amount
== $sumOfPayments) {
3396 // update contribution status and
3397 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3398 $contributionDAO->contribution_status_id
= $statusId;
3399 $contributionDAO->cancel_date
= 'null';
3400 $contributionDAO->cancel_reason
= NULL;
3401 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3402 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3403 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3404 $contributionDAO->save();
3406 //Change status of financial record too
3407 $financialTrxn->status_id
= $statusId;
3408 $financialTrxn->save();
3410 // note : not using the self::add method,
3411 // the reason because it performs 'status change' related code execution for financial records
3412 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3413 // are coded below i.e. just updating financial_item status to 'Paid'
3415 if ($participantId) {
3416 // update participant status
3417 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3418 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3419 foreach ($ids as $val) {
3420 $participantUpdate['id'] = $val;
3421 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3422 CRM_Event_BAO_Participant
::add($participantUpdate);
3426 // update financial item statuses
3427 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3428 $paidStatus = array_search('Paid', $financialItemStatus);
3430 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3431 $sqlFinancialItemUpdate = "
3432 UPDATE civicrm_financial_item fi
3433 LEFT JOIN civicrm_entity_financial_trxn eft
3434 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3435 SET status_id = {$paidStatus}
3436 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3438 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3441 elseif ($paymentType == 'refund') {
3442 // build params for recording financial trxn entry
3443 $params['contribution'] = $contributionDAO;
3444 $params = array_merge($defaults, $params);
3445 $params['skipLineItem'] = TRUE;
3446 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3447 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3449 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3450 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3451 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3453 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3455 // note : not using the self::add method,
3456 // the reason because it performs 'status change' related code execution for financial records
3457 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3458 // are coded below i.e. just updating financial_item status to 'Paid'
3459 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3461 // add financial item entry
3462 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3463 $getLine['entity_id'] = $contributionDAO->id
;
3464 $getLine['entity_table'] = 'civicrm_contribution';
3465 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3466 if (!empty($lineItemId->id
)) {
3467 $addFinancialEntry = array(
3468 'transaction_date' => $financialTrxn->trxn_date
,
3469 'contact_id' => $contributionDAO->contact_id
,
3470 'amount' => $financialTrxn->total_amount
,
3471 'status_id' => array_search('Paid', $financialItemStatus),
3472 'entity_id' => $lineItemId->id
,
3473 'entity_table' => 'civicrm_line_item',
3475 $trxnIds['id'] = $financialTrxn->id
;
3476 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3478 if ($participantId) {
3479 // update participant status
3480 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3481 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3482 foreach ($ids as $val) {
3483 $participantUpdate['id'] = $val;
3484 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3485 CRM_Event_BAO_Participant
::add($participantUpdate);
3490 // activity creation
3491 if (!empty($financialTrxn)) {
3492 if ($participantId) {
3493 $inputParams['id'] = $participantId;
3496 $component = 'event';
3497 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3498 $entityObj = $entityObj[$participantId];
3500 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3502 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3504 return $financialTrxn;
3510 * @param $activityType
3512 * @param int $contributionId
3514 * @throws CRM_Core_Exception
3516 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3517 if ($component == 'event') {
3518 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3519 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3520 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3521 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3522 $targetCid = $entityObj->contact_id
;
3523 // source record id would be the contribution id
3524 $srcRecId = $contributionId;
3528 $activityParams = array(
3529 'source_contact_id' => $targetCid,
3530 'source_record_id' => $srcRecId,
3531 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3535 'subject' => $subject,
3536 'activity_date_time' => $date,
3537 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3541 'skipRecentView' => TRUE,
3544 // create activity with target contacts
3545 $session = CRM_Core_Session
::singleton();
3546 $id = $session->get('userID');
3548 $activityParams['source_contact_id'] = $id;
3549 $activityParams['target_contact_id'][] = $targetCid;
3551 CRM_Activity_BAO_Activity
::create($activityParams);
3555 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3559 * @param bool $getTrxnInfo
3560 * @param bool $usingLineTotal
3564 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3565 if ($component == 'event') {
3566 $entity = 'participant';
3567 $entityTable = 'civicrm_participant';
3568 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3570 if (!$contributionId) {
3571 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3572 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3573 $id = $primaryParticipantId;
3575 if (!$contributionId) {
3580 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3581 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3587 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3588 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3591 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3592 // for additional participants
3593 if ($entityTable == 'civicrm_participant') {
3594 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3596 foreach ($ids as $val) {
3597 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3601 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3605 $baseTrxnId = $total['trxn_id'];
3606 $total = $total['total_amount'];
3609 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3610 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3612 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3613 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3614 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3616 if ($paymentBalance == 0 && $contributionIsPayLater) {
3617 $paymentBalance = $total;
3620 $info['total'] = $total;
3621 $info['paid'] = $total - $paymentBalance;
3622 $info['balance'] = $paymentBalance;
3624 $info['component'] = $component;
3625 $info['payLater'] = $contributionIsPayLater;
3627 if ($getTrxnInfo && $baseTrxnId) {
3628 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3630 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3631 FROM civicrm_contribution con
3632 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3633 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3634 WHERE con.id = {$contributionId}
3637 // conditioned WHERE clause
3639 // if balance trxn exists don't include details of it in transaction info
3640 $sql .= " AND ft.id != {$baseTrxnId} ";
3642 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3644 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3645 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3646 while ($resultDAO->fetch()) {
3647 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3648 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3650 'total_amount' => $resultDAO->total_amount
,
3651 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3652 'payment_instrument' => $paidByLabel,
3653 'receive_date' => $resultDAO->trxn_date
,
3654 'trxn_id' => $resultDAO->trxn_id
,
3655 'status' => $statuses[$resultDAO->status_id
],
3657 if ($paidByName == 'Check') {
3658 $val['check_number'] = $resultDAO->check_number
;
3662 $info['transaction'] = $rows;
3668 * Get financial account id has 'Sales Tax Account is'
3669 * account relationship with financial type
3671 * @param int $financialTypeId
3673 * @return FinancialAccountId
3675 public static function getFinancialAccountId($financialTypeId) {
3676 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3677 $searchParams = array(
3678 'entity_table' => 'civicrm_financial_type',
3679 'entity_id' => $financialTypeId,
3680 'account_relationship' => $accountRel,
3683 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3685 return CRM_Utils_Array
::value('financial_account_id', $result);
3691 * @param array $params
3692 * @param bool $isLineItem
3696 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3697 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3699 // Update contribution.
3700 if (!empty($params['id'])) {
3701 $id = $params['id'];
3702 $values = $ids = array();
3703 $contrbutionParams = array('id' => $id);
3704 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3706 // To assign pervious finantial type on update of contribution
3707 if (!isset($params['financial_type_id'])) {
3708 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3710 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3711 // Assisn tax Amount on update of contrbution
3712 if (!empty($prevContributionValue->tax_amount
)) {
3713 $params['tax_amount'] = 'null';
3714 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3715 foreach ($params['line_item'] as $setID => $priceField) {
3716 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3717 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3724 // New Contrbution and update of contribution with tax rate financial type
3725 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3726 empty($params['skipLineItem']) && !$isLineItem
3728 $taxRateParams = $taxRates[$params['financial_type_id']];
3729 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3730 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3732 // Get Line Item on update of contribution
3733 if (isset($params['id'])) {
3734 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3737 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3739 foreach ($params['line_item'] as $setID => $priceField) {
3740 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3741 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3744 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3746 elseif (isset($params['api.line_item.create'])) {
3747 // Update total amount of contribution using lineItem
3748 $taxAmountArray = array();
3749 foreach ($params['api.line_item.create'] as $key => $value) {
3750 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3751 $taxRate = $taxRates[$value['financial_type_id']];
3752 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3753 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3756 $params['tax_amount'] = array_sum($taxAmountArray);
3757 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3760 // update line item of contrbution
3761 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3762 $taxRate = $taxRates[$params['financial_type_id']];
3763 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3764 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3771 * Check financial type validation on update of a contribution.
3773 * @param Integer $financialTypeId
3774 * Value of latest Financial Type.
3776 * @param Integer $contributionId
3779 * @param array $errors
3784 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3785 if (!empty($financialTypeId)) {
3786 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3787 if ($oldFinancialTypeId == $financialTypeId) {
3791 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3793 '1' => array($contributionId, 'Integer'),
3795 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3796 if ($result->N
> 1) {
3797 $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.');
3802 * Update related pledge payment payments.
3804 * This function has been refactored out of the back office contribution form and may
3805 * still overlap with other functions.
3807 * @param string $action
3808 * @param int $pledgePaymentID
3809 * @param int $contributionID
3810 * @param bool $adjustTotalAmount
3811 * @param float $total_amount
3812 * @param float $original_total_amount
3813 * @param int $contribution_status_id
3814 * @param int $original_contribution_status_id
3816 public static function updateRelatedPledge(
3822 $original_total_amount,
3823 $contribution_status_id,
3824 $original_contribution_status_id
3826 if (!$pledgePaymentID ||
$action & CRM_Core_Action
::ADD
&& !$contributionID) {
3830 if ($pledgePaymentID) {
3831 //store contribution id in payment record.
3832 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
3835 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3841 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3847 $updatePledgePaymentStatus = FALSE;
3849 // If either the status or the amount has changed we update the pledge status.
3850 if ($action & CRM_Core_Action
::ADD
) {
3851 $updatePledgePaymentStatus = TRUE;
3853 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
3854 ($original_total_amount != $total_amount))
3856 $updatePledgePaymentStatus = TRUE;
3859 if ($updatePledgePaymentStatus) {
3860 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
3861 array($pledgePaymentID),
3862 $contribution_status_id,
3871 * Compute the stats values
3873 * @param $stat either 'mode' or 'median'
3875 * @param $alias of civicrm_contribution
3877 public static function computeStats($stat, $sql, $alias = NULL) {
3878 $mode = $median = array();
3881 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
3882 while ($modeDAO->fetch()) {
3883 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
3884 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
3893 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
3894 foreach ($currencies as $currency => $val) {
3896 $where = "AND {$alias}.currency = '{$currency}'";
3897 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
3901 $medianRow = floor($rowCount / 2);
3902 if ($rowCount %
2 == 0 && !empty($medianRow)) {
3908 $medianValue = "SELECT {$alias}.total_amount as median
3910 ORDER BY median LIMIT {$medianRow},{$offset}";
3911 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
3912 while ($medianValDAO->fetch()) {
3914 $midValue = $midValue +
$medianValDAO->median
;
3917 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
3921 $midValue = $midValue / 2;
3922 $median[] = CRM_Utils_Money
::format($midValue, $currency);