3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
35 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
38 * static field for all the contribution information that we can potentially import
43 static $_importableFields = NULL;
46 * static field for all the contribution information that we can potentially export
51 static $_exportableFields = NULL;
54 * field for all the objects related to this contribution
55 * @var array of objects (e.g membership object, participant object)
57 public $_relatedObjects = array();
60 * field for the component - either 'event' (participant) or 'contribute'
61 * (any item related to a contribution page e.g. membership, pledge, contribution)
62 * This is used for composing messages because they have dependency on the
63 * contribution_page or event page - although over time we may eliminate that
65 * @var string component or event
67 public $_component = NULL;
72 function __construct() {
73 parent
::__construct();
77 * takes an associative array and creates a contribution object
79 * the function extract all the params it needs to initialize the create a
80 * contribution object. the params array could contain additional unused name/value
83 * @param array $params (reference ) an assoc array of name/value pairs
84 * @param array $ids the array that holds all the db ids
86 * @return object CRM_Contribute_BAO_Contribution object
90 static function add(&$params, $ids = array()) {
94 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
95 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
97 $duplicates = array();
98 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
99 $error = CRM_Core_Error
::singleton();
100 $d = implode(', ', $duplicates);
101 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
104 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
109 // first clean up all the money fields
110 $moneyFields = array(
114 'non_deductible_amount',
117 //if priceset is used, no need to cleanup money
118 if (CRM_Utils_Array
::value('skipCleanMoney', $params)) {
119 unset($moneyFields[0]);
122 foreach ($moneyFields as $field) {
123 if (isset($params[$field])) {
124 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
128 // CRM-13420, set payment instrument to default if payment_instrument_id is empty
129 if (!$contributionID && !CRM_Utils_Array
::value('payment_instrument_id', $params)) {
130 $params['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument',
131 FALSE, FALSE, FALSE, 'AND is_default = 1'));
134 if (CRM_Utils_Array
::value('payment_instrument_id', $params)) {
135 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
136 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
137 $params['check_number'] = 'null';
141 // contribution status is missing, choose Completed as default status
142 // do this for create mode only
143 if (!CRM_Utils_Array
::value('contribution', $ids) && !CRM_Utils_Array
::value('contribution_status_id', $params)) {
144 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
147 // CRM-13964 partial payment
148 if (empty($contributionID)) {
149 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
150 $partialAmtTotal = $params['partial_payment_total'];
151 $partialAmtPay = $params['partial_amount_pay'];
152 $params['total_amount'] = $partialAmtTotal;
153 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
157 if ($contributionID) {
158 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
161 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
163 $contribution = new CRM_Contribute_BAO_Contribution();
164 $contribution->copyValues($params);
166 $contribution->id
= $contributionID;
168 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
169 $config = CRM_Core_Config
::singleton();
170 $contribution->currency
= $config->defaultCurrency
;
173 if ($contributionID) {
174 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
177 $result = $contribution->save();
179 // Add financial_trxn details as part of fix for CRM-4724
180 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
181 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
183 //add Account details
184 $params['contribution'] = $contribution;
185 self
::recordFinancialAccounts($params);
187 // reset the group contact cache for this group
188 CRM_Contact_BAO_GroupContactCache
::remove();
190 if ($contributionID) {
191 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
194 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
201 * Given the list of params in the params array, fetch the object
202 * and store the values in the values array
204 * @param array $params input parameters to find object
205 * @param array $values output values of the object
206 * @param array $ids the array that holds all the db ids
208 * @return CRM_Contribute_BAO_Contribution|null the found object or null
212 static function &getValues($params, &$values, &$ids) {
213 if (empty($params)) {
216 $contribution = new CRM_Contribute_BAO_Contribution();
218 $contribution->copyValues($params);
220 if ($contribution->find(TRUE)) {
221 $ids['contribution'] = $contribution->id
;
223 CRM_Core_DAO
::storeValues($contribution, $values);
225 return $contribution;
231 * takes an associative array and creates a contribution object
233 * @param array $params (reference ) an assoc array of name/value pairs
234 * @param array $ids the array that holds all the db ids
236 * @return object CRM_Contribute_BAO_Contribution object
240 static function &create(&$params, $ids = array()) {
241 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
242 foreach ($dateFields as $df) {
243 if (isset($params[$df])) {
244 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
248 $transaction = new CRM_Core_Transaction();
250 $contribution = self
::add($params, $ids);
252 if (is_a($contribution, 'CRM_Core_Error')) {
253 $transaction->rollback();
254 return $contribution;
257 $params['contribution_id'] = $contribution->id
;
259 if (CRM_Utils_Array
::value('custom', $params) &&
260 is_array($params['custom'])
262 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
265 $session = CRM_Core_Session
::singleton();
267 if (CRM_Utils_Array
::value('note', $params)) {
269 'entity_table' => 'civicrm_contribution',
270 'note' => $params['note'],
271 'entity_id' => $contribution->id
,
272 'contact_id' => $session->get('userID'),
273 'modified_date' => date('Ymd'),
275 if (!$noteParams['contact_id']) {
276 $noteParams['contact_id'] = $params['contact_id'];
278 CRM_Core_BAO_Note
::add($noteParams);
281 // make entry in batch entity batch table
282 if (CRM_Utils_Array
::value('batch_id', $params)) {
283 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
284 $titleFields = array(
290 $retrieveRequired = 0;
291 foreach ($titleFields as $titleField) {
292 if(!isset($contribution->$titleField)){
293 $retrieveRequired = 1;
297 if ($retrieveRequired == 1) {
298 $contribution->find(TRUE);
302 // check if activity record exist for this contribution, if
304 $activity = new CRM_Activity_DAO_Activity();
305 $activity->source_record_id
= $contribution->id
;
306 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
310 if (!$activity->find(TRUE)) {
311 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
314 // CRM-13237 : if activity record found, update it with campaign id of contribution
315 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
318 // Handle soft credit and / or link to personal campaign page
319 list($type, $softIDs) = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditType($contribution->id
);
320 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
321 if (!empty($type) && $type == 'soft') {
322 $deleteParams = array('contribution_id' => $contribution->id
);
323 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
325 $softParams = array();
326 $softParams['contribution_id'] = $contribution->id
;
327 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
328 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
329 $pcp['pcp_made_through_id'], 'contact_id'
331 $softParams['currency'] = $contribution->currency
;
332 $softParams['amount'] = $contribution->total_amount
;
333 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
334 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
335 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
336 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
337 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
339 elseif (CRM_Utils_Array
::value('soft_credit', $params)) {
340 $softParams = $params['soft_credit'];
342 if (!empty($softIDs)) {
343 foreach ( $softIDs as $softID) {
344 if (!in_array($softID, $params['soft_credit_ids'])) {
345 $deleteParams = array('id' => $softID);
346 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
351 foreach ($softParams as $softParam) {
352 $softParam['contribution_id'] = $contribution->id
;
353 $softParam['currency'] = $contribution->currency
;
354 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
358 $transaction->commit();
360 // do not add to recent items for import, CRM-4399
361 if (!CRM_Utils_Array
::value('skipRecentView', $params)) {
362 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
363 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
365 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
366 $titleFields = array(
372 $retrieveRequired = 0;
373 foreach ($titleFields as $titleField) {
374 if(!isset($contribution->$titleField)){
375 $retrieveRequired = 1;
379 if($retrieveRequired == 1){
380 $contribution->find(TRUE);
382 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
383 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
385 $recentOther = array();
386 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
387 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
388 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
392 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
393 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
394 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
398 // add the recently created Contribution
399 CRM_Utils_Recent
::add($title,
403 $contribution->contact_id
,
409 return $contribution;
413 * Get the values for pseudoconstants for name->value and reverse.
415 * @param array $defaults (reference) the default values, some of which need to be resolved.
416 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
422 static function resolveDefaults(&$defaults, $reverse = FALSE) {
423 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
424 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
425 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
426 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
430 * This function is used to convert associative array names to values
433 * This function is used by both the web form layer and the api. Note that
434 * the api needs the name => value conversion, also the view layer typically
435 * requires value => name conversion
437 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
438 $id = $property . '_id';
440 $src = $reverse ?
$property : $id;
441 $dst = $reverse ?
$id : $property;
443 if (!array_key_exists($src, $defaults)) {
447 $look = $reverse ?
array_flip($lookup) : $lookup;
449 if (is_array($look)) {
450 if (!array_key_exists($defaults[$src], $look)) {
454 $defaults[$dst] = $look[$defaults[$src]];
459 * Takes a bunch of params that are needed to match certain criteria and
460 * retrieves the relevant objects. We'll tweak this function to be more
461 * full featured over a period of time. This is the inverse function of
462 * create. It also stores all the retrieved values in the default array
464 * @param array $params (reference ) an assoc array of name/value pairs
465 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
466 * in a hierarchical manner
467 * @param array $ids (reference) the array that holds all the db ids
469 * @return object CRM_Contribute_BAO_Contribution object
473 static function retrieve(&$params, &$defaults, &$ids) {
474 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
475 return $contribution;
479 * combine all the importable fields from the lower levels object
481 * The ordering is important, since currently we do not have a weight
482 * scheme. Adding weight is super important and should be done in the
483 * next week or so, before this can be called complete.
485 * @return array array of importable Fields
489 static function &importableFields($contactType = 'Individual', $status = TRUE) {
490 if (!self
::$_importableFields) {
491 if (!self
::$_importableFields) {
492 self
::$_importableFields = array();
496 $fields = array('' => array('title' => ts('- do not import -')));
499 $fields = array('' => array('title' => ts('- Contribution Fields -')));
502 $note = CRM_Core_DAO_Note
::import();
503 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
504 unset($tmpFields['option_value']);
505 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
506 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
508 // Using new Dedupe rule.
510 'contact_type' => $contactType,
511 'used' => 'Unsupervised',
513 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
514 $tmpContactField = array();
515 if (is_array($fieldsArray)) {
516 foreach ($fieldsArray as $value) {
517 //skip if there is no dupe rule
518 if ($value == 'none') {
521 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
526 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
527 $tmpContactField[trim($value)] = $contactFields[trim($value)];
529 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
532 $title = $tmpContactField[trim($value)]['title'];
534 $tmpContactField[trim($value)]['title'] = $title;
538 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
539 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
540 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
541 $fields = array_merge($fields, $tmpContactField);
542 $fields = array_merge($fields, $tmpFields);
543 $fields = array_merge($fields, $note);
544 $fields = array_merge($fields, $optionFields);
545 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
546 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
547 self
::$_importableFields = $fields;
549 return self
::$_importableFields;
552 static function &exportableFields() {
553 if (!self
::$_exportableFields) {
554 if (!self
::$_exportableFields) {
555 self
::$_exportableFields = array();
558 $impFields = CRM_Contribute_DAO_Contribution
::export();
559 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
560 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
561 $typeField = CRM_Financial_DAO_FinancialType
::export();
562 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
563 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
564 $contributionStatus = array(
565 'contribution_status' => array(
566 'title' => ts('Contribution Status'),
567 'name' => 'contribution_status',
568 'data_type' => CRM_Utils_Type
::T_STRING
571 $contributionNote = array(
572 'contribution_note' =>
574 'title' => ts('Contribution Note'),
575 'name' => 'contribution_note',
576 'data_type' => CRM_Utils_Type
::T_TEXT
580 $contributionRecurId = array(
581 'contribution_recur_id' =>
583 'title' => ts('Recurring Contributions ID'),
584 'name' => 'contribution_recur_id',
585 'where' => 'civicrm_contribution.contribution_recur_id',
586 'data_type' => CRM_Utils_Type
::T_INT
589 $extraFields = array(
590 'contribution_batch' => array(
591 'title' => ts('Batch Name')
595 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
596 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $financialAccount,
597 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
600 self
::$_exportableFields = $fields;
603 return self
::$_exportableFields;
606 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
610 $where[] = 'contribution_status_id = 1';
614 $where[] = 'contribution_status_id = 3';
619 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
622 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
625 $whereCond = implode(' AND ', $where);
628 SELECT sum( total_amount ) as total_amount,
629 count( civicrm_contribution.id ) as total_count,
631 FROM civicrm_contribution
632 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
634 AND ( is_test = 0 OR is_test IS NULL )
635 AND contact.is_deleted = 0
639 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
642 while ($dao->fetch()) {
643 $count +
= $dao->total_count
;
644 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
647 return array('amount' => implode(', ', $amount),
655 * Delete the indirect records associated with this contribution first
657 * @return $results no of deleted Contribution on success, false otherwise
661 static function deleteContribution($id) {
662 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
664 $transaction = new CRM_Core_Transaction();
667 //delete activity record
669 'source_record_id' => $id,
670 // activity type id for contribution
671 'activity_type_id' => 6,
674 CRM_Activity_BAO_Activity
::deleteActivity($params);
676 //delete billing address if exists for this contribution.
677 self
::deleteAddress($id);
679 //update pledge and pledge payment, CRM-3961
680 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
682 // remove entry from civicrm_price_set_entity, CRM-5095
683 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
684 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
686 // cleanup line items.
687 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
689 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
690 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
692 if ($participantId) {
693 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
696 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
700 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
701 $noteId = key($note);
703 CRM_Core_BAO_Note
::del($noteId, FALSE);
706 $dao = new CRM_Contribute_DAO_Contribution();
709 $results = $dao->delete();
711 $transaction->commit();
713 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
715 // delete the recently created Contribution
716 $contributionRecent = array(
718 'type' => 'Contribution',
720 CRM_Utils_Recent
::del($contributionRecent);
726 * Check if there is a contribution with the same trxn_id or invoice_id
728 * @param array $params (reference ) an assoc array of name/value pairs
729 * @param array $duplicates (reference ) store ids of duplicate contribs
731 * @return boolean true if duplicate, false otherwise
735 static function checkDuplicate($input, &$duplicates, $id = NULL) {
737 $id = CRM_Utils_Array
::value('id', $input);
739 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
740 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
746 $clause[] = "trxn_id = %1";
747 $input[1] = array($trxn_id, 'String');
751 $clause[] = "invoice_id = %2";
752 $input[2] = array($invoice_id, 'String');
755 if (empty($clause)) {
759 $clause = implode(' OR ', $clause);
761 $clause = "( $clause ) AND id != %3";
762 $input[3] = array($id, 'Integer');
765 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
766 $dao = CRM_Core_DAO
::executeQuery($query, $input);
768 while ($dao->fetch()) {
769 $duplicates[] = $dao->id
;
776 * takes an associative array and creates a contribution_product object
778 * the function extract all the params it needs to initialize the create a
779 * contribution_product object. the params array could contain additional unused name/value
782 * @param array $params (reference ) an assoc array of name/value pairs
784 * @return object CRM_Contribute_BAO_ContributionProduct object
788 static function addPremium(&$params) {
789 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
790 $contributionProduct->copyValues($params);
791 return $contributionProduct->save();
795 * Function to get list of contribution fields for profile
796 * For now we only allow custom contribution fields to be in
799 * @param boolean $addExtraFields true if special fields needs to be added
801 * @return return the list of contribution fields
805 static function getContributionFields($addExtraFields = TRUE) {
806 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
807 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
809 if ($addExtraFields) {
810 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
813 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
815 foreach ($contributionFields as $key => $var) {
816 if ($key == 'contribution_contact_id') {
819 elseif ($key == 'contribution_campaign_id') {
820 $var['title'] = ts('Campaign');
822 $fields[$key] = $var;
825 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
830 * Function to add extra fields specific to contribtion
834 static function getSpecialContributionFields() {
835 $extraFields = array(
836 'honor_contact_name' => array(
837 'name' => 'honor_contact_name',
838 'title' => 'Honor Contact Name',
839 'headerPattern' => '/^honor_contact_name$/i',
840 'where' => 'civicrm_contact_c.display_name',
842 'honor_contact_email' => array(
843 'name' => 'honor_contact_email',
844 'title' => 'Honor Contact Email',
845 'headerPattern' => '/^honor_contact_email$/i',
846 'where' => 'honor_email.email',
848 'honor_contact_id' => array(
849 'name' => 'honor_contact_id',
850 'title' => 'Honor Contact ID',
851 'headerPattern' => '/^honor_contact_id$/i',
852 'where' => 'civicrm_contribution.honor_contact_id',
854 'honor_type_label' => array(
855 'name' => 'honor_type_label',
856 'title' => 'Honor Type Label',
857 'headerPattern' => '/^honor_type_label$/i',
858 'where' => 'honor_type.label',
860 'soft_credit_name' => array(
861 'name' => 'soft_credit_name',
862 'title' => 'Soft Credit Name',
863 'headerPattern' => '/^soft_credit_name$/i',
864 'where' => 'civicrm_contact_d.display_name',
866 'soft_credit_email' => array(
867 'name' => 'soft_credit_email',
868 'title' => 'Soft Credit Email',
869 'headerPattern' => '/^soft_credit_email$/i',
870 'where' => 'soft_email.email',
872 'soft_credit_phone' => array(
873 'name' => 'soft_credit_phone',
874 'title' => 'Soft Credit Phone',
875 'headerPattern' => '/^soft_credit_phone$/i',
876 'where' => 'soft_phone.phone',
878 'soft_credit_contact_id' => array(
879 'name' => 'soft_credit_contact_id',
880 'title' => 'Soft Credit Contact ID',
881 'headerPattern' => '/^soft_credit_contact_id$/i',
882 'where' => 'civicrm_contribution_soft.contact_id',
889 static function getCurrentandGoalAmount($pageID) {
891 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
892 FROM civicrm_contribution_page p,
893 civicrm_contribution c
894 WHERE p.id = c.contribution_page_id
896 AND c.cancel_date is null
900 $config = CRM_Core_Config
::singleton();
901 $params = array(1 => array($pageID, 'Integer'));
902 $dao = CRM_Core_DAO
::executeQuery($query, $params);
905 return array($dao->goal
, $dao->total
);
908 return array(NULL, NULL);
913 * Function to get list of contribution In Honor of contact Ids
915 * @param int $honorId In Honor of Contact ID
917 * @return return the list of contribution fields
922 static function getHonorContacts($honorId) {
924 $honorDAO = new CRM_Contribute_DAO_Contribution();
925 $honorDAO->honor_contact_id
= $honorId;
928 $status = CRM_Contribute_PseudoConstant
::contributionStatus($honorDAO->contribution_status_id
);
929 $type = CRM_Contribute_PseudoConstant
::financialType();
931 while ($honorDAO->fetch()) {
932 $params[$honorDAO->id
]['honorId'] = $honorDAO->contact_id
;
933 $params[$honorDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $honorDAO->contact_id
, 'display_name');
934 $params[$honorDAO->id
]['type'] = $type[$honorDAO->financial_type_id
];
935 $params[$honorDAO->id
]['type_id'] = $honorDAO->financial_type_id
;
936 $params[$honorDAO->id
]['amount'] = CRM_Utils_Money
::format($honorDAO->total_amount
, $honorDAO->currency
);
937 $params[$honorDAO->id
]['source'] = $honorDAO->source
;
938 $params[$honorDAO->id
]['receive_date'] = $honorDAO->receive_date
;
939 $params[$honorDAO->id
]['contribution_status'] = CRM_Utils_Array
::value($honorDAO->contribution_status_id
, $status);
946 * function to get the sort name of a contact for a particular contribution
948 * @param int $id id of the contribution
950 * @return null|string sort name of the contact if found
954 static function sortName($id) {
955 $id = CRM_Utils_Type
::escape($id, 'Integer');
958 SELECT civicrm_contact.sort_name
959 FROM civicrm_contribution, civicrm_contact
960 WHERE civicrm_contribution.contact_id = civicrm_contact.id
961 AND civicrm_contribution.id = {$id}
963 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
966 static function annual($contactID) {
967 if (is_array($contactID)) {
968 $contactIDs = implode(',', $contactID);
971 $contactIDs = $contactID;
974 $config = CRM_Core_Config
::singleton();
975 $startDate = $endDate = NULL;
977 $currentMonth = date('m');
978 $currentDay = date('d');
979 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
980 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
981 (int ) $config->fiscalYearStart
['d'] > $currentDay
984 $year = date('Y') - 1;
989 $nextYear = $year +
1;
991 if ($config->fiscalYearStart
) {
992 if ($config->fiscalYearStart
['M'] < 10) {
993 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
995 if ($config->fiscalYearStart
['d'] < 10) {
996 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
998 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1003 $startDate = "$year$monthDay";
1004 $endDate = "$nextYear$monthDay";
1007 SELECT count(*) as count,
1008 sum(total_amount) as amount,
1009 avg(total_amount) as average,
1011 FROM civicrm_contribution b
1012 WHERE b.contact_id IN ( $contactIDs )
1013 AND b.contribution_status_id = 1
1015 AND b.receive_date >= $startDate
1016 AND b.receive_date < $endDate
1019 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1021 $amount = $average = array();
1022 while ($dao->fetch()) {
1023 if ($dao->count
> 0 && $dao->amount
> 0) {
1024 $count +
= $dao->count
;
1025 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1026 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1032 implode(', ', $amount),
1033 implode(', ', $average),
1036 return array(0, 0, 0);
1040 * Check if there is a contribution with the params passed in.
1041 * Used for trxn_id,invoice_id and contribution_id
1043 * @param array $params an assoc array of name/value pairs
1045 * @return array contribution id if success else NULL
1049 static function checkDuplicateIds($params) {
1050 $dao = new CRM_Contribute_DAO_Contribution();
1054 foreach ($params as $k => $v) {
1056 $clause[] = "$k = '$v'";
1059 $clause = implode(' AND ', $clause);
1060 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1061 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1063 while ($dao->fetch()) {
1071 * Function to get the contribution details for component export
1073 * @param int $exportMode export mode
1074 * @param string $componentIds component ids
1076 * @return array associated array
1081 static function getContributionDetails($exportMode, $componentIds) {
1082 $paymentDetails = array();
1083 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1085 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1086 $componentSelect = " civicrm_participant_payment.participant_id id";
1087 $additionalClause = "
1088 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1089 AND civicrm_participant_payment.participant_id {$componentClause} )
1092 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1093 $componentSelect = " civicrm_membership_payment.membership_id id";
1094 $additionalClause = "
1095 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1096 AND civicrm_membership_payment.membership_id {$componentClause} )
1099 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1100 $componentSelect = " civicrm_pledge_payment.id id";
1101 $additionalClause = "
1102 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1103 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1107 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1108 trxn_id, {$componentSelect}
1109 FROM civicrm_contribution
1110 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1111 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1112 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1113 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1114 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1115 AND option_group_contribution_status.id = contribution_status.option_group_id )
1119 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1121 while ($dao->fetch()) {
1122 $paymentDetails[$dao->id
] = array(
1123 'total_amount' => $dao->total_amount
,
1124 'contribution_status' => $dao->status
,
1125 'receive_date' => $dao->receive_date
,
1126 'pay_instru' => $dao->payment_instrument
,
1127 'trxn_id' => $dao->trxn_id
,
1131 return $paymentDetails;
1135 * Function to create address associated with contribution record.
1136 * @param array $params an associated array
1137 * @param int $billingID $billingLocationTypeID
1139 * @return address id
1142 static function createAddress(&$params, $billingLocationTypeID) {
1143 $billingFields = array(
1146 'state_province_id',
1151 //build address array
1152 $addressParams = array();
1153 $addressParams['location_type_id'] = $billingLocationTypeID;
1154 $addressParams['is_billing'] = 1;
1156 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1157 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1158 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1159 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1161 foreach ($billingFields as $value) {
1162 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1165 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1167 return $address->id
;
1171 * Delete billing address record related contribution
1173 * @param int $contact_id contact id
1174 * @param int $contribution_id contributionId
1178 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1180 $contactJoin = NULL;
1182 if ($contributionId) {
1183 $clauses[] = "cc.id = {$contributionId}";
1187 $clauses[] = "cco.id = {$contactId}";
1188 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1191 if (empty($clauses)) {
1192 CRM_Core_Error
::fatal();
1195 $condition = implode(' OR ', $clauses);
1199 FROM civicrm_address ca
1200 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1204 $dao = CRM_Core_DAO
::executeQuery($query);
1206 while ($dao->fetch()) {
1207 $params = array('id' => $dao->id
);
1208 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1213 * This function check online pending contribution associated w/
1214 * Online Event Registration or Online Membership signup.
1216 * @param int $componentId participant/membership id.
1217 * @param string $componentName Event/Membership.
1219 * @return $contributionId pending contribution id.
1222 static function checkOnlinePendingContribution($componentId, $componentName) {
1223 $contributionId = NULL;
1224 if (!$componentId ||
1225 !in_array($componentName, array('Event', 'Membership'))
1227 return $contributionId;
1230 if ($componentName == 'Event') {
1231 $idName = 'participant_id';
1232 $componentTable = 'civicrm_participant';
1233 $paymentTable = 'civicrm_participant_payment';
1234 $source = ts('Online Event Registration');
1237 if ($componentName == 'Membership') {
1238 $idName = 'membership_id';
1239 $componentTable = 'civicrm_membership';
1240 $paymentTable = 'civicrm_membership_payment';
1241 $source = ts('Online Contribution');
1244 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1247 SELECT component.id as {$idName},
1248 componentPayment.contribution_id as contribution_id,
1249 contribution.source source,
1250 contribution.contribution_status_id as contribution_status_id,
1251 contribution.is_pay_later as is_pay_later
1252 FROM $componentTable component
1253 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1254 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1255 WHERE component.id = {$componentId}";
1257 $dao = CRM_Core_DAO
::executeQuery($query);
1259 while ($dao->fetch()) {
1260 if ($dao->contribution_id
&&
1261 $dao->is_pay_later
&&
1262 $dao->contribution_status_id
== $pendingStatusId &&
1263 strpos($dao->source
, $source) !== FALSE
1265 $contributionId = $dao->contribution_id
;
1270 return $contributionId;
1274 * This function update contribution as well as related objects.
1276 static function transitionComponents($params, $processContributionObject = FALSE) {
1277 // get minimum required values.
1278 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1279 $componentId = CRM_Utils_Array
::value('component_id', $params);
1280 $componentName = CRM_Utils_Array
::value('componentName', $params);
1281 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1282 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1284 // if we already processed contribution object pass previous status id.
1285 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1287 $updateResult = array();
1289 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1291 // we process only ( Completed, Cancelled, or Failed ) contributions.
1292 if (!$contributionId ||
1293 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1294 array_search('Cancelled', $contributionStatuses),
1295 array_search('Failed', $contributionStatuses),
1298 return $updateResult;
1301 if (!$componentName ||
!$componentId) {
1302 // get the related component details.
1303 $componentDetails = self
::getComponentDetails($contributionId);
1306 $componentDetails['contact_id'] = $contactId;
1307 $componentDetails['component'] = $componentName;
1309 if ($componentName == 'event') {
1310 $componentDetails['participant'] = $componentId;
1313 $componentDetails['membership'] = $componentId;
1317 if (CRM_Utils_Array
::value('contact_id', $componentDetails)) {
1318 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1324 // do check for required ids.
1325 if (!CRM_Utils_Array
::value('membership', $componentDetails) &&
1326 !CRM_Utils_Array
::value('participant', $componentDetails) &&
1327 !CRM_Utils_Array
::value('pledge_payment', $componentDetails) ||
1328 !CRM_Utils_Array
::value('contact_id', $componentDetails)
1330 return $updateResult;
1333 //now we are ready w/ required ids, start processing.
1335 $baseIPN = new CRM_Core_Payment_BaseIPN();
1337 $input = $ids = $objects = array();
1339 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1340 $ids['contribution'] = $contributionId;
1341 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1342 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1343 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1344 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1345 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1346 $ids['contributionRecur'] = NULL;
1347 $ids['contributionPage'] = NULL;
1349 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1350 CRM_Core_Error
::fatal();
1353 $memberships = &$objects['membership'];
1354 $participant = &$objects['participant'];
1355 $pledgePayment = &$objects['pledge_payment'];
1356 $contribution = &$objects['contribution'];
1358 if ($pledgePayment) {
1359 $pledgePaymentIDs = array();
1360 foreach ($pledgePayment as $key => $object) {
1361 $pledgePaymentIDs[] = $object->id
;
1363 $pledgeID = $pledgePayment[0]->pledge_id
;
1366 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1369 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1370 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1375 // we might want to process contribution object.
1376 $processContribution = FALSE;
1377 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1378 if (is_array($memberships)) {
1379 foreach ($memberships as $membership) {
1381 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1382 $membership->save();
1384 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1385 if ($processContributionObject) {
1386 $processContribution = TRUE;
1393 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1394 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1396 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1397 if ($processContributionObject) {
1398 $processContribution = TRUE;
1402 if ($pledgePayment) {
1403 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1405 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1406 if ($processContributionObject) {
1407 $processContribution = TRUE;
1411 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1412 if (is_array($memberships)) {
1413 foreach ($memberships as $membership) {
1415 $membership->status_id
= array_search('Expired', $membershipStatuses);
1416 $membership->save();
1418 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1419 if ($processContributionObject) {
1420 $processContribution = TRUE;
1426 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1427 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1429 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1430 if ($processContributionObject) {
1431 $processContribution = TRUE;
1435 if ($pledgePayment) {
1436 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1438 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1439 if ($processContributionObject) {
1440 $processContribution = TRUE;
1444 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1446 // only pending contribution related object processed.
1447 if ($previousContriStatusId &&
1448 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1450 // this is case when we already processed contribution object.
1451 return $updateResult;
1453 elseif (!$previousContriStatusId &&
1454 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1456 // this is case when we are going to process contribution object later.
1457 return $updateResult;
1460 if (is_array($memberships)) {
1461 foreach ($memberships as $membership) {
1466 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1467 $membership->membership_type_id
,
1468 $membership->is_test
, $membership->id
1471 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1472 // this picks up membership type changes during renewals
1474 SELECT membership_type_id
1475 FROM civicrm_membership_log
1476 WHERE membership_id=$membership->id
1479 $dao = new CRM_Core_DAO
;
1481 if ($dao->fetch()) {
1482 if (!empty($dao->membership_type_id
)) {
1483 $membership->membership_type_id
= $dao->membership_type_id
;
1484 $membership->save();
1487 // else fall back to using current membership type
1490 // Figure out number of terms
1492 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1493 foreach ($lineitems as $lineitem) {
1494 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1495 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1497 // in case membership_num_terms comes through as null or zero
1498 $numterms = $numterms >= 1 ?
$numterms : 1;
1503 if ($currentMembership) {
1504 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1505 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1506 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1509 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1512 //get the status for membership.
1513 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1515 $dates['join_date'],
1520 $formattedParams = array(
1521 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1522 array_search('Current', $membershipStatuses)
1524 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1525 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1526 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1529 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1531 $membership->copyValues($formattedParams);
1532 $membership->save();
1534 //updating the membership log
1535 $membershipLog = array();
1536 $membershipLog = $formattedParams;
1537 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1538 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1540 $membershipLog['start_date'] = $logStartDate;
1541 $membershipLog['membership_id'] = $membership->id
;
1542 $membershipLog['modified_id'] = $membership->contact_id
;
1543 $membershipLog['modified_date'] = date('Ymd');
1544 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1546 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1548 //update related Memberships.
1549 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1551 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1554 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1555 if ($processContributionObject) {
1556 $processContribution = TRUE;
1559 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1565 $updatedStatusId = array_search('Registered', $participantStatuses);
1566 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1568 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1569 if ($processContributionObject) {
1570 $processContribution = TRUE;
1574 if ($pledgePayment) {
1575 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1577 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1578 if ($processContributionObject) {
1579 $processContribution = TRUE;
1584 // process contribution object.
1585 if ($processContribution) {
1586 $contributionParams = array();
1588 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1589 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1590 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1592 foreach ($fields as $field) {
1593 if (!CRM_Utils_Array
::value($field, $params)) {
1596 $contributionParams[$field] = $params[$field];
1599 $ids = array('contribution' => $contributionId);
1600 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1603 return $updateResult;
1607 * This function returns all contribution related object ids.
1609 public static function getComponentDetails($contributionId) {
1610 $componentDetails = $pledgePayment = array();
1611 if (!$contributionId) {
1612 return $componentDetails;
1616 SELECT c.id as contribution_id,
1617 c.contact_id as contact_id,
1618 mp.membership_id as membership_id,
1619 m.membership_type_id as membership_type_id,
1620 pp.participant_id as participant_id,
1621 p.event_id as event_id,
1622 pgp.id as pledge_payment_id
1623 FROM civicrm_contribution c
1624 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1625 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1626 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1627 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1628 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1629 WHERE c.id = $contributionId";
1631 $dao = CRM_Core_DAO
::executeQuery($query);
1632 $componentDetails = array();
1634 while ($dao->fetch()) {
1635 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1636 $componentDetails['contact_id'] = $dao->contact_id
;
1637 if ($dao->event_id
) {
1638 $componentDetails['event'] = $dao->event_id
;
1640 if ($dao->participant_id
) {
1641 $componentDetails['participant'] = $dao->participant_id
;
1643 if ($dao->membership_id
) {
1644 if (!isset($componentDetails['membership'])) {
1645 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1647 $componentDetails['membership'][] = $dao->membership_id
;
1648 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1650 if ($dao->pledge_payment_id
) {
1651 $pledgePayment[] = $dao->pledge_payment_id
;
1655 if ($pledgePayment) {
1656 $componentDetails['pledge_payment'] = $pledgePayment;
1659 return $componentDetails;
1662 static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1667 $contactContributionsSQL = "
1668 SELECT contribution.id AS id
1669 FROM civicrm_contribution contribution
1670 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1672 $contactSoftCreditContributionsSQL = "
1673 SELECT contribution.id
1674 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1675 ON ( contribution.id = softContribution.contribution_id )
1676 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1677 $query = "SELECT count( x.id ) count FROM ( ";
1678 $query .= $contactContributionsSQL;
1680 if ($includeSoftCredit) {
1681 $query .= " UNION ";
1682 $query .= $contactSoftCreditContributionsSQL;
1687 return CRM_Core_DAO
::singleValueQuery($query);
1691 * Function to get individual id for onbehalf contribution
1693 * @param int $contributionId contribution id
1694 * @param int $contributorId contributor id
1696 * @return array $ids containing organization id and individual id
1699 static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1703 if (!$contributionId) {
1707 // fetch contributor id if null
1708 if (!$contributorId) {
1709 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1710 $contributionId, 'contact_id'
1714 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1715 $activityTypeId = array_search('Contribution', $activityTypeIds);
1717 if ($activityTypeId && $contributorId) {
1719 SELECT civicrm_activity_contact.contact_id
1720 FROM civicrm_activity_contact
1721 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1722 WHERE civicrm_activity.activity_type_id = %1
1723 AND civicrm_activity.source_record_id = %2
1724 AND civicrm_activity_contact.record_type_id = %3
1727 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1728 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1731 1 => array($activityTypeId, 'Integer'),
1732 2 => array($contributionId, 'Integer'),
1733 3 => array($sourceID, 'Integer'),
1736 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1738 // for on behalf contribution source is individual and contributor is organization
1739 if ($sourceContactId && $sourceContactId != $contributorId) {
1740 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1741 // get rel type id for employee of relation
1742 foreach ($relationshipTypeIds as $id => $typeVals) {
1743 if ($typeVals['name_a_b'] == 'Employee of') {
1744 $relationshipTypeId = $id;
1749 $rel = new CRM_Contact_DAO_Relationship();
1750 $rel->relationship_type_id
= $relationshipTypeId;
1751 $rel->contact_id_a
= $sourceContactId;
1752 $rel->contact_id_b
= $contributorId;
1753 if ($rel->find(TRUE)) {
1754 $ids['individual_id'] = $rel->contact_id_a
;
1755 $ids['organization_id'] = $rel->contact_id_b
;
1767 static function getContributionDates() {
1768 $config = CRM_Core_Config
::singleton();
1769 $currentMonth = date('m');
1770 $currentDay = date('d');
1771 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1772 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1773 (int ) $config->fiscalYearStart
['d'] > $currentDay
1776 $year = date('Y') - 1;
1781 $year = array('Y' => $year);
1782 $yearDate = $config->fiscalYearStart
;
1783 $yearDate = array_merge($year, $yearDate);
1784 $yearDate = CRM_Utils_Date
::format($yearDate);
1786 $monthDate = date('Ym') . '01';
1792 'yearDate' => $yearDate,
1793 'monthDate' => $monthDate,
1798 * Load objects relations to contribution object
1799 * Objects are stored in the $_relatedObjects property
1800 * In the first instance we are just moving functionality from BASEIpn -
1801 * see http://issues.civicrm.org/jira/browse/CRM-9996
1803 * @param array $input Input as delivered from Payment Processor
1804 * @param array $ids Ids as Loaded by Payment Processor
1805 * @param boolean $required Is Payment processor / contribution page required
1806 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1807 * Note that the unit test for the BaseIPN class tests this function
1809 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1811 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
1812 if(empty($ids['contact']) && isset($this->contact_id
)){
1813 $ids['contact'] = $this->contact_id
;
1816 if (empty($this->_component
)) {
1817 if (! empty($ids['event'])) {
1818 $this->_component
= 'event';
1821 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1824 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1825 $contributionType = new CRM_Financial_BAO_FinancialType();
1826 $contributionType->id
= $this->financial_type_id
;
1827 if (!$contributionType->find(TRUE)) {
1828 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1830 if (!empty($ids['contact'])) {
1831 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1832 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1833 $this->_relatedObjects
['contact']->find(TRUE);
1835 $this->_relatedObjects
['contributionType'] = $contributionType;
1837 if ($this->_component
== 'contribute') {
1838 // retrieve the other optional objects first so
1839 // stuff down the line can use this info and do things
1841 //in any case get the memberships associated with the contribution
1842 //because we now support multiple memberships w/ price set
1843 // see if there are any other memberships to be considered for same contribution.
1845 SELECT membership_id
1846 FROM civicrm_membership_payment
1847 WHERE contribution_id = %1 ";
1848 $params = array(1 => array($this->id
, 'Integer'));
1850 $dao = CRM_Core_DAO
::executeQuery($query, $params );
1851 while ($dao->fetch()) {
1852 if ($dao->membership_id
) {
1853 if (!is_array($ids['membership'])) {
1854 $ids['membership'] = array();
1856 $ids['membership'][] = $dao->membership_id
;
1860 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1861 foreach ($ids['membership'] as $id) {
1863 $membership = new CRM_Member_BAO_Membership();
1864 $membership->id
= $id;
1865 if (!$membership->find(TRUE)) {
1866 throw new Exception("Could not find membership record: $id");
1868 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
1869 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
1870 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
1871 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
1872 $membership->free();
1877 if (!empty($ids['pledge_payment'])) {
1879 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1880 if (empty($paymentID)) {
1883 $payment = new CRM_Pledge_BAO_PledgePayment();
1884 $payment->id
= $paymentID;
1885 if (!$payment->find(TRUE)) {
1886 throw new Exception("Could not find pledge payment record: " . $paymentID);
1888 $this->_relatedObjects
['pledge_payment'][] = $payment;
1892 if (!empty($ids['contributionRecur'])) {
1893 $recur = new CRM_Contribute_BAO_ContributionRecur();
1894 $recur->id
= $ids['contributionRecur'];
1895 if (!$recur->find(TRUE)) {
1896 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
1898 $this->_relatedObjects
['contributionRecur'] = &$recur;
1899 //get payment processor id from recur object.
1900 $paymentProcessorID = $recur->payment_processor_id
;
1902 //for normal contribution get the payment processor id.
1903 if (!$paymentProcessorID) {
1904 if ($this->contribution_page_id
) {
1905 // get the payment processor id from contribution page
1906 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
1907 $this->contribution_page_id
,
1911 //fail to load payment processor id.
1912 elseif (!CRM_Utils_Array
::value('pledge_payment', $ids)) {
1913 $loadObjectSuccess = TRUE;
1915 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
1917 return $loadObjectSuccess;
1922 // we are in event mode
1923 // make sure event exists and is valid
1924 $event = new CRM_Event_BAO_Event();
1925 $event->id
= $ids['event'];
1926 if ($ids['event'] &&
1929 throw new Exception("Could not find event: " . $ids['event']);
1932 $this->_relatedObjects
['event'] = &$event;
1934 $participant = new CRM_Event_BAO_Participant();
1935 $participant->id
= $ids['participant'];
1936 if ($ids['participant'] &&
1937 !$participant->find(TRUE)
1939 throw new Exception("Could not find participant: " . $ids['participant']);
1941 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
1943 $this->_relatedObjects
['participant'] = &$participant;
1945 if (!$paymentProcessorID) {
1946 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
1950 $loadObjectSuccess = TRUE;
1951 if ($paymentProcessorID) {
1952 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
1953 $this->is_test ?
'test' : 'live'
1955 $ids['paymentProcessor'] = $paymentProcessorID;
1956 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
1958 elseif ($required) {
1959 $loadObjectSuccess = FALSE;
1960 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
1963 return $loadObjectSuccess;
1967 * Create array of message information - ie. return html version, txt version, to field
1969 * @param array $input incoming information
1970 * - is_recur - should this be treated as recurring (not sure why you wouldn't
1971 * just check presence of recur object but maintaining legacy approach
1973 * @param array $ids IDs of related objects
1974 * @param array $values any values that may have already been compiled by calling process
1975 * This is augmented by values 'gathered' by gatherMessageValues
1976 * @param bool $returnMessageText distinguishes between whether to send message or return
1977 * message text. We are working towards this function ALWAYS returning message text & calling
1978 * function doing emails / pdfs with it
1979 * @return array $messageArray - messages
1981 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
1982 if (empty($this->_relatedObjects
)) {
1983 $this->loadRelatedObjects($input, $ids);
1985 if (empty($this->_component
)) {
1986 $this->_component
= CRM_Utils_Array
::value('component', $input);
1989 //not really sure what params might be passed in but lets merge em into values
1990 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
1991 $template = CRM_Core_Smarty
::singleton();
1992 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
1993 //what does recur 'mean here - to do with payment processor return functionality but
1994 // what is the importance
1995 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
1996 $paymentObject = &CRM_Core_Payment
::singleton(
1997 $this->is_test ?
'test' : 'live',
1998 $this->_relatedObjects
['paymentProcessor']
2001 $entityID = $entity = NULL;
2002 if (isset($ids['contribution'])) {
2003 $entity = 'contribution';
2004 $entityID = $ids['contribution'];
2006 if (isset($ids['membership']) && $ids['membership']) {
2007 $entity = 'membership';
2008 $entityID = $ids['membership'];
2011 $url = $paymentObject->subscriptionURL($entityID, $entity);
2012 $template->assign('cancelSubscriptionUrl', $url);
2014 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2015 $template->assign('updateSubscriptionBillingUrl', $url);
2017 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2018 $template->assign('updateSubscriptionUrl', $url);
2020 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2021 //direct mode showing billing block, so use directIPN for temporary
2022 $template->assign('contributeMode', 'directIPN');
2025 // todo remove strtolower - check consistency
2026 if (strtolower($this->_component
) == 'event') {
2027 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2028 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2032 $values['contribution_id'] = $this->id
;
2033 if (CRM_Utils_Array
::value('related_contact', $ids)) {
2034 $values['related_contact'] = $ids['related_contact'];
2035 if (isset($ids['onbehalf_dupe_alert'])) {
2036 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2038 $entityBlock = array(
2039 'contact_id' => $ids['contact'],
2040 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2041 'Home', 'id', 'name'
2044 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2045 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2048 if ($this->is_test
) {
2051 if (!empty($this->_relatedObjects
['membership'])) {
2052 foreach ($this->_relatedObjects
['membership'] as $membership) {
2053 if ($membership->id
) {
2054 $values['membership_id'] = $membership->id
;
2056 // need to set the membership values here
2057 $template->assign('membership_assign', 1);
2058 $template->assign('membership_name',
2059 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2061 $template->assign('mem_start_date', $membership->start_date
);
2062 $template->assign('mem_join_date', $membership->join_date
);
2063 $template->assign('mem_end_date', $membership->end_date
);
2064 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2065 $template->assign('mem_status', $membership_status);
2066 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2067 $template->assign('is_pay_later', 1);
2070 // if separate payment there are two contributions recorded and the
2071 // admin will need to send a receipt for each of them separately.
2072 // we dont link the two in the db (but can potentially infer it if needed)
2073 $template->assign('is_separate_payment', 0);
2075 if ($recur && $paymentObject) {
2076 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2077 $template->assign('cancelSubscriptionUrl', $url);
2078 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2079 $template->assign('updateSubscriptionBillingUrl', $url);
2080 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2081 $template->assign('updateSubscriptionUrl', $url);
2084 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2087 // otherwise if its about sending emails, continue sending without return, as we
2088 // don't want to exit the loop.
2093 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2099 * Gather values for contribution mail - this function has been created
2100 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2101 * Values related to the contribution in question are gathered
2103 * @param array $input input into function (probably from payment processor)
2104 * @param array $ids the set of ids related to the inpurt
2106 * @return array $values
2108 * NB don't add direct calls to the function as we intend to change the signature
2110 function _gatherMessageValues($input, &$values, $ids = array()) {
2111 // set display address of contributor
2112 if ($this->address_id
) {
2113 $addressParams = array('id' => $this->address_id
);
2114 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2115 $addressDetails = array_values($addressDetails);
2116 $values['address'] = $addressDetails[0]['display'];
2118 if ($this->_component
== 'contribute') {
2119 if (isset($this->contribution_page_id
)) {
2120 CRM_Contribute_BAO_ContributionPage
::setValues(
2121 $this->contribution_page_id
,
2124 if ($this->contribution_page_id
) {
2125 // CRM-8254 - override default currency if applicable
2126 $config = CRM_Core_Config
::singleton();
2127 $config->defaultCurrency
= CRM_Utils_Array
::value(
2130 $config->defaultCurrency
2134 // no contribution page -probably back office
2136 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2137 $values['is_email_receipt'] = 1;
2138 $values['title'] = 'Contribution';
2140 // set lineItem for contribution
2142 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2143 if (!empty($lineItem)) {
2144 $itemId = key($lineItem);
2145 foreach ($lineItem as &$eachItem) {
2146 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2147 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2148 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2149 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2152 $values['lineItem'][0] = $lineItem;
2153 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2157 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2161 // if this is onbehalf of contribution then set related contact
2162 if (CRM_Utils_Array
::value('individual_id', $relatedContact)) {
2163 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2168 $eventParams = array(
2169 'id' => $this->_relatedObjects
['event']->id
,
2171 $values['event'] = array();
2173 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2175 //get location details
2176 $locationParams = array(
2177 'entity_id' => $this->_relatedObjects
['event']->id
,
2178 'entity_table' => 'civicrm_event',
2180 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2182 $ufJoinParams = array(
2183 'entity_table' => 'civicrm_event',
2184 'entity_id' => $ids['event'],
2185 'module' => 'CiviEvent',
2188 list($custom_pre_id,
2190 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2192 $values['custom_pre_id'] = $custom_pre_id;
2193 $values['custom_post_id'] = $custom_post_ids;
2195 // set lineItem for event contribution
2197 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2198 if (!empty($participantIds)) {
2199 foreach ($participantIds as $pIDs) {
2200 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2201 if (!CRM_Utils_System
::isNull($lineItem)) {
2202 $values['lineItem'][] = $lineItem;
2213 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2214 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2215 * Note we send directly from this function in some cases because it is only partly refactored
2216 * Don't call this function directly as the signature will change
2218 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2219 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2220 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2221 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2222 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2223 $template->assign('useForMember', true);
2225 //assign honor infomation to receiptmessage
2226 $honorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2230 if (!empty($honorID)) {
2232 $honorDefault = $honorIds = array();
2233 $honorIds['contribution'] = $this->id
;
2234 $idParams = array('id' => $honorID, 'contact_id' => $honorID);
2235 CRM_Contact_BAO_Contact
::retrieve($idParams, $honorDefault, $honorIds);
2236 $honorType = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'honor_type_id');
2238 $template->assign('honor_block_is_active', 1);
2239 if (CRM_Utils_Array
::value('prefix_id', $honorDefault)) {
2240 $prefix = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id');
2241 $template->assign('honor_prefix', $prefix[$honorDefault['prefix_id']]);
2243 $template->assign('honor_first_name', CRM_Utils_Array
::value('first_name', $honorDefault));
2244 $template->assign('honor_last_name', CRM_Utils_Array
::value('last_name', $honorDefault));
2245 $template->assign('honor_email', CRM_Utils_Array
::value('email', $honorDefault['email'][1]));
2246 $template->assign('honor_type', $honorType[$this->honor_type_id
]);
2249 $dao = new CRM_Contribute_DAO_ContributionProduct();
2250 $dao->contribution_id
= $this->id
;
2251 if ($dao->find(TRUE)) {
2252 $premiumId = $dao->product_id
;
2253 $template->assign('option', $dao->product_option
);
2255 $productDAO = new CRM_Contribute_DAO_Product();
2256 $productDAO->id
= $premiumId;
2257 $productDAO->find(TRUE);
2258 $template->assign('selectPremium', TRUE);
2259 $template->assign('product_name', $productDAO->name
);
2260 $template->assign('price', $productDAO->price
);
2261 $template->assign('sku', $productDAO->sku
);
2263 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2264 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2265 if(empty($amount) && isset($this->total_amount
)){
2266 $amount = $this->total_amount
;
2268 $template->assign('amount', $amount);
2269 // add the new contribution values
2270 if (strtolower($this->_component
) == 'contribute') {
2272 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2273 $softDAO->contribution_id
= $this->id
;
2274 if ($softDAO->find(TRUE)) {
2275 $template->assign('pcpBlock', TRUE);
2276 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2277 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2278 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2280 //assign the pcp page title for email subject
2281 $pcpDAO = new CRM_PCP_DAO_PCP();
2282 $pcpDAO->id
= $softDAO->pcp_id
;
2283 if ($pcpDAO->find(TRUE)) {
2284 $template->assign('title', $pcpDAO->title
);
2289 if ($this->financial_type_id
) {
2290 $values['financial_type_id'] = $this->financial_type_id
;
2294 $template->assign('trxn_id', $this->trxn_id
);
2295 $template->assign('receive_date',
2296 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2298 $template->assign('contributeMode', 'notify');
2299 $template->assign('action', $this->is_test ?
1024 : 1);
2300 $template->assign('receipt_text',
2301 CRM_Utils_Array
::value('receipt_text',
2305 $template->assign('is_monetary', 1);
2306 $template->assign('is_recur', (bool) $recur);
2307 $template->assign('currency', $this->currency
);
2308 $template->assign('address', CRM_Utils_Address
::format($input));
2309 if ($this->_component
== 'event') {
2310 $template->assign('title', $values['event']['title']);
2311 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2312 $viewRoles = array();
2313 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2314 $viewRoles[] = $participantRoles[$v];
2316 $values['event']['participant_role'] = implode(', ', $viewRoles);
2317 $template->assign('event', $values['event']);
2318 $template->assign('location', $values['location']);
2319 $template->assign('customPre', $values['custom_pre_id']);
2320 $template->assign('customPost', $values['custom_post_id']);
2323 if ($this->_relatedObjects
['participant']->is_test
) {
2327 $values['params'] = array();
2328 //to get email of primary participant.
2329 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2330 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2331 //build an array of cId/pId of participants
2332 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2333 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2334 //send receipt to additional participant if exists
2335 if (count($additionalIDs)) {
2336 $template->assign('isPrimary', 0);
2337 $template->assign('customProfile', NULL);
2338 //set additionalParticipant true
2339 $values['params']['additionalParticipant'] = TRUE;
2340 foreach ($additionalIDs as $pId => $cId) {
2342 //to change the status pending to completed
2343 $additional = new CRM_Event_DAO_Participant();
2344 $additional->id
= $pId;
2345 $additional->contact_id
= $cId;
2346 $additional->find(TRUE);
2347 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2348 $additional->status_id
= 1;
2349 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2350 //if additional participant dont have email
2352 if (!$additionalParticipantInfo) {
2353 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2355 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2356 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2357 $additional->save();
2358 $additional->free();
2359 $template->assign('amount', $amount);
2360 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2364 //build an array of custom profile and assigning it to template
2365 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2367 if (count($customProfile)) {
2368 $template->assign('customProfile', $customProfile);
2371 // for primary contact
2372 $values['params']['additionalParticipant'] = FALSE;
2373 $template->assign('isPrimary', 1);
2374 $template->assign('amount', $primaryAmount);
2375 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2376 if ($this->payment_instrument_id
) {
2377 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2378 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2380 // carry paylater, since we did not created billing,
2381 // so need to pull email from primary location, CRM-4395
2382 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2388 * Function to check whether payment processor supports
2389 * cancellation of contribution subscription
2391 * @param int $contributionId contribution id
2397 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2398 $cacheKeyString = "$contributionId";
2399 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2401 static $supportsCancel = array();
2403 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2404 $supportsCancel[$cacheKeyString] = FALSE;
2405 $isCancelled = FALSE;
2407 if ($isNotCancelled) {
2408 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2411 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2412 if (!empty($paymentObject)) {
2413 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2416 return $supportsCancel[$cacheKeyString];
2420 * Function to check whether subscription is already cancelled
2422 * @param int $contributionId contribution id
2424 * @return string $status contribution status
2428 static function isSubscriptionCancelled($contributionId) {
2430 SELECT cr.contribution_status_id
2431 FROM civicrm_contribution_recur cr
2432 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2433 WHERE con.id = %1 LIMIT 1";
2434 $params = array(1 => array($contributionId, 'Integer'));
2435 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2436 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2437 if ($status == 'Cancelled') {
2444 * Function to create all financial accounts entry
2446 * @param array $params contribution object, line item array and params for trxn
2452 static function recordFinancialAccounts(&$params, $financialTrxnVals = NULL) {
2453 $skipRecords = $update = FALSE;
2454 $additionalParticipantId = array();
2455 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2457 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2458 $entityId = $params['participant_id'];
2459 $entityTable = 'civicrm_participant';
2460 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2463 $entityId = $params['contribution']->id
;
2464 $entityTable = 'civicrm_contribution';
2467 $entityID[] = $entityId;
2468 if (!empty($additionalParticipantId)) {
2469 $entityID +
= $additionalParticipantId;
2471 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2472 if (!CRM_Utils_Array
::value('prevContribution', $params)) {
2479 $statusId = $params['contribution']->contribution_status_id
;
2480 // CRM-13964 partial payment
2481 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2482 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
2483 $partialAmtPay = $params['partial_amount_pay'];
2484 $partialAmtTotal = $params['partial_payment_total'];
2486 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2487 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2488 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2489 $params['total_amount'] = $partialAmtPay;
2491 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2492 if (empty($balanceTrxnInfo['trxn_id'])) {
2493 // create new balance transaction record
2494 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2495 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2497 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2498 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2499 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2500 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2501 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2502 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2503 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2504 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2505 $balanceTrxnParams['status_id'] = $statusId;
2506 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2507 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2508 if (CRM_Utils_Array
::value('payment_processor', $params)) {
2509 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2511 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2515 // build line item array if its not set in $params
2516 if (!CRM_Utils_Array
::value('line_item', $params) ||
$additionalParticipantId) {
2517 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
2520 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2521 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2522 $skipRecords = TRUE;
2523 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses)) {
2524 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2525 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2527 elseif (CRM_Utils_Array
::value('payment_processor', $params)) {
2528 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2530 elseif (CRM_Utils_Array
::value('payment_instrument_id', $params)) {
2531 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2534 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2535 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2536 $params['to_financial_account_id'] = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
2539 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2540 if (!isset($totalAmount) && CRM_Utils_Array
::value('prevContribution', $params)) {
2541 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2544 //build financial transaction params
2545 $trxnParams = array(
2546 'contribution_id' => $params['contribution']->id
,
2547 'to_financial_account_id' => $params['to_financial_account_id'],
2548 'trxn_date' => date('YmdHis'),
2549 'total_amount' => $totalAmount,
2550 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2551 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2552 'currency' => $params['contribution']->currency
,
2553 'trxn_id' => $params['contribution']->trxn_id
,
2554 'status_id' => $statusId,
2555 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2556 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2559 if (CRM_Utils_Array
::value('payment_processor', $params)) {
2560 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2563 if (isset($fromFinancialAccountId)) {
2564 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2567 // consider external values passed for recording transaction entry
2568 if (!empty($financialTrxnVals)) {
2569 $trxnParams = array_merge($trxnParams, $financialTrxnVals);
2572 $params['trxnParams'] = $trxnParams;
2574 if (CRM_Utils_Array
::value('prevContribution', $params)) {
2575 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2576 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2577 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2578 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2579 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2580 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2581 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2583 //if financial type is changed
2584 if (CRM_Utils_Array
::value('financial_type_id', $params) &&
2585 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2586 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2587 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2588 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2589 if ($oldFinancialAccount != $newFinancialAccount) {
2590 $params['total_amount'] = 0;
2591 if ($params['contribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)) {
2592 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2593 $params['prevContribution']->financial_type_id
, $relationTypeId);
2596 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2597 if (CRM_Utils_Array
::value('financialTrxnId', $lastFinancialTrxnId)) {
2598 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2601 self
::updateFinancialAccounts($params, 'changeFinancialType');
2602 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2603 $params['financial_account_id'] = $newFinancialAccount;
2604 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2605 self
::updateFinancialAccounts($params);
2606 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2610 //Update contribution status
2611 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2612 if (CRM_Utils_Array
::value('contribution_status_id', $params) &&
2613 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2614 //Update Financial Records
2615 self
::updateFinancialAccounts($params, 'changedStatus');
2618 // change Payment Instrument for a Completed contribution
2619 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2620 // instrument is null and now new payment instrument is added along with the payment
2621 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2622 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2623 if (array_key_exists('payment_instrument_id', $params)) {
2624 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2625 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2626 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2627 //check if status is changed from Pending to Completed
2628 // do not update payment instrument changes for Pending to Completed
2629 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2630 $params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses))) {
2631 // for all other statuses create new financial records
2632 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2633 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2634 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2637 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2638 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2639 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2640 // for any other payment instrument changes create new financial records
2641 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2642 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2643 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2645 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2646 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2647 // another special case when check number is changed, create new financial records
2648 // create financial trxn with negative amount
2649 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2650 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2651 // create financial trxn with positive amount
2652 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2653 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2654 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2658 //if Change contribution amount
2659 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2660 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2661 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2662 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2663 if (isset($totalAmount) &&
2664 $totalAmount != $params['prevContribution']->total_amount
) {
2665 //Update Financial Records
2666 $params['trxnParams']['from_financial_account_id'] = NULL;
2667 self
::updateFinancialAccounts($params, 'changedAmount');
2672 //records finanical trxn and entity financial trxn
2673 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2674 $params['entity_id'] = $financialTxn->id
;
2677 // record line items and finacial items
2678 if (!CRM_Utils_Array
::value('skipLineItem', $params)) {
2679 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2682 // create batch entry if batch_id is passed
2683 if (CRM_Utils_Array
::value('batch_id', $params)) {
2684 $entityParams = array(
2685 'batch_id' => $params['batch_id'],
2686 'entity_table' => 'civicrm_financial_trxn',
2687 'entity_id' => $financialTxn->id
,
2689 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2692 // when a fee is charged
2693 if (CRM_Utils_Array
::value('fee_amount', $params) && (!CRM_Utils_Array
::value('prevContribution', $params)
2694 ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2695 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2698 if (CRM_Utils_Array
::value('prevContribution', $params) && $entityTable == 'civicrm_participant'
2699 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2700 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2701 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2702 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2704 unset($params['line_item']);
2707 return $financialTxn;
2712 * Function to update all financial accounts entry
2714 * @param array $params contribution object, line item array and params for trxn
2716 * @param string $context update scenarios
2721 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2722 $itemAmount = $trxnID = NULL;
2723 //get all the statuses
2724 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2725 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus) &&
2726 $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2727 && $context == 'changePaymentInstrument') {
2730 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2731 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2733 if ($context == 'changedStatus') {
2734 //get all the statuses
2735 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2737 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2738 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2739 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2741 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2743 elseif ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2744 && $params['prevContribution']->is_pay_later
) {
2745 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2746 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2747 $params['trxnParams']['to_financial_account_id'] = NULL;
2748 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2750 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2751 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2752 $financialTypeID, $relationTypeId);
2754 $itemAmount = $params['trxnParams']['total_amount'];
2756 elseif ($context == 'changePaymentInstrument') {
2757 if ($params['trxnParams']['total_amount'] < 0) {
2758 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2759 if (CRM_Utils_Array
::value('financialTrxnId', $lastFinancialTrxnId)) {
2760 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2761 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2765 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2766 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2769 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2770 $params['entity_id'] = $trxn->id
;
2772 if ($context == 'changedStatus') {
2773 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) &&
2774 ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2775 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2776 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2778 $entityParams = array(
2779 'entity_table' => 'civicrm_financial_item',
2780 'financial_trxn_id' => $trxn->id
,
2782 foreach ($params['line_item'] as $fieldId => $fields) {
2783 foreach ($fields as $fieldValueId => $fieldValues) {
2785 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2786 2 => array($fieldValues['id'], 'Integer'),
2788 CRM_Core_DAO
::executeQuery($query, $fparams);
2790 1 => array($fieldValues['id'], 'Integer'),
2792 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2793 while ($financialItem->fetch()) {
2794 $entityParams['entity_id'] = $financialItem->id
;
2795 $entityParams['amount'] = $financialItem->amount
;
2796 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2803 if ($context != 'changePaymentInstrument') {
2804 $itemParams['entity_table'] = 'civicrm_line_item';
2805 $trxnIds['id'] = $params['entity_id'];
2806 foreach ($params['line_item'] as $fieldId => $fields) {
2807 foreach ($fields as $fieldValueId => $fieldValues) {
2808 $prevParams['entity_id'] = $fieldValues['id'];
2809 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2811 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2812 if ($params['contribution']->receive_date
) {
2813 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2816 $financialAccount = $prevfinancialItem->financial_account_id
;
2817 if (CRM_Utils_Array
::value('financial_account_id', $params)) {
2818 $financialAccount = $params['financial_account_id'];
2821 $currency = $params['prevContribution']->currency
;
2822 if ($params['contribution']->currency
) {
2823 $currency = $params['contribution']->currency
;
2825 if (CRM_Utils_Array
::value('is_quick_config', $params)) {
2826 $amount = $itemAmount;
2828 $amount = $params['total_amount'];
2833 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2836 $amount = $diff * $fieldValues['line_total'];
2839 $itemParams = array(
2840 'transaction_date' => $receiveDate,
2841 'contact_id' => $params['prevContribution']->contact_id
,
2842 'currency' => $currency,
2843 'amount' => $amount,
2844 'description' => $prevfinancialItem->description
,
2845 'status_id' => $prevfinancialItem->status_id
,
2846 'financial_account_id' => $financialAccount,
2847 'entity_table' => 'civicrm_line_item',
2848 'entity_id' => $fieldValues['id']
2850 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
2857 * Function to check status validation on update of a contribution
2859 * @param array $values previous form values before submit
2861 * @param array $fields the input form values
2863 * @param array $errors list of errors
2868 static function checkStatusValidation($values, &$fields, &$errors) {
2869 if (CRM_Utils_System
::isNull($values) && CRM_Utils_Array
::value('id', $fields)) {
2870 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
2871 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
2875 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2876 $checkStatus = array(
2877 'Cancelled' => array('Completed', 'Refunded'),
2878 'Completed' => array('Cancelled', 'Refunded'),
2879 'Pending' => array('Cancelled', 'Completed', 'Failed'),
2880 'Refunded' => array('Cancelled', 'Completed')
2883 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
2884 $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']]));
2889 * Function to delete contribution of contact
2893 * @param integer $contactId contact id
2898 static function deleteContactContribution($contactId) {
2899 $contribution = new CRM_Contribute_DAO_Contribution();
2900 $contribution->contact_id
= $contactId;
2901 $contribution->find();
2902 while ($contribution->fetch()) {
2903 self
::deleteContribution($contribution->id
);
2908 * Get options for a given contribution field.
2909 * @see CRM_Core_DAO::buildOptions
2911 * @param String $fieldName
2912 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
2913 * @param Array $props: whatever is known about this dao object
2915 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2916 $className = __CLASS__
;
2918 switch ($fieldName) {
2919 // This field is not part of this object but the api supports it
2920 case 'payment_processor':
2921 $className = 'CRM_Contribute_BAO_ContributionPage';
2922 // Filter results by contribution page
2923 if (!empty($props['contribution_page_id'])) {
2924 $page = civicrm_api('contribution_page', 'getsingle', array(
2926 'id' => ($props['contribution_page_id'])
2928 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
2929 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
2932 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
2936 * Function to validate financial type
2940 * @param integer $financialTypeId Financial Type id
2945 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
2946 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
2947 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
2949 if (!$financialAccount) {
2950 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
2955 static function recordAdditionPayment($contributionId, $trxnsData, $paymentType, $participantId = NULL) {
2956 // FIXME : needs handling of partial payment validness checking, if its valid then only record new entries
2957 $params = $ids = $defaults = array();
2958 $getInfoOf['id'] = $contributionId;
2960 // build params for recording financial trxn entry
2961 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, $ids);
2962 $params['contribution'] = $contributionDAO;
2963 $params = array_merge($defaults, $params);
2964 $params['skipLineItem'] = TRUE;
2965 $params['partial_payment_total'] = $contributionDAO->total_amount
;
2966 $params['partial_amount_pay'] = $trxnsData['total_amount'];
2967 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
2970 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
2972 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2973 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2974 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
2976 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
2977 $trxnId = $trxnId['trxn_id'];
2980 // criteria for updates contribution total_amount == financial_trxns of partial_payments
2981 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
2982 FROM civicrm_financial_trxn ft
2983 LEFT JOIN civicrm_entity_financial_trxn eft
2984 ON (ft.id = eft.financial_trxn_id)
2985 WHERE eft.entity_table = 'civicrm_contribution'
2986 AND eft.entity_id = {$contributionId}
2987 AND ft.to_financial_account_id != {$toFinancialAccount}
2988 AND ft.status_id = {$statusId}
2990 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
2993 if ($contributionDAO->total_amount
== $sumOfPayments) {
2994 // update contribution status
2995 $contributionUpdate['id'] = $contributionId;
2996 $contributionUpdate['contribution_status_id'] = $statusId;
2997 $contributionUpdate['skipLineItem'] = TRUE;
2998 // note : not using the self::add method,
2999 // the reason because it performs 'status change' related code execution for financial records
3000 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3001 // are coded below i.e. just updating financial_item status to 'Paid'
3002 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3004 if ($participantId) {
3005 // update participant status
3006 $participantUpdate['id'] = $participantId;
3007 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3008 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3009 CRM_Event_BAO_Participant
::add($participantUpdate);
3012 // update financial item statuses
3013 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3014 $paidStatus = array_search('Paid', $financialItemStatus);
3016 $sqlFinancialItemUpdate = "
3017 UPDATE civicrm_financial_item fi
3018 LEFT JOIN civicrm_entity_financial_trxn eft
3019 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3020 SET status_id = {$paidStatus}
3021 WHERE eft.financial_trxn_id = {$trxnId}
3023 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3026 if (!empty($financialTrxn)) {
3027 if ($participantId) {
3028 $inputParams['id'] = $participantId;
3031 $component = 'event';
3032 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3033 $entityObj = $entityObj[$participantId];
3035 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3037 // creation of activity
3038 $activity = new CRM_Activity_DAO_Activity();
3039 $activity->source_record_id
= $financialTrxn->id
;
3040 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
3044 if (!$activity->find(TRUE)) {
3045 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component);
3048 return $financialTrxn;
3051 static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component) {
3052 if ($component == 'event') {
3053 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3054 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3055 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3056 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3057 $targetCid = $entityObj->contact_id
;
3058 $srcRecId = $trxnObj->id
;
3062 $activityParams = array(
3063 'source_contact_id' => $targetCid,
3064 'source_record_id' => $srcRecId,
3065 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3069 'subject' => $subject,
3070 'activity_date_time' => $date,
3071 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3075 'skipRecentView' => TRUE,
3078 // create activity with target contacts
3079 $session = CRM_Core_Session
::singleton();
3080 $id = $session->get('userID');
3082 $activityParams['source_contact_id'] = $id;
3083 $activityParams['target_contact_id'][] = $targetCid;
3085 CRM_Activity_BAO_Activity
::create($activityParams);
3088 function getPaymentInfo($id, $component, $getTrxnInfo = FALSE) {
3089 if ($component == 'event') {
3090 $entity = 'participant';
3091 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3093 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3095 if (empty($total)) {
3096 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, 'civicrm_participant');
3099 $baseTrxnId = $total['trxn_id'];
3100 $total = $total['total_amount'];
3102 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3103 $info['total'] = $total;
3104 $info['paid'] = $total - $paymentBalance;
3105 $info['balance'] = $paymentBalance;
3107 $info['component'] = $component;
3109 if ($getTrxnInfo && $baseTrxnId) {
3111 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id
3112 FROM civicrm_contribution con
3113 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3114 LEFT JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
3115 WHERE ft.id != {$baseTrxnId} AND con.id = {$contributionId}
3117 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3119 while($resultDAO->fetch()) {
3120 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3121 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3122 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3124 'total_amount' => $resultDAO->total_amount
,
3125 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3126 'payment_instrument' => $paymentInstrument[$resultDAO->payment_instrument_id
],
3127 'receive_date' => $resultDAO->trxn_date
,
3128 'trxn_id' => $resultDAO->trxn_id
,
3129 'status' => $statuses[$resultDAO->status_id
],
3132 $info['transaction'] = $rows;