5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.3 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2013 |
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
33 * @copyright CiviCRM LLC (c) 2004-2013
37 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
40 * static field for all the contribution information that we can potentially import
45 static $_importableFields = NULL;
48 * static field for all the contribution information that we can potentially export
53 static $_exportableFields = NULL;
56 * field for all the objects related to this contribution
57 * @var array of objects (e.g membership object, participant object)
59 public $_relatedObjects = array();
62 * field for the component - either 'event' (participant) or 'contribute'
63 * (any item related to a contribution page e.g. membership, pledge, contribution)
64 * This is used for composing messages because they have dependency on the
65 * contribution_page or event page - although over time we may eliminate that
67 * @var string component or event
69 public $_component = NULL;
74 function __construct() {
75 parent
::__construct();
79 * takes an associative array and creates a contribution object
81 * the function extract all the params it needs to initialize the create a
82 * contribution object. the params array could contain additional unused name/value
85 * @param array $params (reference ) an assoc array of name/value pairs
86 * @param array $ids the array that holds all the db ids
88 * @return object CRM_Contribute_BAO_Contribution object
92 static function add(&$params, &$ids) {
97 $duplicates = array();
98 if (self
::checkDuplicate($params, $duplicates,
99 CRM_Utils_Array
::value('contribution', $ids)
101 $error = CRM_Core_Error
::singleton();
102 $d = implode(', ', $duplicates);
103 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
106 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
111 // first clean up all the money fields
112 $moneyFields = array(
116 'non_deductible_amount',
118 //if priceset is used, no need to cleanup money
119 if (CRM_Utils_Array
::value('skipCleanMoney', $params)) {
120 unset($moneyFields[0]);
123 foreach ($moneyFields as $field) {
124 if (isset($params[$field])) {
125 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
129 if (CRM_Utils_Array
::value('payment_instrument_id', $params)) {
130 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
131 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
132 $params['check_number'] = 'null';
136 // contribution status is missing, choose Completed as default status
137 if (!CRM_Utils_Array
::value('contribution_status_id', $params)) {
138 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
141 if (CRM_Utils_Array
::value('contribution', $ids)) {
142 CRM_Utils_Hook
::pre('edit', 'Contribution', $ids['contribution'], $params);
145 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
148 $contribution = new CRM_Contribute_BAO_Contribution();
149 $contribution->copyValues($params);
151 $contribution->id
= CRM_Utils_Array
::value('contribution', $ids);
153 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
154 $config = CRM_Core_Config
::singleton();
155 $contribution->currency
= $config->defaultCurrency
;
158 if (CRM_Utils_Array
::value('contribution', $ids)) {
159 $contributionId['id'] = $ids['contribution'];
160 $params['prevContribution'] = self
::getValues($contributionId, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
161 /*if (CRM_Utils_Array::value('soft_credit_to', $params)) {
162 foreach (array('financial_type_id', 'total_amount') as $field) {
163 if (!isset($contribution->$field)) {
164 $contribution->$field = $params['prevContribution']->$field;
170 $result = $contribution->save();
172 // Add financial_trxn details as part of fix for CRM-4724
173 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
174 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
176 //add Account details
177 $params['contribution'] = $contribution;
178 self
::recordFinancialAccounts($params, $ids);
180 // Add soft_contribution details as part of fix for CRM-8908
181 //$contribution->soft_credit_to = CRM_Utils_Array::value('soft_credit_to', $params);
183 // reset the group contact cache for this group
184 CRM_Contact_BAO_GroupContactCache
::remove();
186 if (CRM_Utils_Array
::value('contribution', $ids)) {
187 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
190 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
197 * Given the list of params in the params array, fetch the object
198 * and store the values in the values array
200 * @param array $params input parameters to find object
201 * @param array $values output values of the object
202 * @param array $ids the array that holds all the db ids
204 * @return CRM_Contribute_BAO_Contribution|null the found object or null
208 static function &getValues(&$params, &$values, &$ids) {
209 if (empty($params)) {
212 $contribution = new CRM_Contribute_BAO_Contribution();
214 $contribution->copyValues($params);
216 if ($contribution->find(TRUE)) {
217 $ids['contribution'] = $contribution->id
;
219 CRM_Core_DAO
::storeValues($contribution, $values);
221 return $contribution;
227 * takes an associative array and creates a contribution object
229 * @param array $params (reference ) an assoc array of name/value pairs
230 * @param array $ids the array that holds all the db ids
232 * @return object CRM_Contribute_BAO_Contribution object
236 static function &create(&$params, &$ids) {
237 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
238 foreach ($dateFields as $df) {
239 if (isset($params[$df])) {
240 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
244 /*if (CRM_Utils_Array::value('contribution', $ids) &&
245 !CRM_Utils_Array::value('softID', $params)
247 if ($softID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionSoft', $ids['contribution'], 'id', 'contribution_id')) {
248 $params['softID'] = $softID;
252 $transaction = new CRM_Core_Transaction();
254 // delete the soft credit record if no soft credit contact ID AND no PCP is set in the form
255 /*if (CRM_Utils_Array::value('contribution', $ids) &&
256 (!CRM_Utils_Array::value('soft_credit_to', $params) &&
257 !CRM_Utils_Array::value('pcp_made_through_id', $params)
259 CRM_Utils_Array::value('softID', $params)
261 $softCredit = new CRM_Contribute_DAO_ContributionSoft();
262 $softCredit->id = $params['softID'];
263 $softCredit->delete();
266 $contribution = self
::add($params, $ids);
268 /* if (CRM_Utils_Array::value('deleteSoftCredit', $params, TRUE)) {
269 // first delete soft credits if any
270 CRM_Contribute_BAO_ContributionSoft::del($contribution->id);
272 if ($pcp = CRM_Utils_Array::value('pcp_made_through_id', $params)) {
273 $softParams = array();
274 $softParams['contribution_id'] = $contribution->id;
275 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
276 $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
277 $pcp['pcp_id'], 'contact_id'
279 $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
280 $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
281 $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
282 CRM_Contribute_BAO_ContributionSoft::add($softParams);
284 elseif (CRM_Utils_Array::value('soft_credit', $params)) {
285 $softParams = $params['soft_credit'];
286 foreach ($softParams as $softParam) {
287 $softParam['contribution_id'] = $contribution->id;
288 $softParam['currency'] = $contribution->currency;
289 CRM_Contribute_BAO_ContributionSoft::add($softParam);
294 if (is_a($contribution, 'CRM_Core_Error')) {
295 $transaction->rollback();
296 return $contribution;
299 $params['contribution_id'] = $contribution->id
;
301 if (CRM_Utils_Array
::value('custom', $params) &&
302 is_array($params['custom'])
304 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
307 $session = CRM_Core_Session
::singleton();
309 if (CRM_Utils_Array
::value('note', $params)) {
312 'entity_table' => 'civicrm_contribution',
313 'note' => $params['note'],
314 'entity_id' => $contribution->id
,
315 'contact_id' => $session->get('userID'),
316 'modified_date' => date('Ymd'),
318 if (!$noteParams['contact_id']) {
319 $noteParams['contact_id'] = $params['contact_id'];
321 CRM_Core_BAO_Note
::add($noteParams,
322 CRM_Utils_Array
::value('note', $ids)
326 // make entry in batch entity batch table
327 if (CRM_Utils_Array
::value('batch_id', $params)) {
328 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
329 $titleFields = array(
335 $retrieverequired = 0;
336 foreach ($titleFields as $titleField) {
337 if(!isset($contribution->$titleField)){
338 $retrieverequired = 1;
342 if ($retrieverequired == 1) {
343 $contribution->find(true);
347 // check if activity record exist for this contribution, if
349 $activity = new CRM_Activity_DAO_Activity();
350 $activity->source_record_id
= $contribution->id
;
351 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
355 if (!$activity->find()) {
356 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
358 // Handle soft credit and / or link to personal campaign page
359 if (CRM_Utils_Array
::value('deleteSoftCredit', $params, TRUE)) {
360 // first delete soft credits if any
361 CRM_Contribute_BAO_ContributionSoft
::del($contribution->id
);
363 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
364 $softParams = array();
365 $softParams['contribution_id'] = $contribution->id
;
366 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
367 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
368 $pcp['pcp_made_through_id'], 'contact_id'
370 $softParams['currency'] = $contribution->currency
;
371 $softParams['amount'] = $contribution->total_amount
;
372 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
373 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
374 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
375 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
377 elseif (CRM_Utils_Array
::value('soft_credit', $params)) {
378 $softParams = $params['soft_credit'];
379 foreach ($softParams as $softParam) {
380 $softParam['contribution_id'] = $contribution->id
;
381 $softParam['currency'] = $contribution->currency
;
382 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
386 /* if (CRM_Utils_Array::value('soft_credit_to', $params) ||
387 CRM_Utils_Array::value('pcp_made_through_id', $params)
390 if ($id = CRM_Utils_Array::value('softID', $params)) {
391 $csParams['id'] = $params['softID'];
394 $csParams['contribution_id'] = $contribution->id;
395 // If pcp_made_through_id set, we define soft_credit_to contact based on selected PCP,
396 // else use passed soft_credit_to
397 if (CRM_Utils_Array::value('pcp_made_through_id', $params)) {
398 $csParams['pcp_display_in_roll'] = $params['pcp_display_in_roll'] ? 1 : 0;
400 'pcp_roll_nickname', 'pcp_personal_note') as $val) {
401 $csParams[$val] = $params[$val];
404 $csParams['pcp_id'] = CRM_Utils_Array::value('pcp_made_through_id', $params);
405 $csParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
406 $csParams['pcp_id'], 'contact_id'
410 $csParams['contact_id'] = $params['soft_credit_to'];
411 $csParams['pcp_id'] = '';
414 // first stage: we register whole amount as credited to given person
415 $csParams['amount'] = $contribution->total_amount;
417 self::addSoftContribution($csParams);
420 $transaction->commit();
422 // do not add to recent items for import, CRM-4399
423 if (!CRM_Utils_Array
::value('skipRecentView', $params)) {
424 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
425 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
427 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
428 $titleFields = array(
434 $retrieverequired = 0;
435 foreach ($titleFields as $titleField) {
436 if(!isset($contribution->$titleField)){
437 $retrieverequired = 1;
441 if($retrieverequired == 1){
442 $contribution->find(true);
444 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
445 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
447 $recentOther = array();
448 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
449 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
450 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
454 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
455 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
456 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
460 // add the recently created Contribution
461 CRM_Utils_Recent
::add($title,
465 $contribution->contact_id
,
471 return $contribution;
475 * Get the values for pseudoconstants for name->value and reverse.
477 * @param array $defaults (reference) the default values, some of which need to be resolved.
478 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
484 static function resolveDefaults(&$defaults, $reverse = FALSE) {
485 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
486 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
487 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
488 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
492 * This function is used to convert associative array names to values
495 * This function is used by both the web form layer and the api. Note that
496 * the api needs the name => value conversion, also the view layer typically
497 * requires value => name conversion
499 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
500 $id = $property . '_id';
502 $src = $reverse ?
$property : $id;
503 $dst = $reverse ?
$id : $property;
505 if (!array_key_exists($src, $defaults)) {
509 $look = $reverse ?
array_flip($lookup) : $lookup;
511 if (is_array($look)) {
512 if (!array_key_exists($defaults[$src], $look)) {
516 $defaults[$dst] = $look[$defaults[$src]];
521 * Takes a bunch of params that are needed to match certain criteria and
522 * retrieves the relevant objects. We'll tweak this function to be more
523 * full featured over a period of time. This is the inverse function of
524 * create. It also stores all the retrieved values in the default array
526 * @param array $params (reference ) an assoc array of name/value pairs
527 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
528 * in a hierarchical manner
529 * @param array $ids (reference) the array that holds all the db ids
531 * @return object CRM_Contribute_BAO_Contribution object
535 static function retrieve(&$params, &$defaults, &$ids) {
536 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
537 return $contribution;
541 * combine all the importable fields from the lower levels object
543 * The ordering is important, since currently we do not have a weight
544 * scheme. Adding weight is super important and should be done in the
545 * next week or so, before this can be called complete.
547 * @return array array of importable Fields
551 static function &importableFields($contacType = 'Individual', $status = TRUE) {
552 if (!self
::$_importableFields) {
553 if (!self
::$_importableFields) {
554 self
::$_importableFields = array();
558 $fields = array('' => array('title' => ts('- do not import -')));
561 $fields = array('' => array('title' => ts('- Contribution Fields -')));
564 $note = CRM_Core_DAO_Note
::import();
565 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
566 unset($tmpFields['option_value']);
567 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
568 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contacType, NULL);
570 // Using new Dedupe rule.
572 'contact_type' => $contacType,
573 'used' => 'Unsupervised',
575 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
576 $tmpConatctField = array();
577 if (is_array($fieldsArray)) {
578 foreach ($fieldsArray as $value) {
579 //skip if there is no dupe rule
580 if ($value == 'none') {
583 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
588 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
589 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
591 $title = $tmpConatctField[trim($value)]['title'] . ' ' . ts('(match to contact)');
594 $title = $tmpConatctField[trim($value)]['title'];
596 $tmpConatctField[trim($value)]['title'] = $title;
600 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
601 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
602 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
603 $fields = array_merge($fields, $tmpConatctField);
604 $fields = array_merge($fields, $tmpFields);
605 $fields = array_merge($fields, $note);
606 $fields = array_merge($fields, $optionFields);
607 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
608 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
609 self
::$_importableFields = $fields;
611 return self
::$_importableFields;
614 static function &exportableFields() {
615 if (!self
::$_exportableFields) {
616 if (!self
::$_exportableFields) {
617 self
::$_exportableFields = array();
620 $impFields = CRM_Contribute_DAO_Contribution
::export();
621 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
622 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
623 $typeField = CRM_Financial_DAO_FinancialType
::export();
624 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
625 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
626 $contributionStatus = array(
627 'contribution_status' => array(
628 'title' => ts('Contribution Status'),
629 'name' => 'contribution_status',
630 'data_type' => CRM_Utils_Type
::T_STRING
633 $contributionNote = array(
634 'contribution_note' =>
636 'title' => ts('Contribution Note'),
637 'name' => 'contribution_note',
638 'data_type' => CRM_Utils_Type
::T_TEXT
642 $contributionRecurId = array(
643 'contribution_recur_id' =>
645 'title' => ts('Recurring Contributions ID'),
646 'name' => 'contribution_recur_id',
647 'where' => 'civicrm_contribution.contribution_recur_id',
648 'data_type' => CRM_Utils_Type
::T_INT
651 $extraFields = array(
652 'contribution_campaign' =>
654 'title' => ts('Campaign Title')
656 'contribution_batch' =>
658 'title' => ts('Batch Name')
662 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
663 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $financialAccount,
664 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
667 self
::$_exportableFields = $fields;
670 return self
::$_exportableFields;
673 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
677 $where[] = 'contribution_status_id = 1';
681 $where[] = 'contribution_status_id = 3';
686 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
689 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
692 $whereCond = implode(' AND ', $where);
695 SELECT sum( total_amount ) as total_amount,
696 count( civicrm_contribution.id ) as total_count,
698 FROM civicrm_contribution
699 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
701 AND ( is_test = 0 OR is_test IS NULL )
702 AND contact.is_deleted = 0
706 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
709 while ($dao->fetch()) {
710 $count +
= $dao->total_count
;
711 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
714 return array('amount' => implode(', ', $amount),
722 * Delete the indirect records associated with this contribution first
724 * @return $results no of deleted Contribution on success, false otherwise
728 static function deleteContribution($id) {
729 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
731 $transaction = new CRM_Core_Transaction();
734 //delete activity record
736 'source_record_id' => $id,
737 // activity type id for contribution
738 'activity_type_id' => 6,
741 CRM_Activity_BAO_Activity
::deleteActivity($params);
743 //delete billing address if exists for this contribution.
744 self
::deleteAddress($id);
746 //update pledge and pledge payment, CRM-3961
747 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
749 // remove entry from civicrm_price_set_entity, CRM-5095
750 if (CRM_Price_BAO_Set
::getFor('civicrm_contribution', $id)) {
751 CRM_Price_BAO_Set
::removeFrom('civicrm_contribution', $id);
753 // cleanup line items.
754 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
756 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
757 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
759 if ($participantId) {
760 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
763 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
767 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
768 $noteId = key($note);
770 CRM_Core_BAO_Note
::del($noteId, FALSE);
773 $dao = new CRM_Contribute_DAO_Contribution();
776 $results = $dao->delete();
778 $transaction->commit();
780 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
782 // delete the recently created Contribution
783 $contributionRecent = array(
785 'type' => 'Contribution',
787 CRM_Utils_Recent
::del($contributionRecent);
793 * Check if there is a contribution with the same trxn_id or invoice_id
795 * @param array $params (reference ) an assoc array of name/value pairs
796 * @param array $duplicates (reference ) store ids of duplicate contribs
798 * @return boolean true if duplicate, false otherwise
802 static function checkDuplicate($input, &$duplicates, $id = NULL) {
804 $id = CRM_Utils_Array
::value('id', $input);
806 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
807 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
813 $clause[] = "trxn_id = %1";
814 $input[1] = array($trxn_id, 'String');
818 $clause[] = "invoice_id = %2";
819 $input[2] = array($invoice_id, 'String');
822 if (empty($clause)) {
826 $clause = implode(' OR ', $clause);
828 $clause = "( $clause ) AND id != %3";
829 $input[3] = array($id, 'Integer');
832 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
833 $dao = CRM_Core_DAO
::executeQuery($query, $input);
835 while ($dao->fetch()) {
836 $duplicates[] = $dao->id
;
843 * takes an associative array and creates a contribution_product object
845 * the function extract all the params it needs to initialize the create a
846 * contribution_product object. the params array could contain additional unused name/value
849 * @param array $params (reference ) an assoc array of name/value pairs
851 * @return object CRM_Contribute_BAO_ContributionProduct object
855 static function addPremium(&$params) {
856 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
857 $contributionProduct->copyValues($params);
858 return $contributionProduct->save();
862 * Function to get list of contribution fields for profile
863 * For now we only allow custom contribution fields to be in
866 * @param boolean $addExtraFields true if special fields needs to be added
868 * @return return the list of contribution fields
872 static function getContributionFields($addExtraFields = TRUE) {
873 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
874 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
876 if ($addExtraFields) {
877 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
880 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
882 foreach ($contributionFields as $key => $var) {
883 if ($key == 'contribution_contact_id') {
886 elseif ($key == 'contribution_campaign_id') {
887 $var['title'] = ts('Campaign');
889 $fields[$key] = $var;
892 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
897 * Function to add extra fields specific to contribtion
901 static function getSpecialContributionFields() {
902 $extraFields = array(
903 'honor_contact_name' => array(
904 'name' => 'honor_contact_name',
905 'title' => 'Honor Contact Name',
906 'headerPattern' => '/^honor_contact_name$/i',
907 'where' => 'civicrm_contact_c.display_name',
909 'honor_contact_email' => array(
910 'name' => 'honor_contact_email',
911 'title' => 'Honor Contact Email',
912 'headerPattern' => '/^honor_contact_email$/i',
913 'where' => 'honor_email.email',
915 'honor_contact_id' => array(
916 'name' => 'honor_contact_id',
917 'title' => 'Honor Contact ID',
918 'headerPattern' => '/^honor_contact_id$/i',
919 'where' => 'civicrm_contribution.honor_contact_id',
921 'honor_type_label' => array(
922 'name' => 'honor_type_label',
923 'title' => 'Honor Type Label',
924 'headerPattern' => '/^honor_type_label$/i',
925 'where' => 'honor_type.label',
927 'soft_credit_name' => array(
928 'name' => 'soft_credit_name',
929 'title' => 'Soft Credit Name',
930 'headerPattern' => '/^soft_credit_name$/i',
931 'where' => 'civicrm_contact_d.display_name',
933 'soft_credit_email' => array(
934 'name' => 'soft_credit_email',
935 'title' => 'Soft Credit Email',
936 'headerPattern' => '/^soft_credit_email$/i',
937 'where' => 'soft_email.email',
939 'soft_credit_phone' => array(
940 'name' => 'soft_credit_phone',
941 'title' => 'Soft Credit Phone',
942 'headerPattern' => '/^soft_credit_phone$/i',
943 'where' => 'soft_phone.phone',
945 'soft_credit_contact_id' => array(
946 'name' => 'soft_credit_contact_id',
947 'title' => 'Soft Credit Contact ID',
948 'headerPattern' => '/^soft_credit_contact_id$/i',
949 'where' => 'civicrm_contribution_soft.contact_id',
956 static function getCurrentandGoalAmount($pageID) {
958 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
959 FROM civicrm_contribution_page p,
960 civicrm_contribution c
961 WHERE p.id = c.contribution_page_id
963 AND c.cancel_date is null
967 $config = CRM_Core_Config
::singleton();
968 $params = array(1 => array($pageID, 'Integer'));
969 $dao = CRM_Core_DAO
::executeQuery($query, $params);
972 return array($dao->goal
, $dao->total
);
975 return array(NULL, NULL);
980 * Function to create is honor of
982 * @param array $params associated array of fields (by reference)
983 * @param int $honorId honor Id
984 * @param array $honorParams any params that should be send to the create function
988 static function createHonorContact(&$params, $honorId = NULL, $honorParams = array()) {
989 $honorParams = array_merge(
991 'first_name' => $params['honor_first_name'],
992 'last_name' => $params['honor_last_name'],
993 'prefix_id' => $params['honor_prefix_id'],
994 'email-Primary' => $params['honor_email'],
999 $honorParams['email'] = $params['honor_email'];
1001 $dedupeParams = CRM_Dedupe_Finder
::formatParams($honorParams, 'Individual');
1002 $dedupeParams['check_permission'] = FALSE;
1003 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
1005 // if we find more than one contact, use the first one
1006 $honorId = CRM_Utils_Array
::value(0, $ids);
1009 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
1011 CRM_Core_DAO
::$_nullArray,
1018 * Function to get list of contribution In Honor of contact Ids
1020 * @param int $honorId In Honor of Contact ID
1022 * @return return the list of contribution fields
1027 static function getHonorContacts($honorId) {
1029 $honorDAO = new CRM_Contribute_DAO_Contribution();
1030 $honorDAO->honor_contact_id
= $honorId;
1033 $status = CRM_Contribute_PseudoConstant
::contributionStatus($honorDAO->contribution_status_id
);
1034 $type = CRM_Contribute_PseudoConstant
::financialType();
1036 while ($honorDAO->fetch()) {
1037 $params[$honorDAO->id
]['honorId'] = $honorDAO->contact_id
;
1038 $params[$honorDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $honorDAO->contact_id
, 'display_name');
1039 $params[$honorDAO->id
]['type'] = $type[$honorDAO->financial_type_id
];
1040 $params[$honorDAO->id
]['type_id'] = $honorDAO->financial_type_id
;
1041 $params[$honorDAO->id
]['amount'] = CRM_Utils_Money
::format($honorDAO->total_amount
, $honorDAO->currency
);
1042 $params[$honorDAO->id
]['source'] = $honorDAO->source
;
1043 $params[$honorDAO->id
]['receive_date'] = $honorDAO->receive_date
;
1044 $params[$honorDAO->id
]['contribution_status'] = CRM_Utils_Array
::value($honorDAO->contribution_status_id
, $status);
1051 * function to get the sort name of a contact for a particular contribution
1053 * @param int $id id of the contribution
1055 * @return null|string sort name of the contact if found
1059 static function sortName($id) {
1060 $id = CRM_Utils_Type
::escape($id, 'Integer');
1063 SELECT civicrm_contact.sort_name
1064 FROM civicrm_contribution, civicrm_contact
1065 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1066 AND civicrm_contribution.id = {$id}
1068 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1071 static function annual($contactID) {
1072 if (is_array($contactID)) {
1073 $contactIDs = implode(',', $contactID);
1076 $contactIDs = $contactID;
1079 $config = CRM_Core_Config
::singleton();
1080 $startDate = $endDate = NULL;
1082 $currentMonth = date('m');
1083 $currentDay = date('d');
1084 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1085 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1086 (int ) $config->fiscalYearStart
['d'] > $currentDay
1089 $year = date('Y') - 1;
1094 $nextYear = $year +
1;
1096 if ($config->fiscalYearStart
) {
1097 if ($config->fiscalYearStart
['M'] < 10) {
1098 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1100 if ($config->fiscalYearStart
['d'] < 10) {
1101 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1103 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1108 $startDate = "$year$monthDay";
1109 $endDate = "$nextYear$monthDay";
1112 SELECT count(*) as count,
1113 sum(total_amount) as amount,
1114 avg(total_amount) as average,
1116 FROM civicrm_contribution b
1117 WHERE b.contact_id IN ( $contactIDs )
1118 AND b.contribution_status_id = 1
1120 AND b.receive_date >= $startDate
1121 AND b.receive_date < $endDate
1124 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1126 $amount = $average = array();
1127 while ($dao->fetch()) {
1128 if ($dao->count
> 0 && $dao->amount
> 0) {
1129 $count +
= $dao->count
;
1130 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1131 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1137 implode(', ', $amount),
1138 implode(', ', $average),
1141 return array(0, 0, 0);
1145 * Check if there is a contribution with the params passed in.
1146 * Used for trxn_id,invoice_id and contribution_id
1148 * @param array $params an assoc array of name/value pairs
1150 * @return array contribution id if success else NULL
1154 static function checkDuplicateIds($params) {
1155 $dao = new CRM_Contribute_DAO_Contribution();
1159 foreach ($params as $k => $v) {
1161 $clause[] = "$k = '$v'";
1164 $clause = implode(' AND ', $clause);
1165 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1166 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1168 while ($dao->fetch()) {
1176 * Function to get the contribution details for component export
1178 * @param int $exportMode export mode
1179 * @param string $componentIds component ids
1181 * @return array associated array
1186 static function getContributionDetails($exportMode, $componentIds) {
1187 $paymentDetails = array();
1188 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1190 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1191 $componentSelect = " civicrm_participant_payment.participant_id id";
1192 $additionalClause = "
1193 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1194 AND civicrm_participant_payment.participant_id {$componentClause} )
1197 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1198 $componentSelect = " civicrm_membership_payment.membership_id id";
1199 $additionalClause = "
1200 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1201 AND civicrm_membership_payment.membership_id {$componentClause} )
1204 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1205 $componentSelect = " civicrm_pledge_payment.id id";
1206 $additionalClause = "
1207 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1208 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1212 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1213 trxn_id, {$componentSelect}
1214 FROM civicrm_contribution
1215 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1216 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1217 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1218 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1219 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1220 AND option_group_contribution_status.id = contribution_status.option_group_id )
1224 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1226 while ($dao->fetch()) {
1227 $paymentDetails[$dao->id
] = array(
1228 'total_amount' => $dao->total_amount
,
1229 'contribution_status' => $dao->status
,
1230 'receive_date' => $dao->receive_date
,
1231 'pay_instru' => $dao->payment_instrument
,
1232 'trxn_id' => $dao->trxn_id
,
1236 return $paymentDetails;
1240 * Function to create address associated with contribution record.
1241 * @param array $params an associated array
1242 * @param int $billingID $billingLocationTypeID
1244 * @return address id
1247 static function createAddress(&$params, $billingLocationTypeID) {
1248 $billingFields = array(
1251 'state_province_id',
1256 //build address array
1257 $addressParams = array();
1258 $addressParams['location_type_id'] = $billingLocationTypeID;
1259 $addressParams['is_billing'] = 1;
1260 $addressParams['address_name'] = "{$params['billing_first_name']}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$params['billing_middle_name']}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$params['billing_last_name']}";
1262 foreach ($billingFields as $value) {
1263 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"];
1266 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1268 return $address->id
;
1272 * Function to create soft contributon with contribution record.
1273 * @param array $params an associated array
1275 * @return soft contribution id
1278 static function addSoftContribution($params) {
1279 $softContribution = new CRM_Contribute_DAO_ContributionSoft();
1280 $softContribution->copyValues($params);
1282 // set currency for CRM-1496
1283 if (!isset($softContribution->currency
)) {
1284 $config = CRM_Core_Config
::singleton();
1285 $softContribution->currency
= $config->defaultCurrency
;
1288 return $softContribution->save();
1292 * Function to retrieve soft contributon for contribution record.
1293 * @param array $params an associated array
1295 * @return soft contribution id
1298 static function getSoftContribution($params, $all = FALSE) {
1299 $cs = new CRM_Contribute_DAO_ContributionSoft();
1300 $cs->copyValues($params);
1301 $softContribution = array();
1302 if ($cs->find(TRUE)) {
1305 'pcp_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note') as $key => $val) {
1306 $softContribution[$val] = $cs->$val;
1309 $softContribution['soft_credit_to'] = $cs->contact_id
;
1310 $softContribution['soft_credit_id'] = $cs->id
;
1313 return $softContribution;
1317 * Function to retrieve the list of soft contributons for given contact.
1318 * @param int $contact_id contact id
1323 static function getSoftContributionList($contact_id, $isTest = 0) {
1325 SELECT ccs.id, ccs.amount as amount,
1326 ccs.contribution_id,
1328 ccs.pcp_display_in_roll,
1329 ccs.pcp_roll_nickname,
1330 ccs.pcp_personal_note,
1332 cc.contact_id as contributor_id,
1333 cc.contribution_status_id as contribution_status_id,
1334 cp.title as pcp_title,
1336 contact.display_name,
1337 cct.name as contributionType
1338 FROM civicrm_contribution_soft ccs
1339 LEFT JOIN civicrm_contribution cc
1340 ON ccs.contribution_id = cc.id
1341 LEFT JOIN civicrm_pcp cp
1342 ON ccs.pcp_id = cp.id
1343 LEFT JOIN civicrm_contact contact
1344 ON ccs.contribution_id = cc.id AND
1345 cc.contact_id = contact.id
1346 LEFT JOIN civicrm_financial_type cct
1347 ON cc.financial_type_id = cct.id
1348 WHERE cc.is_test = %2 AND ccs.contact_id = %1
1349 ORDER BY cc.receive_date DESC";
1351 $params = array(1 => array($contact_id, 'Integer'),
1352 2 => array($isTest, 'Integer'));
1353 $cs = CRM_Core_DAO
::executeQuery($query, $params);
1354 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus();
1356 while ($cs->fetch()) {
1357 $result[$cs->id
]['amount'] = $cs->amount
;
1358 $result[$cs->id
]['currency'] = $cs->currency
;
1359 $result[$cs->id
]['contributor_id'] = $cs->contributor_id
;
1360 $result[$cs->id
]['contribution_id'] = $cs->contribution_id
;
1361 $result[$cs->id
]['contributor_name'] = $cs->display_name
;
1362 $result[$cs->id
]['financial_type'] = $cs->contributionType
;
1363 $result[$cs->id
]['receive_date'] = $cs->receive_date
;
1364 $result[$cs->id
]['pcp_id'] = $cs->pcp_id
;
1365 $result[$cs->id
]['pcp_title'] = $cs->pcp_title
;
1366 $result[$cs->id
]['pcp_display_in_roll'] = $cs->pcp_display_in_roll
;
1367 $result[$cs->id
]['pcp_roll_nickname'] = $cs->pcp_roll_nickname
;
1368 $result[$cs->id
]['pcp_personal_note'] = $cs->pcp_personal_note
;
1369 $result[$cs->id
]['contribution_status'] = CRM_Utils_Array
::value($cs->contribution_status_id
, $contributionStatus);
1372 $result[$cs->id
]['contribution_status'] = $result[$cs->id
]['contribution_status'] . '<br /> (test)';
1378 static function getSoftContributionTotals($contact_id, $isTest = 0) {
1380 SELECT SUM(amount) as amount,
1381 AVG(total_amount) as average,
1383 FROM civicrm_contribution_soft ccs
1384 LEFT JOIN civicrm_contribution cc
1385 ON ccs.contribution_id = cc.id
1386 WHERE cc.is_test = %2 AND
1388 GROUP BY currency ";
1390 $params = array(1 => array($contact_id, 'Integer'),
1391 2 => array($isTest, 'Integer'));
1393 $cs = CRM_Core_DAO
::executeQuery($query, $params);
1396 $amount = $average = array();
1398 while ($cs->fetch()) {
1399 if ($cs->amount
> 0) {
1401 $amount[] = $cs->amount
;
1402 $average[] = $cs->average
;
1403 $currency[] = $cs->currency
;
1408 return array(implode(', ', $amount),
1409 implode(', ', $average),
1410 implode(', ', $currency),
1417 * Delete billing address record related contribution
1419 * @param int $contact_id contact id
1420 * @param int $contribution_id contributionId
1424 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1426 $contactJoin = NULL;
1428 if ($contributionId) {
1429 $clauses[] = "cc.id = {$contributionId}";
1433 $clauses[] = "cco.id = {$contactId}";
1434 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1437 if (empty($clauses)) {
1438 CRM_Core_Error
::fatal();
1441 $condition = implode(' OR ', $clauses);
1445 FROM civicrm_address ca
1446 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1450 $dao = CRM_Core_DAO
::executeQuery($query);
1452 while ($dao->fetch()) {
1453 $params = array('id' => $dao->id
);
1454 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1459 * This function check online pending contribution associated w/
1460 * Online Event Registration or Online Membership signup.
1462 * @param int $componentId participant/membership id.
1463 * @param string $componentName Event/Membership.
1465 * @return $contributionId pending contribution id.
1468 static function checkOnlinePendingContribution($componentId, $componentName) {
1469 $contributionId = NULL;
1470 if (!$componentId ||
1471 !in_array($componentName, array('Event', 'Membership'))
1473 return $contributionId;
1476 if ($componentName == 'Event') {
1477 $idName = 'participant_id';
1478 $componentTable = 'civicrm_participant';
1479 $paymentTable = 'civicrm_participant_payment';
1480 $source = ts('Online Event Registration');
1483 if ($componentName == 'Membership') {
1484 $idName = 'membership_id';
1485 $componentTable = 'civicrm_membership';
1486 $paymentTable = 'civicrm_membership_payment';
1487 $source = ts('Online Contribution');
1490 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1493 SELECT component.id as {$idName},
1494 componentPayment.contribution_id as contribution_id,
1495 contribution.source source,
1496 contribution.contribution_status_id as contribution_status_id,
1497 contribution.is_pay_later as is_pay_later
1498 FROM $componentTable component
1499 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1500 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1501 WHERE component.id = {$componentId}";
1503 $dao = CRM_Core_DAO
::executeQuery($query);
1505 while ($dao->fetch()) {
1506 if ($dao->contribution_id
&&
1507 $dao->is_pay_later
&&
1508 $dao->contribution_status_id
== $pendingStatusId &&
1509 strpos($dao->source
, $source) !== FALSE
1511 $contributionId = $dao->contribution_id
;
1516 return $contributionId;
1520 * This function update contribution as well as related objects.
1522 function transitionComponents($params, $processContributionObject = FALSE) {
1523 // get minimum required values.
1524 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1525 $componentId = CRM_Utils_Array
::value('component_id', $params);
1526 $componentName = CRM_Utils_Array
::value('componentName', $params);
1527 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1528 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1530 // if we already processed contribution object pass previous status id.
1531 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1533 $updateResult = array();
1535 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1537 // we process only ( Completed, Cancelled, or Failed ) contributions.
1538 if (!$contributionId ||
1539 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1540 array_search('Cancelled', $contributionStatuses),
1541 array_search('Failed', $contributionStatuses),
1544 return $updateResult;
1547 if (!$componentName ||
!$componentId) {
1548 // get the related component details.
1549 $componentDetails = self
::getComponentDetails($contributionId);
1552 $componentDetails['contact_id'] = $contactId;
1553 $componentDetails['component'] = $componentName;
1555 if ($componentName == 'event') {
1556 $componentDetails['participant'] = $componentId;
1559 $componentDetails['membership'] = $componentId;
1563 if (CRM_Utils_Array
::value('contact_id', $componentDetails)) {
1564 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1570 // do check for required ids.
1571 if (!CRM_Utils_Array
::value('membership', $componentDetails) &&
1572 !CRM_Utils_Array
::value('participant', $componentDetails) &&
1573 !CRM_Utils_Array
::value('pledge_payment', $componentDetails) ||
1574 !CRM_Utils_Array
::value('contact_id', $componentDetails)
1576 return $updateResult;
1579 //now we are ready w/ required ids, start processing.
1581 $baseIPN = new CRM_Core_Payment_BaseIPN();
1583 $input = $ids = $objects = array();
1585 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1586 $ids['contribution'] = $contributionId;
1587 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1588 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1589 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1590 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1591 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1592 $ids['contributionRecur'] = NULL;
1593 $ids['contributionPage'] = NULL;
1595 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1596 CRM_Core_Error
::fatal();
1599 $memberships = &$objects['membership'];
1600 $participant = &$objects['participant'];
1601 $pledgePayment = &$objects['pledge_payment'];
1602 $contribution = &$objects['contribution'];
1604 if ($pledgePayment) {
1605 $pledgePaymentIDs = array();
1606 foreach ($pledgePayment as $key => $object) {
1607 $pledgePaymentIDs[] = $object->id
;
1609 $pledgeID = $pledgePayment[0]->pledge_id
;
1613 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1616 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1617 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1622 // we might want to process contribution object.
1623 $processContribution = FALSE;
1624 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1625 if (is_array($memberships)) {
1626 foreach ($memberships as $membership) {
1628 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1629 $membership->save();
1631 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1632 if ($processContributionObject) {
1633 $processContribution = TRUE;
1640 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1641 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1643 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1644 if ($processContributionObject) {
1645 $processContribution = TRUE;
1649 if ($pledgePayment) {
1650 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1652 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1653 if ($processContributionObject) {
1654 $processContribution = TRUE;
1658 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1659 if (is_array($memberships)) {
1660 foreach ($memberships as $membership) {
1662 $membership->status_id
= array_search('Expired', $membershipStatuses);
1663 $membership->save();
1665 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1666 if ($processContributionObject) {
1667 $processContribution = TRUE;
1673 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1674 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1676 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1677 if ($processContributionObject) {
1678 $processContribution = TRUE;
1682 if ($pledgePayment) {
1683 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1685 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1686 if ($processContributionObject) {
1687 $processContribution = TRUE;
1691 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1693 // only pending contribution related object processed.
1694 if ($previousContriStatusId &&
1695 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1697 // this is case when we already processed contribution object.
1698 return $updateResult;
1700 elseif (!$previousContriStatusId &&
1701 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1703 // this is case when we are going to process contribution object later.
1704 return $updateResult;
1707 if (is_array($memberships)) {
1708 foreach ($memberships as $membership) {
1713 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1714 $membership->membership_type_id
,
1715 $membership->is_test
, $membership->id
1718 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1719 // this picks up membership type changes during renewals
1721 SELECT membership_type_id
1722 FROM civicrm_membership_log
1723 WHERE membership_id=$membership->id
1726 $dao = new CRM_Core_DAO
;
1728 if ($dao->fetch()) {
1729 if (!empty($dao->membership_type_id
)) {
1730 $membership->membership_type_id
= $dao->membership_type_id
;
1731 $membership->save();
1734 // else fall back to using current membership type
1737 // Figure out number of terms
1739 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1740 foreach ($lineitems as $lineitem) {
1741 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1742 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1744 // in case membership_num_terms comes through as null or zero
1745 $numterms = $numterms >= 1 ?
$numterms : 1;
1750 if ($currentMembership) {
1751 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1752 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1753 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1756 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, null, null, null, $numterms);
1759 //get the status for membership.
1760 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1762 $dates['join_date'],
1767 $formatedParams = array(
1768 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1769 array_search('Current', $membershipStatuses)
1771 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1772 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1773 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1776 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formatedParams);
1778 $membership->copyValues($formatedParams);
1779 $membership->save();
1781 //updating the membership log
1782 $membershipLog = array();
1783 $membershipLog = $formatedParams;
1784 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1785 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formatedParams['start_date'];
1787 $membershipLog['start_date'] = $logStartDate;
1788 $membershipLog['membership_id'] = $membership->id
;
1789 $membershipLog['modified_id'] = $membership->contact_id
;
1790 $membershipLog['modified_date'] = date('Ymd');
1791 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1793 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1795 //update related Memberships.
1796 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formatedParams);
1798 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1801 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1802 if ($processContributionObject) {
1803 $processContribution = TRUE;
1806 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1812 $updatedStatusId = array_search('Registered', $participantStatuses);
1813 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1815 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1816 if ($processContributionObject) {
1817 $processContribution = TRUE;
1821 if ($pledgePayment) {
1822 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1824 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1825 if ($processContributionObject) {
1826 $processContribution = TRUE;
1831 // process contribution object.
1832 if ($processContribution) {
1833 $contributionParams = array();
1835 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1836 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1837 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1839 foreach ($fields as $field) {
1840 if (!CRM_Utils_Array
::value($field, $params)) {
1843 $contributionParams[$field] = $params[$field];
1846 $ids = array('contribution' => $contributionId);
1847 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1850 return $updateResult;
1854 * This function returns all contribution related object ids.
1856 function getComponentDetails($contributionId) {
1857 $componentDetails = $pledgePayment = array();
1858 if (!$contributionId) {
1859 return $componentDetails;
1863 SELECT c.id as contribution_id,
1864 c.contact_id as contact_id,
1865 mp.membership_id as membership_id,
1866 m.membership_type_id as membership_type_id,
1867 pp.participant_id as participant_id,
1868 p.event_id as event_id,
1869 pgp.id as pledge_payment_id
1870 FROM civicrm_contribution c
1871 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1872 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1873 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1874 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1875 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1876 WHERE c.id = $contributionId";
1878 $dao = CRM_Core_DAO
::executeQuery($query);
1879 $componentDetails = array();
1881 while ($dao->fetch()) {
1882 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1883 $componentDetails['contact_id'] = $dao->contact_id
;
1884 if ($dao->event_id
) {
1885 $componentDetails['event'] = $dao->event_id
;
1887 if ($dao->participant_id
) {
1888 $componentDetails['participant'] = $dao->participant_id
;
1890 if ($dao->membership_id
) {
1891 if (!isset($componentDetails['membership'])) {
1892 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1894 $componentDetails['membership'][] = $dao->membership_id
;
1895 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1897 if ($dao->pledge_payment_id
) {
1898 $pledgePayment[] = $dao->pledge_payment_id
;
1902 if ($pledgePayment) {
1903 $componentDetails['pledge_payment'] = $pledgePayment;
1906 return $componentDetails;
1909 static function contributionCount($contactId, $includeSoftCredit = TRUE, $includeHonoree = TRUE) {
1914 $fromClause = "civicrm_contribution contribution";
1915 $whereConditions = array("contribution.contact_id = {$contactId}");
1916 if ($includeSoftCredit) {
1917 $fromClause .= " LEFT JOIN civicrm_contribution_soft softContribution
1918 ON ( contribution.id = softContribution.contribution_id )";
1919 $whereConditions[] = " softContribution.contact_id = {$contactId}";
1921 if ($includeHonoree) {
1922 $whereConditions[] = " contribution.honor_contact_id = {$contactId}";
1924 $whereClause = " contribution.is_test = 0 AND ( " . implode(' OR ', $whereConditions) . " )";
1927 SELECT count( contribution.id ) count
1929 WHERE {$whereClause}";
1931 return CRM_Core_DAO
::singleValueQuery($query);
1935 * Function to get individual id for onbehalf contribution
1937 * @param int $contributionId contribution id
1938 * @param int $contributorId contributer id
1940 * @return array $ids containing organization id and individual id
1943 function getOnbehalfIds($contributionId, $contributorId = NULL) {
1947 if (!$contributionId) {
1951 // fetch contributor id if null
1952 if (!$contributorId) {
1953 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1954 $contributionId, 'contact_id'
1958 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1959 $activityTypeId = array_search('Contribution', $activityTypeIds);
1961 if ($activityTypeId && $contributorId) {
1963 SELECT civicrm_activity_contact.contact_id
1964 FROM civicrm_activity_contact
1965 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1966 WHERE civicrm_activity.activity_type_id = %1
1967 AND civicrm_activity.source_record_id = %2
1968 AND civicrm_activity_contact.record_type_id = %3
1971 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
1972 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1975 1 => array($activityTypeId, 'Integer'),
1976 2 => array($contributionId, 'Integer'),
1977 3 => array($sourceID, 'Integer'),
1980 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1982 // for on behalf contribution source is individual and contributor is organization
1983 if ($sourceContactId && $sourceContactId != $contributorId) {
1984 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1985 // get rel type id for employee of relation
1986 foreach ($relationshipTypeIds as $id => $typeVals) {
1987 if ($typeVals['name_a_b'] == 'Employee of') {
1988 $relationshipTypeId = $id;
1993 $rel = new CRM_Contact_DAO_Relationship();
1994 $rel->relationship_type_id
= $relationshipTypeId;
1995 $rel->contact_id_a
= $sourceContactId;
1996 $rel->contact_id_b
= $contributorId;
1997 if ($rel->find(TRUE)) {
1998 $ids['individual_id'] = $rel->contact_id_a
;
1999 $ids['organization_id'] = $rel->contact_id_b
;
2011 static function getContributionDates() {
2012 $config = CRM_Core_Config
::singleton();
2013 $currentMonth = date('m');
2014 $currentDay = date('d');
2015 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2016 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2017 (int ) $config->fiscalYearStart
['d'] > $currentDay
2020 $year = date('Y') - 1;
2025 $year = array('Y' => $year);
2026 $yearDate = $config->fiscalYearStart
;
2027 $yearDate = array_merge($year, $yearDate);
2028 $yearDate = CRM_Utils_Date
::format($yearDate);
2030 $monthDate = date('Ym') . '01';
2036 'yearDate' => $yearDate,
2037 'monthDate' => $monthDate,
2042 * Load objects relations to contribution object
2043 * Objects are stored in the $_relatedObjects property
2044 * In the first instance we are just moving functionality from BASEIpn -
2045 * see http://issues.civicrm.org/jira/browse/CRM-9996
2047 * @param array $input Input as delivered from Payment Processor
2048 * @param array $ids Ids as Loaded by Payment Processor
2049 * @param boolean $required Is Payment processor / contribution page required
2050 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
2051 * Note that the unit test for the BaseIPN class tests this function
2053 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
2055 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
2056 if(empty($ids['contact']) && isset($this->contact_id
)){
2057 $ids['contact'] = $this->contact_id
;
2060 if (empty($this->_component
)) {
2061 if (! empty($ids['event'])) {
2062 $this->_component
= 'event';
2065 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2068 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
2069 $contributionType = new CRM_Financial_BAO_FinancialType();
2070 $contributionType->id
= $this->financial_type_id
;
2071 if (!$contributionType->find(TRUE)) {
2072 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
2074 if (!empty($ids['contact'])) {
2075 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
2076 $this->_relatedObjects
['contact']->id
= $ids['contact'];
2077 $this->_relatedObjects
['contact']->find(TRUE);
2079 $this->_relatedObjects
['contributionType'] = $contributionType;
2081 if ($this->_component
== 'contribute') {
2082 // retrieve the other optional objects first so
2083 // stuff down the line can use this info and do things
2085 //in any case get the memberships associated with the contribution
2086 //because we now support multiple memberships w/ price set
2087 // see if there are any other memberships to be considered for same contribution.
2089 SELECT membership_id
2090 FROM civicrm_membership_payment
2091 WHERE contribution_id = %1 ";
2092 $params = array(1 => array($this->id
, 'Integer'));
2094 $dao = CRM_Core_DAO
::executeQuery($query, $params );
2095 while ($dao->fetch()) {
2096 if ($dao->membership_id
) {
2097 if (!is_array($ids['membership'])) {
2098 $ids['membership'] = array();
2100 $ids['membership'][] = $dao->membership_id
;
2104 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2105 foreach ($ids['membership'] as $id) {
2107 $membership = new CRM_Member_BAO_Membership();
2108 $membership->id
= $id;
2109 if (!$membership->find(TRUE)) {
2110 throw new Exception("Could not find membership record: $id");
2112 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2113 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2114 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2115 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2116 $membership->free();
2121 if (!empty($ids['pledge_payment'])) {
2123 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2124 if (empty($paymentID)) {
2127 $payment = new CRM_Pledge_BAO_PledgePayment();
2128 $payment->id
= $paymentID;
2129 if (!$payment->find(TRUE)) {
2130 throw new Exception("Could not find pledge payment record: " . $paymentID);
2132 $this->_relatedObjects
['pledge_payment'][] = $payment;
2136 if (!empty($ids['contributionRecur'])) {
2137 $recur = new CRM_Contribute_BAO_ContributionRecur();
2138 $recur->id
= $ids['contributionRecur'];
2139 if (!$recur->find(TRUE)) {
2140 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2142 $this->_relatedObjects
['contributionRecur'] = &$recur;
2143 //get payment processor id from recur object.
2144 $paymentProcessorID = $recur->payment_processor_id
;
2146 //for normal contribution get the payment processor id.
2147 if (!$paymentProcessorID) {
2148 if ($this->contribution_page_id
) {
2149 // get the payment processor id from contribution page
2150 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2151 $this->contribution_page_id
,
2155 //fail to load payment processor id.
2156 elseif (!CRM_Utils_Array
::value('pledge_payment', $ids)) {
2157 $loadObjectSuccess = TRUE;
2159 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2161 return $loadObjectSuccess;
2166 // we are in event mode
2167 // make sure event exists and is valid
2168 $event = new CRM_Event_BAO_Event();
2169 $event->id
= $ids['event'];
2170 if ($ids['event'] &&
2173 throw new Exception("Could not find event: " . $ids['event']);
2176 $this->_relatedObjects
['event'] = &$event;
2178 $participant = new CRM_Event_BAO_Participant();
2179 $participant->id
= $ids['participant'];
2180 if ($ids['participant'] &&
2181 !$participant->find(TRUE)
2183 throw new Exception("Could not find participant: " . $ids['participant']);
2185 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2187 $this->_relatedObjects
['participant'] = &$participant;
2189 if (!$paymentProcessorID) {
2190 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2194 $loadObjectSuccess = TRUE;
2195 if ($paymentProcessorID) {
2196 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2197 $this->is_test ?
'test' : 'live'
2199 $ids['paymentProcessor'] = $paymentProcessorID;
2200 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2202 elseif ($required) {
2203 $loadObjectSuccess = FALSE;
2204 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2207 return $loadObjectSuccess;
2211 * Create array of message information - ie. return html version, txt version, to field
2213 * @param array $input incoming information
2214 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2215 * just check presence of recur object but maintaining legacy approach
2217 * @param array $ids IDs of related objects
2218 * @param array $values any values that may have already been compiled by calling process
2219 * This is augmented by values 'gathered' by gatherMessageValues
2220 * @param bool $returnMessageText distinguishes between whether to send message or return
2221 * message text. We are working towards this function ALWAYS returning message text & calling
2222 * function doing emails / pdfs with it
2223 * @return array $messageArray - messages
2225 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2226 if (empty($this->_relatedObjects
)) {
2227 $this->loadRelatedObjects($input, $ids);
2229 if (empty($this->_component
)) {
2230 $this->_component
= CRM_Utils_Array
::value('component', $input);
2233 //not really sure what params might be passed in but lets merge em into values
2234 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2235 $template = CRM_Core_Smarty
::singleton();
2236 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2237 //what does recur 'mean here - to do with payment processor return functionality but
2238 // what is the importance
2239 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2240 $paymentObject = &CRM_Core_Payment
::singleton(
2241 $this->is_test ?
'test' : 'live',
2242 $this->_relatedObjects
['paymentProcessor']
2245 $entityID = $entity = NULL;
2246 if (isset($ids['contribution'])) {
2247 $entity = 'contribution';
2248 $entityID = $ids['contribution'];
2250 if (isset($ids['membership']) && $ids['membership']) {
2251 $entity = 'membership';
2252 $entityID = $ids['membership'];
2255 $url = $paymentObject->subscriptionURL($entityID, $entity);
2256 $template->assign('cancelSubscriptionUrl', $url);
2258 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2259 $template->assign('updateSubscriptionBillingUrl', $url);
2261 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2262 $template->assign('updateSubscriptionUrl', $url);
2264 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2265 //direct mode showing billing block, so use directIPN for temporary
2266 $template->assign('contributeMode', 'directIPN');
2269 // todo remove strtolower - check consistency
2270 if (strtolower($this->_component
) == 'event') {
2271 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2272 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2276 $values['contribution_id'] = $this->id
;
2277 if (CRM_Utils_Array
::value('related_contact', $ids)) {
2278 $values['related_contact'] = $ids['related_contact'];
2279 if (isset($ids['onbehalf_dupe_alert'])) {
2280 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2282 $entityBlock = array(
2283 'contact_id' => $ids['contact'],
2284 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2285 'Home', 'id', 'name'
2288 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2289 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2292 if ($this->is_test
) {
2295 if (!empty($this->_relatedObjects
['membership'])) {
2296 foreach ($this->_relatedObjects
['membership'] as $membership) {
2297 if ($membership->id
) {
2298 $values['membership_id'] = $membership->id
;
2300 // need to set the membership values here
2301 $template->assign('membership_assign', 1);
2302 $template->assign('membership_name',
2303 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2305 $template->assign('mem_start_date', $membership->start_date
);
2306 $template->assign('mem_join_date', $membership->join_date
);
2307 $template->assign('mem_end_date', $membership->end_date
);
2308 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2309 $template->assign('mem_status', $membership_status);
2310 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2311 $template->assign('is_pay_later', 1);
2314 // if separate payment there are two contributions recorded and the
2315 // admin will need to send a receipt for each of them separately.
2316 // we dont link the two in the db (but can potentially infer it if needed)
2317 $template->assign('is_separate_payment', 0);
2319 if ($recur && $paymentObject) {
2320 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2321 $template->assign('cancelSubscriptionUrl', $url);
2322 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2323 $template->assign('updateSubscriptionBillingUrl', $url);
2324 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2325 $template->assign('updateSubscriptionUrl', $url);
2328 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2331 // otherwise if its about sending emails, continue sending without return, as we
2332 // don't want to exit the loop.
2337 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2343 * Gather values for contribution mail - this function has been created
2344 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2345 * Values related to the contribution in question are gathered
2347 * @param array $input input into function (probably from payment processor)
2348 * @param array $ids the set of ids related to the inpurt
2350 * @return array $values
2352 * NB don't add direct calls to the function as we intend to change the signature
2354 function _gatherMessageValues($input, &$values, $ids = array()) {
2355 // set display address of contributor
2356 if ($this->address_id
) {
2357 $addressParams = array('id' => $this->address_id
);
2358 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2359 $addressDetails = array_values($addressDetails);
2360 $values['address'] = $addressDetails[0]['display'];
2362 if ($this->_component
== 'contribute') {
2363 if (isset($this->contribution_page_id
)) {
2364 CRM_Contribute_BAO_ContributionPage
::setValues(
2365 $this->contribution_page_id
,
2368 if ($this->contribution_page_id
) {
2369 // CRM-8254 - override default currency if applicable
2370 $config = CRM_Core_Config
::singleton();
2371 $config->defaultCurrency
= CRM_Utils_Array
::value(
2374 $config->defaultCurrency
2378 // no contribution page -probably back office
2380 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2381 $values['is_email_receipt'] = 1;
2382 $values['title'] = 'Contribution';
2384 // set lineItem for contribution
2386 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2387 if (!empty($lineItem)) {
2388 $itemId = key($lineItem);
2389 foreach ($lineItem as &$eachItem) {
2390 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2391 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2392 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2393 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2396 $values['lineItem'][0] = $lineItem;
2397 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_Field', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2401 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2405 // if this is onbehalf of contribution then set related contact
2406 if (CRM_Utils_Array
::value('individual_id', $relatedContact)) {
2407 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2412 $eventParams = array(
2413 'id' => $this->_relatedObjects
['event']->id
,
2415 $values['event'] = array();
2417 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2419 //get location details
2420 $locationParams = array(
2421 'entity_id' => $this->_relatedObjects
['event']->id
,
2422 'entity_table' => 'civicrm_event',
2424 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2426 $ufJoinParams = array(
2427 'entity_table' => 'civicrm_event',
2428 'entity_id' => $ids['event'],
2429 'module' => 'CiviEvent',
2432 list($custom_pre_id,
2434 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2436 $values['custom_pre_id'] = $custom_pre_id;
2437 $values['custom_post_id'] = $custom_post_ids;
2439 // set lineItem for event contribution
2441 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2442 if (!empty($participantIds)) {
2443 foreach ($participantIds as $pIDs) {
2444 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2445 if (!CRM_Utils_System
::isNull($lineItem)) {
2446 $values['lineItem'][] = $lineItem;
2457 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2458 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2459 * Note we send directly from this function in some cases because it is only partly refactored
2460 * Don't call this function directly as the signature will change
2462 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2463 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2464 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2465 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2466 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2467 $template->assign('useForMember', true);
2469 //assign honor infomation to receiptmessage
2470 $honorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2474 if (!empty($honorID)) {
2476 $honorDefault = $honorIds = array();
2477 $honorIds['contribution'] = $this->id
;
2478 $idParams = array('id' => $honorID, 'contact_id' => $honorID);
2479 CRM_Contact_BAO_Contact
::retrieve($idParams, $honorDefault, $honorIds);
2480 $honorType = CRM_Core_PseudoConstant
::honor();
2482 $template->assign('honor_block_is_active', 1);
2483 if (CRM_Utils_Array
::value('prefix_id', $honorDefault)) {
2484 $prefix = CRM_Core_PseudoConstant
::individualPrefix();
2485 $template->assign('honor_prefix', $prefix[$honorDefault['prefix_id']]);
2487 $template->assign('honor_first_name', CRM_Utils_Array
::value('first_name', $honorDefault));
2488 $template->assign('honor_last_name', CRM_Utils_Array
::value('last_name', $honorDefault));
2489 $template->assign('honor_email', CRM_Utils_Array
::value('email', $honorDefault['email'][1]));
2490 $template->assign('honor_type', $honorType[$this->honor_type_id
]);
2493 $dao = new CRM_Contribute_DAO_ContributionProduct();
2494 $dao->contribution_id
= $this->id
;
2495 if ($dao->find(TRUE)) {
2496 $premiumId = $dao->product_id
;
2497 $template->assign('option', $dao->product_option
);
2499 $productDAO = new CRM_Contribute_DAO_Product();
2500 $productDAO->id
= $premiumId;
2501 $productDAO->find(TRUE);
2502 $template->assign('selectPremium', TRUE);
2503 $template->assign('product_name', $productDAO->name
);
2504 $template->assign('price', $productDAO->price
);
2505 $template->assign('sku', $productDAO->sku
);
2507 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2508 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2509 if(empty($amount) && isset($this->total_amount
)){
2510 $amount = $this->total_amount
;
2512 $template->assign('amount', $amount);
2513 // add the new contribution values
2514 if (strtolower($this->_component
) == 'contribute') {
2516 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2517 $softDAO->contribution_id
= $this->id
;
2518 if ($softDAO->find(TRUE)) {
2519 $template->assign('pcpBlock', TRUE);
2520 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2521 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2522 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2524 //assign the pcp page title for email subject
2525 $pcpDAO = new CRM_PCP_DAO_PCP();
2526 $pcpDAO->id
= $softDAO->pcp_id
;
2527 if ($pcpDAO->find(TRUE)) {
2528 $template->assign('title', $pcpDAO->title
);
2533 if ($this->financial_type_id
) {
2534 $values['financial_type_id'] = $this->financial_type_id
;
2538 $template->assign('trxn_id', $this->trxn_id
);
2539 $template->assign('receive_date',
2540 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2542 $template->assign('contributeMode', 'notify');
2543 $template->assign('action', $this->is_test ?
1024 : 1);
2544 $template->assign('receipt_text',
2545 CRM_Utils_Array
::value('receipt_text',
2549 $template->assign('is_monetary', 1);
2550 $template->assign('is_recur', (bool) $recur);
2551 $template->assign('currency', $this->currency
);
2552 $template->assign('address', CRM_Utils_Address
::format($input));
2553 if ($this->_component
== 'event') {
2554 $template->assign('title', $values['event']['title']);
2555 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2556 $viewRoles = array();
2557 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2558 $viewRoles[] = $participantRoles[$v];
2560 $values['event']['participant_role'] = implode(', ', $viewRoles);
2561 $template->assign('event', $values['event']);
2562 $template->assign('location', $values['location']);
2563 $template->assign('customPre', $values['custom_pre_id']);
2564 $template->assign('customPost', $values['custom_post_id']);
2567 if ($this->_relatedObjects
['participant']->is_test
) {
2571 $values['params'] = array();
2572 //to get email of primary participant.
2573 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2574 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2575 //build an array of cId/pId of participants
2576 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2577 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2578 //send receipt to additional participant if exists
2579 if (count($additionalIDs)) {
2580 $template->assign('isPrimary', 0);
2581 $template->assign('customProfile', NULL);
2582 //set additionalParticipant true
2583 $values['params']['additionalParticipant'] = TRUE;
2584 foreach ($additionalIDs as $pId => $cId) {
2586 //to change the status pending to completed
2587 $additional = new CRM_Event_DAO_Participant();
2588 $additional->id
= $pId;
2589 $additional->contact_id
= $cId;
2590 $additional->find(TRUE);
2591 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2592 $additional->status_id
= 1;
2593 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2594 //if additional participant dont have email
2596 if (!$additionalParticipantInfo) {
2597 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2599 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2600 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2601 $additional->save();
2602 $additional->free();
2603 $template->assign('amount', $amount);
2604 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2608 //build an array of custom profile and assigning it to template
2609 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2611 if (count($customProfile)) {
2612 $template->assign('customProfile', $customProfile);
2615 // for primary contact
2616 $values['params']['additionalParticipant'] = FALSE;
2617 $template->assign('isPrimary', 1);
2618 $template->assign('amount', $primaryAmount);
2619 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2620 if ($this->payment_instrument_id
) {
2621 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2622 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2624 // carry paylater, since we did not created billing,
2625 // so need to pull email from primary location, CRM-4395
2626 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2632 * Function to check whether payment processor supports
2633 * cancellation of contribution subscription
2635 * @param int $contributionId contribution id
2641 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2642 $cacheKeyString = "$contributionId";
2643 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2645 static $supportsCancel = array();
2647 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2648 $supportsCancel[$cacheKeyString] = FALSE;
2649 $isCancelled = FALSE;
2651 if ($isNotCancelled) {
2652 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2655 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2656 if (!empty($paymentObject)) {
2657 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2660 return $supportsCancel[$cacheKeyString];
2664 * Function to check whether subscription is already cancelled
2666 * @param int $contributionId contribution id
2668 * @return string $status contribution status
2672 static function isSubscriptionCancelled($contributionId) {
2674 SELECT cr.contribution_status_id
2675 FROM civicrm_contribution_recur cr
2676 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2677 WHERE con.id = %1 LIMIT 1";
2678 $params = array(1 => array($contributionId, 'Integer'));
2679 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2680 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2681 if ($status == 'Cancelled') {
2688 * Function to create all financial accounts entry
2690 * @param array $params contribution object, line item array and params for trxn
2692 * @param array $ids of contribution id
2697 static function recordFinancialAccounts(&$params, $ids) {
2698 $skipRecords = $update = FALSE;
2699 $additionalPaticipantId = array();
2700 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2702 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2703 $entityId = $params['participant_id'];
2704 $entityTable = 'civicrm_participant';
2705 $additionalPaticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2708 $entityId = $params['contribution']->id
;
2709 $entityTable = 'civicrm_contribution';
2711 $entityID[] = $entityId;
2712 if (!empty($additionalPaticipantId)) {
2713 $entityID +
= $additionalPaticipantId;
2715 if (!CRM_Utils_Array
::value('prevContribution', $params)) {
2718 // build line item array if its not set in $params
2719 if (!CRM_Utils_Array
::value('line_item', $params) ||
$additionalPaticipantId) {
2720 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
2723 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2724 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2725 $skipRecords = TRUE;
2726 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses)) {
2727 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2728 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2730 elseif (CRM_Utils_Array
::value('payment_processor', $params)) {
2731 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2733 elseif (CRM_Utils_Array
::value('payment_instrument_id', $params)) {
2734 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2737 $params['to_financial_account_id'] = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1");
2740 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2741 if (!isset($totalAmount) && CRM_Utils_Array
::value('prevContribution', $params)) {
2742 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2744 //build financial transaction params
2745 $trxnParams = array(
2746 'contribution_id' => $params['contribution']->id
,
2747 'to_financial_account_id' => $params['to_financial_account_id'],
2748 'trxn_date' => date('YmdHis'),
2749 'total_amount' => $totalAmount,
2750 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2751 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2752 'currency' => $params['contribution']->currency
,
2753 'trxn_id' => $params['contribution']->trxn_id
,
2754 'status_id' => $params['contribution']->contribution_status_id
,
2755 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params),
2756 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2759 if (CRM_Utils_Array
::value('payment_processor', $params)) {
2760 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2762 $params['trxnParams'] = $trxnParams;
2764 if (CRM_Utils_Array
::value('prevContribution', $params)) {
2766 //if Change contribution amount
2767 if (array_key_exists('total_amount', $params) && isset($params['total_amount']) &&
2768 $params['total_amount'] != $params['prevContribution']->total_amount
) {
2769 //Update Financial Records
2770 self
::updateFinancialAccounts($params, 'changedAmount');
2773 //Update contribution status
2774 if (CRM_Utils_Array
::value('contribution_status_id', $params) &&
2775 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2776 //Update Financial Records
2777 self
::updateFinancialAccounts($params, 'changedStatus');
2780 // change Payment Instrument for a Completed contribution
2781 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2782 // instrument is null and now new payment instrument is added along with the payment
2783 if (array_key_exists('payment_instrument_id', $params)) {
2784 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2785 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2786 //check if status is changed from Pending to Completed
2787 // do not update payment instrument changes for Pending to Completed
2788 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2789 $params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses))) {
2790 // for all other statuses create new financial records
2791 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2794 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2795 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2796 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2797 // for any other payment instrument changes create new financial records
2798 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2800 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2801 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2802 // another special case when check number is changed, create new financial records
2803 // create financial trxn with negative amount
2804 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2805 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2806 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2807 // create financial trxn with positive amount
2808 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2809 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2810 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2814 //if financial type is changed
2815 if (CRM_Utils_Array
::value('financial_type_id', $params) &&
2816 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2817 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2818 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2819 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2820 if ($oldFinancialAccount != $newFinancialAccount) {
2821 $params['total_amount'] = 0;
2822 if ($params['contribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)) {
2823 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2824 $params['prevContribution']->financial_type_id
, $relationTypeId);
2826 self
::updateFinancialAccounts($params, 'changeFinancialType');
2827 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2828 $params['financial_account_id'] = $newFinancialAccount;
2829 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2830 self
::updateFinancialAccounts($params);
2837 //records finanical trxn and entity financial trxn
2838 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2839 $params['entity_id'] = $financialTxn->id
;
2842 // record line items and finacial items
2844 if (!CRM_Utils_Array
::value('skipLineItem', $params)) {
2845 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2848 // create batch entry if batch_id is passed
2849 if (CRM_Utils_Array
::value('batch_id', $params)) {
2850 $entityParams = array(
2851 'batch_id' => $params['batch_id'],
2852 'entity_table' => 'civicrm_financial_trxn',
2853 'entity_id' => $financialTxn->id
,
2855 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2858 // when a fee is charged
2859 if (CRM_Utils_Array
::value('fee_amount', $params) && (!CRM_Utils_Array
::value('prevContribution', $params)
2860 ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2861 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2864 if (CRM_Utils_Array
::value('prevContribution', $params) && $entityTable == 'civicrm_participant'
2865 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2866 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2867 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2868 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2870 unset($params['line_item']);
2874 * Function to update all financial accounts entry
2876 * @param array $params contribution object, line item array and params for trxn
2878 * @param string $context update scenarios
2883 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2884 $itemAmount = $trxnID = NULL;
2885 //get all the statuses
2886 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2887 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus) &&
2888 $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2889 && $context == 'changePaymentInstrument') {
2892 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2893 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2895 if ($context == 'changedStatus') {
2896 //get all the statuses
2897 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2899 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2900 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2901 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2903 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2905 elseif ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
2906 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2907 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2908 $params['trxnParams']['to_financial_account_id'] = NULL;
2909 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2911 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL,
2912 " AND v.name LIKE 'Accounts Receivable Account is' "));
2913 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2914 $financialTypeID, $relationTypeId);
2916 $itemAmount = $params['trxnParams']['total_amount'];
2918 elseif ($context == 'changePaymentInstrument') {
2919 if ($params['prevContribution']->payment_instrument_id
!= null
2920 && $params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2921 && $params['contribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
2922 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2923 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2925 elseif ($params['prevContribution']->payment_instrument_id
!= null) {
2926 $params['trxnParams']['from_financial_account_id'] =
2927 CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount(
2928 $params['prevContribution']->payment_instrument_id
);
2931 $params['trxnParams']['from_financial_account_id'] = CRM_Core_DAO
::singleValueQuery(
2932 "SELECT id FROM civicrm_financial_account WHERE is_default = 1");
2936 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2937 $params['entity_id'] = $trxn->id
;
2939 if ($context == 'changedStatus') {
2940 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) &&
2941 ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2942 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2943 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2945 $entityParams = array(
2946 'entity_table' => 'civicrm_financial_item',
2947 'financial_trxn_id' => $trxn->id
,
2949 foreach ($params['line_item'] as $fieldId => $fields) {
2950 foreach ($fields as $fieldValueId => $fieldValues) {
2952 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2953 2 => array($fieldValues['id'], 'Integer'),
2955 CRM_Core_DAO
::executeQuery($query, $fparams);
2957 1 => array($fieldValues['id'], 'Integer'),
2959 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2960 while ($financialItem->fetch()) {
2961 $entityParams['entity_id'] = $financialItem->id
;
2962 $entityParams['amount'] = $financialItem->amount
;
2963 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2970 if ($context != 'changePaymentInstrument') {
2971 $itemParams['entity_table'] = 'civicrm_line_item';
2972 $trxnIds['id'] = $params['entity_id'];
2973 foreach ($params['line_item'] as $fieldId => $fields) {
2974 foreach ($fields as $fieldValueId => $fieldValues) {
2975 $prevParams['entity_id'] = $fieldValues['id'];
2976 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2978 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2979 if ($params['contribution']->receive_date
) {
2980 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2983 $financialAccount = $prevfinancialItem->financial_account_id
;
2984 if (CRM_Utils_Array
::value('financial_account_id', $params)) {
2985 $financialAccount = $params['financial_account_id'];
2988 $currency = $params['prevContribution']->currency
;
2989 if ($params['contribution']->currency
) {
2990 $currency = $params['contribution']->currency
;
2992 if (CRM_Utils_Array
::value('is_quick_config', $params)) {
2993 $amount = $itemAmount;
2995 $amount = $params['total_amount'];
3000 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3003 $amount = $diff * $fieldValues['line_total'];
3006 $itemParams = array(
3007 'transaction_date' => $receiveDate,
3008 'contact_id' => $params['prevContribution']->contact_id
,
3009 'currency' => $currency,
3010 'amount' => $amount,
3011 'description' => $prevfinancialItem->description
,
3012 'status_id' => $prevfinancialItem->status_id
,
3013 'financial_account_id' => $financialAccount,
3014 'entity_table' => 'civicrm_line_item',
3015 'entity_id' => $fieldValues['id']
3017 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3024 * Function to check status validation on update of a contribution
3026 * @param array $values previous form values before submit
3028 * @param array $fields the input form values
3030 * @param array $errors list of errors
3035 static function checkStatusValidation($values, &$fields, &$errors) {
3036 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3037 $checkStatus = array(
3038 'Cancelled' => array('Completed', 'Refunded'),
3039 'Completed' => array('Cancelled', 'Refunded'),
3040 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3041 'Refunded' => array('Cancelled', 'Completed')
3044 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3045 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(1 => $contributionStatuses[$values['contribution_status_id']], 2 => $contributionStatuses[$fields['contribution_status_id']]));
3050 * Function to delete contribution of contact
3054 * @param integer $contactId contact id
3059 static function deleteContactContribution($contactId) {
3060 $contribution = new CRM_Contribute_DAO_Contribution();
3061 $contribution->contact_id
= $contactId;
3062 $contribution->find();
3063 while ($contribution->fetch()) {
3064 self
::deleteContribution($contribution->id
);