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, CRM_Core_DAO
::$_nullArray);
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 string $message
948 public static function failPayment($contributionID, $contactID, $message) {
949 civicrm_api3('activity', 'create', array(
950 'activity_type_id' => 'Failed Payment',
951 'details' => $message,
952 'subject' => ts('Payment failed at payment processor'),
953 'source_record_id' => $contributionID,
954 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
960 * Check if there is a contribution with the same trxn_id or invoice_id.
962 * @param array $input
963 * An assoc array of name/value pairs.
964 * @param array $duplicates
965 * (reference) store ids of duplicate contribs.
969 * true if duplicate, false otherwise
971 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
973 $id = CRM_Utils_Array
::value('id', $input);
975 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
976 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
982 $clause[] = "trxn_id = %1";
983 $input[1] = array($trxn_id, 'String');
987 $clause[] = "invoice_id = %2";
988 $input[2] = array($invoice_id, 'String');
991 if (empty($clause)) {
995 $clause = implode(' OR ', $clause);
997 $clause = "( $clause ) AND id != %3";
998 $input[3] = array($id, 'Integer');
1001 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1002 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1004 while ($dao->fetch()) {
1005 $duplicates[] = $dao->id
;
1012 * Takes an associative array and creates a contribution_product object.
1014 * the function extract all the params it needs to initialize the create a
1015 * contribution_product object. the params array could contain additional unused name/value
1018 * @param array $params
1019 * (reference) an assoc array of name/value pairs.
1021 * @return CRM_Contribute_DAO_ContributionProduct
1023 public static function addPremium(&$params) {
1024 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1025 $contributionProduct->copyValues($params);
1026 return $contributionProduct->save();
1030 * Get list of contribution fields for profile.
1031 * For now we only allow custom contribution fields to be in
1034 * @param bool $addExtraFields
1035 * True if special fields needs to be added.
1038 * the list of contribution fields
1040 public static function getContributionFields($addExtraFields = TRUE) {
1041 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1042 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1044 if ($addExtraFields) {
1045 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1048 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1050 foreach ($contributionFields as $key => $var) {
1051 if ($key == 'contribution_contact_id') {
1054 elseif ($key == 'contribution_campaign_id') {
1055 $var['title'] = ts('Campaign');
1057 $fields[$key] = $var;
1060 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1065 * Add extra fields specific to contribution.
1067 public static function getSpecialContributionFields() {
1068 $extraFields = array(
1069 'contribution_soft_credit_name' => array(
1070 'name' => 'contribution_soft_credit_name',
1071 'title' => 'Soft Credit Name',
1072 'headerPattern' => '/^soft_credit_name$/i',
1073 'where' => 'civicrm_contact_d.display_name',
1075 'contribution_soft_credit_email' => array(
1076 'name' => 'contribution_soft_credit_email',
1077 'title' => 'Soft Credit Email',
1078 'headerPattern' => '/^soft_credit_email$/i',
1079 'where' => 'soft_email.email',
1081 'contribution_soft_credit_phone' => array(
1082 'name' => 'contribution_soft_credit_phone',
1083 'title' => 'Soft Credit Phone',
1084 'headerPattern' => '/^soft_credit_phone$/i',
1085 'where' => 'soft_phone.phone',
1087 'contribution_soft_credit_contact_id' => array(
1088 'name' => 'contribution_soft_credit_contact_id',
1089 'title' => 'Soft Credit Contact ID',
1090 'headerPattern' => '/^soft_credit_contact_id$/i',
1091 'where' => 'civicrm_contribution_soft.contact_id',
1093 'contribution_pcp_title' => array(
1094 'name' => 'contribution_pcp_title',
1095 'title' => 'Personal Campaign Page Title',
1096 'headerPattern' => '/^contribution_pcp_title$/i',
1097 'where' => 'contribution_pcp.title',
1101 return $extraFields;
1105 * @param int $pageID
1109 public static function getCurrentandGoalAmount($pageID) {
1111 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1112 FROM civicrm_contribution_page p,
1113 civicrm_contribution c
1114 WHERE p.id = c.contribution_page_id
1116 AND c.cancel_date is null
1120 $config = CRM_Core_Config
::singleton();
1121 $params = array(1 => array($pageID, 'Integer'));
1122 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1124 if ($dao->fetch()) {
1125 return array($dao->goal
, $dao->total
);
1128 return array(NULL, NULL);
1133 * Get list of contribution In Honor of contact Ids.
1135 * @param int $honorId
1136 * In Honor of Contact ID.
1139 * list of contribution fields
1141 public static function getHonorContacts($honorId) {
1143 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1144 $honorDAO->contact_id
= $honorId;
1147 $type = CRM_Contribute_PseudoConstant
::financialType();
1149 while ($honorDAO->fetch()) {
1150 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1151 $contributionDAO->id
= $honorDAO->contribution_id
;
1153 if ($contributionDAO->find(TRUE)) {
1154 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1155 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1156 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1157 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1158 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1159 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1160 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1161 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1162 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1170 * Get the sort name of a contact for a particular contribution.
1173 * Id of the contribution.
1175 * @return null|string
1176 * sort name of the contact if found
1178 public static function sortName($id) {
1179 $id = CRM_Utils_Type
::escape($id, 'Integer');
1182 SELECT civicrm_contact.sort_name
1183 FROM civicrm_contribution, civicrm_contact
1184 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1185 AND civicrm_contribution.id = {$id}
1187 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1191 * @param int $contactID
1195 public static function annual($contactID) {
1196 if (is_array($contactID)) {
1197 $contactIDs = implode(',', $contactID);
1200 $contactIDs = $contactID;
1203 $config = CRM_Core_Config
::singleton();
1204 $startDate = $endDate = NULL;
1206 $currentMonth = date('m');
1207 $currentDay = date('d');
1208 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1209 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1210 (int ) $config->fiscalYearStart
['d'] > $currentDay
1213 $year = date('Y') - 1;
1218 $nextYear = $year +
1;
1220 if ($config->fiscalYearStart
) {
1221 $newFiscalYearStart = $config->fiscalYearStart
;
1222 if ($newFiscalYearStart['M'] < 10) {
1223 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1225 if ($newFiscalYearStart['d'] < 10) {
1226 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1228 $config->fiscalYearStart
= $newFiscalYearStart;
1229 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1234 $startDate = "$year$monthDay";
1235 $endDate = "$nextYear$monthDay";
1236 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1237 $additionalWhere = " AND b.financial_type_id IN (0)";
1238 $liWhere = " AND i.financial_type_id IN (0)";
1239 if (!empty($financialTypes)) {
1240 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1241 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1244 SELECT count(*) as count,
1245 sum(total_amount) as amount,
1246 avg(total_amount) as average,
1248 FROM civicrm_contribution b
1249 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1250 WHERE b.contact_id IN ( $contactIDs )
1251 AND b.contribution_status_id = 1
1253 AND b.receive_date >= $startDate
1254 AND b.receive_date < $endDate
1258 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1260 $amount = $average = array();
1261 while ($dao->fetch()) {
1262 if ($dao->count
> 0 && $dao->amount
> 0) {
1263 $count +
= $dao->count
;
1264 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1265 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1271 implode(', ', $amount),
1272 implode(', ', $average),
1275 return array(0, 0, 0);
1279 * Check if there is a contribution with the params passed in.
1281 * Used for trxn_id,invoice_id and contribution_id
1283 * @param array $params
1284 * An assoc array of name/value pairs.
1287 * contribution id if success else NULL
1289 public static function checkDuplicateIds($params) {
1290 $dao = new CRM_Contribute_DAO_Contribution();
1294 foreach ($params as $k => $v) {
1296 $clause[] = "$k = '$v'";
1299 $clause = implode(' AND ', $clause);
1300 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1301 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1303 while ($dao->fetch()) {
1311 * Get the contribution details for component export.
1313 * @param int $exportMode
1315 * @param string $componentIds
1321 public static function getContributionDetails($exportMode, $componentIds) {
1322 $paymentDetails = array();
1323 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1325 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1326 $componentSelect = " civicrm_participant_payment.participant_id id";
1327 $additionalClause = "
1328 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1329 AND civicrm_participant_payment.participant_id {$componentClause} )
1332 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1333 $componentSelect = " civicrm_membership_payment.membership_id id";
1334 $additionalClause = "
1335 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1336 AND civicrm_membership_payment.membership_id {$componentClause} )
1339 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1340 $componentSelect = " civicrm_pledge_payment.id id";
1341 $additionalClause = "
1342 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1343 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1347 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1348 trxn_id, {$componentSelect}
1349 FROM civicrm_contribution
1350 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1351 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1352 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1353 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1354 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1355 AND option_group_contribution_status.id = contribution_status.option_group_id )
1359 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1361 while ($dao->fetch()) {
1362 $paymentDetails[$dao->id
] = array(
1363 'total_amount' => $dao->total_amount
,
1364 'contribution_status' => $dao->status
,
1365 'receive_date' => $dao->receive_date
,
1366 'pay_instru' => $dao->payment_instrument
,
1367 'trxn_id' => $dao->trxn_id
,
1371 return $paymentDetails;
1375 * Create address associated with contribution record.
1377 * As long as there is one or more billing field in the parameters we will create the address.
1379 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1382 * @param array $params
1383 * @param int $billingLocationTypeID
1388 public static function createAddress($params, $billingLocationTypeID) {
1389 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1390 if ($hasBillingField) {
1391 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1392 return $address->id
;
1399 * Delete billing address record related contribution.
1401 * @param int $contributionId
1402 * @param int $contactId
1404 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1406 $contactJoin = NULL;
1408 if ($contributionId) {
1409 $clauses[] = "cc.id = {$contributionId}";
1413 $clauses[] = "cco.id = {$contactId}";
1414 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1417 if (empty($clauses)) {
1418 CRM_Core_Error
::fatal();
1421 $condition = implode(' OR ', $clauses);
1425 FROM civicrm_address ca
1426 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1430 $dao = CRM_Core_DAO
::executeQuery($query);
1432 while ($dao->fetch()) {
1433 $params = array('id' => $dao->id
);
1434 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1439 * This function check online pending contribution associated w/
1440 * Online Event Registration or Online Membership signup.
1442 * @param int $componentId
1443 * Participant/membership id.
1444 * @param string $componentName
1448 * pending contribution id.
1450 public static function checkOnlinePendingContribution($componentId, $componentName) {
1451 $contributionId = NULL;
1452 if (!$componentId ||
1453 !in_array($componentName, array('Event', 'Membership'))
1455 return $contributionId;
1458 if ($componentName == 'Event') {
1459 $idName = 'participant_id';
1460 $componentTable = 'civicrm_participant';
1461 $paymentTable = 'civicrm_participant_payment';
1462 $source = ts('Online Event Registration');
1465 if ($componentName == 'Membership') {
1466 $idName = 'membership_id';
1467 $componentTable = 'civicrm_membership';
1468 $paymentTable = 'civicrm_membership_payment';
1469 $source = ts('Online Contribution');
1472 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1475 SELECT component.id as {$idName},
1476 componentPayment.contribution_id as contribution_id,
1477 contribution.source source,
1478 contribution.contribution_status_id as contribution_status_id,
1479 contribution.is_pay_later as is_pay_later
1480 FROM $componentTable component
1481 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1482 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1483 WHERE component.id = {$componentId}";
1485 $dao = CRM_Core_DAO
::executeQuery($query);
1487 while ($dao->fetch()) {
1488 if ($dao->contribution_id
&&
1489 $dao->is_pay_later
&&
1490 $dao->contribution_status_id
== $pendingStatusId &&
1491 strpos($dao->source
, $source) !== FALSE
1493 $contributionId = $dao->contribution_id
;
1498 return $contributionId;
1502 * Update contribution as well as related objects.
1504 * This function by-passes hooks - to address this - don't use this function.
1508 * Use api contribute.completetransaction
1509 * For failures use failPayment (preferably exposing by api in the process).
1511 * @param array $params
1512 * @param bool $processContributionObject
1515 * @throws \Exception
1517 public static function transitionComponents($params, $processContributionObject = FALSE) {
1518 // get minimum required values.
1519 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1520 $componentId = CRM_Utils_Array
::value('component_id', $params);
1521 $componentName = CRM_Utils_Array
::value('componentName', $params);
1522 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1523 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1525 // if we already processed contribution object pass previous status id.
1526 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1528 $updateResult = array();
1530 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1532 // we process only ( Completed, Cancelled, or Failed ) contributions.
1533 if (!$contributionId ||
1534 !in_array($contributionStatusId, array(
1535 array_search('Completed', $contributionStatuses),
1536 array_search('Cancelled', $contributionStatuses),
1537 array_search('Failed', $contributionStatuses),
1540 return $updateResult;
1543 if (!$componentName ||
!$componentId) {
1544 // get the related component details.
1545 $componentDetails = self
::getComponentDetails($contributionId);
1548 $componentDetails['contact_id'] = $contactId;
1549 $componentDetails['component'] = $componentName;
1551 if ($componentName == 'event') {
1552 $componentDetails['participant'] = $componentId;
1555 $componentDetails['membership'] = $componentId;
1559 if (!empty($componentDetails['contact_id'])) {
1560 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1566 // do check for required ids.
1567 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1568 return $updateResult;
1571 //now we are ready w/ required ids, start processing.
1573 $baseIPN = new CRM_Core_Payment_BaseIPN();
1575 $input = $ids = $objects = array();
1577 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1578 $ids['contribution'] = $contributionId;
1579 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1580 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1581 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1582 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1583 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1584 $ids['contributionRecur'] = NULL;
1585 $ids['contributionPage'] = NULL;
1587 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1588 CRM_Core_Error
::fatal();
1591 $memberships = &$objects['membership'];
1592 $participant = &$objects['participant'];
1593 $pledgePayment = &$objects['pledge_payment'];
1594 $contribution = &$objects['contribution'];
1596 if ($pledgePayment) {
1597 $pledgePaymentIDs = array();
1598 foreach ($pledgePayment as $key => $object) {
1599 $pledgePaymentIDs[] = $object->id
;
1601 $pledgeID = $pledgePayment[0]->pledge_id
;
1604 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1607 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1608 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1613 // we might want to process contribution object.
1614 $processContribution = FALSE;
1615 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1616 if (is_array($memberships)) {
1617 foreach ($memberships as $membership) {
1619 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1620 $membership->save();
1622 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1623 if ($processContributionObject) {
1624 $processContribution = TRUE;
1631 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1632 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1634 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1635 if ($processContributionObject) {
1636 $processContribution = TRUE;
1640 if ($pledgePayment) {
1641 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1643 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1644 if ($processContributionObject) {
1645 $processContribution = TRUE;
1649 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1650 if (is_array($memberships)) {
1651 foreach ($memberships as $membership) {
1653 $membership->status_id
= array_search('Expired', $membershipStatuses);
1654 $membership->save();
1656 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1657 if ($processContributionObject) {
1658 $processContribution = TRUE;
1664 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1665 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1667 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1668 if ($processContributionObject) {
1669 $processContribution = TRUE;
1673 if ($pledgePayment) {
1674 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1676 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1677 if ($processContributionObject) {
1678 $processContribution = TRUE;
1682 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1684 // only pending contribution related object processed.
1685 if ($previousContriStatusId &&
1686 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1688 // this is case when we already processed contribution object.
1689 return $updateResult;
1691 elseif (!$previousContriStatusId &&
1692 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1694 // this is case when we are going to process contribution object later.
1695 return $updateResult;
1698 if (is_array($memberships)) {
1699 foreach ($memberships as $membership) {
1704 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1705 $membership->membership_type_id
,
1706 $membership->is_test
, $membership->id
1709 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1710 // this picks up membership type changes during renewals
1712 SELECT membership_type_id
1713 FROM civicrm_membership_log
1714 WHERE membership_id=$membership->id
1717 $dao = new CRM_Core_DAO();
1719 if ($dao->fetch()) {
1720 if (!empty($dao->membership_type_id
)) {
1721 $membership->membership_type_id
= $dao->membership_type_id
;
1722 $membership->save();
1725 // else fall back to using current membership type
1728 // Figure out number of terms
1730 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1731 foreach ($lineitems as $lineitem) {
1732 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1733 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1735 // in case membership_num_terms comes through as null or zero
1736 $numterms = $numterms >= 1 ?
$numterms : 1;
1741 // CRM-15735-to update the membership status as per the contribution receive date
1743 if (!empty($params['receive_date'])) {
1744 $joinDate = $params['receive_date'];
1745 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1746 $membership->end_date
,
1747 $membership->join_date
,
1748 $params['receive_date'],
1750 $membership->membership_type_id
,
1753 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1754 $membership->save();
1757 if ($currentMembership) {
1758 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1759 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1760 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1763 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1766 //get the status for membership.
1767 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1769 $dates['join_date'],
1772 $membership->membership_type_id
,
1776 $formattedParams = array(
1777 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1778 array_search('Current', $membershipStatuses)
1780 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1781 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1782 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1785 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1787 $membership->copyValues($formattedParams);
1788 $membership->save();
1790 //updating the membership log
1791 $membershipLog = array();
1792 $membershipLog = $formattedParams;
1793 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1794 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1796 $membershipLog['start_date'] = $logStartDate;
1797 $membershipLog['membership_id'] = $membership->id
;
1798 $membershipLog['modified_id'] = $membership->contact_id
;
1799 $membershipLog['modified_date'] = date('Ymd');
1800 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1802 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1804 //update related Memberships.
1805 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1807 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1810 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1811 if ($processContributionObject) {
1812 $processContribution = TRUE;
1815 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1821 $updatedStatusId = array_search('Registered', $participantStatuses);
1822 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1824 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1825 if ($processContributionObject) {
1826 $processContribution = TRUE;
1830 if ($pledgePayment) {
1831 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1833 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1834 if ($processContributionObject) {
1835 $processContribution = TRUE;
1840 // process contribution object.
1841 if ($processContribution) {
1842 $contributionParams = array();
1849 'payment_instrument_id',
1852 'financial_type_id',
1853 'contribution_status_id',
1854 'non_deductible_amount',
1858 foreach ($fields as $field) {
1859 if (empty($params[$field])) {
1862 $contributionParams[$field] = $params[$field];
1865 $ids = array('contribution' => $contributionId);
1866 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1869 return $updateResult;
1873 * Returns all contribution related object ids.
1875 * @param $contributionId
1879 public static function getComponentDetails($contributionId) {
1880 $componentDetails = $pledgePayment = array();
1881 if (!$contributionId) {
1882 return $componentDetails;
1886 SELECT c.id as contribution_id,
1887 c.contact_id as contact_id,
1888 c.contribution_recur_id,
1889 mp.membership_id as membership_id,
1890 m.membership_type_id as membership_type_id,
1891 pp.participant_id as participant_id,
1892 p.event_id as event_id,
1893 pgp.id as pledge_payment_id
1894 FROM civicrm_contribution c
1895 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1896 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1897 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1898 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1899 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1900 WHERE c.id = $contributionId";
1902 $dao = CRM_Core_DAO
::executeQuery($query);
1903 $componentDetails = array();
1905 while ($dao->fetch()) {
1906 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1907 $componentDetails['contact_id'] = $dao->contact_id
;
1908 if ($dao->event_id
) {
1909 $componentDetails['event'] = $dao->event_id
;
1911 if ($dao->participant_id
) {
1912 $componentDetails['participant'] = $dao->participant_id
;
1914 if ($dao->membership_id
) {
1915 if (!isset($componentDetails['membership'])) {
1916 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1918 $componentDetails['membership'][] = $dao->membership_id
;
1919 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1921 if ($dao->pledge_payment_id
) {
1922 $pledgePayment[] = $dao->pledge_payment_id
;
1924 if ($dao->contribution_recur_id
) {
1925 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1929 if ($pledgePayment) {
1930 $componentDetails['pledge_payment'] = $pledgePayment;
1933 return $componentDetails;
1937 * @param int $contactId
1938 * @param bool $includeSoftCredit
1940 * @return null|string
1942 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1946 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1947 $additionalWhere = " AND contribution.financial_type_id IN (0)";
1948 $liWhere = " AND i.financial_type_id IN (0)";
1949 if (!empty($financialTypes)) {
1950 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1951 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1953 $contactContributionsSQL = "
1954 SELECT contribution.id AS id
1955 FROM civicrm_contribution contribution
1956 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
1957 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
1961 $contactSoftCreditContributionsSQL = "
1962 SELECT contribution.id
1963 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1964 ON ( contribution.id = softContribution.contribution_id )
1965 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1966 $query = "SELECT count( x.id ) count FROM ( ";
1967 $query .= $contactContributionsSQL;
1969 if ($includeSoftCredit) {
1970 $query .= " UNION ";
1971 $query .= $contactSoftCreditContributionsSQL;
1976 return CRM_Core_DAO
::singleValueQuery($query);
1980 * Repeat a transaction as part of a recurring series.
1982 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
1983 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
1984 * subsequent call to the contribution.completetransaction api.
1986 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
1988 * @param CRM_Contribute_BAO_Contribution $contribution
1989 * @param array $input
1990 * @param array $contributionParams
1994 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
1995 if (!empty($contribution->id
)) {
1998 if (empty($contribution->id
)) {
1999 // Unclear why this would only be set for repeats.
2000 if (!empty($input['amount'])) {
2001 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2003 $templateContribution = civicrm_api3('Contribution', 'getsingle', array(
2004 'contribution_recur_id' => $contributionParams['contribution_recur_id'],
2005 'options' => array('limit' => 1),
2007 $contributionParams['skipLineItem'] = TRUE;
2008 $contributionParams['status_id'] = 'Pending';
2009 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2010 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2011 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2012 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2013 $contribution->id
= $createContribution['id'];
2014 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
2015 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2021 * Get individual id for onbehalf contribution.
2023 * @param int $contributionId
2025 * @param int $contributorId
2029 * containing organization id and individual id
2031 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2035 if (!$contributionId) {
2039 // fetch contributor id if null
2040 if (!$contributorId) {
2041 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2042 $contributionId, 'contact_id'
2046 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2047 $activityTypeId = array_search('Contribution', $activityTypeIds);
2049 if ($activityTypeId && $contributorId) {
2051 SELECT civicrm_activity_contact.contact_id
2052 FROM civicrm_activity_contact
2053 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2054 WHERE civicrm_activity.activity_type_id = %1
2055 AND civicrm_activity.source_record_id = %2
2056 AND civicrm_activity_contact.record_type_id = %3
2059 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2060 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2063 1 => array($activityTypeId, 'Integer'),
2064 2 => array($contributionId, 'Integer'),
2065 3 => array($sourceID, 'Integer'),
2068 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2070 // for on behalf contribution source is individual and contributor is organization
2071 if ($sourceContactId && $sourceContactId != $contributorId) {
2072 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2073 // get rel type id for employee of relation
2074 foreach ($relationshipTypeIds as $id => $typeVals) {
2075 if ($typeVals['name_a_b'] == 'Employee of') {
2076 $relationshipTypeId = $id;
2081 $rel = new CRM_Contact_DAO_Relationship();
2082 $rel->relationship_type_id
= $relationshipTypeId;
2083 $rel->contact_id_a
= $sourceContactId;
2084 $rel->contact_id_b
= $contributorId;
2085 if ($rel->find(TRUE)) {
2086 $ids['individual_id'] = $rel->contact_id_a
;
2087 $ids['organization_id'] = $rel->contact_id_b
;
2098 public static function getContributionDates() {
2099 $config = CRM_Core_Config
::singleton();
2100 $currentMonth = date('m');
2101 $currentDay = date('d');
2102 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2103 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2104 (int ) $config->fiscalYearStart
['d'] > $currentDay
2107 $year = date('Y') - 1;
2112 $year = array('Y' => $year);
2113 $yearDate = $config->fiscalYearStart
;
2114 $yearDate = array_merge($year, $yearDate);
2115 $yearDate = CRM_Utils_Date
::format($yearDate);
2117 $monthDate = date('Ym') . '01';
2123 'yearDate' => $yearDate,
2124 'monthDate' => $monthDate,
2129 * Load objects relations to contribution object.
2130 * Objects are stored in the $_relatedObjects property
2131 * In the first instance we are just moving functionality from BASEIpn -
2132 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2134 * Note that the unit test for the BaseIPN class tests this function
2136 * @param array $input
2137 * Input as delivered from Payment Processor.
2139 * Ids as Loaded by Payment Processor.
2140 * @param bool $loadAll
2141 * Load all related objects - even where id not passed in? (allows API to call this).
2146 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2148 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2149 if (empty($ids['contact']) && isset($this->contact_id
)) {
2150 $ids['contact'] = $this->contact_id
;
2153 if (empty($this->_component
)) {
2154 if (!empty($ids['event'])) {
2155 $this->_component
= 'event';
2158 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2162 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2163 // refactoring than anything else, and has unit test coverage.
2164 if (empty($this->financial_type_id
)) {
2168 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2173 if (!$paymentProcessorID && $this->contribution_page_id
) {
2174 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2175 $this->contribution_page_id
,
2178 if ($paymentProcessorID) {
2179 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2183 $ids['contributionType'] = $this->financial_type_id
;
2184 $ids['financialType'] = $this->financial_type_id
;
2187 'contact' => 'CRM_Contact_BAO_Contact',
2188 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2189 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2190 'financialType' => 'CRM_Financial_BAO_FinancialType',
2192 foreach ($entities as $entity => $bao) {
2193 if (!empty($ids[$entity])) {
2194 $this->_relatedObjects
[$entity] = new $bao();
2195 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2196 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2197 throw new CRM_Core_Exception($entity . ' could not be loaded');
2202 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2203 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2206 if (!empty($ids['pledge_payment'])) {
2207 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2208 if (empty($paymentID)) {
2211 $payment = new CRM_Pledge_BAO_PledgePayment();
2212 $payment->id
= $paymentID;
2213 if (!$payment->find(TRUE)) {
2214 throw new Exception("Could not find pledge payment record: " . $paymentID);
2216 $this->_relatedObjects
['pledge_payment'][] = $payment;
2220 if ($this->_component
== 'contribute') {
2221 // retrieve the other optional objects first so
2222 // stuff down the line can use this info and do things
2224 //in any case get the memberships associated with the contribution
2225 //because we now support multiple memberships w/ price set
2226 // see if there are any other memberships to be considered for same contribution.
2228 SELECT membership_id
2229 FROM civicrm_membership_payment
2230 WHERE contribution_id = %1 ";
2231 $params = array(1 => array($this->id
, 'Integer'));
2233 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2234 while ($dao->fetch()) {
2235 if ($dao->membership_id
) {
2236 if (!is_array($ids['membership'])) {
2237 $ids['membership'] = array();
2239 $ids['membership'][] = $dao->membership_id
;
2243 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2244 foreach ($ids['membership'] as $id) {
2246 $membership = new CRM_Member_BAO_Membership();
2247 $membership->id
= $id;
2248 if (!$membership->find(TRUE)) {
2249 throw new Exception("Could not find membership record: $id");
2251 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2252 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2253 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2254 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2255 $membership->free();
2261 // we are in event mode
2262 // make sure event exists and is valid
2263 $event = new CRM_Event_BAO_Event();
2264 $event->id
= $ids['event'];
2265 if ($ids['event'] &&
2268 throw new Exception("Could not find event: " . $ids['event']);
2271 $this->_relatedObjects
['event'] = &$event;
2273 $participant = new CRM_Event_BAO_Participant();
2274 $participant->id
= $ids['participant'];
2275 if ($ids['participant'] &&
2276 !$participant->find(TRUE)
2278 throw new Exception("Could not find participant: " . $ids['participant']);
2280 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2282 $this->_relatedObjects
['participant'] = &$participant;
2284 // get the payment processor id from event - this is inaccurate see CRM-16923
2285 // in future we should look at throwing an exception here rather than an dubious guess.
2286 if (!$paymentProcessorID) {
2287 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2288 if ($paymentProcessorID) {
2289 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2294 if ($paymentProcessorID) {
2295 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2296 $this->is_test ?
'test' : 'live'
2298 $ids['paymentProcessor'] = $paymentProcessorID;
2299 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2305 * Create array of message information - ie. return html version, txt version, to field
2307 * @param array $input
2308 * Incoming information.
2309 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2310 * just check presence of recur object but maintaining legacy approach
2313 * IDs of related objects.
2314 * @param array $values
2315 * Any values that may have already been compiled by calling process.
2316 * This is augmented by values 'gathered' by gatherMessageValues
2317 * @param bool $recur
2318 * @param bool $returnMessageText
2319 * Distinguishes between whether to send message or return.
2320 * message text. We are working towards this function ALWAYS returning message text & calling
2321 * function doing emails / pdfs with it
2327 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2328 $this->loadRelatedObjects($input, $ids);
2330 if (empty($this->_component
)) {
2331 $this->_component
= CRM_Utils_Array
::value('component', $input);
2334 //not really sure what params might be passed in but lets merge em into values
2335 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2336 $template = CRM_Core_Smarty
::singleton();
2337 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2338 //what does recur 'mean here - to do with payment processor return functionality but
2339 // what is the importance
2340 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2341 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2343 $entityID = $entity = NULL;
2344 if (isset($ids['contribution'])) {
2345 $entity = 'contribution';
2346 $entityID = $ids['contribution'];
2348 if (!empty($ids['membership'])) {
2349 //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
2350 // 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
2351 // line having loaded an array
2352 $ids['membership'] = (array) $ids['membership'];
2353 $entity = 'membership';
2354 $entityID = $ids['membership'][0];
2357 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity));
2358 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2359 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2361 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2362 //direct mode showing billing block, so use directIPN for temporary
2363 $template->assign('contributeMode', 'directIPN');
2366 // todo remove strtolower - check consistency
2367 if (strtolower($this->_component
) == 'event') {
2368 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2369 $values['event'] = array();
2371 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2373 //get location details
2374 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2375 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2377 $ufJoinParams = array(
2378 'entity_table' => 'civicrm_event',
2379 'entity_id' => $ids['event'],
2380 'module' => 'CiviEvent',
2383 list($custom_pre_id,
2385 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2387 $values['custom_pre_id'] = $custom_pre_id;
2388 $values['custom_post_id'] = $custom_post_ids;
2389 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2390 //and cases involving status updation through ipn
2391 // whatever that means!
2392 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2393 // perhaps we should throw an e-notice if amount is set & force total_amount?
2394 if (!empty($input['amount'])) {
2395 $values['totalAmount'] = $input['amount'];
2398 if ($values['event']['is_email_confirm']) {
2399 $values['is_email_receipt'] = 1;
2401 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2402 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2406 $values['contribution_id'] = $this->id
;
2407 if (!empty($ids['related_contact'])) {
2408 $values['related_contact'] = $ids['related_contact'];
2409 if (isset($ids['onbehalf_dupe_alert'])) {
2410 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2412 $entityBlock = array(
2413 'contact_id' => $ids['contact'],
2414 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2415 'Home', 'id', 'name'
2418 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2419 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2422 if ($this->is_test
) {
2425 if (!empty($this->_relatedObjects
['membership'])) {
2426 foreach ($this->_relatedObjects
['membership'] as $membership) {
2427 if ($membership->id
) {
2428 $values['isMembership'] = TRUE;
2430 // need to set the membership values here
2431 $template->assign('membership_assign', 1);
2432 $template->assign('membership_name',
2433 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2435 $template->assign('mem_start_date', $membership->start_date
);
2436 $template->assign('mem_join_date', $membership->join_date
);
2437 $template->assign('mem_end_date', $membership->end_date
);
2438 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2439 $template->assign('mem_status', $membership_status);
2440 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2441 $template->assign('is_pay_later', 1);
2444 // if separate payment there are two contributions recorded and the
2445 // admin will need to send a receipt for each of them separately.
2446 // we dont link the two in the db (but can potentially infer it if needed)
2447 $template->assign('is_separate_payment', 0);
2449 if ($recur && $paymentObject) {
2450 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2451 $template->assign('cancelSubscriptionUrl', $url);
2452 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2453 $template->assign('updateSubscriptionBillingUrl', $url);
2454 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2455 $template->assign('updateSubscriptionUrl', $url);
2458 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2461 // otherwise if its about sending emails, continue sending without return, as we
2462 // don't want to exit the loop.
2467 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2473 * Gather values for contribution mail - this function has been created
2474 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2475 * Values related to the contribution in question are gathered
2477 * @param array $input
2478 * Input into function (probably from payment processor).
2479 * @param array $values
2481 * The set of ids related to the input.
2485 public function _gatherMessageValues($input, &$values, $ids = array()) {
2486 // set display address of contributor
2487 if ($this->address_id
) {
2488 $addressParams = array('id' => $this->address_id
);
2489 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2490 $addressDetails = array_values($addressDetails);
2491 $values['address'] = $addressDetails[0]['display'];
2493 if ($this->_component
== 'contribute') {
2494 //get soft contributions
2495 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2496 if (!empty($softContributions)) {
2497 $values['softContributions'] = $softContributions['soft_credit'];
2499 if (isset($this->contribution_page_id
)) {
2500 CRM_Contribute_BAO_ContributionPage
::setValues(
2501 $this->contribution_page_id
,
2504 if ($this->contribution_page_id
) {
2505 // CRM-8254 - override default currency if applicable
2506 $config = CRM_Core_Config
::singleton();
2507 $config->defaultCurrency
= CRM_Utils_Array
::value(
2510 $config->defaultCurrency
2514 // no contribution page -probably back office
2516 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2517 $values['is_email_receipt'] = 1;
2518 $values['title'] = 'Contribution';
2520 // set lineItem for contribution
2522 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2523 if (!empty($lineItem)) {
2524 $itemId = key($lineItem);
2525 foreach ($lineItem as &$eachItem) {
2526 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2527 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2528 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2529 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2532 $values['lineItem'][0] = $lineItem;
2533 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2537 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2541 // if this is onbehalf of contribution then set related contact
2542 if (!empty($relatedContact['individual_id'])) {
2543 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2548 $eventParams = array(
2549 'id' => $this->_relatedObjects
['event']->id
,
2551 $values['event'] = array();
2553 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2554 // add custom fields for event
2555 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2557 $eventCustomGroup = array();
2558 foreach ($eventGroupTree as $key => $group) {
2559 if ($key === 'info') {
2563 foreach ($group['fields'] as $k => $customField) {
2564 $groupLabel = $group['title'];
2565 if (!empty($customField['customValue'])) {
2566 foreach ($customField['customValue'] as $customFieldValues) {
2567 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2572 $values['event']['customGroup'] = $eventCustomGroup;
2574 //get participant details
2575 $participantParams = array(
2576 'id' => $this->_relatedObjects
['participant']->id
,
2579 $values['participant'] = array();
2581 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2582 // add custom fields for event
2583 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2584 $participantCustomGroup = array();
2585 foreach ($participantGroupTree as $key => $group) {
2586 if ($key === 'info') {
2590 foreach ($group['fields'] as $k => $customField) {
2591 $groupLabel = $group['title'];
2592 if (!empty($customField['customValue'])) {
2593 foreach ($customField['customValue'] as $customFieldValues) {
2594 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2599 $values['participant']['customGroup'] = $participantCustomGroup;
2601 //get location details
2602 $locationParams = array(
2603 'entity_id' => $this->_relatedObjects
['event']->id
,
2604 'entity_table' => 'civicrm_event',
2606 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2608 $ufJoinParams = array(
2609 'entity_table' => 'civicrm_event',
2610 'entity_id' => $ids['event'],
2611 'module' => 'CiviEvent',
2614 list($custom_pre_id,
2616 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2618 $values['custom_pre_id'] = $custom_pre_id;
2619 $values['custom_post_id'] = $custom_post_ids;
2621 // set lineItem for event contribution
2623 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2624 if (!empty($participantIds)) {
2625 foreach ($participantIds as $pIDs) {
2626 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2627 if (!CRM_Utils_System
::isNull($lineItem)) {
2628 $values['lineItem'][] = $lineItem;
2635 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2637 $customGroup = array();
2638 foreach ($groupTree as $key => $group) {
2639 if ($key === 'info') {
2643 foreach ($group['fields'] as $k => $customField) {
2644 $groupLabel = $group['title'];
2645 if (!empty($customField['customValue'])) {
2646 foreach ($customField['customValue'] as $customFieldValues) {
2647 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2652 $values['customGroup'] = $customGroup;
2658 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2659 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2660 * Note we send directly from this function in some cases because it is only partly refactored
2661 * Don't call this function directly as the signature will change
2665 * @param CRM_Core_SMARTY $template
2666 * @param bool $recur
2667 * @param bool $returnMessageText
2671 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2672 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2673 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2674 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2675 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2676 $template->assign('useForMember', TRUE);
2678 //assign honor information to receipt message
2679 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2681 if (isset($softRecord['soft_credit'])) {
2682 //if id of contribution page is present
2683 if (!empty($values['id'])) {
2684 $values['honor'] = array(
2685 'honor_profile_values' => array(),
2686 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2687 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2689 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2691 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2692 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2695 //offline contribution
2696 $softCreditTypes = $softCredits = array();
2697 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2698 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2699 $softCredits[$key] = array(
2700 'Name' => $softCredit['contact_name'],
2701 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2704 $template->assign('softCreditTypes', $softCreditTypes);
2705 $template->assign('softCredits', $softCredits);
2709 $dao = new CRM_Contribute_DAO_ContributionProduct();
2710 $dao->contribution_id
= $this->id
;
2711 if ($dao->find(TRUE)) {
2712 $premiumId = $dao->product_id
;
2713 $template->assign('option', $dao->product_option
);
2715 $productDAO = new CRM_Contribute_DAO_Product();
2716 $productDAO->id
= $premiumId;
2717 $productDAO->find(TRUE);
2718 $template->assign('selectPremium', TRUE);
2719 $template->assign('product_name', $productDAO->name
);
2720 $template->assign('price', $productDAO->price
);
2721 $template->assign('sku', $productDAO->sku
);
2723 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2724 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2725 if (empty($amount) && isset($this->total_amount
)) {
2726 $amount = $this->total_amount
;
2728 $template->assign('amount', $amount);
2729 // add the new contribution values
2730 if (strtolower($this->_component
) == 'contribute') {
2732 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2733 $softDAO->contribution_id
= $this->id
;
2734 if ($softDAO->find(TRUE)) {
2735 $template->assign('pcpBlock', TRUE);
2736 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2737 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2738 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2740 //assign the pcp page title for email subject
2741 $pcpDAO = new CRM_PCP_DAO_PCP();
2742 $pcpDAO->id
= $softDAO->pcp_id
;
2743 if ($pcpDAO->find(TRUE)) {
2744 $template->assign('title', $pcpDAO->title
);
2749 if ($this->financial_type_id
) {
2750 $values['financial_type_id'] = $this->financial_type_id
;
2753 $template->assign('trxn_id', $this->trxn_id
);
2754 $template->assign('receive_date',
2755 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2757 $template->assign('contributeMode', 'notify');
2758 $template->assign('action', $this->is_test ?
1024 : 1);
2759 $template->assign('receipt_text',
2760 CRM_Utils_Array
::value('receipt_text',
2764 $template->assign('is_monetary', 1);
2765 $template->assign('is_recur', (bool) $recur);
2766 $template->assign('currency', $this->currency
);
2767 $template->assign('address', CRM_Utils_Address
::format($input));
2768 if (!empty($values['customGroup'])) {
2769 $template->assign('customGroup', $values['customGroup']);
2771 if (!empty($values['softContributions'])) {
2772 $template->assign('softContributions', $values['softContributions']);
2774 if ($this->_component
== 'event') {
2775 $template->assign('title', $values['event']['title']);
2776 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2777 $viewRoles = array();
2778 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2779 $viewRoles[] = $participantRoles[$v];
2781 $values['event']['participant_role'] = implode(', ', $viewRoles);
2782 $template->assign('event', $values['event']);
2783 $template->assign('participant', $values['participant']);
2784 $template->assign('location', $values['location']);
2785 $template->assign('customPre', $values['custom_pre_id']);
2786 $template->assign('customPost', $values['custom_post_id']);
2789 if ($this->_relatedObjects
['participant']->is_test
) {
2793 $values['params'] = array();
2794 //to get email of primary participant.
2795 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2796 $primaryAmount[] = array(
2797 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2798 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2800 //build an array of cId/pId of participants
2801 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2802 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2803 //send receipt to additional participant if exists
2804 if (count($additionalIDs)) {
2805 $template->assign('isPrimary', 0);
2806 $template->assign('customProfile', NULL);
2807 //set additionalParticipant true
2808 $values['params']['additionalParticipant'] = TRUE;
2809 foreach ($additionalIDs as $pId => $cId) {
2811 //to change the status pending to completed
2812 $additional = new CRM_Event_DAO_Participant();
2813 $additional->id
= $pId;
2814 $additional->contact_id
= $cId;
2815 $additional->find(TRUE);
2816 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2817 $additional->status_id
= 1;
2818 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2819 //if additional participant dont have email
2821 if (!$additionalParticipantInfo) {
2822 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2824 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2825 $primaryAmount[] = array(
2826 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2827 'amount' => $additional->fee_amount
,
2829 $additional->save();
2830 $additional->free();
2831 $template->assign('amount', $amount);
2832 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2836 //build an array of custom profile and assigning it to template
2837 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2839 if (count($customProfile)) {
2840 $template->assign('customProfile', $customProfile);
2843 // for primary contact
2844 $values['params']['additionalParticipant'] = FALSE;
2845 $template->assign('isPrimary', 1);
2846 $template->assign('amount', $primaryAmount);
2847 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2848 if ($this->payment_instrument_id
) {
2849 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2850 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2852 // carry paylater, since we did not created billing,
2853 // so need to pull email from primary location, CRM-4395
2854 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2860 * Check whether payment processor supports
2861 * cancellation of contribution subscription
2863 * @param int $contributionId
2866 * @param bool $isNotCancelled
2870 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2871 $cacheKeyString = "$contributionId";
2872 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2874 static $supportsCancel = array();
2876 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2877 $supportsCancel[$cacheKeyString] = FALSE;
2878 $isCancelled = FALSE;
2880 if ($isNotCancelled) {
2881 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2884 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2885 if (!empty($paymentObject)) {
2886 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2889 return $supportsCancel[$cacheKeyString];
2893 * Check whether subscription is already cancelled.
2895 * @param int $contributionId
2899 * contribution status
2901 public static function isSubscriptionCancelled($contributionId) {
2903 SELECT cr.contribution_status_id
2904 FROM civicrm_contribution_recur cr
2905 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2906 WHERE con.id = %1 LIMIT 1";
2907 $params = array(1 => array($contributionId, 'Integer'));
2908 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2909 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2910 if ($status == 'Cancelled') {
2917 * Create all financial accounts entry.
2919 * @param array $params
2920 * Contribution object, line item array and params for trxn.
2923 * @param array $financialTrxnValues
2925 * @return null|object
2927 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2928 $skipRecords = $update = $return = $isRelatedId = FALSE;
2930 $additionalParticipantId = array();
2931 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2933 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2934 $entityId = $params['participant_id'];
2935 $entityTable = 'civicrm_participant';
2936 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2938 elseif (!empty($params['membership_id'])) {
2939 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2940 // are created off one contribution should be handled elsewhere
2941 $entityId = $params['membership_id'];
2942 $entityTable = 'civicrm_membership';
2945 $entityId = $params['contribution']->id
;
2946 $entityTable = 'civicrm_contribution';
2949 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2950 $isRelatedId = TRUE;
2953 $entityID[] = $entityId;
2954 if (!empty($additionalParticipantId)) {
2955 $entityID +
= $additionalParticipantId;
2957 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2958 if (empty($params['prevContribution'])) {
2965 $statusId = $params['contribution']->contribution_status_id
;
2966 // CRM-13964 partial payment
2967 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2968 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2970 $partialAmtPay = $params['partial_amount_pay'];
2971 $partialAmtTotal = $params['partial_payment_total'];
2973 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2974 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2975 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2976 $params['total_amount'] = $partialAmtPay;
2978 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2979 if (empty($balanceTrxnInfo['trxn_id'])) {
2980 // create new balance transaction record
2981 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2982 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2984 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2985 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2986 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2987 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2988 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2989 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2990 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2991 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2992 $balanceTrxnParams['status_id'] = $statusId;
2993 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2994 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2995 if (!empty($params['payment_processor'])) {
2996 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2998 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3002 // build line item array if its not set in $params
3003 if (empty($params['line_item']) ||
$additionalParticipantId) {
3004 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3007 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
3008 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
3010 $skipRecords = TRUE;
3011 $pendingStatus = array(
3012 array_search('Pending', $contributionStatuses),
3013 array_search('In Progress', $contributionStatuses),
3015 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
3016 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3017 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3019 elseif (!empty($params['payment_processor'])) {
3020 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3022 elseif (!empty($params['payment_instrument_id'])) {
3023 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3026 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3027 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3028 $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);
3031 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3032 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3033 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3036 //build financial transaction params
3037 $trxnParams = array(
3038 'contribution_id' => $params['contribution']->id
,
3039 'to_financial_account_id' => $params['to_financial_account_id'],
3040 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3041 'total_amount' => $totalAmount,
3042 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3043 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3044 'currency' => $params['contribution']->currency
,
3045 'trxn_id' => $params['contribution']->trxn_id
,
3046 'status_id' => $statusId,
3047 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
3048 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3051 if (!empty($params['payment_processor'])) {
3052 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3055 if (isset($fromFinancialAccountId)) {
3056 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3059 // consider external values passed for recording transaction entry
3060 if (!empty($financialTrxnValues)) {
3061 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3064 $params['trxnParams'] = $trxnParams;
3066 if (!empty($params['prevContribution'])) {
3067 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3068 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3069 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3070 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3071 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3073 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3074 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3075 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3077 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3078 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3081 //if financial type is changed
3082 if (!empty($params['financial_type_id']) &&
3083 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3085 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3086 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3087 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3088 if ($oldFinancialAccount != $newFinancialAccount) {
3089 $params['total_amount'] = 0;
3090 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3091 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3092 $params['prevContribution']->financial_type_id
, $relationTypeId);
3095 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3096 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3097 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3100 self
::updateFinancialAccounts($params, 'changeFinancialType');
3101 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3102 $params['financial_account_id'] = $newFinancialAccount;
3103 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3104 self
::updateFinancialAccounts($params);
3105 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3109 //Update contribution status
3110 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3111 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3112 if (!empty($params['contribution_status_id']) &&
3113 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3115 //Update Financial Records
3116 self
::updateFinancialAccounts($params, 'changedStatus');
3119 // change Payment Instrument for a Completed contribution
3120 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3121 // instrument is null and now new payment instrument is added along with the payment
3122 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3123 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3124 if (array_key_exists('payment_instrument_id', $params)) {
3125 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3126 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3127 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3129 //check if status is changed from Pending to Completed
3130 // do not update payment instrument changes for Pending to Completed
3131 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3132 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3134 // for all other statuses create new financial records
3135 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3136 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3137 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3140 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3141 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3142 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3144 // for any other payment instrument changes create new financial records
3145 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3146 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3147 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3149 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3150 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3152 // another special case when check number is changed, create new financial records
3153 // create financial trxn with negative amount
3154 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3155 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3156 // create financial trxn with positive amount
3157 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3158 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3159 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3163 //if Change contribution amount
3164 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3165 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3166 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3167 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3168 if (isset($totalAmount) &&
3169 $totalAmount != $params['prevContribution']->total_amount
3171 //Update Financial Records
3172 $params['trxnParams']['from_financial_account_id'] = NULL;
3173 self
::updateFinancialAccounts($params, 'changedAmount');
3178 // records finanical trxn and entity financial trxn
3179 // also make it available as return value
3180 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3181 $params['entity_id'] = $financialTxn->id
;
3184 // record line items and financial items
3185 if (empty($params['skipLineItem'])) {
3186 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3189 // create batch entry if batch_id is passed and
3190 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3191 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3192 $entityParams = array(
3193 'batch_id' => $params['batch_id'],
3194 'entity_table' => 'civicrm_financial_trxn',
3195 'entity_id' => $financialTxn->id
,
3197 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3200 // when a fee is charged
3201 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3202 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3205 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3206 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3208 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3209 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3210 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3212 unset($params['line_item']);
3218 * Update all financial accounts entry.
3220 * @param array $params
3221 * Contribution object, line item array and params for trxn.
3223 * @param string $context
3226 * @param null $skipTrxn
3229 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3230 $itemAmount = $trxnID = NULL;
3231 //get all the statuses
3232 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3233 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3234 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3235 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3236 && $context == 'changePaymentInstrument'
3240 if (($params['prevContribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus))
3241 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3242 && $context == 'changedStatus'
3246 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3247 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3249 if ($context == 'changedStatus') {
3250 //get all the statuses
3251 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3253 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3254 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3255 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3257 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3258 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3259 $creditNoteId = self
::createCreditNoteId();
3260 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3263 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3264 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3266 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3267 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3268 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3270 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3271 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3272 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3273 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3274 $creditNoteId = self
::createCreditNoteId();
3275 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3279 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3282 $itemAmount = $params['trxnParams']['total_amount'];
3284 elseif ($context == 'changePaymentInstrument') {
3285 if ($params['trxnParams']['total_amount'] < 0) {
3286 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3287 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3288 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3289 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3293 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3294 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3297 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3298 $params['entity_id'] = $trxn->id
;
3300 if ($context == 'changedStatus') {
3301 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3302 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3303 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3305 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3306 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3308 $entityParams = array(
3309 'entity_table' => 'civicrm_financial_item',
3310 'financial_trxn_id' => $trxn->id
,
3312 if (empty($params['line_item'])) {
3314 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3315 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3316 // & this can be removed
3319 foreach ($params['line_item'] as $fieldId => $fields) {
3320 foreach ($fields as $fieldValueId => $fieldValues) {
3322 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3323 2 => array($fieldValues['id'], 'Integer'),
3325 CRM_Core_DAO
::executeQuery($query, $fparams);
3327 1 => array($fieldValues['id'], 'Integer'),
3329 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3330 while ($financialItem->fetch()) {
3331 $entityParams['entity_id'] = $financialItem->id
;
3332 $entityParams['amount'] = $financialItem->amount
;
3333 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3340 if ($context != 'changePaymentInstrument') {
3341 $itemParams['entity_table'] = 'civicrm_line_item';
3342 $trxnIds['id'] = $params['entity_id'];
3343 foreach ($params['line_item'] as $fieldId => $fields) {
3344 foreach ($fields as $fieldValueId => $fieldValues) {
3345 $prevParams['entity_id'] = $fieldValues['id'];
3346 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3348 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3349 if ($params['contribution']->receive_date
) {
3350 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3353 $financialAccount = $prevfinancialItem->financial_account_id
;
3354 if (!empty($params['financial_account_id'])) {
3355 $financialAccount = $params['financial_account_id'];
3358 $currency = $params['prevContribution']->currency
;
3359 if ($params['contribution']->currency
) {
3360 $currency = $params['contribution']->currency
;
3363 if (!empty($params['is_quick_config'])) {
3364 $amount = $itemAmount;
3366 $amount = $params['total_amount'];
3370 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3371 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3375 $amount = $diff * $fieldValues['line_total'];
3378 $itemParams = array(
3379 'transaction_date' => $receiveDate,
3380 'contact_id' => $params['prevContribution']->contact_id
,
3381 'currency' => $currency,
3382 'amount' => $amount,
3383 'description' => $prevfinancialItem->description
,
3384 'status_id' => $prevfinancialItem->status_id
,
3385 'financial_account_id' => $financialAccount,
3386 'entity_table' => 'civicrm_line_item',
3387 'entity_id' => $fieldValues['id'],
3389 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3391 if ($fieldValues['tax_amount']) {
3392 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3393 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3394 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3395 $itemParams['description'] = $taxTerm;
3396 if ($fieldValues['financial_type_id']) {
3397 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3399 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3404 if ($context == 'changeFinancialType') {
3405 $params['skipLineItem'] = FALSE;
3406 foreach ($params['line_item'] as &$lineItems) {
3407 foreach ($lineItems as &$line) {
3408 $line['financial_type_id'] = $params['financial_type_id'];
3415 * Check status validation on update of a contribution.
3417 * @param array $values
3418 * Previous form values before submit.
3420 * @param array $fields
3421 * The input form values.
3423 * @param array $errors
3428 public static function checkStatusValidation($values, &$fields, &$errors) {
3429 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3430 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3431 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3435 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3436 $checkStatus = array(
3437 'Cancelled' => array('Completed', 'Refunded'),
3438 'Completed' => array('Cancelled', 'Refunded'),
3439 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3440 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3441 'Refunded' => array('Cancelled', 'Completed'),
3442 'Partially paid' => array('Completed'),
3445 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3446 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3447 1 => $contributionStatuses[$values['contribution_status_id']],
3448 2 => $contributionStatuses[$fields['contribution_status_id']],
3454 * Delete contribution of contact.
3458 * @param int $contactId
3462 public static function deleteContactContribution($contactId) {
3463 $contribution = new CRM_Contribute_DAO_Contribution();
3464 $contribution->contact_id
= $contactId;
3465 $contribution->find();
3466 while ($contribution->fetch()) {
3467 self
::deleteContribution($contribution->id
);
3472 * Get options for a given contribution field.
3473 * @see CRM_Core_DAO::buildOptions
3475 * @param string $fieldName
3476 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3477 * @param array $props whatever is known about this dao object.
3479 * @return array|bool
3481 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3482 $className = __CLASS__
;
3484 switch ($fieldName) {
3485 // This field is not part of this object but the api supports it
3486 case 'payment_processor':
3487 $className = 'CRM_Contribute_BAO_ContributionPage';
3488 // Filter results by contribution page
3489 if (!empty($props['contribution_page_id'])) {
3490 $page = civicrm_api('contribution_page', 'getsingle', array(
3492 'id' => ($props['contribution_page_id']),
3494 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3495 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3499 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3500 case 'honor_type_id':
3501 $className = 'CRM_Contribute_BAO_ContributionSoft';
3502 $fieldName = 'soft_credit_type_id';
3503 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3506 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3510 * Validate financial type.
3514 * @param int $financialTypeId
3515 * Financial Type id.
3517 * @param string $relationName
3519 * @return array|bool
3521 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3522 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3523 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3525 if (!$financialAccount) {
3526 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3533 * Function to record additional payment for partial and refund contributions.
3535 * @param int $contributionId
3536 * is the invoice contribution id (got created after processing participant payment).
3537 * @param array $trxnsData
3538 * to take user provided input of transaction details.
3539 * @param string $paymentType
3540 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3541 * @param int $participantId
3543 * @return null|object
3545 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3546 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3547 $getInfoOf['id'] = $contributionId;
3548 $defaults = array();
3549 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3551 if ($paymentType == 'owed') {
3552 // build params for recording financial trxn entry
3553 $params['contribution'] = $contributionDAO;
3554 $params = array_merge($defaults, $params);
3555 $params['skipLineItem'] = TRUE;
3556 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3557 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3558 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3559 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3562 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3563 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3564 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3566 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3567 if (!empty($trxnId)) {
3568 $trxnId = $trxnId['trxn_id'];
3570 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3571 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3574 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3575 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3576 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3580 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3581 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3582 FROM civicrm_financial_trxn ft
3583 LEFT JOIN civicrm_entity_financial_trxn eft
3584 ON (ft.id = eft.financial_trxn_id)
3585 WHERE eft.entity_table = 'civicrm_contribution'
3586 AND eft.entity_id = {$contributionId}
3587 AND ft.to_financial_account_id != {$toFinancialAccount}
3588 AND ft.status_id = {$statusId}
3590 $query = CRM_Core_DAO
::executeQuery($sql);
3592 $sumOfPayments = $query->sum_of_payments
;
3595 if ($contributionDAO->total_amount
== $sumOfPayments) {
3596 // update contribution status and
3597 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3598 $contributionDAO->contribution_status_id
= $statusId;
3599 $contributionDAO->cancel_date
= 'null';
3600 $contributionDAO->cancel_reason
= NULL;
3601 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3602 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3603 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3604 $contributionDAO->save();
3606 //Change status of financial record too
3607 $financialTrxn->status_id
= $statusId;
3608 $financialTrxn->save();
3610 // note : not using the self::add method,
3611 // the reason because it performs 'status change' related code execution for financial records
3612 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3613 // are coded below i.e. just updating financial_item status to 'Paid'
3615 if ($participantId) {
3616 // update participant status
3617 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3618 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3619 foreach ($ids as $val) {
3620 $participantUpdate['id'] = $val;
3621 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3622 CRM_Event_BAO_Participant
::add($participantUpdate);
3626 // update financial item statuses
3627 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3628 $paidStatus = array_search('Paid', $financialItemStatus);
3630 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3631 $sqlFinancialItemUpdate = "
3632 UPDATE civicrm_financial_item fi
3633 LEFT JOIN civicrm_entity_financial_trxn eft
3634 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3635 SET status_id = {$paidStatus}
3636 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3638 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3641 elseif ($paymentType == 'refund') {
3642 // build params for recording financial trxn entry
3643 $params['contribution'] = $contributionDAO;
3644 $params = array_merge($defaults, $params);
3645 $params['skipLineItem'] = TRUE;
3646 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3647 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3649 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3650 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3651 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3653 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3655 // note : not using the self::add method,
3656 // the reason because it performs 'status change' related code execution for financial records
3657 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3658 // are coded below i.e. just updating financial_item status to 'Paid'
3659 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3661 // add financial item entry
3662 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3663 $getLine['entity_id'] = $contributionDAO->id
;
3664 $getLine['entity_table'] = 'civicrm_contribution';
3665 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3666 if (!empty($lineItemId->id
)) {
3667 $addFinancialEntry = array(
3668 'transaction_date' => $financialTrxn->trxn_date
,
3669 'contact_id' => $contributionDAO->contact_id
,
3670 'amount' => $financialTrxn->total_amount
,
3671 'status_id' => array_search('Paid', $financialItemStatus),
3672 'entity_id' => $lineItemId->id
,
3673 'entity_table' => 'civicrm_line_item',
3675 $trxnIds['id'] = $financialTrxn->id
;
3676 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3678 if ($participantId) {
3679 // update participant status
3680 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3681 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3682 foreach ($ids as $val) {
3683 $participantUpdate['id'] = $val;
3684 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3685 CRM_Event_BAO_Participant
::add($participantUpdate);
3690 // activity creation
3691 if (!empty($financialTrxn)) {
3692 if ($participantId) {
3693 $inputParams['id'] = $participantId;
3696 $component = 'event';
3697 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3698 $entityObj = $entityObj[$participantId];
3700 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3702 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3704 return $financialTrxn;
3710 * @param $activityType
3712 * @param int $contributionId
3714 * @throws CRM_Core_Exception
3716 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3717 if ($component == 'event') {
3718 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3719 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3720 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3721 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3722 $targetCid = $entityObj->contact_id
;
3723 // source record id would be the contribution id
3724 $srcRecId = $contributionId;
3728 $activityParams = array(
3729 'source_contact_id' => $targetCid,
3730 'source_record_id' => $srcRecId,
3731 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3735 'subject' => $subject,
3736 'activity_date_time' => $date,
3737 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3741 'skipRecentView' => TRUE,
3744 // create activity with target contacts
3745 $session = CRM_Core_Session
::singleton();
3746 $id = $session->get('userID');
3748 $activityParams['source_contact_id'] = $id;
3749 $activityParams['target_contact_id'][] = $targetCid;
3751 CRM_Activity_BAO_Activity
::create($activityParams);
3755 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3759 * @param bool $getTrxnInfo
3760 * @param bool $usingLineTotal
3764 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3765 if ($component == 'event') {
3766 $entity = 'participant';
3767 $entityTable = 'civicrm_participant';
3768 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3770 if (!$contributionId) {
3771 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3772 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3773 $id = $primaryParticipantId;
3775 if (!$contributionId) {
3780 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3781 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3787 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3788 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3791 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3792 // for additional participants
3793 if ($entityTable == 'civicrm_participant') {
3794 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3796 foreach ($ids as $val) {
3797 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3801 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3805 $baseTrxnId = $total['trxn_id'];
3806 $total = $total['total_amount'];
3809 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3810 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3812 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3813 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3814 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3816 if ($paymentBalance == 0 && $contributionIsPayLater) {
3817 $paymentBalance = $total;
3820 $info['total'] = $total;
3821 $info['paid'] = $total - $paymentBalance;
3822 $info['balance'] = $paymentBalance;
3824 $info['component'] = $component;
3825 $info['payLater'] = $contributionIsPayLater;
3827 if ($getTrxnInfo && $baseTrxnId) {
3828 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3830 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3831 FROM civicrm_contribution con
3832 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3833 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3834 WHERE con.id = {$contributionId}
3837 // conditioned WHERE clause
3839 // if balance trxn exists don't include details of it in transaction info
3840 $sql .= " AND ft.id != {$baseTrxnId} ";
3842 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3844 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3845 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3846 while ($resultDAO->fetch()) {
3847 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3848 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3850 'total_amount' => $resultDAO->total_amount
,
3851 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3852 'payment_instrument' => $paidByLabel,
3853 'receive_date' => $resultDAO->trxn_date
,
3854 'trxn_id' => $resultDAO->trxn_id
,
3855 'status' => $statuses[$resultDAO->status_id
],
3857 if ($paidByName == 'Check') {
3858 $val['check_number'] = $resultDAO->check_number
;
3862 $info['transaction'] = $rows;
3868 * Get financial account id has 'Sales Tax Account is'
3869 * account relationship with financial type
3871 * @param int $financialTypeId
3873 * @return FinancialAccountId
3875 public static function getFinancialAccountId($financialTypeId) {
3876 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3877 $searchParams = array(
3878 'entity_table' => 'civicrm_financial_type',
3879 'entity_id' => $financialTypeId,
3880 'account_relationship' => $accountRel,
3883 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3885 return CRM_Utils_Array
::value('financial_account_id', $result);
3891 * @param array $params
3892 * @param bool $isLineItem
3896 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3897 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3899 // Update contribution.
3900 if (!empty($params['id'])) {
3901 $id = $params['id'];
3902 $values = $ids = array();
3903 $contrbutionParams = array('id' => $id);
3904 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3906 // To assign pervious finantial type on update of contribution
3907 if (!isset($params['financial_type_id'])) {
3908 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3910 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3911 // Assisn tax Amount on update of contrbution
3912 if (!empty($prevContributionValue->tax_amount
)) {
3913 $params['tax_amount'] = 'null';
3914 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3915 foreach ($params['line_item'] as $setID => $priceField) {
3916 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3917 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3924 // New Contrbution and update of contribution with tax rate financial type
3925 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3926 empty($params['skipLineItem']) && !$isLineItem
3928 $taxRateParams = $taxRates[$params['financial_type_id']];
3929 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3930 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3932 // Get Line Item on update of contribution
3933 if (isset($params['id'])) {
3934 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3937 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3939 foreach ($params['line_item'] as $setID => $priceField) {
3940 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3941 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3944 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3946 elseif (isset($params['api.line_item.create'])) {
3947 // Update total amount of contribution using lineItem
3948 $taxAmountArray = array();
3949 foreach ($params['api.line_item.create'] as $key => $value) {
3950 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3951 $taxRate = $taxRates[$value['financial_type_id']];
3952 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3953 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3956 $params['tax_amount'] = array_sum($taxAmountArray);
3957 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3960 // update line item of contrbution
3961 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3962 $taxRate = $taxRates[$params['financial_type_id']];
3963 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3964 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3971 * Check financial type validation on update of a contribution.
3973 * @param Integer $financialTypeId
3974 * Value of latest Financial Type.
3976 * @param Integer $contributionId
3979 * @param array $errors
3984 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3985 if (!empty($financialTypeId)) {
3986 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3987 if ($oldFinancialTypeId == $financialTypeId) {
3991 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3993 '1' => array($contributionId, 'Integer'),
3995 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3996 if ($result->N
> 1) {
3997 $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.');
4002 * Update related pledge payment payments.
4004 * This function has been refactored out of the back office contribution form and may
4005 * still overlap with other functions.
4007 * @param string $action
4008 * @param int $pledgePaymentID
4009 * @param int $contributionID
4010 * @param bool $adjustTotalAmount
4011 * @param float $total_amount
4012 * @param float $original_total_amount
4013 * @param int $contribution_status_id
4014 * @param int $original_contribution_status_id
4016 public static function updateRelatedPledge(
4022 $original_total_amount,
4023 $contribution_status_id,
4024 $original_contribution_status_id
4026 if (!$pledgePaymentID ||
$action & CRM_Core_Action
::ADD
&& !$contributionID) {
4030 if ($pledgePaymentID) {
4031 //store contribution id in payment record.
4032 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4035 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4041 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4047 $updatePledgePaymentStatus = FALSE;
4049 // If either the status or the amount has changed we update the pledge status.
4050 if ($action & CRM_Core_Action
::ADD
) {
4051 $updatePledgePaymentStatus = TRUE;
4053 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4054 ($original_total_amount != $total_amount))
4056 $updatePledgePaymentStatus = TRUE;
4059 if ($updatePledgePaymentStatus) {
4060 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4061 array($pledgePaymentID),
4062 $contribution_status_id,
4071 * Compute the stats values
4073 * @param $stat either 'mode' or 'median'
4075 * @param $alias of civicrm_contribution
4077 public static function computeStats($stat, $sql, $alias = NULL) {
4078 $mode = $median = array();
4081 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4082 while ($modeDAO->fetch()) {
4083 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4084 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4093 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4094 foreach ($currencies as $currency => $val) {
4096 $where = "AND {$alias}.currency = '{$currency}'";
4097 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4101 $medianRow = floor($rowCount / 2);
4102 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4108 $medianValue = "SELECT {$alias}.total_amount as median
4110 ORDER BY median LIMIT {$medianRow},{$offset}";
4111 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4112 while ($medianValDAO->fetch()) {
4114 $midValue = $midValue +
$medianValDAO->median
;
4117 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4121 $midValue = $midValue / 2;
4122 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4133 * Complete an order.
4135 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4137 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4139 * Moving it out of the BaseIPN class is just the first step.
4141 * @param array $input
4143 * @param array $objects
4144 * @param CRM_Core_Transaction $transaction
4146 * @param CRM_Contribute_BAO_Contribution $contribution
4147 * @param bool $isRecurring
4148 * Duplication of param needs review. Only used by AuthorizeNetIPN
4149 * @param int $isFirstOrLastRecurringPayment
4150 * Deprecated param only used by AuthorizeNetIPN.
4152 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4153 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4154 // The previous details are used when calculating line items so keep it before any code that 'does something'
4155 if (!empty($contribution->id
)) {
4156 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4157 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4159 $inputContributionWhiteList = array(
4164 'payment_instrument_id',
4170 $contributionParams = array_merge(array(
4171 'contribution_status_id' => 'Completed',
4172 'financial_type_id' => $contribution->financial_type_id
,
4173 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4176 $participant = CRM_Utils_Array
::value('participant', $objects);
4177 $memberships = CRM_Utils_Array
::value('membership', $objects);
4178 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4179 if (!empty($recurContrib->id
)) {
4180 $contributionParams['contribution_recur_id'] = $recurContrib->id
;
4182 self
::repeatTransaction($contribution, $input, $contributionParams);
4184 if (is_numeric($memberships)) {
4185 $memberships = array($objects['membership']);
4188 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4191 if (isset($input['is_email_receipt'])) {
4192 $values['is_email_receipt'] = $input['is_email_receipt'];
4195 if ($input['component'] == 'contribute') {
4196 if ($contribution->contribution_page_id
) {
4197 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4198 $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
4200 elseif ($recurContrib && $recurContrib->id
) {
4201 $contributionParams['contribution_page_id'] = NULL;
4202 $values['amount'] = $recurContrib->amount
;
4203 $values['financial_type_id'] = $objects['contributionType']->id
;
4204 $values['title'] = $source = ts('Offline Recurring Contribution');
4205 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
4206 $values['receipt_from_name'] = $domainValues[0];
4207 $values['receipt_from_email'] = $domainValues[1];
4210 if (empty($contributionParams['receive_date']) && $changeDate) {
4211 $contributionParams['receive_date'] = $changeDate;
4214 if ($recurContrib && $recurContrib->id
&& !isset($input['is_email_receipt'])) {
4215 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4216 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4217 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4220 if (!empty($values['is_email_receipt'])) {
4221 $contributionParams['receipt_date'] = $changeDate;
4224 if (!empty($memberships)) {
4225 foreach ($memberships as $membershipTypeIdKey => $membership) {
4227 $membershipParams = array(
4228 'id' => $membership->id
,
4229 'contact_id' => $membership->contact_id
,
4230 'is_test' => $membership->is_test
,
4231 'membership_type_id' => $membership->membership_type_id
,
4234 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4235 $membershipParams['membership_type_id'],
4236 $membershipParams['is_test'],
4237 $membershipParams['id']
4240 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4241 // this picks up membership type changes during renewals
4243 SELECT membership_type_id
4244 FROM civicrm_membership_log
4245 WHERE membership_id={$membershipParams['id']}
4248 $dao = CRM_Core_DAO
::executeQuery($sql);
4249 if ($dao->fetch()) {
4250 if (!empty($dao->membership_type_id
)) {
4251 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4256 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4257 $membershipParams['membership_type_id'],
4258 $primaryContributionID
4260 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4261 if ($currentMembership) {
4263 * Fixed FOR CRM-4433
4264 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4265 * when Contribution mode is notify and membership is for renewal )
4267 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4269 // @todo - we should pass membership_type_id instead of null here but not
4270 // adding as not sure of testing
4271 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4272 $changeDate, NULL, $membershipParams['num_terms']
4275 $dates['join_date'] = $currentMembership['join_date'];
4278 //get the status for membership.
4279 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4281 $dates['join_date'],
4284 $membershipParams['membership_type_id'],
4288 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4289 //we might be renewing membership,
4290 //so make status override false.
4291 $membershipParams['is_override'] = FALSE;
4292 civicrm_api3('Membership', 'create', $membershipParams);
4294 //update related Memberships.
4295 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $membershipParams);
4301 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4302 $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id
));
4303 $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
4304 if ($eventDetail['is_email_confirm']) {
4305 // @todo this should be set by the function that sends the mail after sending.
4306 $contributionParams['receipt_date'] = $changeDate;
4308 $participantParams['id'] = $participant->id
;
4309 $participantParams['status_id'] = 'Registered';
4310 civicrm_api3('Participant', 'create', $participantParams);
4314 $contributionParams['id'] = $contribution->id
;
4316 civicrm_api3('Contribution', 'create', $contributionParams);
4318 // Add new soft credit against current $contribution.
4319 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4320 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4323 $paymentProcessorId = '';
4324 if (isset($objects['paymentProcessor'])) {
4325 if (is_array($objects['paymentProcessor'])) {
4326 $paymentProcessorId = $objects['paymentProcessor']['id'];
4329 $paymentProcessorId = $objects['paymentProcessor']->id
;
4333 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4334 'labelColumn' => 'name',
4337 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4338 $input['payment_processor'] = $paymentProcessorId;
4340 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4341 $input['total_amount'] = $input['amount'];
4342 $input['contribution'] = $contribution;
4343 $input['financial_type_id'] = $contribution->financial_type_id
;
4345 if (!empty($contribution->_relatedObjects
['participant'])) {
4346 $input['contribution_mode'] = 'participant';
4347 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4348 $input['skipLineItem'] = 1;
4350 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4351 $input['skipLineItem'] = TRUE;
4352 $input['contribution_mode'] = 'membership';
4354 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4355 // and subsequent payments. In this case the line items are created at
4356 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4357 // and since the contribution is saved prior to this line there is always a contribution-id,
4358 // however there is never a prevContribution (which appears to mean original contribution not previous
4359 // contribution - or preUpdateContributionObject most accurately)
4360 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4361 // to mean "are we updating an exisitng pending contribution"
4362 //I was able to make the unit test complete as fataling here doesn't prevent
4363 // the contribution being created - but activities would not be created or emails sent
4365 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4367 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4368 $transaction->commit();
4370 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution);
4372 // create an activity record
4373 if ($input['component'] == 'contribute') {
4375 $targetContactID = NULL;
4376 if (!empty($ids['related_contact'])) {
4377 $targetContactID = $contribution->contact_id
;
4378 $contribution->contact_id
= $ids['related_contact'];
4380 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4384 CRM_Activity_BAO_Activity
::addActivity($participant);
4387 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4388 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4389 if (!array_key_exists('is_email_receipt', $values) ||
4390 $values['is_email_receipt'] == 1
4392 self
::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
4393 CRM_Core_Error
::debug_log_message("Receipt sent");
4396 CRM_Core_Error
::debug_log_message("Success: Database updated");
4398 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4399 $isFirstOrLastRecurringPayment);
4404 * Send receipt from contribution.
4406 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4408 * Note that the compose message part has been moved to contribution
4409 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4411 * @param array $input
4412 * Incoming data from Payment processor.
4414 * Related object IDs.
4415 * @param CRM_Contribute_BAO_Contribution $contribution
4416 * @param array $values
4417 * Values related to objects that have already been loaded.
4418 * @param bool $recur
4419 * Is it part of a recurring contribution.
4420 * @param bool $returnMessageText
4421 * Should text be returned instead of sent. This.
4422 * is because the function is also used to generate pdfs
4426 public static function sendMail(&$input, &$ids, $contribution, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4427 $input['is_recur'] = $recur;
4428 // set receipt from e-mail and name in value
4429 if (!$returnMessageText) {
4430 $session = CRM_Core_Session
::singleton();
4431 $userID = $session->get('userID');
4432 if (!empty($userID)) {
4433 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4434 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4435 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4438 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4442 * Generate credit note id with next avaible number
4447 public static function createCreditNoteId() {
4448 $prefixValue = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
4450 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4451 $creditNoteId = NULL;
4455 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4456 $result = civicrm_api3('Contribution', 'getcount', array(
4458 'creditnote_id' => $creditNoteId,
4460 } while ($result > 0);
4462 return $creditNoteId;