3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
33 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
36 * Static field for all the contribution information that we can potentially import
40 static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 static $_exportableFields = NULL;
50 * Field for all the objects related to this contribution
51 * @var array of objects (e.g membership object, participant object)
53 public $_relatedObjects = array();
56 * Field for the component - either 'event' (participant) or 'contribute'
57 * (any item related to a contribution page e.g. membership, pledge, contribution)
58 * This is used for composing messages because they have dependency on the
59 * contribution_page or event page - although over time we may eliminate that
61 * @var string component or event
63 public $_component = NULL;
66 * Possibly obsolete variable.
68 * If you use it please explain why it is set in the create function here.
72 public $trxn_result_code;
77 * @return \CRM_Contribute_DAO_Contribution
81 public function __construct() {
82 parent
::__construct();
86 * Takes an associative array and creates a contribution object.
88 * the function extract all the params it needs to initialize the create a
89 * contribution object. the params array could contain additional unused name/value
92 * @param array $params
93 * (reference ) an assoc array of name/value pairs.
95 * The array that holds all the db ids.
97 * @return CRM_Contribute_BAO_Contribution|void
99 public static function add(&$params, $ids = array()) {
100 if (empty($params)) {
103 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
104 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
105 $duplicates = array();
106 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
107 $error = CRM_Core_Error
::singleton();
108 $d = implode(', ', $duplicates);
109 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
112 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
117 // first clean up all the money fields
118 $moneyFields = array(
122 'non_deductible_amount',
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
127 unset($moneyFields[0]);
130 foreach ($moneyFields as $field) {
131 if (isset($params[$field])) {
132 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
136 //set defaults in create mode
137 if (!$contributionID) {
138 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
139 self
::calculateMissingAmountParams($params);
142 if (!empty($params['payment_instrument_id'])) {
143 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
144 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
145 $params['check_number'] = 'null';
149 $setPrevContribution = TRUE;
150 // CRM-13964 partial payment
151 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
152 $partialAmtTotal = $params['partial_payment_total'];
153 $partialAmtPay = $params['partial_amount_pay'];
154 $params['total_amount'] = $partialAmtTotal;
155 if ($partialAmtPay < $partialAmtTotal) {
156 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
157 $params['is_pay_later'] = 0;
158 $setPrevContribution = FALSE;
162 if ($contributionID) {
163 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
166 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
168 $contribution = new CRM_Contribute_BAO_Contribution();
169 $contribution->copyValues($params);
171 $contribution->id
= $contributionID;
173 if (empty($contribution->id
)) {
174 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
175 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
176 $config = CRM_Core_Config
::singleton();
177 $contribution->currency
= $config->defaultCurrency
;
181 if ($contributionID && $setPrevContribution) {
182 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
185 $result = $contribution->save();
187 // Add financial_trxn details as part of fix for CRM-4724
188 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
189 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
191 //add Account details
192 $params['contribution'] = $contribution;
193 self
::recordFinancialAccounts($params);
195 // reset the group contact cache for this group
196 CRM_Contact_BAO_GroupContactCache
::remove();
198 if ($contributionID) {
199 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
202 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
209 * Get defaults for new entity.
212 public static function getDefaults() {
214 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
215 FALSE, FALSE, FALSE, 'AND is_default = 1')
217 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
222 * Given the list of params in the params array, fetch the object
223 * and store the values in the values array
225 * @param array $params
226 * Input parameters to find object.
227 * @param array $values
228 * Output values of the object.
230 * The array that holds all the db ids.
232 * @return CRM_Contribute_BAO_Contribution|null
233 * The found object or null
235 public static function getValues($params, &$values, &$ids) {
236 if (empty($params)) {
239 $contribution = new CRM_Contribute_BAO_Contribution();
241 $contribution->copyValues($params);
243 if ($contribution->find(TRUE)) {
244 $ids['contribution'] = $contribution->id
;
246 CRM_Core_DAO
::storeValues($contribution, $values);
248 return $contribution;
250 $null = NULL; // return by reference
255 * Calculate net_amount & fee_amount if they are not set.
257 * Net amount should be total - fee.
258 * This should only be called for new contributions.
260 * @param array $params
261 * Params for a new contribution before they are saved.
263 public static function calculateMissingAmountParams(&$params) {
264 if (!isset($params['fee_amount'])) {
265 if (isset($params['total_amount']) && isset($params['net_amount'])) {
266 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
269 $params['fee_amount'] = 0;
272 if (!isset($params['net_amount'])) {
273 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
279 * @param $billingLocationTypeID
283 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
284 $hasBillingField = FALSE;
285 $billingFields = array(
293 //build address array
294 $addressParams = array();
295 $addressParams['location_type_id'] = $billingLocationTypeID;
296 $addressParams['is_billing'] = 1;
298 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
299 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
300 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
301 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
303 foreach ($billingFields as $value) {
304 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
305 if (!empty($addressParams[$value])) {
306 $hasBillingField = TRUE;
309 return array($hasBillingField, $addressParams);
313 * Get address params ready to be passed to the payment processor.
315 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
316 * To create an address we need state_province_id.
318 * @param array $params
319 * @param int $billingLocationTypeID
323 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
324 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
325 foreach ($addressParams as $name => $field) {
326 if (substr($name, 0, 8) == 'billing_') {
327 $addressParams[substr($name, 9)] = $addressParams[$field];
330 return array($hasBillingField, $addressParams);
334 * Get the number of terms for this contribution for a given membership type
335 * based on querying the line item table and relevant price field values
336 * Note that any one contribution should only be able to have one line item relating to a particular membership
339 * @param int $membershipTypeID
341 * @param int $contributionID
345 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
346 $numTerms = CRM_Core_DAO
::singleValueQuery("
347 SELECT membership_num_terms FROM civicrm_line_item li
348 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
349 WHERE contribution_id = %1 AND membership_type_id = %2",
350 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
352 // default of 1 is precautionary
353 return empty($numTerms) ?
1 : $numTerms;
357 * Takes an associative array and creates a contribution object.
359 * @param array $params
360 * (reference ) an assoc array of name/value pairs.
362 * The array that holds all the db ids.
364 * @return CRM_Contribute_BAO_Contribution
366 public static function create(&$params, $ids = array()) {
367 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
368 foreach ($dateFields as $df) {
369 if (isset($params[$df])) {
370 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
374 $transaction = new CRM_Core_Transaction();
376 $contribution = self
::add($params, $ids);
378 if (is_a($contribution, 'CRM_Core_Error')) {
379 $transaction->rollback();
380 return $contribution;
383 $params['contribution_id'] = $contribution->id
;
385 if (!empty($params['custom']) &&
386 is_array($params['custom'])
388 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
391 $session = CRM_Core_Session
::singleton();
393 if (!empty($params['note'])) {
395 'entity_table' => 'civicrm_contribution',
396 'note' => $params['note'],
397 'entity_id' => $contribution->id
,
398 'contact_id' => $session->get('userID'),
399 'modified_date' => date('Ymd'),
401 if (!$noteParams['contact_id']) {
402 $noteParams['contact_id'] = $params['contact_id'];
404 CRM_Core_BAO_Note
::add($noteParams);
407 // make entry in batch entity batch table
408 if (!empty($params['batch_id'])) {
409 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
410 $titleFields = array(
416 $retrieveRequired = 0;
417 foreach ($titleFields as $titleField) {
418 if (!isset($contribution->$titleField)) {
419 $retrieveRequired = 1;
423 if ($retrieveRequired == 1) {
424 $contribution->find(TRUE);
428 // Handle soft credit and / or link to personal campaign page
429 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
431 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
433 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
434 $softParams = array();
435 $softParams['id'] = $pcpId ?
$pcpId : NULL;
436 $softParams['contribution_id'] = $contribution->id
;
437 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
438 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
439 $pcp['pcp_made_through_id'], 'contact_id'
441 $softParams['currency'] = $contribution->currency
;
442 $softParams['amount'] = $contribution->total_amount
;
443 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
444 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
445 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
446 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
447 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($softParams);
448 //Send notification to owner for PCP
449 if ($contributionSoft->pcp_id
&& empty($pcpId)) {
450 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
453 //Delete PCP against this contribution and create new on submitted PCP information
454 elseif (array_key_exists('pcp', $params) && $pcpId) {
455 $deleteParams = array('id' => $pcpId);
456 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
458 if (isset($params['soft_credit'])) {
459 $softParams = $params['soft_credit'];
460 foreach ($softParams as $softParam) {
461 if (!empty($softIDs)) {
462 $key = key($softIDs);
463 $softParam['id'] = $softIDs[$key];
464 unset($softIDs[$key]);
466 $softParam['contribution_id'] = $contribution->id
;
467 $softParam['currency'] = $contribution->currency
;
468 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
469 if (empty($softParam['amount'])) {
470 $softParam['amount'] = $contribution->total_amount
;
472 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
475 if (!empty($softIDs)) {
476 foreach ($softIDs as $softID) {
477 if (!in_array($softID, $params['soft_credit_ids'])) {
478 $deleteParams = array('id' => $softID);
479 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
485 $transaction->commit();
487 // check if activity record exist for this contribution, if
489 $activity = new CRM_Activity_DAO_Activity();
490 $activity->source_record_id
= $contribution->id
;
491 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
495 if (!$activity->find(TRUE)) {
496 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
499 // CRM-13237 : if activity record found, update it with campaign id of contribution
500 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
503 // do not add to recent items for import, CRM-4399
504 if (empty($params['skipRecentView'])) {
505 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
506 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
508 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
509 $titleFields = array(
515 $retrieveRequired = 0;
516 foreach ($titleFields as $titleField) {
517 if (!isset($contribution->$titleField)) {
518 $retrieveRequired = 1;
522 if ($retrieveRequired == 1) {
523 $contribution->find(TRUE);
525 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
526 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
528 $recentOther = array();
529 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
530 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
531 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
535 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
536 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
537 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
541 // add the recently created Contribution
542 CRM_Utils_Recent
::add($title,
546 $contribution->contact_id
,
552 return $contribution;
556 * Get the values for pseudoconstants for name->value and reverse.
558 * @param array $defaults
559 * (reference) the default values, some of which need to be resolved.
560 * @param bool $reverse
561 * True if we want to resolve the values in the reverse direction (value -> name).
563 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
564 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
565 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
566 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
567 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
571 * Convert associative array names to values and vice-versa.
573 * This function is used by both the web form layer and the api. Note that
574 * the api needs the name => value conversion, also the view layer typically
575 * requires value => name conversion
577 * @param array $defaults
578 * @param string $property
579 * @param array $lookup
580 * @param bool $reverse
584 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
585 $id = $property . '_id';
587 $src = $reverse ?
$property : $id;
588 $dst = $reverse ?
$id : $property;
590 if (!array_key_exists($src, $defaults)) {
594 $look = $reverse ?
array_flip($lookup) : $lookup;
596 if (is_array($look)) {
597 if (!array_key_exists($defaults[$src], $look)) {
601 $defaults[$dst] = $look[$defaults[$src]];
606 * Retrieve DB object based on input parameters.
608 * It also stores all the retrieved values in the default array.
610 * @param array $params
611 * (reference ) an assoc array of name/value pairs.
612 * @param array $defaults
613 * (reference ) an assoc array to hold the name / value pairs.
614 * in a hierarchical manner
616 * (reference) the array that holds all the db ids.
618 * @return CRM_Contribute_BAO_Contribution
620 public static function retrieve(&$params, &$defaults, &$ids) {
621 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
622 return $contribution;
626 * Combine all the importable fields from the lower levels object.
628 * The ordering is important, since currently we do not have a weight
629 * scheme. Adding weight is super important and should be done in the
630 * next week or so, before this can be called complete.
632 * @param string $contactType
633 * @param bool $status
636 * array of importable Fields
638 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
639 if (!self
::$_importableFields) {
640 if (!self
::$_importableFields) {
641 self
::$_importableFields = array();
645 $fields = array('' => array('title' => ts('- do not import -')));
648 $fields = array('' => array('title' => ts('- Contribution Fields -')));
651 $note = CRM_Core_DAO_Note
::import();
652 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
653 unset($tmpFields['option_value']);
654 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
655 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
657 // Using new Dedupe rule.
659 'contact_type' => $contactType,
660 'used' => 'Unsupervised',
662 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
663 $tmpContactField = array();
664 if (is_array($fieldsArray)) {
665 foreach ($fieldsArray as $value) {
666 //skip if there is no dupe rule
667 if ($value == 'none') {
670 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
675 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
676 $tmpContactField[trim($value)] = $contactFields[trim($value)];
678 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
681 $title = $tmpContactField[trim($value)]['title'];
683 $tmpContactField[trim($value)]['title'] = $title;
687 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
688 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
689 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
690 $fields = array_merge($fields, $tmpContactField);
691 $fields = array_merge($fields, $tmpFields);
692 $fields = array_merge($fields, $note);
693 $fields = array_merge($fields, $optionFields);
694 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
695 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
696 self
::$_importableFields = $fields;
698 return self
::$_importableFields;
704 public static function &exportableFields() {
705 if (!self
::$_exportableFields) {
706 if (!self
::$_exportableFields) {
707 self
::$_exportableFields = array();
710 $impFields = CRM_Contribute_DAO_Contribution
::export();
711 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
712 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
713 $typeField = CRM_Financial_DAO_FinancialType
::export();
714 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
715 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
716 $contributionStatus = array(
717 'contribution_status' => array(
718 'title' => ts('Contribution Status'),
719 'name' => 'contribution_status',
720 'data_type' => CRM_Utils_Type
::T_STRING
,
724 $contributionPage = array(
725 'contribution_page' => array(
726 'title' => ts('Contribution Page'),
727 'name' => 'contribution_page',
728 'where' => 'civicrm_contribution_page.title',
729 'data_type' => CRM_Utils_Type
::T_STRING
,
733 $contributionNote = array(
734 'contribution_note' => array(
735 'title' => ts('Contribution Note'),
736 'name' => 'contribution_note',
737 'data_type' => CRM_Utils_Type
::T_TEXT
,
741 $contributionRecurId = array(
742 'contribution_recur_id' => array(
743 'title' => ts('Recurring Contributions ID'),
744 'name' => 'contribution_recur_id',
745 'where' => 'civicrm_contribution.contribution_recur_id',
746 'data_type' => CRM_Utils_Type
::T_INT
,
750 $extraFields = array(
751 'contribution_batch' => array(
752 'title' => ts('Batch Name'),
756 $softCreditFields = array(
757 'contribution_soft_credit_name' => array(
758 'name' => 'contribution_soft_credit_name',
759 'title' => 'Soft Credit For',
760 'where' => 'civicrm_contact_d.display_name',
761 'data_type' => CRM_Utils_Type
::T_STRING
,
763 'contribution_soft_credit_amount' => array(
764 'name' => 'contribution_soft_credit_amount',
765 'title' => 'Soft Credit Amount',
766 'where' => 'civicrm_contribution_soft.amount',
767 'data_type' => CRM_Utils_Type
::T_MONEY
,
769 'contribution_soft_credit_type' => array(
770 'name' => 'contribution_soft_credit_type',
771 'title' => 'Soft Credit Type',
772 'where' => 'contribution_softcredit_type.label',
773 'data_type' => CRM_Utils_Type
::T_STRING
,
775 'contribution_soft_credit_contribution_id' => array(
776 'name' => 'contribution_soft_credit_contribution_id',
777 'title' => 'Soft Credit For Contribution ID',
778 'where' => 'civicrm_contribution_soft.contribution_id',
779 'data_type' => CRM_Utils_Type
::T_INT
,
783 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
785 'contribution_product_id' => array(
786 'title' => ts('Premium'),
787 'name' => 'contribution_product_id',
788 'where' => 'civicrm_product.id',
789 'data_type' => CRM_Utils_Type
::T_INT
,
793 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
794 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums,
795 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
798 self
::$_exportableFields = $fields;
801 return self
::$_exportableFields;
805 * @param null $status
806 * @param null $startDate
807 * @param null $endDate
811 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
815 $where[] = 'contribution_status_id = 1';
819 $where[] = 'contribution_status_id = 3';
824 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
827 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
830 $whereCond = implode(' AND ', $where);
833 SELECT sum( total_amount ) as total_amount,
834 count( civicrm_contribution.id ) as total_count,
836 FROM civicrm_contribution
837 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
839 AND ( is_test = 0 OR is_test IS NULL )
840 AND contact.is_deleted = 0
844 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
847 while ($dao->fetch()) {
848 $count +
= $dao->total_count
;
849 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
853 'amount' => implode(', ', $amount),
861 * Delete the indirect records associated with this contribution first.
866 * $results no of deleted Contribution on success, false otherwise
868 public static function deleteContribution($id) {
869 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
871 $transaction = new CRM_Core_Transaction();
874 //delete activity record
876 'source_record_id' => $id,
877 // activity type id for contribution
878 'activity_type_id' => 6,
881 CRM_Activity_BAO_Activity
::deleteActivity($params);
883 //delete billing address if exists for this contribution.
884 self
::deleteAddress($id);
886 //update pledge and pledge payment, CRM-3961
887 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
889 // remove entry from civicrm_price_set_entity, CRM-5095
890 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
891 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
893 // cleanup line items.
894 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
896 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
897 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
899 if ($participantId) {
900 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
903 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
907 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
908 $noteId = key($note);
910 CRM_Core_BAO_Note
::del($noteId, FALSE);
913 $dao = new CRM_Contribute_DAO_Contribution();
916 $results = $dao->delete();
918 $transaction->commit();
920 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
922 // delete the recently created Contribution
923 $contributionRecent = array(
925 'type' => 'Contribution',
927 CRM_Utils_Recent
::del($contributionRecent);
933 * React to a financial transaction (payment) failure.
935 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
936 * payments is important for forensic and outreach reasons.
938 * @param int $contributionID
939 * @param string $message
941 public static function failPayment($contributionID, $contactID, $message) {
942 civicrm_api3('activity', 'create', array(
943 'activity_type_id' => 'Failed Payment',
944 'details' => $message,
945 'subject' => ts('Payment failed at payment processor'),
946 'source_record_id' => $contributionID,
947 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
953 * Check if there is a contribution with the same trxn_id or invoice_id.
955 * @param array $input
956 * An assoc array of name/value pairs.
957 * @param array $duplicates
958 * (reference) store ids of duplicate contribs.
962 * true if duplicate, false otherwise
964 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
966 $id = CRM_Utils_Array
::value('id', $input);
968 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
969 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
975 $clause[] = "trxn_id = %1";
976 $input[1] = array($trxn_id, 'String');
980 $clause[] = "invoice_id = %2";
981 $input[2] = array($invoice_id, 'String');
984 if (empty($clause)) {
988 $clause = implode(' OR ', $clause);
990 $clause = "( $clause ) AND id != %3";
991 $input[3] = array($id, 'Integer');
994 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
995 $dao = CRM_Core_DAO
::executeQuery($query, $input);
997 while ($dao->fetch()) {
998 $duplicates[] = $dao->id
;
1005 * Takes an associative array and creates a contribution_product object.
1007 * the function extract all the params it needs to initialize the create a
1008 * contribution_product object. the params array could contain additional unused name/value
1011 * @param array $params
1012 * (reference) an assoc array of name/value pairs.
1014 * @return CRM_Contribute_DAO_ContributionProduct
1016 public static function addPremium(&$params) {
1017 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1018 $contributionProduct->copyValues($params);
1019 return $contributionProduct->save();
1023 * Get list of contribution fields for profile.
1024 * For now we only allow custom contribution fields to be in
1027 * @param bool $addExtraFields
1028 * True if special fields needs to be added.
1031 * the list of contribution fields
1033 public static function getContributionFields($addExtraFields = TRUE) {
1034 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1035 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1037 if ($addExtraFields) {
1038 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1041 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1043 foreach ($contributionFields as $key => $var) {
1044 if ($key == 'contribution_contact_id') {
1047 elseif ($key == 'contribution_campaign_id') {
1048 $var['title'] = ts('Campaign');
1050 $fields[$key] = $var;
1053 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1058 * Add extra fields specific to contribution.
1060 public static function getSpecialContributionFields() {
1061 $extraFields = array(
1062 'contribution_soft_credit_name' => array(
1063 'name' => 'contribution_soft_credit_name',
1064 'title' => 'Soft Credit Name',
1065 'headerPattern' => '/^soft_credit_name$/i',
1066 'where' => 'civicrm_contact_d.display_name',
1068 'contribution_soft_credit_email' => array(
1069 'name' => 'contribution_soft_credit_email',
1070 'title' => 'Soft Credit Email',
1071 'headerPattern' => '/^soft_credit_email$/i',
1072 'where' => 'soft_email.email',
1074 'contribution_soft_credit_phone' => array(
1075 'name' => 'contribution_soft_credit_phone',
1076 'title' => 'Soft Credit Phone',
1077 'headerPattern' => '/^soft_credit_phone$/i',
1078 'where' => 'soft_phone.phone',
1080 'contribution_soft_credit_contact_id' => array(
1081 'name' => 'contribution_soft_credit_contact_id',
1082 'title' => 'Soft Credit Contact ID',
1083 'headerPattern' => '/^soft_credit_contact_id$/i',
1084 'where' => 'civicrm_contribution_soft.contact_id',
1088 return $extraFields;
1092 * @param int $pageID
1096 public static function getCurrentandGoalAmount($pageID) {
1098 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1099 FROM civicrm_contribution_page p,
1100 civicrm_contribution c
1101 WHERE p.id = c.contribution_page_id
1103 AND c.cancel_date is null
1107 $config = CRM_Core_Config
::singleton();
1108 $params = array(1 => array($pageID, 'Integer'));
1109 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1111 if ($dao->fetch()) {
1112 return array($dao->goal
, $dao->total
);
1115 return array(NULL, NULL);
1120 * Get list of contribution In Honor of contact Ids.
1122 * @param int $honorId
1123 * In Honor of Contact ID.
1126 * list of contribution fields
1128 public static function getHonorContacts($honorId) {
1130 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1131 $honorDAO->contact_id
= $honorId;
1134 $type = CRM_Contribute_PseudoConstant
::financialType();
1136 while ($honorDAO->fetch()) {
1137 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1138 $contributionDAO->id
= $honorDAO->contribution_id
;
1140 if ($contributionDAO->find(TRUE)) {
1141 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1142 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1143 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1144 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1145 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1146 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1147 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1148 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1149 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1157 * Get the sort name of a contact for a particular contribution.
1160 * Id of the contribution.
1162 * @return null|string
1163 * sort name of the contact if found
1165 public static function sortName($id) {
1166 $id = CRM_Utils_Type
::escape($id, 'Integer');
1169 SELECT civicrm_contact.sort_name
1170 FROM civicrm_contribution, civicrm_contact
1171 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1172 AND civicrm_contribution.id = {$id}
1174 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1178 * @param int $contactID
1182 public static function annual($contactID) {
1183 if (is_array($contactID)) {
1184 $contactIDs = implode(',', $contactID);
1187 $contactIDs = $contactID;
1190 $config = CRM_Core_Config
::singleton();
1191 $startDate = $endDate = NULL;
1193 $currentMonth = date('m');
1194 $currentDay = date('d');
1195 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1196 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1197 (int ) $config->fiscalYearStart
['d'] > $currentDay
1200 $year = date('Y') - 1;
1205 $nextYear = $year +
1;
1207 if ($config->fiscalYearStart
) {
1208 if ($config->fiscalYearStart
['M'] < 10) {
1209 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1211 if ($config->fiscalYearStart
['d'] < 10) {
1212 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1214 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1219 $startDate = "$year$monthDay";
1220 $endDate = "$nextYear$monthDay";
1223 SELECT count(*) as count,
1224 sum(total_amount) as amount,
1225 avg(total_amount) as average,
1227 FROM civicrm_contribution b
1228 WHERE b.contact_id IN ( $contactIDs )
1229 AND b.contribution_status_id = 1
1231 AND b.receive_date >= $startDate
1232 AND b.receive_date < $endDate
1235 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1237 $amount = $average = array();
1238 while ($dao->fetch()) {
1239 if ($dao->count
> 0 && $dao->amount
> 0) {
1240 $count +
= $dao->count
;
1241 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1242 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1248 implode(', ', $amount),
1249 implode(', ', $average),
1252 return array(0, 0, 0);
1256 * Check if there is a contribution with the params passed in.
1258 * Used for trxn_id,invoice_id and contribution_id
1260 * @param array $params
1261 * An assoc array of name/value pairs.
1264 * contribution id if success else NULL
1266 public static function checkDuplicateIds($params) {
1267 $dao = new CRM_Contribute_DAO_Contribution();
1271 foreach ($params as $k => $v) {
1273 $clause[] = "$k = '$v'";
1276 $clause = implode(' AND ', $clause);
1277 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1278 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1280 while ($dao->fetch()) {
1288 * Get the contribution details for component export.
1290 * @param int $exportMode
1292 * @param string $componentIds
1298 public static function getContributionDetails($exportMode, $componentIds) {
1299 $paymentDetails = array();
1300 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1302 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1303 $componentSelect = " civicrm_participant_payment.participant_id id";
1304 $additionalClause = "
1305 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1306 AND civicrm_participant_payment.participant_id {$componentClause} )
1309 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1310 $componentSelect = " civicrm_membership_payment.membership_id id";
1311 $additionalClause = "
1312 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1313 AND civicrm_membership_payment.membership_id {$componentClause} )
1316 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1317 $componentSelect = " civicrm_pledge_payment.id id";
1318 $additionalClause = "
1319 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1320 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1324 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1325 trxn_id, {$componentSelect}
1326 FROM civicrm_contribution
1327 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1328 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1329 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1330 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1331 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1332 AND option_group_contribution_status.id = contribution_status.option_group_id )
1336 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1338 while ($dao->fetch()) {
1339 $paymentDetails[$dao->id
] = array(
1340 'total_amount' => $dao->total_amount
,
1341 'contribution_status' => $dao->status
,
1342 'receive_date' => $dao->receive_date
,
1343 'pay_instru' => $dao->payment_instrument
,
1344 'trxn_id' => $dao->trxn_id
,
1348 return $paymentDetails;
1352 * Create address associated with contribution record.
1354 * As long as there is one or more billing field in the parameters we will create the address.
1356 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1359 * @param array $params
1360 * @param int $billingLocationTypeID
1365 public static function createAddress($params, $billingLocationTypeID) {
1366 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1367 if ($hasBillingField) {
1368 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1369 return $address->id
;
1376 * Delete billing address record related contribution.
1378 * @param int $contributionId
1379 * @param int $contactId
1381 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1383 $contactJoin = NULL;
1385 if ($contributionId) {
1386 $clauses[] = "cc.id = {$contributionId}";
1390 $clauses[] = "cco.id = {$contactId}";
1391 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1394 if (empty($clauses)) {
1395 CRM_Core_Error
::fatal();
1398 $condition = implode(' OR ', $clauses);
1402 FROM civicrm_address ca
1403 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1407 $dao = CRM_Core_DAO
::executeQuery($query);
1409 while ($dao->fetch()) {
1410 $params = array('id' => $dao->id
);
1411 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1416 * This function check online pending contribution associated w/
1417 * Online Event Registration or Online Membership signup.
1419 * @param int $componentId
1420 * Participant/membership id.
1421 * @param string $componentName
1425 * pending contribution id.
1427 public static function checkOnlinePendingContribution($componentId, $componentName) {
1428 $contributionId = NULL;
1429 if (!$componentId ||
1430 !in_array($componentName, array('Event', 'Membership'))
1432 return $contributionId;
1435 if ($componentName == 'Event') {
1436 $idName = 'participant_id';
1437 $componentTable = 'civicrm_participant';
1438 $paymentTable = 'civicrm_participant_payment';
1439 $source = ts('Online Event Registration');
1442 if ($componentName == 'Membership') {
1443 $idName = 'membership_id';
1444 $componentTable = 'civicrm_membership';
1445 $paymentTable = 'civicrm_membership_payment';
1446 $source = ts('Online Contribution');
1449 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1452 SELECT component.id as {$idName},
1453 componentPayment.contribution_id as contribution_id,
1454 contribution.source source,
1455 contribution.contribution_status_id as contribution_status_id,
1456 contribution.is_pay_later as is_pay_later
1457 FROM $componentTable component
1458 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1459 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1460 WHERE component.id = {$componentId}";
1462 $dao = CRM_Core_DAO
::executeQuery($query);
1464 while ($dao->fetch()) {
1465 if ($dao->contribution_id
&&
1466 $dao->is_pay_later
&&
1467 $dao->contribution_status_id
== $pendingStatusId &&
1468 strpos($dao->source
, $source) !== FALSE
1470 $contributionId = $dao->contribution_id
;
1475 return $contributionId;
1479 * Update contribution as well as related objects.
1481 * @param array $params
1482 * @param bool $processContributionObject
1485 * @throws \Exception
1487 public static function transitionComponents($params, $processContributionObject = FALSE) {
1488 // get minimum required values.
1489 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1490 $componentId = CRM_Utils_Array
::value('component_id', $params);
1491 $componentName = CRM_Utils_Array
::value('componentName', $params);
1492 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1493 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1495 // if we already processed contribution object pass previous status id.
1496 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1498 $updateResult = array();
1500 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1502 // we process only ( Completed, Cancelled, or Failed ) contributions.
1503 if (!$contributionId ||
1504 !in_array($contributionStatusId, array(
1505 array_search('Completed', $contributionStatuses),
1506 array_search('Cancelled', $contributionStatuses),
1507 array_search('Failed', $contributionStatuses),
1510 return $updateResult;
1513 if (!$componentName ||
!$componentId) {
1514 // get the related component details.
1515 $componentDetails = self
::getComponentDetails($contributionId);
1518 $componentDetails['contact_id'] = $contactId;
1519 $componentDetails['component'] = $componentName;
1521 if ($componentName == 'event') {
1522 $componentDetails['participant'] = $componentId;
1525 $componentDetails['membership'] = $componentId;
1529 if (!empty($componentDetails['contact_id'])) {
1530 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1536 // do check for required ids.
1537 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1538 return $updateResult;
1541 //now we are ready w/ required ids, start processing.
1543 $baseIPN = new CRM_Core_Payment_BaseIPN();
1545 $input = $ids = $objects = array();
1547 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1548 $ids['contribution'] = $contributionId;
1549 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1550 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1551 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1552 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1553 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1554 $ids['contributionRecur'] = NULL;
1555 $ids['contributionPage'] = NULL;
1557 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1558 CRM_Core_Error
::fatal();
1561 $memberships = &$objects['membership'];
1562 $participant = &$objects['participant'];
1563 $pledgePayment = &$objects['pledge_payment'];
1564 $contribution = &$objects['contribution'];
1566 if ($pledgePayment) {
1567 $pledgePaymentIDs = array();
1568 foreach ($pledgePayment as $key => $object) {
1569 $pledgePaymentIDs[] = $object->id
;
1571 $pledgeID = $pledgePayment[0]->pledge_id
;
1574 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1577 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1578 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1583 // we might want to process contribution object.
1584 $processContribution = FALSE;
1585 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1586 if (is_array($memberships)) {
1587 foreach ($memberships as $membership) {
1589 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1590 $membership->save();
1592 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1593 if ($processContributionObject) {
1594 $processContribution = TRUE;
1601 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1602 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1604 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1605 if ($processContributionObject) {
1606 $processContribution = TRUE;
1610 if ($pledgePayment) {
1611 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1613 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1614 if ($processContributionObject) {
1615 $processContribution = TRUE;
1619 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1620 if (is_array($memberships)) {
1621 foreach ($memberships as $membership) {
1623 $membership->status_id
= array_search('Expired', $membershipStatuses);
1624 $membership->save();
1626 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1627 if ($processContributionObject) {
1628 $processContribution = TRUE;
1634 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1635 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1637 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1638 if ($processContributionObject) {
1639 $processContribution = TRUE;
1643 if ($pledgePayment) {
1644 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1646 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1647 if ($processContributionObject) {
1648 $processContribution = TRUE;
1652 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1654 // only pending contribution related object processed.
1655 if ($previousContriStatusId &&
1656 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1658 // this is case when we already processed contribution object.
1659 return $updateResult;
1661 elseif (!$previousContriStatusId &&
1662 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1664 // this is case when we are going to process contribution object later.
1665 return $updateResult;
1668 if (is_array($memberships)) {
1669 foreach ($memberships as $membership) {
1674 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1675 $membership->membership_type_id
,
1676 $membership->is_test
, $membership->id
1679 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1680 // this picks up membership type changes during renewals
1682 SELECT membership_type_id
1683 FROM civicrm_membership_log
1684 WHERE membership_id=$membership->id
1687 $dao = new CRM_Core_DAO();
1689 if ($dao->fetch()) {
1690 if (!empty($dao->membership_type_id
)) {
1691 $membership->membership_type_id
= $dao->membership_type_id
;
1692 $membership->save();
1695 // else fall back to using current membership type
1698 // Figure out number of terms
1700 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1701 foreach ($lineitems as $lineitem) {
1702 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1703 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1705 // in case membership_num_terms comes through as null or zero
1706 $numterms = $numterms >= 1 ?
$numterms : 1;
1711 // CRM-15735-to update the membership status as per the contribution receive date
1713 if (!empty($params['receive_date'])) {
1714 $joinDate = $params['receive_date'];
1715 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1716 $membership->end_date
,
1717 $membership->join_date
,
1718 $params['receive_date'],
1720 $membership->membership_type_id
,
1723 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1724 $membership->save();
1727 if ($currentMembership) {
1728 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1729 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1730 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1733 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1736 //get the status for membership.
1737 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1739 $dates['join_date'],
1742 $membership->membership_type_id
,
1746 $formattedParams = array(
1747 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1748 array_search('Current', $membershipStatuses)
1750 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1751 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1752 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1755 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1757 $membership->copyValues($formattedParams);
1758 $membership->save();
1760 //updating the membership log
1761 $membershipLog = array();
1762 $membershipLog = $formattedParams;
1763 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1764 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1766 $membershipLog['start_date'] = $logStartDate;
1767 $membershipLog['membership_id'] = $membership->id
;
1768 $membershipLog['modified_id'] = $membership->contact_id
;
1769 $membershipLog['modified_date'] = date('Ymd');
1770 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1772 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1774 //update related Memberships.
1775 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1777 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1780 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1781 if ($processContributionObject) {
1782 $processContribution = TRUE;
1785 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1791 $updatedStatusId = array_search('Registered', $participantStatuses);
1792 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1794 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1795 if ($processContributionObject) {
1796 $processContribution = TRUE;
1800 if ($pledgePayment) {
1801 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1803 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1804 if ($processContributionObject) {
1805 $processContribution = TRUE;
1810 // process contribution object.
1811 if ($processContribution) {
1812 $contributionParams = array();
1819 'payment_instrument_id',
1822 'financial_type_id',
1823 'contribution_status_id',
1824 'non_deductible_amount',
1828 foreach ($fields as $field) {
1829 if (empty($params[$field])) {
1832 $contributionParams[$field] = $params[$field];
1835 $ids = array('contribution' => $contributionId);
1836 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1839 return $updateResult;
1843 * Returns all contribution related object ids.
1845 * @param $contributionId
1849 public static function getComponentDetails($contributionId) {
1850 $componentDetails = $pledgePayment = array();
1851 if (!$contributionId) {
1852 return $componentDetails;
1856 SELECT c.id as contribution_id,
1857 c.contact_id as contact_id,
1858 c.contribution_recur_id,
1859 mp.membership_id as membership_id,
1860 m.membership_type_id as membership_type_id,
1861 pp.participant_id as participant_id,
1862 p.event_id as event_id,
1863 pgp.id as pledge_payment_id
1864 FROM civicrm_contribution c
1865 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1866 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1867 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1868 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1869 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1870 WHERE c.id = $contributionId";
1872 $dao = CRM_Core_DAO
::executeQuery($query);
1873 $componentDetails = array();
1875 while ($dao->fetch()) {
1876 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1877 $componentDetails['contact_id'] = $dao->contact_id
;
1878 if ($dao->event_id
) {
1879 $componentDetails['event'] = $dao->event_id
;
1881 if ($dao->participant_id
) {
1882 $componentDetails['participant'] = $dao->participant_id
;
1884 if ($dao->membership_id
) {
1885 if (!isset($componentDetails['membership'])) {
1886 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1888 $componentDetails['membership'][] = $dao->membership_id
;
1889 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1891 if ($dao->pledge_payment_id
) {
1892 $pledgePayment[] = $dao->pledge_payment_id
;
1894 if ($dao->contribution_recur_id
) {
1895 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1899 if ($pledgePayment) {
1900 $componentDetails['pledge_payment'] = $pledgePayment;
1903 return $componentDetails;
1907 * @param int $contactId
1908 * @param bool $includeSoftCredit
1910 * @return null|string
1912 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1917 $contactContributionsSQL = "
1918 SELECT contribution.id AS id
1919 FROM civicrm_contribution contribution
1920 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1922 $contactSoftCreditContributionsSQL = "
1923 SELECT contribution.id
1924 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1925 ON ( contribution.id = softContribution.contribution_id )
1926 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1927 $query = "SELECT count( x.id ) count FROM ( ";
1928 $query .= $contactContributionsSQL;
1930 if ($includeSoftCredit) {
1931 $query .= " UNION ";
1932 $query .= $contactSoftCreditContributionsSQL;
1937 return CRM_Core_DAO
::singleValueQuery($query);
1941 * Get individual id for onbehalf contribution.
1943 * @param int $contributionId
1945 * @param int $contributorId
1949 * containing organization id and individual id
1951 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1955 if (!$contributionId) {
1959 // fetch contributor id if null
1960 if (!$contributorId) {
1961 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1962 $contributionId, 'contact_id'
1966 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1967 $activityTypeId = array_search('Contribution', $activityTypeIds);
1969 if ($activityTypeId && $contributorId) {
1971 SELECT civicrm_activity_contact.contact_id
1972 FROM civicrm_activity_contact
1973 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1974 WHERE civicrm_activity.activity_type_id = %1
1975 AND civicrm_activity.source_record_id = %2
1976 AND civicrm_activity_contact.record_type_id = %3
1979 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1980 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1983 1 => array($activityTypeId, 'Integer'),
1984 2 => array($contributionId, 'Integer'),
1985 3 => array($sourceID, 'Integer'),
1988 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1990 // for on behalf contribution source is individual and contributor is organization
1991 if ($sourceContactId && $sourceContactId != $contributorId) {
1992 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1993 // get rel type id for employee of relation
1994 foreach ($relationshipTypeIds as $id => $typeVals) {
1995 if ($typeVals['name_a_b'] == 'Employee of') {
1996 $relationshipTypeId = $id;
2001 $rel = new CRM_Contact_DAO_Relationship();
2002 $rel->relationship_type_id
= $relationshipTypeId;
2003 $rel->contact_id_a
= $sourceContactId;
2004 $rel->contact_id_b
= $contributorId;
2005 if ($rel->find(TRUE)) {
2006 $ids['individual_id'] = $rel->contact_id_a
;
2007 $ids['organization_id'] = $rel->contact_id_b
;
2018 public static function getContributionDates() {
2019 $config = CRM_Core_Config
::singleton();
2020 $currentMonth = date('m');
2021 $currentDay = date('d');
2022 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2023 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2024 (int ) $config->fiscalYearStart
['d'] > $currentDay
2027 $year = date('Y') - 1;
2032 $year = array('Y' => $year);
2033 $yearDate = $config->fiscalYearStart
;
2034 $yearDate = array_merge($year, $yearDate);
2035 $yearDate = CRM_Utils_Date
::format($yearDate);
2037 $monthDate = date('Ym') . '01';
2043 'yearDate' => $yearDate,
2044 'monthDate' => $monthDate,
2049 * Load objects relations to contribution object.
2050 * Objects are stored in the $_relatedObjects property
2051 * In the first instance we are just moving functionality from BASEIpn -
2052 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2054 * Note that the unit test for the BaseIPN class tests this function
2056 * @param array $input
2057 * Input as delivered from Payment Processor.
2059 * Ids as Loaded by Payment Processor.
2060 * @param bool $required
2061 * Is Payment processor / contribution page required.
2062 * @param bool $loadAll
2063 * Load all related objects - even where id not passed in? (allows API to call this).
2068 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
2070 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2071 if (empty($ids['contact']) && isset($this->contact_id
)) {
2072 $ids['contact'] = $this->contact_id
;
2075 if (empty($this->_component
)) {
2076 if (!empty($ids['event'])) {
2077 $this->_component
= 'event';
2080 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2083 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
2084 $contributionType = new CRM_Financial_BAO_FinancialType();
2085 $contributionType->id
= $this->financial_type_id
;
2086 $contributionType->find(TRUE);
2088 if (!empty($ids['contact'])) {
2089 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
2090 $this->_relatedObjects
['contact']->id
= $ids['contact'];
2091 $this->_relatedObjects
['contact']->find(TRUE);
2093 $this->_relatedObjects
['contributionType'] = $contributionType;
2095 if ($this->_component
== 'contribute') {
2096 // retrieve the other optional objects first so
2097 // stuff down the line can use this info and do things
2099 //in any case get the memberships associated with the contribution
2100 //because we now support multiple memberships w/ price set
2101 // see if there are any other memberships to be considered for same contribution.
2103 SELECT membership_id
2104 FROM civicrm_membership_payment
2105 WHERE contribution_id = %1 ";
2106 $params = array(1 => array($this->id
, 'Integer'));
2108 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2109 while ($dao->fetch()) {
2110 if ($dao->membership_id
) {
2111 if (!is_array($ids['membership'])) {
2112 $ids['membership'] = array();
2114 $ids['membership'][] = $dao->membership_id
;
2118 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2119 foreach ($ids['membership'] as $id) {
2121 $membership = new CRM_Member_BAO_Membership();
2122 $membership->id
= $id;
2123 if (!$membership->find(TRUE)) {
2124 throw new Exception("Could not find membership record: $id");
2126 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2127 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2128 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2129 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2130 $membership->free();
2135 if (!empty($ids['pledge_payment'])) {
2137 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2138 if (empty($paymentID)) {
2141 $payment = new CRM_Pledge_BAO_PledgePayment();
2142 $payment->id
= $paymentID;
2143 if (!$payment->find(TRUE)) {
2144 throw new Exception("Could not find pledge payment record: " . $paymentID);
2146 $this->_relatedObjects
['pledge_payment'][] = $payment;
2150 if (!empty($ids['contributionRecur'])) {
2151 $recur = new CRM_Contribute_BAO_ContributionRecur();
2152 $recur->id
= $ids['contributionRecur'];
2153 if (!$recur->find(TRUE)) {
2154 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2156 $this->_relatedObjects
['contributionRecur'] = &$recur;
2157 //get payment processor id from recur object.
2158 $paymentProcessorID = $recur->payment_processor_id
;
2160 //for normal contribution get the payment processor id.
2161 if (!$paymentProcessorID) {
2162 if ($this->contribution_page_id
) {
2163 // get the payment processor id from contribution page
2164 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2165 $this->contribution_page_id
,
2169 //fail to load payment processor id.
2170 elseif (empty($ids['pledge_payment'])) {
2171 $loadObjectSuccess = TRUE;
2173 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2175 return $loadObjectSuccess;
2180 // we are in event mode
2181 // make sure event exists and is valid
2182 $event = new CRM_Event_BAO_Event();
2183 $event->id
= $ids['event'];
2184 if ($ids['event'] &&
2187 throw new Exception("Could not find event: " . $ids['event']);
2190 $this->_relatedObjects
['event'] = &$event;
2192 $participant = new CRM_Event_BAO_Participant();
2193 $participant->id
= $ids['participant'];
2194 if ($ids['participant'] &&
2195 !$participant->find(TRUE)
2197 throw new Exception("Could not find participant: " . $ids['participant']);
2199 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2201 $this->_relatedObjects
['participant'] = &$participant;
2203 if (!$paymentProcessorID) {
2204 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2208 if ($paymentProcessorID) {
2209 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2210 $this->is_test ?
'test' : 'live'
2212 $ids['paymentProcessor'] = $paymentProcessorID;
2213 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2215 elseif ($required) {
2216 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2223 * Create array of message information - ie. return html version, txt version, to field
2225 * @param array $input
2226 * Incoming information.
2227 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2228 * just check presence of recur object but maintaining legacy approach
2231 * IDs of related objects.
2232 * @param array $values
2233 * Any values that may have already been compiled by calling process.
2234 * This is augmented by values 'gathered' by gatherMessageValues
2235 * @param bool $recur
2236 * @param bool $returnMessageText
2237 * Distinguishes between whether to send message or return.
2238 * message text. We are working towards this function ALWAYS returning message text & calling
2239 * function doing emails / pdfs with it
2245 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2246 if (empty($this->_relatedObjects
)) {
2247 $this->loadRelatedObjects($input, $ids);
2249 if (empty($this->_component
)) {
2250 $this->_component
= CRM_Utils_Array
::value('component', $input);
2253 //not really sure what params might be passed in but lets merge em into values
2254 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2255 $template = CRM_Core_Smarty
::singleton();
2256 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2257 //what does recur 'mean here - to do with payment processor return functionality but
2258 // what is the importance
2259 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2260 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2262 $entityID = $entity = NULL;
2263 if (isset($ids['contribution'])) {
2264 $entity = 'contribution';
2265 $entityID = $ids['contribution'];
2267 if (!empty($ids['membership'])) {
2268 //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
2269 // 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
2270 // line having loaded an array
2271 $ids['membership'] = (array) $ids['membership'];
2272 $entity = 'membership';
2273 $entityID = $ids['membership'][0];
2276 $url = $paymentObject->subscriptionURL($entityID, $entity);
2277 $template->assign('cancelSubscriptionUrl', $url);
2279 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2280 $template->assign('updateSubscriptionBillingUrl', $url);
2282 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2283 $template->assign('updateSubscriptionUrl', $url);
2285 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2286 //direct mode showing billing block, so use directIPN for temporary
2287 $template->assign('contributeMode', 'directIPN');
2290 // todo remove strtolower - check consistency
2291 if (strtolower($this->_component
) == 'event') {
2292 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2293 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2297 $values['contribution_id'] = $this->id
;
2298 if (!empty($ids['related_contact'])) {
2299 $values['related_contact'] = $ids['related_contact'];
2300 if (isset($ids['onbehalf_dupe_alert'])) {
2301 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2303 $entityBlock = array(
2304 'contact_id' => $ids['contact'],
2305 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2306 'Home', 'id', 'name'
2309 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2310 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2313 if ($this->is_test
) {
2316 if (!empty($this->_relatedObjects
['membership'])) {
2317 foreach ($this->_relatedObjects
['membership'] as $membership) {
2318 if ($membership->id
) {
2319 $values['isMembership'] = TRUE;
2321 // need to set the membership values here
2322 $template->assign('membership_assign', 1);
2323 $template->assign('membership_name',
2324 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2326 $template->assign('mem_start_date', $membership->start_date
);
2327 $template->assign('mem_join_date', $membership->join_date
);
2328 $template->assign('mem_end_date', $membership->end_date
);
2329 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2330 $template->assign('mem_status', $membership_status);
2331 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2332 $template->assign('is_pay_later', 1);
2335 // if separate payment there are two contributions recorded and the
2336 // admin will need to send a receipt for each of them separately.
2337 // we dont link the two in the db (but can potentially infer it if needed)
2338 $template->assign('is_separate_payment', 0);
2340 if ($recur && $paymentObject) {
2341 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2342 $template->assign('cancelSubscriptionUrl', $url);
2343 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2344 $template->assign('updateSubscriptionBillingUrl', $url);
2345 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2346 $template->assign('updateSubscriptionUrl', $url);
2349 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2352 // otherwise if its about sending emails, continue sending without return, as we
2353 // don't want to exit the loop.
2358 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2364 * Gather values for contribution mail - this function has been created
2365 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2366 * Values related to the contribution in question are gathered
2368 * @param array $input
2369 * Input into function (probably from payment processor).
2370 * @param array $values
2372 * The set of ids related to the input.
2376 public function _gatherMessageValues($input, &$values, $ids = array()) {
2377 // set display address of contributor
2378 if ($this->address_id
) {
2379 $addressParams = array('id' => $this->address_id
);
2380 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2381 $addressDetails = array_values($addressDetails);
2382 $values['address'] = $addressDetails[0]['display'];
2384 if ($this->_component
== 'contribute') {
2385 if (isset($this->contribution_page_id
)) {
2386 CRM_Contribute_BAO_ContributionPage
::setValues(
2387 $this->contribution_page_id
,
2390 if ($this->contribution_page_id
) {
2391 // CRM-8254 - override default currency if applicable
2392 $config = CRM_Core_Config
::singleton();
2393 $config->defaultCurrency
= CRM_Utils_Array
::value(
2396 $config->defaultCurrency
2400 // no contribution page -probably back office
2402 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2403 $values['is_email_receipt'] = 1;
2404 $values['title'] = 'Contribution';
2406 // set lineItem for contribution
2408 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2409 if (!empty($lineItem)) {
2410 $itemId = key($lineItem);
2411 foreach ($lineItem as &$eachItem) {
2412 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2413 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2414 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2415 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2418 $values['lineItem'][0] = $lineItem;
2419 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2423 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2427 // if this is onbehalf of contribution then set related contact
2428 if (!empty($relatedContact['individual_id'])) {
2429 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2434 $eventParams = array(
2435 'id' => $this->_relatedObjects
['event']->id
,
2437 $values['event'] = array();
2439 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2441 //get location details
2442 $locationParams = array(
2443 'entity_id' => $this->_relatedObjects
['event']->id
,
2444 'entity_table' => 'civicrm_event',
2446 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2448 $ufJoinParams = array(
2449 'entity_table' => 'civicrm_event',
2450 'entity_id' => $ids['event'],
2451 'module' => 'CiviEvent',
2454 list($custom_pre_id,
2456 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2458 $values['custom_pre_id'] = $custom_pre_id;
2459 $values['custom_post_id'] = $custom_post_ids;
2461 // set lineItem for event contribution
2463 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2464 if (!empty($participantIds)) {
2465 foreach ($participantIds as $pIDs) {
2466 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2467 if (!CRM_Utils_System
::isNull($lineItem)) {
2468 $values['lineItem'][] = $lineItem;
2479 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2480 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2481 * Note we send directly from this function in some cases because it is only partly refactored
2482 * Don't call this function directly as the signature will change
2486 * @param CRM_Core_SMARTY $template
2487 * @param bool $recur
2488 * @param bool $returnMessageText
2492 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2493 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2494 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2495 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2496 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2497 $template->assign('useForMember', TRUE);
2499 //assign honor information to receipt message
2500 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2502 if (isset($softRecord['soft_credit'])) {
2503 //if id of contribution page is present
2504 if (!empty($values['id'])) {
2505 $values['honor'] = array(
2506 'honor_profile_values' => array(),
2507 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2508 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2510 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2512 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2513 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2516 //offline contribution
2517 $softCreditTypes = $softCredits = array();
2518 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2519 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2520 $softCredits[$key] = array(
2521 'Name' => $softCredit['contact_name'],
2522 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2525 $template->assign('softCreditTypes', $softCreditTypes);
2526 $template->assign('softCredits', $softCredits);
2530 $dao = new CRM_Contribute_DAO_ContributionProduct();
2531 $dao->contribution_id
= $this->id
;
2532 if ($dao->find(TRUE)) {
2533 $premiumId = $dao->product_id
;
2534 $template->assign('option', $dao->product_option
);
2536 $productDAO = new CRM_Contribute_DAO_Product();
2537 $productDAO->id
= $premiumId;
2538 $productDAO->find(TRUE);
2539 $template->assign('selectPremium', TRUE);
2540 $template->assign('product_name', $productDAO->name
);
2541 $template->assign('price', $productDAO->price
);
2542 $template->assign('sku', $productDAO->sku
);
2544 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2545 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2546 if (empty($amount) && isset($this->total_amount
)) {
2547 $amount = $this->total_amount
;
2549 $template->assign('amount', $amount);
2550 // add the new contribution values
2551 if (strtolower($this->_component
) == 'contribute') {
2553 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2554 $softDAO->contribution_id
= $this->id
;
2555 if ($softDAO->find(TRUE)) {
2556 $template->assign('pcpBlock', TRUE);
2557 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2558 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2559 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2561 //assign the pcp page title for email subject
2562 $pcpDAO = new CRM_PCP_DAO_PCP();
2563 $pcpDAO->id
= $softDAO->pcp_id
;
2564 if ($pcpDAO->find(TRUE)) {
2565 $template->assign('title', $pcpDAO->title
);
2570 if ($this->financial_type_id
) {
2571 $values['financial_type_id'] = $this->financial_type_id
;
2574 $template->assign('trxn_id', $this->trxn_id
);
2575 $template->assign('receive_date',
2576 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2578 $template->assign('contributeMode', 'notify');
2579 $template->assign('action', $this->is_test ?
1024 : 1);
2580 $template->assign('receipt_text',
2581 CRM_Utils_Array
::value('receipt_text',
2585 $template->assign('is_monetary', 1);
2586 $template->assign('is_recur', (bool) $recur);
2587 $template->assign('currency', $this->currency
);
2588 $template->assign('address', CRM_Utils_Address
::format($input));
2589 if ($this->_component
== 'event') {
2590 $template->assign('title', $values['event']['title']);
2591 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2592 $viewRoles = array();
2593 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2594 $viewRoles[] = $participantRoles[$v];
2596 $values['event']['participant_role'] = implode(', ', $viewRoles);
2597 $template->assign('event', $values['event']);
2598 $template->assign('location', $values['location']);
2599 $template->assign('customPre', $values['custom_pre_id']);
2600 $template->assign('customPost', $values['custom_post_id']);
2603 if ($this->_relatedObjects
['participant']->is_test
) {
2607 $values['params'] = array();
2608 //to get email of primary participant.
2609 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2610 $primaryAmount[] = array(
2611 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2612 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2614 //build an array of cId/pId of participants
2615 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2616 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2617 //send receipt to additional participant if exists
2618 if (count($additionalIDs)) {
2619 $template->assign('isPrimary', 0);
2620 $template->assign('customProfile', NULL);
2621 //set additionalParticipant true
2622 $values['params']['additionalParticipant'] = TRUE;
2623 foreach ($additionalIDs as $pId => $cId) {
2625 //to change the status pending to completed
2626 $additional = new CRM_Event_DAO_Participant();
2627 $additional->id
= $pId;
2628 $additional->contact_id
= $cId;
2629 $additional->find(TRUE);
2630 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2631 $additional->status_id
= 1;
2632 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2633 //if additional participant dont have email
2635 if (!$additionalParticipantInfo) {
2636 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2638 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2639 $primaryAmount[] = array(
2640 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2641 'amount' => $additional->fee_amount
,
2643 $additional->save();
2644 $additional->free();
2645 $template->assign('amount', $amount);
2646 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2650 //build an array of custom profile and assigning it to template
2651 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2653 if (count($customProfile)) {
2654 $template->assign('customProfile', $customProfile);
2657 // for primary contact
2658 $values['params']['additionalParticipant'] = FALSE;
2659 $template->assign('isPrimary', 1);
2660 $template->assign('amount', $primaryAmount);
2661 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2662 if ($this->payment_instrument_id
) {
2663 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2664 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2666 // carry paylater, since we did not created billing,
2667 // so need to pull email from primary location, CRM-4395
2668 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2674 * Check whether payment processor supports
2675 * cancellation of contribution subscription
2677 * @param int $contributionId
2680 * @param bool $isNotCancelled
2684 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2685 $cacheKeyString = "$contributionId";
2686 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2688 static $supportsCancel = array();
2690 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2691 $supportsCancel[$cacheKeyString] = FALSE;
2692 $isCancelled = FALSE;
2694 if ($isNotCancelled) {
2695 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2698 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2699 if (!empty($paymentObject)) {
2700 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2703 return $supportsCancel[$cacheKeyString];
2707 * Check whether subscription is already cancelled.
2709 * @param int $contributionId
2713 * contribution status
2715 public static function isSubscriptionCancelled($contributionId) {
2717 SELECT cr.contribution_status_id
2718 FROM civicrm_contribution_recur cr
2719 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2720 WHERE con.id = %1 LIMIT 1";
2721 $params = array(1 => array($contributionId, 'Integer'));
2722 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2723 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2724 if ($status == 'Cancelled') {
2731 * Create all financial accounts entry.
2733 * @param array $params
2734 * Contribution object, line item array and params for trxn.
2737 * @param array $financialTrxnValues
2739 * @return null|object
2741 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2742 $skipRecords = $update = $return = $isRelatedId = FALSE;
2744 $additionalParticipantId = array();
2745 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2747 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2748 $entityId = $params['participant_id'];
2749 $entityTable = 'civicrm_participant';
2750 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2752 elseif (!empty($params['membership_id'])) {
2753 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2754 // are created off one contribution should be handled elsewhere
2755 $entityId = $params['membership_id'];
2756 $entityTable = 'civicrm_membership';
2759 $entityId = $params['contribution']->id
;
2760 $entityTable = 'civicrm_contribution';
2763 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2764 $isRelatedId = TRUE;
2767 $entityID[] = $entityId;
2768 if (!empty($additionalParticipantId)) {
2769 $entityID +
= $additionalParticipantId;
2771 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2772 if (empty($params['prevContribution'])) {
2779 $statusId = $params['contribution']->contribution_status_id
;
2780 // CRM-13964 partial payment
2781 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2782 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2784 $partialAmtPay = $params['partial_amount_pay'];
2785 $partialAmtTotal = $params['partial_payment_total'];
2787 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2788 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2789 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2790 $params['total_amount'] = $partialAmtPay;
2792 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2793 if (empty($balanceTrxnInfo['trxn_id'])) {
2794 // create new balance transaction record
2795 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2796 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2798 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2799 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2800 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2801 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2802 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2803 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2804 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2805 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2806 $balanceTrxnParams['status_id'] = $statusId;
2807 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2808 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2809 if (!empty($params['payment_processor'])) {
2810 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2812 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2816 // build line item array if its not set in $params
2817 if (empty($params['line_item']) ||
$additionalParticipantId) {
2818 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2821 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2822 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2824 $skipRecords = TRUE;
2825 $pendingStatus = array(
2826 array_search('Pending', $contributionStatuses),
2827 array_search('In Progress', $contributionStatuses),
2829 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2830 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2831 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2833 elseif (!empty($params['payment_processor'])) {
2834 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2836 elseif (!empty($params['payment_instrument_id'])) {
2837 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2840 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2841 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2842 $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);
2845 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2846 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2847 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2850 //build financial transaction params
2851 $trxnParams = array(
2852 'contribution_id' => $params['contribution']->id
,
2853 'to_financial_account_id' => $params['to_financial_account_id'],
2854 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2855 'total_amount' => $totalAmount,
2856 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2857 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2858 'currency' => $params['contribution']->currency
,
2859 'trxn_id' => $params['contribution']->trxn_id
,
2860 'status_id' => $statusId,
2861 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2862 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2865 if (!empty($params['payment_processor'])) {
2866 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2869 if (isset($fromFinancialAccountId)) {
2870 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2873 // consider external values passed for recording transaction entry
2874 if (!empty($financialTrxnValues)) {
2875 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2878 $params['trxnParams'] = $trxnParams;
2880 if (!empty($params['prevContribution'])) {
2881 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2882 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2883 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2884 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2885 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2887 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2888 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2889 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2891 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2892 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2895 //if financial type is changed
2896 if (!empty($params['financial_type_id']) &&
2897 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2899 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2900 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2901 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2902 if ($oldFinancialAccount != $newFinancialAccount) {
2903 $params['total_amount'] = 0;
2904 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2905 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2906 $params['prevContribution']->financial_type_id
, $relationTypeId);
2909 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2910 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2911 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2914 self
::updateFinancialAccounts($params, 'changeFinancialType');
2915 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2916 $params['financial_account_id'] = $newFinancialAccount;
2917 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2918 self
::updateFinancialAccounts($params);
2919 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2923 //Update contribution status
2924 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2925 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2926 if (!empty($params['contribution_status_id']) &&
2927 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2929 //Update Financial Records
2930 self
::updateFinancialAccounts($params, 'changedStatus');
2933 // change Payment Instrument for a Completed contribution
2934 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2935 // instrument is null and now new payment instrument is added along with the payment
2936 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2937 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2938 if (array_key_exists('payment_instrument_id', $params)) {
2939 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2940 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2941 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2943 //check if status is changed from Pending to Completed
2944 // do not update payment instrument changes for Pending to Completed
2945 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2946 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2948 // for all other statuses create new financial records
2949 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2950 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2951 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2954 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2955 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2956 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2958 // for any other payment instrument changes create new financial records
2959 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2960 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2961 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2963 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2964 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2966 // another special case when check number is changed, create new financial records
2967 // create financial trxn with negative amount
2968 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2969 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2970 // create financial trxn with positive amount
2971 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2972 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2973 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2977 //if Change contribution amount
2978 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2979 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2980 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2981 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2982 if (isset($totalAmount) &&
2983 $totalAmount != $params['prevContribution']->total_amount
2985 //Update Financial Records
2986 $params['trxnParams']['from_financial_account_id'] = NULL;
2987 self
::updateFinancialAccounts($params, 'changedAmount');
2992 // records finanical trxn and entity financial trxn
2993 // also make it available as return value
2994 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2995 $params['entity_id'] = $financialTxn->id
;
2998 // record line items and financial items
2999 if (empty($params['skipLineItem'])) {
3000 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3003 // create batch entry if batch_id is passed and
3004 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3005 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3006 $entityParams = array(
3007 'batch_id' => $params['batch_id'],
3008 'entity_table' => 'civicrm_financial_trxn',
3009 'entity_id' => $financialTxn->id
,
3011 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3014 // when a fee is charged
3015 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3016 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3019 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3020 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3022 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3023 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3024 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3026 unset($params['line_item']);
3032 * Update all financial accounts entry.
3034 * @param array $params
3035 * Contribution object, line item array and params for trxn.
3037 * @param string $context
3040 * @param null $skipTrxn
3043 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3044 $itemAmount = $trxnID = NULL;
3045 //get all the statuses
3046 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3047 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3048 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3049 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3050 && $context == 'changePaymentInstrument'
3054 if (($params['prevContribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus))
3055 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3056 && $context == 'changedStatus'
3060 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3061 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3063 if ($context == 'changedStatus') {
3064 //get all the statuses
3065 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3067 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3068 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3069 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3071 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3073 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3074 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3076 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3077 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3078 $params['trxnParams']['to_financial_account_id'] = NULL;
3079 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3081 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3082 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3083 $financialTypeID, $relationTypeId);
3085 $itemAmount = $params['trxnParams']['total_amount'];
3087 elseif ($context == 'changePaymentInstrument') {
3088 if ($params['trxnParams']['total_amount'] < 0) {
3089 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3090 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3091 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3092 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3096 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3097 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3100 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3101 $params['entity_id'] = $trxn->id
;
3103 if ($context == 'changedStatus') {
3104 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3105 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3106 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3108 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3109 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3111 $entityParams = array(
3112 'entity_table' => 'civicrm_financial_item',
3113 'financial_trxn_id' => $trxn->id
,
3115 if (empty($params['line_item'])) {
3117 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3118 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3119 // & this can be removed
3122 foreach ($params['line_item'] as $fieldId => $fields) {
3123 foreach ($fields as $fieldValueId => $fieldValues) {
3125 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3126 2 => array($fieldValues['id'], 'Integer'),
3128 CRM_Core_DAO
::executeQuery($query, $fparams);
3130 1 => array($fieldValues['id'], 'Integer'),
3132 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3133 while ($financialItem->fetch()) {
3134 $entityParams['entity_id'] = $financialItem->id
;
3135 $entityParams['amount'] = $financialItem->amount
;
3136 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3143 if ($context != 'changePaymentInstrument') {
3144 $itemParams['entity_table'] = 'civicrm_line_item';
3145 $trxnIds['id'] = $params['entity_id'];
3146 foreach ($params['line_item'] as $fieldId => $fields) {
3147 foreach ($fields as $fieldValueId => $fieldValues) {
3148 $prevParams['entity_id'] = $fieldValues['id'];
3149 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3151 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3152 if ($params['contribution']->receive_date
) {
3153 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3156 $financialAccount = $prevfinancialItem->financial_account_id
;
3157 if (!empty($params['financial_account_id'])) {
3158 $financialAccount = $params['financial_account_id'];
3161 $currency = $params['prevContribution']->currency
;
3162 if ($params['contribution']->currency
) {
3163 $currency = $params['contribution']->currency
;
3166 if (!empty($params['is_quick_config'])) {
3167 $amount = $itemAmount;
3169 $amount = $params['total_amount'];
3173 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3174 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3178 $amount = $diff * $fieldValues['line_total'];
3181 $itemParams = array(
3182 'transaction_date' => $receiveDate,
3183 'contact_id' => $params['prevContribution']->contact_id
,
3184 'currency' => $currency,
3185 'amount' => $amount,
3186 'description' => $prevfinancialItem->description
,
3187 'status_id' => $prevfinancialItem->status_id
,
3188 'financial_account_id' => $financialAccount,
3189 'entity_table' => 'civicrm_line_item',
3190 'entity_id' => $fieldValues['id'],
3192 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3194 if ($fieldValues['tax_amount']) {
3195 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3196 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3197 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3198 $itemParams['description'] = $taxTerm;
3199 if ($fieldValues['financial_type_id']) {
3200 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3202 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3207 if ($context == 'changeFinancialType') {
3208 $params['skipLineItem'] = FALSE;
3209 foreach ($params['line_item'] as &$lineItems) {
3210 foreach ($lineItems as &$line) {
3211 $line['financial_type_id'] = $params['financial_type_id'];
3218 * Check status validation on update of a contribution.
3220 * @param array $values
3221 * Previous form values before submit.
3223 * @param array $fields
3224 * The input form values.
3226 * @param array $errors
3231 public static function checkStatusValidation($values, &$fields, &$errors) {
3232 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3233 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3234 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3238 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3239 $checkStatus = array(
3240 'Cancelled' => array('Completed', 'Refunded'),
3241 'Completed' => array('Cancelled', 'Refunded'),
3242 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3243 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3244 'Refunded' => array('Cancelled', 'Completed'),
3245 'Partially paid' => array('Completed'),
3248 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3249 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3250 1 => $contributionStatuses[$values['contribution_status_id']],
3251 2 => $contributionStatuses[$fields['contribution_status_id']],
3257 * Delete contribution of contact.
3261 * @param int $contactId
3265 public static function deleteContactContribution($contactId) {
3266 $contribution = new CRM_Contribute_DAO_Contribution();
3267 $contribution->contact_id
= $contactId;
3268 $contribution->find();
3269 while ($contribution->fetch()) {
3270 self
::deleteContribution($contribution->id
);
3275 * Get options for a given contribution field.
3276 * @see CRM_Core_DAO::buildOptions
3278 * @param string $fieldName
3279 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3280 * @param array $props whatever is known about this dao object.
3282 * @return array|bool
3284 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3285 $className = __CLASS__
;
3287 switch ($fieldName) {
3288 // This field is not part of this object but the api supports it
3289 case 'payment_processor':
3290 $className = 'CRM_Contribute_BAO_ContributionPage';
3291 // Filter results by contribution page
3292 if (!empty($props['contribution_page_id'])) {
3293 $page = civicrm_api('contribution_page', 'getsingle', array(
3295 'id' => ($props['contribution_page_id']),
3297 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3298 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3302 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3303 case 'honor_type_id':
3304 $className = 'CRM_Contribute_BAO_ContributionSoft';
3305 $fieldName = 'soft_credit_type_id';
3306 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3309 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3313 * Validate financial type.
3317 * @param int $financialTypeId
3318 * Financial Type id.
3320 * @param string $relationName
3322 * @return array|bool
3324 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3325 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3326 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3328 if (!$financialAccount) {
3329 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3336 * Function to record additional payment for partial and refund contributions.
3338 * @param int $contributionId
3339 * is the invoice contribution id (got created after processing participant payment).
3340 * @param array $trxnsData
3341 * to take user provided input of transaction details.
3342 * @param string $paymentType
3343 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3344 * @param int $participantId
3346 * @return null|object
3348 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3349 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3350 $getInfoOf['id'] = $contributionId;
3351 $defaults = array();
3352 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3354 if ($paymentType == 'owed') {
3355 // build params for recording financial trxn entry
3356 $params['contribution'] = $contributionDAO;
3357 $params = array_merge($defaults, $params);
3358 $params['skipLineItem'] = TRUE;
3359 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3360 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3361 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3362 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3365 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3366 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3367 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3369 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3370 if (!empty($trxnId)) {
3371 $trxnId = $trxnId['trxn_id'];
3373 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3374 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3377 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3378 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3379 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3383 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3384 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3385 FROM civicrm_financial_trxn ft
3386 LEFT JOIN civicrm_entity_financial_trxn eft
3387 ON (ft.id = eft.financial_trxn_id)
3388 WHERE eft.entity_table = 'civicrm_contribution'
3389 AND eft.entity_id = {$contributionId}
3390 AND ft.to_financial_account_id != {$toFinancialAccount}
3391 AND ft.status_id = {$statusId}
3393 $query = CRM_Core_DAO
::executeQuery($sql);
3395 $sumOfPayments = $query->sum_of_payments
;
3398 if ($contributionDAO->total_amount
== $sumOfPayments) {
3399 // update contribution status and
3400 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3401 $contributionDAO->contribution_status_id
= $statusId;
3402 $contributionDAO->cancel_date
= 'null';
3403 $contributionDAO->cancel_reason
= NULL;
3404 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3405 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3406 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3407 $contributionDAO->save();
3409 //Change status of financial record too
3410 $financialTrxn->status_id
= $statusId;
3411 $financialTrxn->save();
3413 // note : not using the self::add method,
3414 // the reason because it performs 'status change' related code execution for financial records
3415 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3416 // are coded below i.e. just updating financial_item status to 'Paid'
3418 if ($participantId) {
3419 // update participant status
3420 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3421 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3422 foreach ($ids as $val) {
3423 $participantUpdate['id'] = $val;
3424 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3425 CRM_Event_BAO_Participant
::add($participantUpdate);
3429 // update financial item statuses
3430 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3431 $paidStatus = array_search('Paid', $financialItemStatus);
3433 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3434 $sqlFinancialItemUpdate = "
3435 UPDATE civicrm_financial_item fi
3436 LEFT JOIN civicrm_entity_financial_trxn eft
3437 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3438 SET status_id = {$paidStatus}
3439 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3441 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3444 elseif ($paymentType == 'refund') {
3445 // build params for recording financial trxn entry
3446 $params['contribution'] = $contributionDAO;
3447 $params = array_merge($defaults, $params);
3448 $params['skipLineItem'] = TRUE;
3449 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3450 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3452 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3453 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3454 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3456 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3458 // note : not using the self::add method,
3459 // the reason because it performs 'status change' related code execution for financial records
3460 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3461 // are coded below i.e. just updating financial_item status to 'Paid'
3462 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3464 // add financial item entry
3465 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3466 $getLine['entity_id'] = $contributionDAO->id
;
3467 $getLine['entity_table'] = 'civicrm_contribution';
3468 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3469 if (!empty($lineItemId->id
)) {
3470 $addFinancialEntry = array(
3471 'transaction_date' => $financialTrxn->trxn_date
,
3472 'contact_id' => $contributionDAO->contact_id
,
3473 'amount' => $financialTrxn->total_amount
,
3474 'status_id' => array_search('Paid', $financialItemStatus),
3475 'entity_id' => $lineItemId->id
,
3476 'entity_table' => 'civicrm_line_item',
3478 $trxnIds['id'] = $financialTrxn->id
;
3479 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3481 if ($participantId) {
3482 // update participant status
3483 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3484 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3485 foreach ($ids as $val) {
3486 $participantUpdate['id'] = $val;
3487 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3488 CRM_Event_BAO_Participant
::add($participantUpdate);
3493 // activity creation
3494 if (!empty($financialTrxn)) {
3495 if ($participantId) {
3496 $inputParams['id'] = $participantId;
3499 $component = 'event';
3500 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3501 $entityObj = $entityObj[$participantId];
3503 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3505 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3507 return $financialTrxn;
3513 * @param $activityType
3515 * @param int $contributionId
3517 * @throws CRM_Core_Exception
3519 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3520 if ($component == 'event') {
3521 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3522 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3523 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3524 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3525 $targetCid = $entityObj->contact_id
;
3526 // source record id would be the contribution id
3527 $srcRecId = $contributionId;
3531 $activityParams = array(
3532 'source_contact_id' => $targetCid,
3533 'source_record_id' => $srcRecId,
3534 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3538 'subject' => $subject,
3539 'activity_date_time' => $date,
3540 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3544 'skipRecentView' => TRUE,
3547 // create activity with target contacts
3548 $session = CRM_Core_Session
::singleton();
3549 $id = $session->get('userID');
3551 $activityParams['source_contact_id'] = $id;
3552 $activityParams['target_contact_id'][] = $targetCid;
3554 CRM_Activity_BAO_Activity
::create($activityParams);
3558 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3562 * @param bool $getTrxnInfo
3563 * @param bool $usingLineTotal
3567 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3568 if ($component == 'event') {
3569 $entity = 'participant';
3570 $entityTable = 'civicrm_participant';
3571 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3573 if (!$contributionId) {
3574 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3575 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3576 $id = $primaryParticipantId;
3578 if (!$contributionId) {
3583 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3584 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3590 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3591 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3594 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3595 // for additional participants
3596 if ($entityTable == 'civicrm_participant') {
3597 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3599 foreach ($ids as $val) {
3600 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3604 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3608 $baseTrxnId = $total['trxn_id'];
3609 $total = $total['total_amount'];
3612 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3613 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3615 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3616 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3617 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3619 if ($paymentBalance == 0 && $contributionIsPayLater) {
3620 $paymentBalance = $total;
3623 $info['total'] = $total;
3624 $info['paid'] = $total - $paymentBalance;
3625 $info['balance'] = $paymentBalance;
3627 $info['component'] = $component;
3628 $info['payLater'] = $contributionIsPayLater;
3630 if ($getTrxnInfo && $baseTrxnId) {
3631 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3633 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3634 FROM civicrm_contribution con
3635 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3636 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3637 WHERE con.id = {$contributionId}
3640 // conditioned WHERE clause
3642 // if balance trxn exists don't include details of it in transaction info
3643 $sql .= " AND ft.id != {$baseTrxnId} ";
3645 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3647 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3648 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3649 while ($resultDAO->fetch()) {
3650 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3651 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3653 'total_amount' => $resultDAO->total_amount
,
3654 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3655 'payment_instrument' => $paidByLabel,
3656 'receive_date' => $resultDAO->trxn_date
,
3657 'trxn_id' => $resultDAO->trxn_id
,
3658 'status' => $statuses[$resultDAO->status_id
],
3660 if ($paidByName == 'Check') {
3661 $val['check_number'] = $resultDAO->check_number
;
3665 $info['transaction'] = $rows;
3671 * Get financial account id has 'Sales Tax Account is'
3672 * account relationship with financial type
3674 * @param int $financialTypeId
3676 * @return FinancialAccountId
3678 public static function getFinancialAccountId($financialTypeId) {
3679 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3680 $searchParams = array(
3681 'entity_table' => 'civicrm_financial_type',
3682 'entity_id' => $financialTypeId,
3683 'account_relationship' => $accountRel,
3686 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3688 return CRM_Utils_Array
::value('financial_account_id', $result);
3694 * @param array $params
3695 * @param bool $isLineItem
3699 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3700 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3702 // Update contribution.
3703 if (!empty($params['id'])) {
3704 $id = $params['id'];
3705 $values = $ids = array();
3706 $contrbutionParams = array('id' => $id);
3707 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3709 // To assign pervious finantial type on update of contribution
3710 if (!isset($params['financial_type_id'])) {
3711 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3713 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3714 // Assisn tax Amount on update of contrbution
3715 if (!empty($prevContributionValue->tax_amount
)) {
3716 $params['tax_amount'] = 'null';
3717 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3718 foreach ($params['line_item'] as $setID => $priceField) {
3719 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3720 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3727 // New Contrbution and update of contribution with tax rate financial type
3728 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3729 empty($params['skipLineItem']) && !$isLineItem
3731 $taxRateParams = $taxRates[$params['financial_type_id']];
3732 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3733 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3735 // Get Line Item on update of contribution
3736 if (isset($params['id'])) {
3737 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3740 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3742 foreach ($params['line_item'] as $setID => $priceField) {
3743 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3744 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3747 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3749 elseif (isset($params['api.line_item.create'])) {
3750 // Update total amount of contribution using lineItem
3751 $taxAmountArray = array();
3752 foreach ($params['api.line_item.create'] as $key => $value) {
3753 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3754 $taxRate = $taxRates[$value['financial_type_id']];
3755 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3756 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3759 $params['tax_amount'] = array_sum($taxAmountArray);
3760 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3763 // update line item of contrbution
3764 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3765 $taxRate = $taxRates[$params['financial_type_id']];
3766 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3767 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3774 * Check financial type validation on update of a contribution.
3776 * @param Integer $financialTypeId
3777 * Value of latest Financial Type.
3779 * @param Integer $contributionId
3782 * @param array $errors
3787 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3788 if (!empty($financialTypeId)) {
3789 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3790 if ($oldFinancialTypeId == $financialTypeId) {
3794 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3796 '1' => array($contributionId, 'Integer'),
3798 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3799 if ($result->N
> 1) {
3800 $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.');
3805 * Update related pledge payment payments.
3807 * This function has been refactored out of the back office contribution form and may
3808 * still overlap with other functions.
3810 * @param string $action
3811 * @param int $pledgePaymentID
3812 * @param int $contributionID
3813 * @param bool $adjustTotalAmount
3814 * @param float $total_amount
3815 * @param float $original_total_amount
3816 * @param int $contribution_status_id
3817 * @param int $original_contribution_status_id
3819 public static function updateRelatedPledge(
3825 $original_total_amount,
3826 $contribution_status_id,
3827 $original_contribution_status_id
3829 if (!$pledgePaymentID ||
$action & CRM_Core_Action
::ADD
&& !$contributionID) {
3833 if ($pledgePaymentID) {
3834 //store contribution id in payment record.
3835 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
3838 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3844 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3850 $updatePledgePaymentStatus = FALSE;
3852 // If either the status or the amount has changed we update the pledge status.
3853 if ($action & CRM_Core_Action
::ADD
) {
3854 $updatePledgePaymentStatus = TRUE;
3856 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
3857 ($original_total_amount != $total_amount))
3859 $updatePledgePaymentStatus = TRUE;
3862 if ($updatePledgePaymentStatus) {
3863 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
3864 array($pledgePaymentID),
3865 $contribution_status_id,
3874 * Compute the stats values
3876 * @param $stat either 'mode' or 'median'
3878 * @param $alias of civicrm_contribution
3880 public static function computeStats($stat, $sql, $alias = NULL) {
3881 $mode = $median = array();
3884 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
3885 while ($modeDAO->fetch()) {
3886 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
3887 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
3896 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
3897 foreach ($currencies as $currency => $val) {
3899 $where = "AND {$alias}.currency = '{$currency}'";
3900 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
3904 $medianRow = floor($rowCount / 2);
3905 if ($rowCount %
2 == 0 && !empty($medianRow)) {
3911 $medianValue = "SELECT {$alias}.total_amount as median
3913 ORDER BY median LIMIT {$medianRow},{$offset}";
3914 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
3915 while ($medianValDAO->fetch()) {
3917 $midValue = $midValue +
$medianValDAO->median
;
3920 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
3924 $midValue = $midValue / 2;
3925 $median[] = CRM_Utils_Money
::format($midValue, $currency);
3936 * Complete an order.
3938 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
3940 * Currently overloaded to complete a transaction & repeat a transaction - fix!
3942 * Moving it out of the BaseIPN class is just the first step.
3944 * @param array $input
3946 * @param array $objects
3947 * @param CRM_Core_Transaction $transaction
3949 * @param CRM_Contribute_BAO_Contribution $contribution
3950 * @param bool $isRecurring
3951 * Duplication of param needs review.
3952 * @param int $isFirstOrLastRecurringPayment
3954 public static function completeOrder(&$input, &$ids, $objects, &$transaction, $recur, $contribution, $isRecurring,
3955 $isFirstOrLastRecurringPayment) {
3956 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
3958 $participant = CRM_Utils_Array
::value('participant', $objects);
3959 $memberships = CRM_Utils_Array
::value('membership', $objects);
3960 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
3962 if (is_numeric($memberships)) {
3963 $memberships = array($objects['membership']);
3966 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
3969 if (isset($input['is_email_receipt'])) {
3970 $values['is_email_receipt'] = $input['is_email_receipt'];
3973 if ($input['component'] == 'contribute') {
3974 if ($contribution->contribution_page_id
) {
3975 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
3976 $source = ts('Online Contribution') . ': ' . $values['title'];
3978 elseif ($recurContrib && $recurContrib->id
) {
3979 $contribution->contribution_page_id
= NULL;
3980 $values['amount'] = $recurContrib->amount
;
3981 $values['financial_type_id'] = $objects['contributionType']->id
;
3982 $values['title'] = $source = ts('Offline Recurring Contribution');
3983 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
3984 $values['receipt_from_name'] = $domainValues[0];
3985 $values['receipt_from_email'] = $domainValues[1];
3988 if ($recurContrib && $recurContrib->id
&& !isset($input['is_email_receipt'])) {
3989 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
3990 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
3991 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
3994 $contribution->source
= $source;
3995 if (!empty($values['is_email_receipt'])) {
3996 $contribution->receipt_date
= $changeDate;
3999 if (!empty($memberships)) {
4000 $membershipsUpdate = array();
4001 foreach ($memberships as $membershipTypeIdKey => $membership) {
4005 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
4006 $membership->membership_type_id
,
4007 $membership->is_test
, $membership->id
4010 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4011 // this picks up membership type changes during renewals
4013 SELECT membership_type_id
4014 FROM civicrm_membership_log
4015 WHERE membership_id=$membership->id
4018 $dao = new CRM_Core_DAO();
4020 if ($dao->fetch()) {
4021 if (!empty($dao->membership_type_id
)) {
4022 $membership->membership_type_id
= $dao->membership_type_id
;
4023 $membership->save();
4025 // else fall back to using current membership type
4027 // else fall back to using current membership type
4030 $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id
, $primaryContributionID);
4031 if ($currentMembership) {
4033 * Fixed FOR CRM-4433
4034 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4035 * when Contribution mode is notify and membership is for renewal )
4037 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4039 // @todo - we should pass membership_type_id instead of null here but not
4040 // adding as not sure of testing
4041 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
4042 $changeDate, NULL, $num_terms
4045 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
4048 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $num_terms);
4051 //get the status for membership.
4052 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4054 $dates['join_date'],
4057 $membership->membership_type_id
,
4061 $formatedParams = array(
4062 'status_id' => CRM_Utils_Array
::value('id', $calcStatus, 2),
4063 'join_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('join_date', $dates), $format),
4064 'start_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('start_date', $dates), $format),
4065 'end_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('end_date', $dates), $format),
4067 //we might be renewing membership,
4068 //so make status override false.
4069 $formatedParams['is_override'] = FALSE;
4070 $membership->copyValues($formatedParams);
4071 $membership->save();
4073 //updating the membership log
4074 $membershipLog = array();
4075 $membershipLog = $formatedParams;
4077 $logStartDate = $formatedParams['start_date'];
4078 if (!empty($dates['log_start_date'])) {
4079 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
4080 $logStartDate = CRM_Utils_Date
::isoToMysql($logStartDate);
4083 $membershipLog['start_date'] = $logStartDate;
4084 $membershipLog['membership_id'] = $membership->id
;
4085 $membershipLog['modified_id'] = $membership->contact_id
;
4086 $membershipLog['modified_date'] = date('Ymd');
4087 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
4089 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
4091 //update related Memberships.
4092 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formatedParams);
4094 //update the membership type key of membership relatedObjects array
4095 //if it has changed after membership update
4096 if ($membershipTypeIdKey != $membership->membership_type_id
) {
4097 $membershipsUpdate[$membership->membership_type_id
] = $membership;
4098 $contribution->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4099 unset($contribution->_relatedObjects
['membership'][$membershipTypeIdKey]);
4100 unset($memberships[$membershipTypeIdKey]);
4104 //update the memberships object with updated membershipTypeId data
4105 //if membershipTypeId has changed after membership update
4106 if (!empty($membershipsUpdate)) {
4107 $memberships = $memberships +
$membershipsUpdate;
4113 $eventParams = array('id' => $objects['event']->id
);
4114 $values['event'] = array();
4116 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
4118 //get location details
4119 $locationParams = array('entity_id' => $objects['event']->id
, 'entity_table' => 'civicrm_event');
4120 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
4122 $ufJoinParams = array(
4123 'entity_table' => 'civicrm_event',
4124 'entity_id' => $ids['event'],
4125 'module' => 'CiviEvent',
4128 list($custom_pre_id,
4130 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
4132 $values['custom_pre_id'] = $custom_pre_id;
4133 $values['custom_post_id'] = $custom_post_ids;
4134 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
4135 //and cases involving status updation through ipn
4136 $values['totalAmount'] = $input['amount'];
4138 $contribution->source
= ts('Online Event Registration') . ': ' . $values['event']['title'];
4140 if ($values['event']['is_email_confirm']) {
4141 $contribution->receipt_date
= $changeDate;
4142 $values['is_email_receipt'] = 1;
4144 if (empty($input['skipComponentSync'])) {
4145 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array(
4146 'labelColumn' => 'name',
4149 $participant->status_id
= $participantStatuses['Registered'];
4151 $participant->save();
4154 if (CRM_Utils_Array
::value('net_amount', $input, 0) == 0 &&
4155 CRM_Utils_Array
::value('fee_amount', $input, 0) != 0
4157 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
4159 // This complete transaction function is being overloaded to create new contributions too.
4160 // here we record if it is a new contribution.
4161 // @todo separate the 2 more appropriately.
4162 $isNewContribution = FALSE;
4163 if (empty($contribution->id
)) {
4164 $isNewContribution = TRUE;
4165 if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount
) {
4166 $contribution->total_amount
= $input['amount'];
4167 // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner)
4168 // so we have to handle net_amount in this (naughty) code.
4169 if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) {
4170 $contribution->fee_amount
= $input['fee_amount'];
4172 $contribution->net_amount
= $contribution->total_amount
- $contribution->fee_amount
;
4174 if (!empty($input['campaign_id'])) {
4175 $contribution->campaign_id
= $input['campaign_id'];
4179 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4180 'labelColumn' => 'name',
4184 // @todo this section should call the api in order to have hooks called &
4185 // because all this 'messiness' setting variables could be avoided
4186 // by letting the api resolve pseudoconstants & copy set values and format dates.
4187 $contribution->contribution_status_id
= $contributionStatuses['Completed'];
4188 $contribution->is_test
= $input['is_test'];
4190 // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out.
4191 if (isset($input['net_amount'])) {
4192 $contribution->fee_amount
= CRM_Utils_Array
::value('fee_amount', $input, 0);
4194 if (isset($input['net_amount'])) {
4195 $contribution->net_amount
= $input['net_amount'];
4198 $contribution->trxn_id
= $input['trxn_id'];
4199 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4200 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
4201 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
4202 $contribution->cancel_date
= 'null';
4204 if (!empty($input['check_number'])) {
4205 $contribution->check_number
= $input['check_number'];
4208 if (!empty($input['payment_instrument_id'])) {
4209 $contribution->payment_instrument_id
= $input['payment_instrument_id'];
4212 if (!empty($contribution->id
)) {
4213 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4214 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4217 $contribution->save();
4219 // Add new soft credit against current $contribution.
4220 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4221 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4224 //add line items for recurring payments
4225 if (!empty($contribution->contribution_recur_id
)) {
4226 if ($isNewContribution) {
4227 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
4230 // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
4231 $input['line_item'] = array();
4235 //copy initial contribution custom fields for recurring contributions
4236 if ($recurContrib && $recurContrib->id
) {
4237 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($recurContrib->id
, $contribution->id
);
4240 $paymentProcessorId = '';
4241 if (isset($objects['paymentProcessor'])) {
4242 if (is_array($objects['paymentProcessor'])) {
4243 $paymentProcessorId = $objects['paymentProcessor']['id'];
4246 $paymentProcessorId = $objects['paymentProcessor']->id
;
4250 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4251 'labelColumn' => 'name',
4254 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4255 $input['payment_processor'] = $paymentProcessorId;
4257 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4258 $input['total_amount'] = $input['amount'];
4259 $input['contribution'] = $contribution;
4260 $input['financial_type_id'] = $contribution->financial_type_id
;
4262 if (!empty($contribution->_relatedObjects
['participant'])) {
4263 $input['contribution_mode'] = 'participant';
4264 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4265 $input['skipLineItem'] = 1;
4267 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4268 $input['skipLineItem'] = TRUE;
4269 $input['contribution_mode'] = 'membership';
4271 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4272 // and subsequent payments. In this case the line items are created at
4273 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4274 // and since the contribution is saved prior to this line there is always a contribution-id,
4275 // however there is never a prevContribution (which appears to mean original contribution not previous
4276 // contribution - or preUpdateContributionObject most accurately)
4277 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4278 // to mean "are we updating an exisitng pending contribution"
4279 //I was able to make the unit test complete as fataling here doesn't prevent
4280 // the contribution being created - but activities would not be created or emails sent
4282 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4284 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4285 $transaction->commit();
4287 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution);
4289 // create an activity record
4290 if ($input['component'] == 'contribute') {
4292 $targetContactID = NULL;
4293 if (!empty($ids['related_contact'])) {
4294 $targetContactID = $contribution->contact_id
;
4295 $contribution->contact_id
= $ids['related_contact'];
4297 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4301 CRM_Activity_BAO_Activity
::addActivity($participant);
4304 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4305 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4306 if (!array_key_exists('is_email_receipt', $values) ||
4307 $values['is_email_receipt'] == 1
4309 self
::sendMail($input, $ids, $objects, $values, $recur, FALSE);
4310 CRM_Core_Error
::debug_log_message("Receipt sent");
4313 CRM_Core_Error
::debug_log_message("Success: Database updated");
4315 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4316 $isFirstOrLastRecurringPayment);
4321 * Send receipt from contribution.
4323 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4325 * Note that the compose message part has been moved to contribution
4326 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4328 * @param array $input
4329 * Incoming data from Payment processor.
4331 * Related object IDs.
4333 * @param array $values
4334 * Values related to objects that have already been loaded.
4335 * @param bool $recur
4336 * Is it part of a recurring contribution.
4337 * @param bool $returnMessageText
4338 * Should text be returned instead of sent. This.
4339 * is because the function is also used to generate pdfs
4343 public static function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4344 $contribution = &$objects['contribution'];
4345 $input['is_recur'] = $recur;
4346 // set receipt from e-mail and name in value
4347 if (!$returnMessageText) {
4348 $session = CRM_Core_Session
::singleton();
4349 $userID = $session->get('userID');
4350 if (!empty($userID)) {
4351 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4352 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4353 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4356 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);