3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
33 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
36 * Static field for all the contribution information that we can potentially import
40 static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 static $_exportableFields = NULL;
50 * Field for all the objects related to this contribution
51 * @var array of objects (e.g membership object, participant object)
53 public $_relatedObjects = array();
56 * Field for the component - either 'event' (participant) or 'contribute'
57 * (any item related to a contribution page e.g. membership, pledge, contribution)
58 * This is used for composing messages because they have dependency on the
59 * contribution_page or event page - although over time we may eliminate that
61 * @var string component or event
63 public $_component = NULL;
66 * Possibly obsolete variable.
68 * If you use it please explain why it is set in the create function here.
72 public $trxn_result_code;
77 * @return \CRM_Contribute_DAO_Contribution
81 public function __construct() {
82 parent
::__construct();
86 * Takes an associative array and creates a contribution object.
88 * the function extract all the params it needs to initialize the create a
89 * contribution object. the params array could contain additional unused name/value
92 * @param array $params
93 * (reference ) an assoc array of name/value pairs.
95 * The array that holds all the db ids.
97 * @return CRM_Contribute_BAO_Contribution|void
99 public static function add(&$params, $ids = array()) {
100 if (empty($params)) {
103 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
104 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
105 $duplicates = array();
106 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
107 $error = CRM_Core_Error
::singleton();
108 $d = implode(', ', $duplicates);
109 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
112 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
117 // first clean up all the money fields
118 $moneyFields = array(
122 'non_deductible_amount',
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
127 unset($moneyFields[0]);
130 foreach ($moneyFields as $field) {
131 if (isset($params[$field])) {
132 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
136 //if contribution is created with cancelled or refunded status, add credit note id
137 if (!empty($params['contribution_status_id'])) {
138 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
140 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
141 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
143 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
144 $params['creditnote_id'] = self
::createCreditNoteId();
149 //set defaults in create mode
150 if (!$contributionID) {
151 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
153 self
::calculateMissingAmountParams($params, $contributionID);
155 if (!empty($params['payment_instrument_id'])) {
156 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
157 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
158 $params['check_number'] = 'null';
162 $setPrevContribution = TRUE;
163 // CRM-13964 partial payment
164 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
165 $partialAmtTotal = $params['partial_payment_total'];
166 $partialAmtPay = $params['partial_amount_pay'];
167 $params['total_amount'] = $partialAmtTotal;
168 if ($partialAmtPay < $partialAmtTotal) {
169 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
170 $params['is_pay_later'] = 0;
171 $setPrevContribution = FALSE;
174 if ($contributionID && $setPrevContribution) {
175 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
178 if ($contributionID) {
179 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
182 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
184 $contribution = new CRM_Contribute_BAO_Contribution();
185 $contribution->copyValues($params);
187 $contribution->id
= $contributionID;
189 if (empty($contribution->id
)) {
190 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
191 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
192 $config = CRM_Core_Config
::singleton();
193 $contribution->currency
= $config->defaultCurrency
;
197 $result = $contribution->save();
199 // Add financial_trxn details as part of fix for CRM-4724
200 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
201 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
203 //add Account details
204 $params['contribution'] = $contribution;
205 self
::recordFinancialAccounts($params);
207 // reset the group contact cache for this group
208 CRM_Contact_BAO_GroupContactCache
::remove();
210 if ($contributionID) {
211 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
214 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
221 * Get defaults for new entity.
224 public static function getDefaults() {
226 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
227 FALSE, FALSE, FALSE, 'AND is_default = 1')
229 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
234 * Given the list of params in the params array, fetch the object
235 * and store the values in the values array
237 * @param array $params
238 * Input parameters to find object.
239 * @param array $values
240 * Output values of the object.
242 * The array that holds all the db ids.
244 * @return CRM_Contribute_BAO_Contribution|null
245 * The found object or null
247 public static function getValues($params, &$values, &$ids) {
248 if (empty($params)) {
251 $contribution = new CRM_Contribute_BAO_Contribution();
253 $contribution->copyValues($params);
255 if ($contribution->find(TRUE)) {
256 $ids['contribution'] = $contribution->id
;
258 CRM_Core_DAO
::storeValues($contribution, $values);
260 return $contribution;
262 $null = NULL; // return by reference
267 * Calculate net_amount & fee_amount if they are not set.
269 * Net amount should be total - fee.
270 * This should only be called for new contributions.
272 * @param array $params
273 * Params for a new contribution before they are saved.
274 * @param int|null $contributionID
275 * Contribution ID if we are dealing with an update.
277 * @throws \CiviCRM_API3_Exception
279 public static function calculateMissingAmountParams(&$params, $contributionID) {
280 if (!$contributionID && !isset($params['fee_amount'])) {
281 if (isset($params['total_amount']) && isset($params['net_amount'])) {
282 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
285 $params['fee_amount'] = 0;
288 if (!isset($params['net_amount'])) {
289 if (!$contributionID) {
290 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
293 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
294 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
295 // net_amount may need adjusting.
296 $contribution = civicrm_api3('Contribution', 'getsingle', array(
297 'id' => $contributionID,
298 'return' => array('total_amount', 'net_amount'),
300 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
301 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
302 $params['net_amount'] = $totalAmount - $feeAmount;
310 * @param $billingLocationTypeID
314 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
315 $hasBillingField = FALSE;
316 $billingFields = array(
324 //build address array
325 $addressParams = array();
326 $addressParams['location_type_id'] = $billingLocationTypeID;
327 $addressParams['is_billing'] = 1;
329 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
330 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
331 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
332 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
334 foreach ($billingFields as $value) {
335 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
336 if (!empty($addressParams[$value])) {
337 $hasBillingField = TRUE;
340 return array($hasBillingField, $addressParams);
344 * Get address params ready to be passed to the payment processor.
346 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
347 * To create an address we need state_province_id.
349 * @param array $params
350 * @param int $billingLocationTypeID
354 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
355 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
356 foreach ($addressParams as $name => $field) {
357 if (substr($name, 0, 8) == 'billing_') {
358 $addressParams[substr($name, 9)] = $addressParams[$field];
361 return array($hasBillingField, $addressParams);
365 * Get the number of terms for this contribution for a given membership type
366 * based on querying the line item table and relevant price field values
367 * Note that any one contribution should only be able to have one line item relating to a particular membership
370 * @param int $membershipTypeID
372 * @param int $contributionID
376 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
377 $numTerms = CRM_Core_DAO
::singleValueQuery("
378 SELECT membership_num_terms FROM civicrm_line_item li
379 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
380 WHERE contribution_id = %1 AND membership_type_id = %2",
381 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
383 // default of 1 is precautionary
384 return empty($numTerms) ?
1 : $numTerms;
388 * Takes an associative array and creates a contribution object.
390 * @param array $params
391 * (reference ) an assoc array of name/value pairs.
393 * The array that holds all the db ids.
395 * @return CRM_Contribute_BAO_Contribution
397 public static function create(&$params, $ids = array()) {
398 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
399 foreach ($dateFields as $df) {
400 if (isset($params[$df])) {
401 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
405 //if contribution is created with cancelled or refunded status, add credit note id
406 if (!empty($params['contribution_status_id'])) {
407 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
409 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
410 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
412 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
413 $params['creditnote_id'] = self
::createCreditNoteId();
418 $transaction = new CRM_Core_Transaction();
420 $contribution = self
::add($params, $ids);
422 if (is_a($contribution, 'CRM_Core_Error')) {
423 $transaction->rollback();
424 return $contribution;
427 $params['contribution_id'] = $contribution->id
;
429 if (!empty($params['custom']) &&
430 is_array($params['custom'])
432 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
435 $session = CRM_Core_Session
::singleton();
437 if (!empty($params['note'])) {
439 'entity_table' => 'civicrm_contribution',
440 'note' => $params['note'],
441 'entity_id' => $contribution->id
,
442 'contact_id' => $session->get('userID'),
443 'modified_date' => date('Ymd'),
445 if (!$noteParams['contact_id']) {
446 $noteParams['contact_id'] = $params['contact_id'];
448 CRM_Core_BAO_Note
::add($noteParams);
451 // make entry in batch entity batch table
452 if (!empty($params['batch_id'])) {
453 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
454 $titleFields = array(
460 $retrieveRequired = 0;
461 foreach ($titleFields as $titleField) {
462 if (!isset($contribution->$titleField)) {
463 $retrieveRequired = 1;
467 if ($retrieveRequired == 1) {
468 $contribution->find(TRUE);
472 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
474 $transaction->commit();
476 // check if activity record exist for this contribution, if
478 $activity = new CRM_Activity_DAO_Activity();
479 $activity->source_record_id
= $contribution->id
;
480 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
484 if (!$activity->find(TRUE)) {
485 if (empty($contribution->contact_id
)) {
486 $contribution->find(TRUE);
488 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
491 // CRM-13237 : if activity record found, update it with campaign id of contribution
492 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
495 // do not add to recent items for import, CRM-4399
496 if (empty($params['skipRecentView'])) {
497 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
498 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
500 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
501 $titleFields = array(
507 $retrieveRequired = 0;
508 foreach ($titleFields as $titleField) {
509 if (!isset($contribution->$titleField)) {
510 $retrieveRequired = 1;
514 if ($retrieveRequired == 1) {
515 $contribution->find(TRUE);
517 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
518 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
520 $recentOther = array();
521 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
522 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
523 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
527 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
528 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
529 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
533 // add the recently created Contribution
534 CRM_Utils_Recent
::add($title,
538 $contribution->contact_id
,
544 return $contribution;
548 * Get the values for pseudoconstants for name->value and reverse.
550 * @param array $defaults
551 * (reference) the default values, some of which need to be resolved.
552 * @param bool $reverse
553 * True if we want to resolve the values in the reverse direction (value -> name).
555 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
556 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
557 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
558 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
559 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
563 * Convert associative array names to values and vice-versa.
565 * This function is used by both the web form layer and the api. Note that
566 * the api needs the name => value conversion, also the view layer typically
567 * requires value => name conversion
569 * @param array $defaults
570 * @param string $property
571 * @param array $lookup
572 * @param bool $reverse
576 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
577 $id = $property . '_id';
579 $src = $reverse ?
$property : $id;
580 $dst = $reverse ?
$id : $property;
582 if (!array_key_exists($src, $defaults)) {
586 $look = $reverse ?
array_flip($lookup) : $lookup;
588 if (is_array($look)) {
589 if (!array_key_exists($defaults[$src], $look)) {
593 $defaults[$dst] = $look[$defaults[$src]];
598 * Retrieve DB object based on input parameters.
600 * It also stores all the retrieved values in the default array.
602 * @param array $params
603 * (reference ) an assoc array of name/value pairs.
604 * @param array $defaults
605 * (reference ) an assoc array to hold the name / value pairs.
606 * in a hierarchical manner
608 * (reference) the array that holds all the db ids.
610 * @return CRM_Contribute_BAO_Contribution
612 public static function retrieve(&$params, &$defaults, &$ids) {
613 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
614 return $contribution;
618 * Combine all the importable fields from the lower levels object.
620 * The ordering is important, since currently we do not have a weight
621 * scheme. Adding weight is super important and should be done in the
622 * next week or so, before this can be called complete.
624 * @param string $contactType
625 * @param bool $status
628 * array of importable Fields
630 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
631 if (!self
::$_importableFields) {
632 if (!self
::$_importableFields) {
633 self
::$_importableFields = array();
637 $fields = array('' => array('title' => ts('- do not import -')));
640 $fields = array('' => array('title' => ts('- Contribution Fields -')));
643 $note = CRM_Core_DAO_Note
::import();
644 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
645 unset($tmpFields['option_value']);
646 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
647 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
649 // Using new Dedupe rule.
651 'contact_type' => $contactType,
652 'used' => 'Unsupervised',
654 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
655 $tmpContactField = array();
656 if (is_array($fieldsArray)) {
657 foreach ($fieldsArray as $value) {
658 //skip if there is no dupe rule
659 if ($value == 'none') {
662 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
667 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
668 $tmpContactField[trim($value)] = $contactFields[trim($value)];
670 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
673 $title = $tmpContactField[trim($value)]['title'];
675 $tmpContactField[trim($value)]['title'] = $title;
679 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
680 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
681 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
682 $fields = array_merge($fields, $tmpContactField);
683 $fields = array_merge($fields, $tmpFields);
684 $fields = array_merge($fields, $note);
685 $fields = array_merge($fields, $optionFields);
686 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
687 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
688 self
::$_importableFields = $fields;
690 return self
::$_importableFields;
696 public static function &exportableFields() {
697 if (!self
::$_exportableFields) {
698 if (!self
::$_exportableFields) {
699 self
::$_exportableFields = array();
702 $impFields = CRM_Contribute_DAO_Contribution
::export();
703 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
704 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
705 $typeField = CRM_Financial_DAO_FinancialType
::export();
706 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
707 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
708 $contributionStatus = array(
709 'contribution_status' => array(
710 'title' => ts('Contribution Status'),
711 'name' => 'contribution_status',
712 'data_type' => CRM_Utils_Type
::T_STRING
,
716 $contributionPage = array(
717 'contribution_page' => array(
718 'title' => ts('Contribution Page'),
719 'name' => 'contribution_page',
720 'where' => 'civicrm_contribution_page.title',
721 'data_type' => CRM_Utils_Type
::T_STRING
,
725 $contributionNote = array(
726 'contribution_note' => array(
727 'title' => ts('Contribution Note'),
728 'name' => 'contribution_note',
729 'data_type' => CRM_Utils_Type
::T_TEXT
,
733 $contributionRecurId = array(
734 'contribution_recur_id' => array(
735 'title' => ts('Recurring Contributions ID'),
736 'name' => 'contribution_recur_id',
737 'where' => 'civicrm_contribution.contribution_recur_id',
738 'data_type' => CRM_Utils_Type
::T_INT
,
742 $extraFields = array(
743 'contribution_batch' => array(
744 'title' => ts('Batch Name'),
748 $softCreditFields = array(
749 'contribution_soft_credit_name' => array(
750 'name' => 'contribution_soft_credit_name',
751 'title' => 'Soft Credit For',
752 'where' => 'civicrm_contact_d.display_name',
753 'data_type' => CRM_Utils_Type
::T_STRING
,
755 'contribution_soft_credit_amount' => array(
756 'name' => 'contribution_soft_credit_amount',
757 'title' => 'Soft Credit Amount',
758 'where' => 'civicrm_contribution_soft.amount',
759 'data_type' => CRM_Utils_Type
::T_MONEY
,
761 'contribution_soft_credit_type' => array(
762 'name' => 'contribution_soft_credit_type',
763 'title' => 'Soft Credit Type',
764 'where' => 'contribution_softcredit_type.label',
765 'data_type' => CRM_Utils_Type
::T_STRING
,
767 'contribution_soft_credit_contribution_id' => array(
768 'name' => 'contribution_soft_credit_contribution_id',
769 'title' => 'Soft Credit For Contribution ID',
770 'where' => 'civicrm_contribution_soft.contribution_id',
771 'data_type' => CRM_Utils_Type
::T_INT
,
773 'contribution_soft_credit_contact_id' => array(
774 'name' => 'contribution_soft_credit_contact_id',
775 'title' => 'Soft Credit For Contact ID',
776 'where' => 'civicrm_contact_d.id',
777 'data_type' => CRM_Utils_Type
::T_INT
,
781 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
783 'contribution_product_id' => array(
784 'title' => ts('Premium'),
785 'name' => 'contribution_product_id',
786 'where' => 'civicrm_product.id',
787 'data_type' => CRM_Utils_Type
::T_INT
,
791 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
792 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums,
793 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
796 self
::$_exportableFields = $fields;
799 return self
::$_exportableFields;
803 * @param null $status
804 * @param null $startDate
805 * @param null $endDate
809 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
813 $where[] = 'contribution_status_id = 1';
817 $where[] = 'contribution_status_id = 3';
822 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
825 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
827 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
828 if ($financialTypes) {
829 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
830 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
833 $where[] = "c.financial_type_id IN (0)";
836 $whereCond = implode(' AND ', $where);
839 SELECT sum( total_amount ) as total_amount,
840 count( c.id ) as total_count,
842 FROM civicrm_contribution c
843 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
844 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
846 AND ( is_test = 0 OR is_test IS NULL )
847 AND contact.is_deleted = 0
851 $dao = CRM_Core_DAO
::executeQuery($query);
854 while ($dao->fetch()) {
855 $count +
= $dao->total_count
;
856 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
860 'amount' => implode(', ', $amount),
868 * Delete the indirect records associated with this contribution first.
873 * $results no of deleted Contribution on success, false otherwise
875 public static function deleteContribution($id) {
876 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
878 $transaction = new CRM_Core_Transaction();
881 //delete activity record
883 'source_record_id' => $id,
884 // activity type id for contribution
885 'activity_type_id' => 6,
888 CRM_Activity_BAO_Activity
::deleteActivity($params);
890 //delete billing address if exists for this contribution.
891 self
::deleteAddress($id);
893 //update pledge and pledge payment, CRM-3961
894 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
896 // remove entry from civicrm_price_set_entity, CRM-5095
897 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
898 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
900 // cleanup line items.
901 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
903 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
904 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
906 if ($participantId) {
907 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
910 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
914 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
915 $noteId = key($note);
917 CRM_Core_BAO_Note
::del($noteId, FALSE);
920 $dao = new CRM_Contribute_DAO_Contribution();
923 $results = $dao->delete();
925 $transaction->commit();
927 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
929 // delete the recently created Contribution
930 $contributionRecent = array(
932 'type' => 'Contribution',
934 CRM_Utils_Recent
::del($contributionRecent);
940 * React to a financial transaction (payment) failure.
942 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
943 * payments is important for forensic and outreach reasons.
945 * @param int $contributionID
946 * @param int $contactID
947 * @param string $message
949 * @throws \CiviCRM_API3_Exception
951 public static function failPayment($contributionID, $contactID, $message) {
952 civicrm_api3('activity', 'create', array(
953 'activity_type_id' => 'Failed Payment',
954 'details' => $message,
955 'subject' => ts('Payment failed at payment processor'),
956 'source_record_id' => $contributionID,
957 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
963 * Check if there is a contribution with the same trxn_id or invoice_id.
965 * @param array $input
966 * An assoc array of name/value pairs.
967 * @param array $duplicates
968 * (reference) store ids of duplicate contribs.
972 * true if duplicate, false otherwise
974 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
976 $id = CRM_Utils_Array
::value('id', $input);
978 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
979 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
985 $clause[] = "trxn_id = %1";
986 $input[1] = array($trxn_id, 'String');
990 $clause[] = "invoice_id = %2";
991 $input[2] = array($invoice_id, 'String');
994 if (empty($clause)) {
998 $clause = implode(' OR ', $clause);
1000 $clause = "( $clause ) AND id != %3";
1001 $input[3] = array($id, 'Integer');
1004 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1005 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1007 while ($dao->fetch()) {
1008 $duplicates[] = $dao->id
;
1015 * Takes an associative array and creates a contribution_product object.
1017 * the function extract all the params it needs to initialize the create a
1018 * contribution_product object. the params array could contain additional unused name/value
1021 * @param array $params
1022 * (reference) an assoc array of name/value pairs.
1024 * @return CRM_Contribute_DAO_ContributionProduct
1026 public static function addPremium(&$params) {
1027 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1028 $contributionProduct->copyValues($params);
1029 return $contributionProduct->save();
1033 * Get list of contribution fields for profile.
1034 * For now we only allow custom contribution fields to be in
1037 * @param bool $addExtraFields
1038 * True if special fields needs to be added.
1041 * the list of contribution fields
1043 public static function getContributionFields($addExtraFields = TRUE) {
1044 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1045 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1047 if ($addExtraFields) {
1048 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1051 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1053 foreach ($contributionFields as $key => $var) {
1054 if ($key == 'contribution_contact_id') {
1057 elseif ($key == 'contribution_campaign_id') {
1058 $var['title'] = ts('Campaign');
1060 $fields[$key] = $var;
1063 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1068 * Add extra fields specific to contribution.
1070 public static function getSpecialContributionFields() {
1071 $extraFields = array(
1072 'contribution_soft_credit_name' => array(
1073 'name' => 'contribution_soft_credit_name',
1074 'title' => 'Soft Credit Name',
1075 'headerPattern' => '/^soft_credit_name$/i',
1076 'where' => 'civicrm_contact_d.display_name',
1078 'contribution_soft_credit_email' => array(
1079 'name' => 'contribution_soft_credit_email',
1080 'title' => 'Soft Credit Email',
1081 'headerPattern' => '/^soft_credit_email$/i',
1082 'where' => 'soft_email.email',
1084 'contribution_soft_credit_phone' => array(
1085 'name' => 'contribution_soft_credit_phone',
1086 'title' => 'Soft Credit Phone',
1087 'headerPattern' => '/^soft_credit_phone$/i',
1088 'where' => 'soft_phone.phone',
1090 'contribution_soft_credit_contact_id' => array(
1091 'name' => 'contribution_soft_credit_contact_id',
1092 'title' => 'Soft Credit Contact ID',
1093 'headerPattern' => '/^soft_credit_contact_id$/i',
1094 'where' => 'civicrm_contribution_soft.contact_id',
1096 'contribution_pcp_title' => array(
1097 'name' => 'contribution_pcp_title',
1098 'title' => 'Personal Campaign Page Title',
1099 'headerPattern' => '/^contribution_pcp_title$/i',
1100 'where' => 'contribution_pcp.title',
1104 return $extraFields;
1108 * @param int $pageID
1112 public static function getCurrentandGoalAmount($pageID) {
1114 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1115 FROM civicrm_contribution_page p,
1116 civicrm_contribution c
1117 WHERE p.id = c.contribution_page_id
1119 AND c.cancel_date is null
1123 $config = CRM_Core_Config
::singleton();
1124 $params = array(1 => array($pageID, 'Integer'));
1125 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1127 if ($dao->fetch()) {
1128 return array($dao->goal
, $dao->total
);
1131 return array(NULL, NULL);
1136 * Get list of contribution In Honor of contact Ids.
1138 * @param int $honorId
1139 * In Honor of Contact ID.
1142 * list of contribution fields
1144 public static function getHonorContacts($honorId) {
1146 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1147 $honorDAO->contact_id
= $honorId;
1150 $type = CRM_Contribute_PseudoConstant
::financialType();
1152 while ($honorDAO->fetch()) {
1153 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1154 $contributionDAO->id
= $honorDAO->contribution_id
;
1156 if ($contributionDAO->find(TRUE)) {
1157 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1158 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1159 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1160 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1161 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1162 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1163 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1164 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1165 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1173 * Get the sort name of a contact for a particular contribution.
1176 * Id of the contribution.
1178 * @return null|string
1179 * sort name of the contact if found
1181 public static function sortName($id) {
1182 $id = CRM_Utils_Type
::escape($id, 'Integer');
1185 SELECT civicrm_contact.sort_name
1186 FROM civicrm_contribution, civicrm_contact
1187 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1188 AND civicrm_contribution.id = {$id}
1190 return CRM_Core_DAO
::singleValueQuery($query);
1194 * @param int $contactID
1198 public static function annual($contactID) {
1199 if (is_array($contactID)) {
1200 $contactIDs = implode(',', $contactID);
1203 $contactIDs = $contactID;
1206 $config = CRM_Core_Config
::singleton();
1207 $startDate = $endDate = NULL;
1209 $currentMonth = date('m');
1210 $currentDay = date('d');
1211 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1212 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1213 (int ) $config->fiscalYearStart
['d'] > $currentDay
1216 $year = date('Y') - 1;
1221 $nextYear = $year +
1;
1223 if ($config->fiscalYearStart
) {
1224 $newFiscalYearStart = $config->fiscalYearStart
;
1225 if ($newFiscalYearStart['M'] < 10) {
1226 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1228 if ($newFiscalYearStart['d'] < 10) {
1229 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1231 $config->fiscalYearStart
= $newFiscalYearStart;
1232 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1237 $startDate = "$year$monthDay";
1238 $endDate = "$nextYear$monthDay";
1239 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1240 $additionalWhere = " AND b.financial_type_id IN (0)";
1241 $liWhere = " AND i.financial_type_id IN (0)";
1242 if (!empty($financialTypes)) {
1243 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1244 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1247 SELECT count(*) as count,
1248 sum(total_amount) as amount,
1249 avg(total_amount) as average,
1251 FROM civicrm_contribution b
1252 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1253 WHERE b.contact_id IN ( $contactIDs )
1254 AND b.contribution_status_id = 1
1256 AND b.receive_date >= $startDate
1257 AND b.receive_date < $endDate
1261 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1263 $amount = $average = array();
1264 while ($dao->fetch()) {
1265 if ($dao->count
> 0 && $dao->amount
> 0) {
1266 $count +
= $dao->count
;
1267 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1268 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1274 implode(', ', $amount),
1275 implode(', ', $average),
1278 return array(0, 0, 0);
1282 * Check if there is a contribution with the params passed in.
1284 * Used for trxn_id,invoice_id and contribution_id
1286 * @param array $params
1287 * An assoc array of name/value pairs.
1290 * contribution id if success else NULL
1292 public static function checkDuplicateIds($params) {
1293 $dao = new CRM_Contribute_DAO_Contribution();
1297 foreach ($params as $k => $v) {
1299 $clause[] = "$k = '$v'";
1302 $clause = implode(' AND ', $clause);
1303 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1304 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1306 while ($dao->fetch()) {
1314 * Get the contribution details for component export.
1316 * @param int $exportMode
1318 * @param string $componentIds
1324 public static function getContributionDetails($exportMode, $componentIds) {
1325 $paymentDetails = array();
1326 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1328 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1329 $componentSelect = " civicrm_participant_payment.participant_id id";
1330 $additionalClause = "
1331 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1332 AND civicrm_participant_payment.participant_id {$componentClause} )
1335 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1336 $componentSelect = " civicrm_membership_payment.membership_id id";
1337 $additionalClause = "
1338 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1339 AND civicrm_membership_payment.membership_id {$componentClause} )
1342 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1343 $componentSelect = " civicrm_pledge_payment.id id";
1344 $additionalClause = "
1345 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1346 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1350 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1351 trxn_id, {$componentSelect}
1352 FROM civicrm_contribution
1353 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1354 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1355 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1356 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1357 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1358 AND option_group_contribution_status.id = contribution_status.option_group_id )
1362 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1364 while ($dao->fetch()) {
1365 $paymentDetails[$dao->id
] = array(
1366 'total_amount' => $dao->total_amount
,
1367 'contribution_status' => $dao->status
,
1368 'receive_date' => $dao->receive_date
,
1369 'pay_instru' => $dao->payment_instrument
,
1370 'trxn_id' => $dao->trxn_id
,
1374 return $paymentDetails;
1378 * Create address associated with contribution record.
1380 * As long as there is one or more billing field in the parameters we will create the address.
1382 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1385 * @param array $params
1386 * @param int $billingLocationTypeID
1391 public static function createAddress($params, $billingLocationTypeID) {
1392 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1393 if ($hasBillingField) {
1394 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1395 return $address->id
;
1402 * Delete billing address record related contribution.
1404 * @param int $contributionId
1405 * @param int $contactId
1407 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1409 $contactJoin = NULL;
1411 if ($contributionId) {
1412 $clauses[] = "cc.id = {$contributionId}";
1416 $clauses[] = "cco.id = {$contactId}";
1417 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1420 if (empty($clauses)) {
1421 CRM_Core_Error
::fatal();
1424 $condition = implode(' OR ', $clauses);
1428 FROM civicrm_address ca
1429 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1433 $dao = CRM_Core_DAO
::executeQuery($query);
1435 while ($dao->fetch()) {
1436 $params = array('id' => $dao->id
);
1437 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1442 * This function check online pending contribution associated w/
1443 * Online Event Registration or Online Membership signup.
1445 * @param int $componentId
1446 * Participant/membership id.
1447 * @param string $componentName
1451 * pending contribution id.
1453 public static function checkOnlinePendingContribution($componentId, $componentName) {
1454 $contributionId = NULL;
1455 if (!$componentId ||
1456 !in_array($componentName, array('Event', 'Membership'))
1458 return $contributionId;
1461 if ($componentName == 'Event') {
1462 $idName = 'participant_id';
1463 $componentTable = 'civicrm_participant';
1464 $paymentTable = 'civicrm_participant_payment';
1465 $source = ts('Online Event Registration');
1468 if ($componentName == 'Membership') {
1469 $idName = 'membership_id';
1470 $componentTable = 'civicrm_membership';
1471 $paymentTable = 'civicrm_membership_payment';
1472 $source = ts('Online Contribution');
1475 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1478 SELECT component.id as {$idName},
1479 componentPayment.contribution_id as contribution_id,
1480 contribution.source source,
1481 contribution.contribution_status_id as contribution_status_id,
1482 contribution.is_pay_later as is_pay_later
1483 FROM $componentTable component
1484 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1485 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1486 WHERE component.id = {$componentId}";
1488 $dao = CRM_Core_DAO
::executeQuery($query);
1490 while ($dao->fetch()) {
1491 if ($dao->contribution_id
&&
1492 $dao->is_pay_later
&&
1493 $dao->contribution_status_id
== $pendingStatusId &&
1494 strpos($dao->source
, $source) !== FALSE
1496 $contributionId = $dao->contribution_id
;
1501 return $contributionId;
1505 * Update contribution as well as related objects.
1507 * This function by-passes hooks - to address this - don't use this function.
1511 * Use api contribute.completetransaction
1512 * For failures use failPayment (preferably exposing by api in the process).
1514 * @param array $params
1515 * @param bool $processContributionObject
1518 * @throws \Exception
1520 public static function transitionComponents($params, $processContributionObject = FALSE) {
1521 // get minimum required values.
1522 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1523 $componentId = CRM_Utils_Array
::value('component_id', $params);
1524 $componentName = CRM_Utils_Array
::value('componentName', $params);
1525 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1526 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1528 // if we already processed contribution object pass previous status id.
1529 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1531 $updateResult = array();
1533 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1535 // we process only ( Completed, Cancelled, or Failed ) contributions.
1536 if (!$contributionId ||
1537 !in_array($contributionStatusId, array(
1538 array_search('Completed', $contributionStatuses),
1539 array_search('Cancelled', $contributionStatuses),
1540 array_search('Failed', $contributionStatuses),
1543 return $updateResult;
1546 if (!$componentName ||
!$componentId) {
1547 // get the related component details.
1548 $componentDetails = self
::getComponentDetails($contributionId);
1551 $componentDetails['contact_id'] = $contactId;
1552 $componentDetails['component'] = $componentName;
1554 if ($componentName == 'event') {
1555 $componentDetails['participant'] = $componentId;
1558 $componentDetails['membership'] = $componentId;
1562 if (!empty($componentDetails['contact_id'])) {
1563 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1569 // do check for required ids.
1570 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1571 return $updateResult;
1574 //now we are ready w/ required ids, start processing.
1576 $baseIPN = new CRM_Core_Payment_BaseIPN();
1578 $input = $ids = $objects = array();
1580 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1581 $ids['contribution'] = $contributionId;
1582 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1583 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1584 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1585 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1586 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1587 $ids['contributionRecur'] = NULL;
1588 $ids['contributionPage'] = NULL;
1590 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1591 CRM_Core_Error
::fatal();
1594 $memberships = &$objects['membership'];
1595 $participant = &$objects['participant'];
1596 $pledgePayment = &$objects['pledge_payment'];
1597 $contribution = &$objects['contribution'];
1599 if ($pledgePayment) {
1600 $pledgePaymentIDs = array();
1601 foreach ($pledgePayment as $key => $object) {
1602 $pledgePaymentIDs[] = $object->id
;
1604 $pledgeID = $pledgePayment[0]->pledge_id
;
1607 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1610 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1611 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1616 // we might want to process contribution object.
1617 $processContribution = FALSE;
1618 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1619 if (is_array($memberships)) {
1620 foreach ($memberships as $membership) {
1622 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1623 $membership->save();
1625 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1626 if ($processContributionObject) {
1627 $processContribution = TRUE;
1634 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1635 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1637 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1638 if ($processContributionObject) {
1639 $processContribution = TRUE;
1643 if ($pledgePayment) {
1644 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1646 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1647 if ($processContributionObject) {
1648 $processContribution = TRUE;
1652 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1653 if (is_array($memberships)) {
1654 foreach ($memberships as $membership) {
1656 $membership->status_id
= array_search('Expired', $membershipStatuses);
1657 $membership->save();
1659 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1660 if ($processContributionObject) {
1661 $processContribution = TRUE;
1667 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1668 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1670 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1671 if ($processContributionObject) {
1672 $processContribution = TRUE;
1676 if ($pledgePayment) {
1677 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1679 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1680 if ($processContributionObject) {
1681 $processContribution = TRUE;
1685 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1687 // only pending contribution related object processed.
1688 if ($previousContriStatusId &&
1689 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1691 // this is case when we already processed contribution object.
1692 return $updateResult;
1694 elseif (!$previousContriStatusId &&
1695 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1697 // this is case when we are going to process contribution object later.
1698 return $updateResult;
1701 if (is_array($memberships)) {
1702 foreach ($memberships as $membership) {
1707 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1708 $membership->membership_type_id
,
1709 $membership->is_test
, $membership->id
1712 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1713 // this picks up membership type changes during renewals
1715 SELECT membership_type_id
1716 FROM civicrm_membership_log
1717 WHERE membership_id=$membership->id
1720 $dao = new CRM_Core_DAO();
1722 if ($dao->fetch()) {
1723 if (!empty($dao->membership_type_id
)) {
1724 $membership->membership_type_id
= $dao->membership_type_id
;
1725 $membership->save();
1728 // else fall back to using current membership type
1731 // Figure out number of terms
1733 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1734 foreach ($lineitems as $lineitem) {
1735 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1736 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1738 // in case membership_num_terms comes through as null or zero
1739 $numterms = $numterms >= 1 ?
$numterms : 1;
1744 // CRM-15735-to update the membership status as per the contribution receive date
1746 if (!empty($params['receive_date'])) {
1747 $joinDate = $params['receive_date'];
1748 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1749 $membership->end_date
,
1750 $membership->join_date
,
1751 $params['receive_date'],
1753 $membership->membership_type_id
,
1756 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1757 $membership->save();
1760 if ($currentMembership) {
1761 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1762 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1763 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1766 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1769 //get the status for membership.
1770 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1772 $dates['join_date'],
1775 $membership->membership_type_id
,
1779 $formattedParams = array(
1780 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1781 array_search('Current', $membershipStatuses)
1783 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1784 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1785 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1788 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1790 $membership->copyValues($formattedParams);
1791 $membership->save();
1793 //updating the membership log
1794 $membershipLog = array();
1795 $membershipLog = $formattedParams;
1796 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1797 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1799 $membershipLog['start_date'] = $logStartDate;
1800 $membershipLog['membership_id'] = $membership->id
;
1801 $membershipLog['modified_id'] = $membership->contact_id
;
1802 $membershipLog['modified_date'] = date('Ymd');
1803 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1805 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1807 //update related Memberships.
1808 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1810 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1813 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1814 if ($processContributionObject) {
1815 $processContribution = TRUE;
1818 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1824 $updatedStatusId = array_search('Registered', $participantStatuses);
1825 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1827 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1828 if ($processContributionObject) {
1829 $processContribution = TRUE;
1833 if ($pledgePayment) {
1834 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1836 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1837 if ($processContributionObject) {
1838 $processContribution = TRUE;
1843 // process contribution object.
1844 if ($processContribution) {
1845 $contributionParams = array();
1852 'payment_instrument_id',
1855 'financial_type_id',
1856 'contribution_status_id',
1857 'non_deductible_amount',
1861 foreach ($fields as $field) {
1862 if (empty($params[$field])) {
1865 $contributionParams[$field] = $params[$field];
1868 $ids = array('contribution' => $contributionId);
1869 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1872 return $updateResult;
1876 * Returns all contribution related object ids.
1878 * @param $contributionId
1882 public static function getComponentDetails($contributionId) {
1883 $componentDetails = $pledgePayment = array();
1884 if (!$contributionId) {
1885 return $componentDetails;
1889 SELECT c.id as contribution_id,
1890 c.contact_id as contact_id,
1891 c.contribution_recur_id,
1892 mp.membership_id as membership_id,
1893 m.membership_type_id as membership_type_id,
1894 pp.participant_id as participant_id,
1895 p.event_id as event_id,
1896 pgp.id as pledge_payment_id
1897 FROM civicrm_contribution c
1898 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1899 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1900 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1901 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1902 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1903 WHERE c.id = $contributionId";
1905 $dao = CRM_Core_DAO
::executeQuery($query);
1906 $componentDetails = array();
1908 while ($dao->fetch()) {
1909 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1910 $componentDetails['contact_id'] = $dao->contact_id
;
1911 if ($dao->event_id
) {
1912 $componentDetails['event'] = $dao->event_id
;
1914 if ($dao->participant_id
) {
1915 $componentDetails['participant'] = $dao->participant_id
;
1917 if ($dao->membership_id
) {
1918 if (!isset($componentDetails['membership'])) {
1919 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1921 $componentDetails['membership'][] = $dao->membership_id
;
1922 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1924 if ($dao->pledge_payment_id
) {
1925 $pledgePayment[] = $dao->pledge_payment_id
;
1927 if ($dao->contribution_recur_id
) {
1928 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1932 if ($pledgePayment) {
1933 $componentDetails['pledge_payment'] = $pledgePayment;
1936 return $componentDetails;
1940 * @param int $contactId
1941 * @param bool $includeSoftCredit
1943 * @return null|string
1945 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1949 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1950 $additionalWhere = " AND contribution.financial_type_id IN (0)";
1951 $liWhere = " AND i.financial_type_id IN (0)";
1952 if (!empty($financialTypes)) {
1953 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1954 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1956 $contactContributionsSQL = "
1957 SELECT contribution.id AS id
1958 FROM civicrm_contribution contribution
1959 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
1960 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
1964 $contactSoftCreditContributionsSQL = "
1965 SELECT contribution.id
1966 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1967 ON ( contribution.id = softContribution.contribution_id )
1968 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1969 $query = "SELECT count( x.id ) count FROM ( ";
1970 $query .= $contactContributionsSQL;
1972 if ($includeSoftCredit) {
1973 $query .= " UNION ";
1974 $query .= $contactSoftCreditContributionsSQL;
1979 return CRM_Core_DAO
::singleValueQuery($query);
1983 * Repeat a transaction as part of a recurring series.
1985 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
1986 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
1987 * subsequent call to the contribution.completetransaction api.
1989 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
1991 * @param CRM_Contribute_BAO_Contribution $contribution
1992 * @param array $input
1993 * @param array $contributionParams
1997 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
1998 if (!empty($contribution->id
)) {
2001 if (empty($contribution->id
)) {
2002 // Unclear why this would only be set for repeats.
2003 if (!empty($input['amount'])) {
2004 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2006 $templateContribution = civicrm_api3('Contribution', 'getsingle', array(
2007 'contribution_recur_id' => $contributionParams['contribution_recur_id'],
2008 'options' => array('limit' => 1),
2010 $contributionParams['skipLineItem'] = TRUE;
2011 $contributionParams['status_id'] = 'Pending';
2012 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2013 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2014 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2015 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2016 $contribution->id
= $createContribution['id'];
2017 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
2018 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2024 * Get individual id for onbehalf contribution.
2026 * @param int $contributionId
2028 * @param int $contributorId
2032 * containing organization id and individual id
2034 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2038 if (!$contributionId) {
2042 // fetch contributor id if null
2043 if (!$contributorId) {
2044 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2045 $contributionId, 'contact_id'
2049 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2050 $activityTypeId = array_search('Contribution', $activityTypeIds);
2052 if ($activityTypeId && $contributorId) {
2054 SELECT civicrm_activity_contact.contact_id
2055 FROM civicrm_activity_contact
2056 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2057 WHERE civicrm_activity.activity_type_id = %1
2058 AND civicrm_activity.source_record_id = %2
2059 AND civicrm_activity_contact.record_type_id = %3
2062 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2063 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2066 1 => array($activityTypeId, 'Integer'),
2067 2 => array($contributionId, 'Integer'),
2068 3 => array($sourceID, 'Integer'),
2071 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2073 // for on behalf contribution source is individual and contributor is organization
2074 if ($sourceContactId && $sourceContactId != $contributorId) {
2075 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2076 // get rel type id for employee of relation
2077 foreach ($relationshipTypeIds as $id => $typeVals) {
2078 if ($typeVals['name_a_b'] == 'Employee of') {
2079 $relationshipTypeId = $id;
2084 $rel = new CRM_Contact_DAO_Relationship();
2085 $rel->relationship_type_id
= $relationshipTypeId;
2086 $rel->contact_id_a
= $sourceContactId;
2087 $rel->contact_id_b
= $contributorId;
2088 if ($rel->find(TRUE)) {
2089 $ids['individual_id'] = $rel->contact_id_a
;
2090 $ids['organization_id'] = $rel->contact_id_b
;
2101 public static function getContributionDates() {
2102 $config = CRM_Core_Config
::singleton();
2103 $currentMonth = date('m');
2104 $currentDay = date('d');
2105 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2106 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2107 (int ) $config->fiscalYearStart
['d'] > $currentDay
2110 $year = date('Y') - 1;
2115 $year = array('Y' => $year);
2116 $yearDate = $config->fiscalYearStart
;
2117 $yearDate = array_merge($year, $yearDate);
2118 $yearDate = CRM_Utils_Date
::format($yearDate);
2120 $monthDate = date('Ym') . '01';
2126 'yearDate' => $yearDate,
2127 'monthDate' => $monthDate,
2132 * Load objects relations to contribution object.
2133 * Objects are stored in the $_relatedObjects property
2134 * In the first instance we are just moving functionality from BASEIpn -
2135 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2137 * Note that the unit test for the BaseIPN class tests this function
2139 * @param array $input
2140 * Input as delivered from Payment Processor.
2142 * Ids as Loaded by Payment Processor.
2143 * @param bool $loadAll
2144 * Load all related objects - even where id not passed in? (allows API to call this).
2149 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2151 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2152 if (empty($ids['contact']) && isset($this->contact_id
)) {
2153 $ids['contact'] = $this->contact_id
;
2156 if (empty($this->_component
)) {
2157 if (!empty($ids['event'])) {
2158 $this->_component
= 'event';
2161 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2165 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2166 // refactoring than anything else, and has unit test coverage.
2167 if (empty($this->financial_type_id
)) {
2171 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2176 if (!$paymentProcessorID && $this->contribution_page_id
) {
2177 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2178 $this->contribution_page_id
,
2181 if ($paymentProcessorID) {
2182 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2186 $ids['contributionType'] = $this->financial_type_id
;
2187 $ids['financialType'] = $this->financial_type_id
;
2190 'contact' => 'CRM_Contact_BAO_Contact',
2191 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2192 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2193 'financialType' => 'CRM_Financial_BAO_FinancialType',
2195 foreach ($entities as $entity => $bao) {
2196 if (!empty($ids[$entity])) {
2197 $this->_relatedObjects
[$entity] = new $bao();
2198 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2199 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2200 throw new CRM_Core_Exception($entity . ' could not be loaded');
2205 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2206 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2209 if (!empty($ids['pledge_payment'])) {
2210 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2211 if (empty($paymentID)) {
2214 $payment = new CRM_Pledge_BAO_PledgePayment();
2215 $payment->id
= $paymentID;
2216 if (!$payment->find(TRUE)) {
2217 throw new Exception("Could not find pledge payment record: " . $paymentID);
2219 $this->_relatedObjects
['pledge_payment'][] = $payment;
2223 if ($this->_component
== 'contribute') {
2224 // retrieve the other optional objects first so
2225 // stuff down the line can use this info and do things
2227 //in any case get the memberships associated with the contribution
2228 //because we now support multiple memberships w/ price set
2229 // see if there are any other memberships to be considered for same contribution.
2231 SELECT membership_id
2232 FROM civicrm_membership_payment
2233 WHERE contribution_id = %1 ";
2234 $params = array(1 => array($this->id
, 'Integer'));
2236 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2237 while ($dao->fetch()) {
2238 if ($dao->membership_id
) {
2239 if (!is_array($ids['membership'])) {
2240 $ids['membership'] = array();
2242 $ids['membership'][] = $dao->membership_id
;
2246 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2247 foreach ($ids['membership'] as $id) {
2249 $membership = new CRM_Member_BAO_Membership();
2250 $membership->id
= $id;
2251 if (!$membership->find(TRUE)) {
2252 throw new Exception("Could not find membership record: $id");
2254 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2255 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2256 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2257 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2258 $membership->free();
2264 // we are in event mode
2265 // make sure event exists and is valid
2266 $event = new CRM_Event_BAO_Event();
2267 $event->id
= $ids['event'];
2268 if ($ids['event'] &&
2271 throw new Exception("Could not find event: " . $ids['event']);
2274 $this->_relatedObjects
['event'] = &$event;
2276 $participant = new CRM_Event_BAO_Participant();
2277 $participant->id
= $ids['participant'];
2278 if ($ids['participant'] &&
2279 !$participant->find(TRUE)
2281 throw new Exception("Could not find participant: " . $ids['participant']);
2283 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2285 $this->_relatedObjects
['participant'] = &$participant;
2287 // get the payment processor id from event - this is inaccurate see CRM-16923
2288 // in future we should look at throwing an exception here rather than an dubious guess.
2289 if (!$paymentProcessorID) {
2290 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2291 if ($paymentProcessorID) {
2292 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2297 if ($paymentProcessorID) {
2298 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2299 $this->is_test ?
'test' : 'live'
2301 $ids['paymentProcessor'] = $paymentProcessorID;
2302 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2308 * Create array of message information - ie. return html version, txt version, to field
2310 * @param array $input
2311 * Incoming information.
2312 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2313 * just check presence of recur object but maintaining legacy approach
2316 * IDs of related objects.
2317 * @param array $values
2318 * Any values that may have already been compiled by calling process.
2319 * This is augmented by values 'gathered' by gatherMessageValues
2320 * @param bool $recur
2321 * @param bool $returnMessageText
2322 * Distinguishes between whether to send message or return.
2323 * message text. We are working towards this function ALWAYS returning message text & calling
2324 * function doing emails / pdfs with it
2330 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2331 $this->loadRelatedObjects($input, $ids);
2333 if (empty($this->_component
)) {
2334 $this->_component
= CRM_Utils_Array
::value('component', $input);
2337 //not really sure what params might be passed in but lets merge em into values
2338 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2339 $template = CRM_Core_Smarty
::singleton();
2340 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2341 //what does recur 'mean here - to do with payment processor return functionality but
2342 // what is the importance
2343 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2344 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2346 $entityID = $entity = NULL;
2347 if (isset($ids['contribution'])) {
2348 $entity = 'contribution';
2349 $entityID = $ids['contribution'];
2351 if (!empty($ids['membership'])) {
2352 //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
2353 // 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
2354 // line having loaded an array
2355 $ids['membership'] = (array) $ids['membership'];
2356 $entity = 'membership';
2357 $entityID = $ids['membership'][0];
2360 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity));
2361 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2362 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2364 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2365 //direct mode showing billing block, so use directIPN for temporary
2366 $template->assign('contributeMode', 'directIPN');
2369 // todo remove strtolower - check consistency
2370 if (strtolower($this->_component
) == 'event') {
2371 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2372 $values['event'] = array();
2374 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2376 //get location details
2377 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2378 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2380 $ufJoinParams = array(
2381 'entity_table' => 'civicrm_event',
2382 'entity_id' => $ids['event'],
2383 'module' => 'CiviEvent',
2386 list($custom_pre_id,
2388 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2390 $values['custom_pre_id'] = $custom_pre_id;
2391 $values['custom_post_id'] = $custom_post_ids;
2392 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2393 //and cases involving status updation through ipn
2394 // whatever that means!
2395 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2396 // perhaps we should throw an e-notice if amount is set & force total_amount?
2397 if (!empty($input['amount'])) {
2398 $values['totalAmount'] = $input['amount'];
2401 if ($values['event']['is_email_confirm']) {
2402 $values['is_email_receipt'] = 1;
2404 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2405 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2409 $values['contribution_id'] = $this->id
;
2410 if (!empty($ids['related_contact'])) {
2411 $values['related_contact'] = $ids['related_contact'];
2412 if (isset($ids['onbehalf_dupe_alert'])) {
2413 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2415 $entityBlock = array(
2416 'contact_id' => $ids['contact'],
2417 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2418 'Home', 'id', 'name'
2421 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2422 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2425 if ($this->is_test
) {
2428 if (!empty($this->_relatedObjects
['membership'])) {
2429 foreach ($this->_relatedObjects
['membership'] as $membership) {
2430 if ($membership->id
) {
2431 $values['isMembership'] = TRUE;
2433 // need to set the membership values here
2434 $template->assign('membership_assign', 1);
2435 $template->assign('membership_name',
2436 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2438 $template->assign('mem_start_date', $membership->start_date
);
2439 $template->assign('mem_join_date', $membership->join_date
);
2440 $template->assign('mem_end_date', $membership->end_date
);
2441 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2442 $template->assign('mem_status', $membership_status);
2443 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2444 $template->assign('is_pay_later', 1);
2447 // if separate payment there are two contributions recorded and the
2448 // admin will need to send a receipt for each of them separately.
2449 // we dont link the two in the db (but can potentially infer it if needed)
2450 $template->assign('is_separate_payment', 0);
2452 if ($recur && $paymentObject) {
2453 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2454 $template->assign('cancelSubscriptionUrl', $url);
2455 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2456 $template->assign('updateSubscriptionBillingUrl', $url);
2457 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2458 $template->assign('updateSubscriptionUrl', $url);
2461 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2464 // otherwise if its about sending emails, continue sending without return, as we
2465 // don't want to exit the loop.
2470 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2476 * Gather values for contribution mail - this function has been created
2477 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2478 * Values related to the contribution in question are gathered
2480 * @param array $input
2481 * Input into function (probably from payment processor).
2482 * @param array $values
2484 * The set of ids related to the input.
2488 public function _gatherMessageValues($input, &$values, $ids = array()) {
2489 // set display address of contributor
2490 if ($this->address_id
) {
2491 $addressParams = array('id' => $this->address_id
);
2492 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2493 $addressDetails = array_values($addressDetails);
2494 $values['address'] = $addressDetails[0]['display'];
2496 if ($this->_component
== 'contribute') {
2497 //get soft contributions
2498 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2499 if (!empty($softContributions)) {
2500 $values['softContributions'] = $softContributions['soft_credit'];
2502 if (isset($this->contribution_page_id
)) {
2503 CRM_Contribute_BAO_ContributionPage
::setValues(
2504 $this->contribution_page_id
,
2507 if ($this->contribution_page_id
) {
2508 // CRM-8254 - override default currency if applicable
2509 $config = CRM_Core_Config
::singleton();
2510 $config->defaultCurrency
= CRM_Utils_Array
::value(
2513 $config->defaultCurrency
2517 // no contribution page -probably back office
2519 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2520 $values['is_email_receipt'] = 1;
2521 $values['title'] = 'Contribution';
2523 // set lineItem for contribution
2525 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2526 if (!empty($lineItem)) {
2527 $itemId = key($lineItem);
2528 foreach ($lineItem as &$eachItem) {
2529 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2530 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2531 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2532 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2535 $values['lineItem'][0] = $lineItem;
2536 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2540 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2544 // if this is onbehalf of contribution then set related contact
2545 if (!empty($relatedContact['individual_id'])) {
2546 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2551 $eventParams = array(
2552 'id' => $this->_relatedObjects
['event']->id
,
2554 $values['event'] = array();
2556 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2557 // add custom fields for event
2558 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2560 $eventCustomGroup = array();
2561 foreach ($eventGroupTree as $key => $group) {
2562 if ($key === 'info') {
2566 foreach ($group['fields'] as $k => $customField) {
2567 $groupLabel = $group['title'];
2568 if (!empty($customField['customValue'])) {
2569 foreach ($customField['customValue'] as $customFieldValues) {
2570 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2575 $values['event']['customGroup'] = $eventCustomGroup;
2577 //get participant details
2578 $participantParams = array(
2579 'id' => $this->_relatedObjects
['participant']->id
,
2582 $values['participant'] = array();
2584 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2585 // add custom fields for event
2586 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2587 $participantCustomGroup = array();
2588 foreach ($participantGroupTree as $key => $group) {
2589 if ($key === 'info') {
2593 foreach ($group['fields'] as $k => $customField) {
2594 $groupLabel = $group['title'];
2595 if (!empty($customField['customValue'])) {
2596 foreach ($customField['customValue'] as $customFieldValues) {
2597 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2602 $values['participant']['customGroup'] = $participantCustomGroup;
2604 //get location details
2605 $locationParams = array(
2606 'entity_id' => $this->_relatedObjects
['event']->id
,
2607 'entity_table' => 'civicrm_event',
2609 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2611 $ufJoinParams = array(
2612 'entity_table' => 'civicrm_event',
2613 'entity_id' => $ids['event'],
2614 'module' => 'CiviEvent',
2617 list($custom_pre_id,
2619 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2621 $values['custom_pre_id'] = $custom_pre_id;
2622 $values['custom_post_id'] = $custom_post_ids;
2624 // set lineItem for event contribution
2626 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2627 if (!empty($participantIds)) {
2628 foreach ($participantIds as $pIDs) {
2629 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2630 if (!CRM_Utils_System
::isNull($lineItem)) {
2631 $values['lineItem'][] = $lineItem;
2638 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2640 $customGroup = array();
2641 foreach ($groupTree as $key => $group) {
2642 if ($key === 'info') {
2646 foreach ($group['fields'] as $k => $customField) {
2647 $groupLabel = $group['title'];
2648 if (!empty($customField['customValue'])) {
2649 foreach ($customField['customValue'] as $customFieldValues) {
2650 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2655 $values['customGroup'] = $customGroup;
2661 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2662 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2663 * Note we send directly from this function in some cases because it is only partly refactored
2664 * Don't call this function directly as the signature will change
2668 * @param CRM_Core_SMARTY $template
2669 * @param bool $recur
2670 * @param bool $returnMessageText
2674 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2675 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2676 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2677 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2678 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2679 $template->assign('useForMember', TRUE);
2681 //assign honor information to receipt message
2682 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2684 if (isset($softRecord['soft_credit'])) {
2685 //if id of contribution page is present
2686 if (!empty($values['id'])) {
2687 $values['honor'] = array(
2688 'honor_profile_values' => array(),
2689 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2690 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2692 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2694 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2695 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2698 //offline contribution
2699 $softCreditTypes = $softCredits = array();
2700 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2701 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2702 $softCredits[$key] = array(
2703 'Name' => $softCredit['contact_name'],
2704 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2707 $template->assign('softCreditTypes', $softCreditTypes);
2708 $template->assign('softCredits', $softCredits);
2712 $dao = new CRM_Contribute_DAO_ContributionProduct();
2713 $dao->contribution_id
= $this->id
;
2714 if ($dao->find(TRUE)) {
2715 $premiumId = $dao->product_id
;
2716 $template->assign('option', $dao->product_option
);
2718 $productDAO = new CRM_Contribute_DAO_Product();
2719 $productDAO->id
= $premiumId;
2720 $productDAO->find(TRUE);
2721 $template->assign('selectPremium', TRUE);
2722 $template->assign('product_name', $productDAO->name
);
2723 $template->assign('price', $productDAO->price
);
2724 $template->assign('sku', $productDAO->sku
);
2726 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2727 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2728 if (empty($amount) && isset($this->total_amount
)) {
2729 $amount = $this->total_amount
;
2731 $template->assign('amount', $amount);
2732 // add the new contribution values
2733 if (strtolower($this->_component
) == 'contribute') {
2735 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2736 $softDAO->contribution_id
= $this->id
;
2737 if ($softDAO->find(TRUE)) {
2738 $template->assign('pcpBlock', TRUE);
2739 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2740 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2741 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2743 //assign the pcp page title for email subject
2744 $pcpDAO = new CRM_PCP_DAO_PCP();
2745 $pcpDAO->id
= $softDAO->pcp_id
;
2746 if ($pcpDAO->find(TRUE)) {
2747 $template->assign('title', $pcpDAO->title
);
2752 if ($this->financial_type_id
) {
2753 $values['financial_type_id'] = $this->financial_type_id
;
2756 $template->assign('trxn_id', $this->trxn_id
);
2757 $template->assign('receive_date',
2758 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2760 $template->assign('contributeMode', 'notify');
2761 $template->assign('action', $this->is_test ?
1024 : 1);
2762 $template->assign('receipt_text',
2763 CRM_Utils_Array
::value('receipt_text',
2767 $template->assign('is_monetary', 1);
2768 $template->assign('is_recur', (bool) $recur);
2769 $template->assign('currency', $this->currency
);
2770 $template->assign('address', CRM_Utils_Address
::format($input));
2771 if (!empty($values['customGroup'])) {
2772 $template->assign('customGroup', $values['customGroup']);
2774 if (!empty($values['softContributions'])) {
2775 $template->assign('softContributions', $values['softContributions']);
2777 if ($this->_component
== 'event') {
2778 $template->assign('title', $values['event']['title']);
2779 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2780 $viewRoles = array();
2781 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2782 $viewRoles[] = $participantRoles[$v];
2784 $values['event']['participant_role'] = implode(', ', $viewRoles);
2785 $template->assign('event', $values['event']);
2786 $template->assign('participant', $values['participant']);
2787 $template->assign('location', $values['location']);
2788 $template->assign('customPre', $values['custom_pre_id']);
2789 $template->assign('customPost', $values['custom_post_id']);
2792 if ($this->_relatedObjects
['participant']->is_test
) {
2796 $values['params'] = array();
2797 //to get email of primary participant.
2798 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2799 $primaryAmount[] = array(
2800 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2801 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2803 //build an array of cId/pId of participants
2804 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2805 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2806 //send receipt to additional participant if exists
2807 if (count($additionalIDs)) {
2808 $template->assign('isPrimary', 0);
2809 $template->assign('customProfile', NULL);
2810 //set additionalParticipant true
2811 $values['params']['additionalParticipant'] = TRUE;
2812 foreach ($additionalIDs as $pId => $cId) {
2814 //to change the status pending to completed
2815 $additional = new CRM_Event_DAO_Participant();
2816 $additional->id
= $pId;
2817 $additional->contact_id
= $cId;
2818 $additional->find(TRUE);
2819 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2820 $additional->status_id
= 1;
2821 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2822 //if additional participant dont have email
2824 if (!$additionalParticipantInfo) {
2825 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2827 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2828 $primaryAmount[] = array(
2829 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2830 'amount' => $additional->fee_amount
,
2832 $additional->save();
2833 $additional->free();
2834 $template->assign('amount', $amount);
2835 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2839 //build an array of custom profile and assigning it to template
2840 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2842 if (count($customProfile)) {
2843 $template->assign('customProfile', $customProfile);
2846 // for primary contact
2847 $values['params']['additionalParticipant'] = FALSE;
2848 $template->assign('isPrimary', 1);
2849 $template->assign('amount', $primaryAmount);
2850 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2851 if ($this->payment_instrument_id
) {
2852 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2853 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2855 // carry paylater, since we did not created billing,
2856 // so need to pull email from primary location, CRM-4395
2857 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2863 * Check whether payment processor supports
2864 * cancellation of contribution subscription
2866 * @param int $contributionId
2869 * @param bool $isNotCancelled
2873 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2874 $cacheKeyString = "$contributionId";
2875 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2877 static $supportsCancel = array();
2879 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2880 $supportsCancel[$cacheKeyString] = FALSE;
2881 $isCancelled = FALSE;
2883 if ($isNotCancelled) {
2884 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2887 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2888 if (!empty($paymentObject)) {
2889 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2892 return $supportsCancel[$cacheKeyString];
2896 * Check whether subscription is already cancelled.
2898 * @param int $contributionId
2902 * contribution status
2904 public static function isSubscriptionCancelled($contributionId) {
2906 SELECT cr.contribution_status_id
2907 FROM civicrm_contribution_recur cr
2908 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2909 WHERE con.id = %1 LIMIT 1";
2910 $params = array(1 => array($contributionId, 'Integer'));
2911 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2912 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2913 if ($status == 'Cancelled') {
2920 * Create all financial accounts entry.
2922 * @param array $params
2923 * Contribution object, line item array and params for trxn.
2926 * @param array $financialTrxnValues
2928 * @return null|object
2930 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2931 $skipRecords = $update = $return = $isRelatedId = FALSE;
2933 $additionalParticipantId = array();
2934 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2936 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2937 $entityId = $params['participant_id'];
2938 $entityTable = 'civicrm_participant';
2939 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2941 elseif (!empty($params['membership_id'])) {
2942 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2943 // are created off one contribution should be handled elsewhere
2944 $entityId = $params['membership_id'];
2945 $entityTable = 'civicrm_membership';
2948 $entityId = $params['contribution']->id
;
2949 $entityTable = 'civicrm_contribution';
2952 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2953 $isRelatedId = TRUE;
2956 $entityID[] = $entityId;
2957 if (!empty($additionalParticipantId)) {
2958 $entityID +
= $additionalParticipantId;
2960 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2961 if (empty($params['prevContribution'])) {
2968 $statusId = $params['contribution']->contribution_status_id
;
2969 // CRM-13964 partial payment
2970 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2971 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2973 $partialAmtPay = $params['partial_amount_pay'];
2974 $partialAmtTotal = $params['partial_payment_total'];
2976 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2977 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2978 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2979 $params['total_amount'] = $partialAmtPay;
2981 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2982 if (empty($balanceTrxnInfo['trxn_id'])) {
2983 // create new balance transaction record
2984 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2985 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2987 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2988 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2989 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2990 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2991 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2992 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2993 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2994 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2995 $balanceTrxnParams['status_id'] = $statusId;
2996 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2997 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2998 if (!empty($params['payment_processor'])) {
2999 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3001 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3005 // build line item array if its not set in $params
3006 if (empty($params['line_item']) ||
$additionalParticipantId) {
3007 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3010 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
3011 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
3013 $skipRecords = TRUE;
3014 $pendingStatus = array(
3015 array_search('Pending', $contributionStatuses),
3016 array_search('In Progress', $contributionStatuses),
3018 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
3019 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3020 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3022 elseif (!empty($params['payment_processor'])) {
3023 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3025 elseif (!empty($params['payment_instrument_id'])) {
3026 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3029 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3030 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3031 $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);
3034 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3035 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3036 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3039 //build financial transaction params
3040 $trxnParams = array(
3041 'contribution_id' => $params['contribution']->id
,
3042 'to_financial_account_id' => $params['to_financial_account_id'],
3043 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3044 'total_amount' => $totalAmount,
3045 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3046 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3047 'currency' => $params['contribution']->currency
,
3048 'trxn_id' => $params['contribution']->trxn_id
,
3049 'status_id' => $statusId,
3050 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
3051 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3054 if (!empty($params['payment_processor'])) {
3055 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3058 if (isset($fromFinancialAccountId)) {
3059 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3062 // consider external values passed for recording transaction entry
3063 if (!empty($financialTrxnValues)) {
3064 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3067 $params['trxnParams'] = $trxnParams;
3069 if (!empty($params['prevContribution'])) {
3070 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3071 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3072 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3073 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3074 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3076 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3077 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3078 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3080 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3081 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3084 //if financial type is changed
3085 if (!empty($params['financial_type_id']) &&
3086 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3088 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3089 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3090 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3091 if ($oldFinancialAccount != $newFinancialAccount) {
3092 $params['total_amount'] = 0;
3093 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3094 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3095 $params['prevContribution']->financial_type_id
, $relationTypeId);
3098 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3099 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3100 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3103 self
::updateFinancialAccounts($params, 'changeFinancialType');
3104 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3105 $params['financial_account_id'] = $newFinancialAccount;
3106 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3107 self
::updateFinancialAccounts($params);
3108 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3112 //Update contribution status
3113 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3114 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3115 if (!empty($params['contribution_status_id']) &&
3116 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3118 //Update Financial Records
3119 self
::updateFinancialAccounts($params, 'changedStatus');
3122 // change Payment Instrument for a Completed contribution
3123 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3124 // instrument is null and now new payment instrument is added along with the payment
3125 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3126 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3127 if (array_key_exists('payment_instrument_id', $params)) {
3128 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3129 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3130 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3132 //check if status is changed from Pending to Completed
3133 // do not update payment instrument changes for Pending to Completed
3134 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3135 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3137 // for all other statuses create new financial records
3138 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3139 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3140 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3143 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3144 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3145 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3147 // for any other payment instrument changes create new financial records
3148 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3149 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3150 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3152 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3153 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3155 // another special case when check number is changed, create new financial records
3156 // create financial trxn with negative amount
3157 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3158 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3159 // create financial trxn with positive amount
3160 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3161 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3162 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3166 //if Change contribution amount
3167 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3168 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3169 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3170 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3171 if (isset($totalAmount) &&
3172 $totalAmount != $params['prevContribution']->total_amount
3174 //Update Financial Records
3175 $params['trxnParams']['from_financial_account_id'] = NULL;
3176 self
::updateFinancialAccounts($params, 'changedAmount');
3181 // records finanical trxn and entity financial trxn
3182 // also make it available as return value
3183 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3184 $params['entity_id'] = $financialTxn->id
;
3187 // record line items and financial items
3188 if (empty($params['skipLineItem'])) {
3189 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3192 // create batch entry if batch_id is passed and
3193 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3194 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3195 $entityParams = array(
3196 'batch_id' => $params['batch_id'],
3197 'entity_table' => 'civicrm_financial_trxn',
3198 'entity_id' => $financialTxn->id
,
3200 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3203 // when a fee is charged
3204 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3205 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3208 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3209 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3211 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3212 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3213 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3215 unset($params['line_item']);
3221 * Update all financial accounts entry.
3223 * @param array $params
3224 * Contribution object, line item array and params for trxn.
3226 * @param string $context
3229 * @param null $skipTrxn
3232 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3233 $itemAmount = $trxnID = NULL;
3234 //get all the statuses
3235 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3236 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3237 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3238 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3239 && $context == 'changePaymentInstrument'
3243 if (($params['prevContribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus))
3244 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3245 && $context == 'changedStatus'
3249 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3250 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3252 if ($context == 'changedStatus') {
3253 //get all the statuses
3254 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3256 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3257 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3258 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3260 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3261 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3262 $creditNoteId = self
::createCreditNoteId();
3263 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3266 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3267 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3269 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3270 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3271 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3273 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3274 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3275 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3276 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3277 $creditNoteId = self
::createCreditNoteId();
3278 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3282 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3285 $itemAmount = $params['trxnParams']['total_amount'];
3287 elseif ($context == 'changePaymentInstrument') {
3288 if ($params['trxnParams']['total_amount'] < 0) {
3289 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3290 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3291 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3292 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3296 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3297 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3300 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3301 $params['entity_id'] = $trxn->id
;
3303 if ($context == 'changedStatus') {
3304 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3305 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3306 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3308 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3309 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3311 $entityParams = array(
3312 'entity_table' => 'civicrm_financial_item',
3313 'financial_trxn_id' => $trxn->id
,
3315 if (empty($params['line_item'])) {
3317 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3318 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3319 // & this can be removed
3322 foreach ($params['line_item'] as $fieldId => $fields) {
3323 foreach ($fields as $fieldValueId => $fieldValues) {
3325 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3326 2 => array($fieldValues['id'], 'Integer'),
3328 CRM_Core_DAO
::executeQuery($query, $fparams);
3330 1 => array($fieldValues['id'], 'Integer'),
3332 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3333 while ($financialItem->fetch()) {
3334 $entityParams['entity_id'] = $financialItem->id
;
3335 $entityParams['amount'] = $financialItem->amount
;
3336 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3343 if ($context != 'changePaymentInstrument') {
3344 $itemParams['entity_table'] = 'civicrm_line_item';
3345 $trxnIds['id'] = $params['entity_id'];
3346 foreach ($params['line_item'] as $fieldId => $fields) {
3347 foreach ($fields as $fieldValueId => $fieldValues) {
3348 $prevParams['entity_id'] = $fieldValues['id'];
3349 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3351 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3352 if ($params['contribution']->receive_date
) {
3353 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3356 $financialAccount = $prevfinancialItem->financial_account_id
;
3357 if (!empty($params['financial_account_id'])) {
3358 $financialAccount = $params['financial_account_id'];
3361 $currency = $params['prevContribution']->currency
;
3362 if ($params['contribution']->currency
) {
3363 $currency = $params['contribution']->currency
;
3366 if (!empty($params['is_quick_config'])) {
3367 $amount = $itemAmount;
3369 $amount = $params['total_amount'];
3373 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3374 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3378 $amount = $diff * $fieldValues['line_total'];
3381 $itemParams = array(
3382 'transaction_date' => $receiveDate,
3383 'contact_id' => $params['prevContribution']->contact_id
,
3384 'currency' => $currency,
3385 'amount' => $amount,
3386 'description' => $prevfinancialItem->description
,
3387 'status_id' => $prevfinancialItem->status_id
,
3388 'financial_account_id' => $financialAccount,
3389 'entity_table' => 'civicrm_line_item',
3390 'entity_id' => $fieldValues['id'],
3392 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3394 if ($fieldValues['tax_amount']) {
3395 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3396 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3397 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3398 $itemParams['description'] = $taxTerm;
3399 if ($fieldValues['financial_type_id']) {
3400 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3402 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3407 if ($context == 'changeFinancialType') {
3408 $params['skipLineItem'] = FALSE;
3409 foreach ($params['line_item'] as &$lineItems) {
3410 foreach ($lineItems as &$line) {
3411 $line['financial_type_id'] = $params['financial_type_id'];
3418 * Check status validation on update of a contribution.
3420 * @param array $values
3421 * Previous form values before submit.
3423 * @param array $fields
3424 * The input form values.
3426 * @param array $errors
3431 public static function checkStatusValidation($values, &$fields, &$errors) {
3432 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3433 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3434 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3438 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3439 $checkStatus = array(
3440 'Cancelled' => array('Completed', 'Refunded'),
3441 'Completed' => array('Cancelled', 'Refunded'),
3442 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3443 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3444 'Refunded' => array('Cancelled', 'Completed'),
3445 'Partially paid' => array('Completed'),
3448 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3449 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3450 1 => $contributionStatuses[$values['contribution_status_id']],
3451 2 => $contributionStatuses[$fields['contribution_status_id']],
3457 * Delete contribution of contact.
3461 * @param int $contactId
3465 public static function deleteContactContribution($contactId) {
3466 $contribution = new CRM_Contribute_DAO_Contribution();
3467 $contribution->contact_id
= $contactId;
3468 $contribution->find();
3469 while ($contribution->fetch()) {
3470 self
::deleteContribution($contribution->id
);
3475 * Get options for a given contribution field.
3476 * @see CRM_Core_DAO::buildOptions
3478 * @param string $fieldName
3479 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3480 * @param array $props whatever is known about this dao object.
3482 * @return array|bool
3484 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3485 $className = __CLASS__
;
3487 switch ($fieldName) {
3488 // This field is not part of this object but the api supports it
3489 case 'payment_processor':
3490 $className = 'CRM_Contribute_BAO_ContributionPage';
3491 // Filter results by contribution page
3492 if (!empty($props['contribution_page_id'])) {
3493 $page = civicrm_api('contribution_page', 'getsingle', array(
3495 'id' => ($props['contribution_page_id']),
3497 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3498 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3502 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3503 case 'honor_type_id':
3504 $className = 'CRM_Contribute_BAO_ContributionSoft';
3505 $fieldName = 'soft_credit_type_id';
3506 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3509 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3513 * Validate financial type.
3517 * @param int $financialTypeId
3518 * Financial Type id.
3520 * @param string $relationName
3522 * @return array|bool
3524 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3525 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3526 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3528 if (!$financialAccount) {
3529 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3536 * Function to record additional payment for partial and refund contributions.
3538 * @param int $contributionId
3539 * is the invoice contribution id (got created after processing participant payment).
3540 * @param array $trxnsData
3541 * to take user provided input of transaction details.
3542 * @param string $paymentType
3543 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3544 * @param int $participantId
3546 * @return null|object
3548 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3549 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3550 $getInfoOf['id'] = $contributionId;
3551 $defaults = array();
3552 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3554 if ($paymentType == 'owed') {
3555 // build params for recording financial trxn entry
3556 $params['contribution'] = $contributionDAO;
3557 $params = array_merge($defaults, $params);
3558 $params['skipLineItem'] = TRUE;
3559 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3560 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3561 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3562 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3565 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3566 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3567 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3569 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3570 if (!empty($trxnId)) {
3571 $trxnId = $trxnId['trxn_id'];
3573 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3574 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3577 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3578 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3579 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3583 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3584 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3585 FROM civicrm_financial_trxn ft
3586 LEFT JOIN civicrm_entity_financial_trxn eft
3587 ON (ft.id = eft.financial_trxn_id)
3588 WHERE eft.entity_table = 'civicrm_contribution'
3589 AND eft.entity_id = {$contributionId}
3590 AND ft.to_financial_account_id != {$toFinancialAccount}
3591 AND ft.status_id = {$statusId}
3593 $query = CRM_Core_DAO
::executeQuery($sql);
3595 $sumOfPayments = $query->sum_of_payments
;
3598 if ($contributionDAO->total_amount
== $sumOfPayments) {
3599 // update contribution status and
3600 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3601 $contributionDAO->contribution_status_id
= $statusId;
3602 $contributionDAO->cancel_date
= 'null';
3603 $contributionDAO->cancel_reason
= NULL;
3604 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3605 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3606 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3607 $contributionDAO->save();
3609 //Change status of financial record too
3610 $financialTrxn->status_id
= $statusId;
3611 $financialTrxn->save();
3613 // note : not using the self::add method,
3614 // the reason because it performs 'status change' related code execution for financial records
3615 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3616 // are coded below i.e. just updating financial_item status to 'Paid'
3618 if ($participantId) {
3619 // update participant status
3620 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3621 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3622 foreach ($ids as $val) {
3623 $participantUpdate['id'] = $val;
3624 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3625 CRM_Event_BAO_Participant
::add($participantUpdate);
3629 // update financial item statuses
3630 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3631 $paidStatus = array_search('Paid', $financialItemStatus);
3633 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3634 $sqlFinancialItemUpdate = "
3635 UPDATE civicrm_financial_item fi
3636 LEFT JOIN civicrm_entity_financial_trxn eft
3637 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3638 SET status_id = {$paidStatus}
3639 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3641 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3644 elseif ($paymentType == 'refund') {
3645 // build params for recording financial trxn entry
3646 $params['contribution'] = $contributionDAO;
3647 $params = array_merge($defaults, $params);
3648 $params['skipLineItem'] = TRUE;
3649 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3650 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3652 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3653 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3654 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3656 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3658 // note : not using the self::add method,
3659 // the reason because it performs 'status change' related code execution for financial records
3660 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3661 // are coded below i.e. just updating financial_item status to 'Paid'
3662 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3664 // add financial item entry
3665 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3666 $getLine['entity_id'] = $contributionDAO->id
;
3667 $getLine['entity_table'] = 'civicrm_contribution';
3668 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3669 if (!empty($lineItemId->id
)) {
3670 $addFinancialEntry = array(
3671 'transaction_date' => $financialTrxn->trxn_date
,
3672 'contact_id' => $contributionDAO->contact_id
,
3673 'amount' => $financialTrxn->total_amount
,
3674 'status_id' => array_search('Paid', $financialItemStatus),
3675 'entity_id' => $lineItemId->id
,
3676 'entity_table' => 'civicrm_line_item',
3678 $trxnIds['id'] = $financialTrxn->id
;
3679 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3681 if ($participantId) {
3682 // update participant status
3683 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3684 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3685 foreach ($ids as $val) {
3686 $participantUpdate['id'] = $val;
3687 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3688 CRM_Event_BAO_Participant
::add($participantUpdate);
3693 // activity creation
3694 if (!empty($financialTrxn)) {
3695 if ($participantId) {
3696 $inputParams['id'] = $participantId;
3699 $component = 'event';
3700 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3701 $entityObj = $entityObj[$participantId];
3703 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3705 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3707 return $financialTrxn;
3713 * @param $activityType
3715 * @param int $contributionId
3717 * @throws CRM_Core_Exception
3719 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3720 if ($component == 'event') {
3721 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3722 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3723 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3724 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3725 $targetCid = $entityObj->contact_id
;
3726 // source record id would be the contribution id
3727 $srcRecId = $contributionId;
3731 $activityParams = array(
3732 'source_contact_id' => $targetCid,
3733 'source_record_id' => $srcRecId,
3734 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3738 'subject' => $subject,
3739 'activity_date_time' => $date,
3740 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3744 'skipRecentView' => TRUE,
3747 // create activity with target contacts
3748 $session = CRM_Core_Session
::singleton();
3749 $id = $session->get('userID');
3751 $activityParams['source_contact_id'] = $id;
3752 $activityParams['target_contact_id'][] = $targetCid;
3754 CRM_Activity_BAO_Activity
::create($activityParams);
3758 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3762 * @param bool $getTrxnInfo
3763 * @param bool $usingLineTotal
3767 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3768 if ($component == 'event') {
3769 $entity = 'participant';
3770 $entityTable = 'civicrm_participant';
3771 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3773 if (!$contributionId) {
3774 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3775 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3776 $id = $primaryParticipantId;
3778 if (!$contributionId) {
3783 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3784 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3790 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3791 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3794 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3795 // for additional participants
3796 if ($entityTable == 'civicrm_participant') {
3797 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3799 foreach ($ids as $val) {
3800 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3804 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3808 $baseTrxnId = $total['trxn_id'];
3809 $total = $total['total_amount'];
3812 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3813 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3815 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3816 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3817 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3819 if ($paymentBalance == 0 && $contributionIsPayLater) {
3820 $paymentBalance = $total;
3823 $info['total'] = $total;
3824 $info['paid'] = $total - $paymentBalance;
3825 $info['balance'] = $paymentBalance;
3827 $info['component'] = $component;
3828 $info['payLater'] = $contributionIsPayLater;
3830 if ($getTrxnInfo && $baseTrxnId) {
3831 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3833 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3834 FROM civicrm_contribution con
3835 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3836 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3837 WHERE con.id = {$contributionId}
3840 // conditioned WHERE clause
3842 // if balance trxn exists don't include details of it in transaction info
3843 $sql .= " AND ft.id != {$baseTrxnId} ";
3845 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3847 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3848 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3849 while ($resultDAO->fetch()) {
3850 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3851 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3853 'total_amount' => $resultDAO->total_amount
,
3854 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3855 'payment_instrument' => $paidByLabel,
3856 'receive_date' => $resultDAO->trxn_date
,
3857 'trxn_id' => $resultDAO->trxn_id
,
3858 'status' => $statuses[$resultDAO->status_id
],
3860 if ($paidByName == 'Check') {
3861 $val['check_number'] = $resultDAO->check_number
;
3865 $info['transaction'] = $rows;
3871 * Get financial account id has 'Sales Tax Account is'
3872 * account relationship with financial type
3874 * @param int $financialTypeId
3876 * @return FinancialAccountId
3878 public static function getFinancialAccountId($financialTypeId) {
3879 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3880 $searchParams = array(
3881 'entity_table' => 'civicrm_financial_type',
3882 'entity_id' => $financialTypeId,
3883 'account_relationship' => $accountRel,
3886 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3888 return CRM_Utils_Array
::value('financial_account_id', $result);
3894 * @param array $params
3895 * @param bool $isLineItem
3899 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3900 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3902 // Update contribution.
3903 if (!empty($params['id'])) {
3904 $id = $params['id'];
3905 $values = $ids = array();
3906 $contrbutionParams = array('id' => $id);
3907 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3909 // To assign pervious finantial type on update of contribution
3910 if (!isset($params['financial_type_id'])) {
3911 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3913 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3914 // Assisn tax Amount on update of contrbution
3915 if (!empty($prevContributionValue->tax_amount
)) {
3916 $params['tax_amount'] = 'null';
3917 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3918 foreach ($params['line_item'] as $setID => $priceField) {
3919 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3920 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3927 // New Contrbution and update of contribution with tax rate financial type
3928 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3929 empty($params['skipLineItem']) && !$isLineItem
3931 $taxRateParams = $taxRates[$params['financial_type_id']];
3932 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3933 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3935 // Get Line Item on update of contribution
3936 if (isset($params['id'])) {
3937 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3940 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3942 foreach ($params['line_item'] as $setID => $priceField) {
3943 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3944 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3947 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3949 elseif (isset($params['api.line_item.create'])) {
3950 // Update total amount of contribution using lineItem
3951 $taxAmountArray = array();
3952 foreach ($params['api.line_item.create'] as $key => $value) {
3953 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3954 $taxRate = $taxRates[$value['financial_type_id']];
3955 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3956 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3959 $params['tax_amount'] = array_sum($taxAmountArray);
3960 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3963 // update line item of contrbution
3964 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3965 $taxRate = $taxRates[$params['financial_type_id']];
3966 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3967 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3974 * Check financial type validation on update of a contribution.
3976 * @param Integer $financialTypeId
3977 * Value of latest Financial Type.
3979 * @param Integer $contributionId
3982 * @param array $errors
3987 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3988 if (!empty($financialTypeId)) {
3989 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3990 if ($oldFinancialTypeId == $financialTypeId) {
3994 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3996 '1' => array($contributionId, 'Integer'),
3998 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3999 if ($result->N
> 1) {
4000 $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.');
4005 * Update related pledge payment payments.
4007 * This function has been refactored out of the back office contribution form and may
4008 * still overlap with other functions.
4010 * @param string $action
4011 * @param int $pledgePaymentID
4012 * @param int $contributionID
4013 * @param bool $adjustTotalAmount
4014 * @param float $total_amount
4015 * @param float $original_total_amount
4016 * @param int $contribution_status_id
4017 * @param int $original_contribution_status_id
4019 public static function updateRelatedPledge(
4025 $original_total_amount,
4026 $contribution_status_id,
4027 $original_contribution_status_id
4029 if (!$pledgePaymentID ||
$action & CRM_Core_Action
::ADD
&& !$contributionID) {
4033 if ($pledgePaymentID) {
4034 //store contribution id in payment record.
4035 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4038 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4044 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4050 $updatePledgePaymentStatus = FALSE;
4052 // If either the status or the amount has changed we update the pledge status.
4053 if ($action & CRM_Core_Action
::ADD
) {
4054 $updatePledgePaymentStatus = TRUE;
4056 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4057 ($original_total_amount != $total_amount))
4059 $updatePledgePaymentStatus = TRUE;
4062 if ($updatePledgePaymentStatus) {
4063 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4064 array($pledgePaymentID),
4065 $contribution_status_id,
4074 * Compute the stats values
4076 * @param $stat either 'mode' or 'median'
4078 * @param $alias of civicrm_contribution
4080 public static function computeStats($stat, $sql, $alias = NULL) {
4081 $mode = $median = array();
4084 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4085 while ($modeDAO->fetch()) {
4086 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4087 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4096 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4097 foreach ($currencies as $currency => $val) {
4099 $where = "AND {$alias}.currency = '{$currency}'";
4100 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4104 $medianRow = floor($rowCount / 2);
4105 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4111 $medianValue = "SELECT {$alias}.total_amount as median
4113 ORDER BY median LIMIT {$medianRow},{$offset}";
4114 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4115 while ($medianValDAO->fetch()) {
4117 $midValue = $midValue +
$medianValDAO->median
;
4120 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4124 $midValue = $midValue / 2;
4125 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4136 * Complete an order.
4138 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4140 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4142 * Moving it out of the BaseIPN class is just the first step.
4144 * @param array $input
4146 * @param array $objects
4147 * @param CRM_Core_Transaction $transaction
4149 * @param CRM_Contribute_BAO_Contribution $contribution
4150 * @param bool $isRecurring
4151 * Duplication of param needs review. Only used by AuthorizeNetIPN
4152 * @param int $isFirstOrLastRecurringPayment
4153 * Deprecated param only used by AuthorizeNetIPN.
4155 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4156 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4157 // The previous details are used when calculating line items so keep it before any code that 'does something'
4158 if (!empty($contribution->id
)) {
4159 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4160 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4162 $inputContributionWhiteList = array(
4167 'payment_instrument_id',
4173 $contributionParams = array_merge(array(
4174 'contribution_status_id' => 'Completed',
4175 'financial_type_id' => $contribution->financial_type_id
,
4176 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4179 $participant = CRM_Utils_Array
::value('participant', $objects);
4180 $memberships = CRM_Utils_Array
::value('membership', $objects);
4181 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4182 if (!empty($recurContrib->id
)) {
4183 $contributionParams['contribution_recur_id'] = $recurContrib->id
;
4185 self
::repeatTransaction($contribution, $input, $contributionParams);
4187 if (is_numeric($memberships)) {
4188 $memberships = array($objects['membership']);
4191 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4194 if (isset($input['is_email_receipt'])) {
4195 $values['is_email_receipt'] = $input['is_email_receipt'];
4198 if ($input['component'] == 'contribute') {
4199 if ($contribution->contribution_page_id
) {
4200 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4201 $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
4203 elseif ($recurContrib && $recurContrib->id
) {
4204 $contributionParams['contribution_page_id'] = NULL;
4205 $values['amount'] = $recurContrib->amount
;
4206 $values['financial_type_id'] = $objects['contributionType']->id
;
4207 $values['title'] = $source = ts('Offline Recurring Contribution');
4208 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
4209 $values['receipt_from_name'] = $domainValues[0];
4210 $values['receipt_from_email'] = $domainValues[1];
4213 if (empty($contributionParams['receive_date']) && $changeDate) {
4214 $contributionParams['receive_date'] = $changeDate;
4217 if ($recurContrib && $recurContrib->id
&& !isset($input['is_email_receipt'])) {
4218 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4219 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4220 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4223 if (!empty($values['is_email_receipt'])) {
4224 $contributionParams['receipt_date'] = $changeDate;
4227 if (!empty($memberships)) {
4228 foreach ($memberships as $membershipTypeIdKey => $membership) {
4230 $membershipParams = array(
4231 'id' => $membership->id
,
4232 'contact_id' => $membership->contact_id
,
4233 'is_test' => $membership->is_test
,
4234 'membership_type_id' => $membership->membership_type_id
,
4237 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4238 $membershipParams['membership_type_id'],
4239 $membershipParams['is_test'],
4240 $membershipParams['id']
4243 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4244 // this picks up membership type changes during renewals
4246 SELECT membership_type_id
4247 FROM civicrm_membership_log
4248 WHERE membership_id={$membershipParams['id']}
4251 $dao = CRM_Core_DAO
::executeQuery($sql);
4252 if ($dao->fetch()) {
4253 if (!empty($dao->membership_type_id
)) {
4254 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4259 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4260 $membershipParams['membership_type_id'],
4261 $primaryContributionID
4263 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4264 if ($currentMembership) {
4266 * Fixed FOR CRM-4433
4267 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4268 * when Contribution mode is notify and membership is for renewal )
4270 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4272 // @todo - we should pass membership_type_id instead of null here but not
4273 // adding as not sure of testing
4274 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4275 $changeDate, NULL, $membershipParams['num_terms']
4278 $dates['join_date'] = $currentMembership['join_date'];
4281 //get the status for membership.
4282 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4284 $dates['join_date'],
4287 $membershipParams['membership_type_id'],
4291 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4292 //we might be renewing membership,
4293 //so make status override false.
4294 $membershipParams['is_override'] = FALSE;
4295 civicrm_api3('Membership', 'create', $membershipParams);
4297 //update related Memberships.
4298 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $membershipParams);
4304 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4305 $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id
));
4306 $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
4307 if ($eventDetail['is_email_confirm']) {
4308 // @todo this should be set by the function that sends the mail after sending.
4309 $contributionParams['receipt_date'] = $changeDate;
4311 $participantParams['id'] = $participant->id
;
4312 $participantParams['status_id'] = 'Registered';
4313 civicrm_api3('Participant', 'create', $participantParams);
4317 $contributionParams['id'] = $contribution->id
;
4319 civicrm_api3('Contribution', 'create', $contributionParams);
4321 // Add new soft credit against current $contribution.
4322 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4323 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4326 $paymentProcessorId = '';
4327 if (isset($objects['paymentProcessor'])) {
4328 if (is_array($objects['paymentProcessor'])) {
4329 $paymentProcessorId = $objects['paymentProcessor']['id'];
4332 $paymentProcessorId = $objects['paymentProcessor']->id
;
4336 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4337 'labelColumn' => 'name',
4340 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4341 $input['payment_processor'] = $paymentProcessorId;
4343 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4344 $input['total_amount'] = $input['amount'];
4345 $input['contribution'] = $contribution;
4346 $input['financial_type_id'] = $contribution->financial_type_id
;
4348 if (!empty($contribution->_relatedObjects
['participant'])) {
4349 $input['contribution_mode'] = 'participant';
4350 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4351 $input['skipLineItem'] = 1;
4353 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4354 $input['skipLineItem'] = TRUE;
4355 $input['contribution_mode'] = 'membership';
4357 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4358 // and subsequent payments. In this case the line items are created at
4359 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4360 // and since the contribution is saved prior to this line there is always a contribution-id,
4361 // however there is never a prevContribution (which appears to mean original contribution not previous
4362 // contribution - or preUpdateContributionObject most accurately)
4363 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4364 // to mean "are we updating an exisitng pending contribution"
4365 //I was able to make the unit test complete as fataling here doesn't prevent
4366 // the contribution being created - but activities would not be created or emails sent
4368 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4370 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4371 $transaction->commit();
4373 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution);
4375 // create an activity record
4376 if ($input['component'] == 'contribute') {
4378 $targetContactID = NULL;
4379 if (!empty($ids['related_contact'])) {
4380 $targetContactID = $contribution->contact_id
;
4381 $contribution->contact_id
= $ids['related_contact'];
4383 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4387 CRM_Activity_BAO_Activity
::addActivity($participant);
4390 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4391 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4392 if (!array_key_exists('is_email_receipt', $values) ||
4393 $values['is_email_receipt'] == 1
4395 self
::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
4396 CRM_Core_Error
::debug_log_message("Receipt sent");
4399 CRM_Core_Error
::debug_log_message("Success: Database updated");
4401 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4402 $isFirstOrLastRecurringPayment);
4407 * Send receipt from contribution.
4409 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4411 * Note that the compose message part has been moved to contribution
4412 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4414 * @param array $input
4415 * Incoming data from Payment processor.
4417 * Related object IDs.
4418 * @param CRM_Contribute_BAO_Contribution $contribution
4419 * @param array $values
4420 * Values related to objects that have already been loaded.
4421 * @param bool $recur
4422 * Is it part of a recurring contribution.
4423 * @param bool $returnMessageText
4424 * Should text be returned instead of sent. This.
4425 * is because the function is also used to generate pdfs
4429 public static function sendMail(&$input, &$ids, $contribution, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4430 $input['is_recur'] = $recur;
4431 // set receipt from e-mail and name in value
4432 if (!$returnMessageText) {
4433 $session = CRM_Core_Session
::singleton();
4434 $userID = $session->get('userID');
4435 if (!empty($userID)) {
4436 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4437 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4438 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4441 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4445 * Generate credit note id with next avaible number
4450 public static function createCreditNoteId() {
4451 $prefixValue = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
4453 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4454 $creditNoteId = NULL;
4458 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4459 $result = civicrm_api3('Contribution', 'getcount', array(
4461 'creditnote_id' => $creditNoteId,
4463 } while ($result > 0);
4465 return $creditNoteId;