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 (!$contributionID && !CRM_Utils_Array
::value('contribution_status_id', $params)) {
144 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
147 if ($contributionID) {
148 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
151 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
154 $contribution = new CRM_Contribute_BAO_Contribution();
155 $contribution->copyValues($params);
157 $contribution->id
= $contributionID;
159 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
160 $config = CRM_Core_Config
::singleton();
161 $contribution->currency
= $config->defaultCurrency
;
164 if ($contributionID) {
165 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
168 $result = $contribution->save();
170 // Add financial_trxn details as part of fix for CRM-4724
171 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
172 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
174 //add Account details
175 $params['contribution'] = $contribution;
176 self
::recordFinancialAccounts($params);
178 // reset the group contact cache for this group
179 CRM_Contact_BAO_GroupContactCache
::remove();
181 if ($contributionID) {
182 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
185 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
192 * Given the list of params in the params array, fetch the object
193 * and store the values in the values array
195 * @param array $params input parameters to find object
196 * @param array $values output values of the object
197 * @param array $ids the array that holds all the db ids
199 * @return CRM_Contribute_BAO_Contribution|null the found object or null
203 static function &getValues($params, &$values, &$ids) {
204 if (empty($params)) {
207 $contribution = new CRM_Contribute_BAO_Contribution();
209 $contribution->copyValues($params);
211 if ($contribution->find(TRUE)) {
212 $ids['contribution'] = $contribution->id
;
214 CRM_Core_DAO
::storeValues($contribution, $values);
216 return $contribution;
222 * takes an associative array and creates a contribution object
224 * @param array $params (reference ) an assoc array of name/value pairs
225 * @param array $ids the array that holds all the db ids
227 * @return object CRM_Contribute_BAO_Contribution object
231 static function &create(&$params, $ids = array()) {
232 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
233 foreach ($dateFields as $df) {
234 if (isset($params[$df])) {
235 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
239 $transaction = new CRM_Core_Transaction();
241 $contribution = self
::add($params, $ids);
243 if (is_a($contribution, 'CRM_Core_Error')) {
244 $transaction->rollback();
245 return $contribution;
248 $params['contribution_id'] = $contribution->id
;
250 if (CRM_Utils_Array
::value('custom', $params) &&
251 is_array($params['custom'])
253 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
256 $session = CRM_Core_Session
::singleton();
258 if (CRM_Utils_Array
::value('note', $params)) {
260 'entity_table' => 'civicrm_contribution',
261 'note' => $params['note'],
262 'entity_id' => $contribution->id
,
263 'contact_id' => $session->get('userID'),
264 'modified_date' => date('Ymd'),
266 if (!$noteParams['contact_id']) {
267 $noteParams['contact_id'] = $params['contact_id'];
269 CRM_Core_BAO_Note
::add($noteParams);
272 // make entry in batch entity batch table
273 if (CRM_Utils_Array
::value('batch_id', $params)) {
274 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
275 $titleFields = array(
281 $retrieveRequired = 0;
282 foreach ($titleFields as $titleField) {
283 if(!isset($contribution->$titleField)){
284 $retrieveRequired = 1;
288 if ($retrieveRequired == 1) {
289 $contribution->find(TRUE);
293 // check if activity record exist for this contribution, if
295 $activity = new CRM_Activity_DAO_Activity();
296 $activity->source_record_id
= $contribution->id
;
297 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
301 if (!$activity->find(TRUE)) {
302 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
305 // CRM-13237 : if activity record found, update it with campaign id of contribution
306 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
309 // Handle soft credit and / or link to personal campaign page
310 list($type, $softIDs) = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditType($contribution->id
);
311 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
312 if (!empty($type) && $type == 'soft') {
313 $deleteParams = array('contribution_id' => $contribution->id
);
314 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
316 $softParams = array();
317 $softParams['contribution_id'] = $contribution->id
;
318 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
319 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
320 $pcp['pcp_made_through_id'], 'contact_id'
322 $softParams['currency'] = $contribution->currency
;
323 $softParams['amount'] = $contribution->total_amount
;
324 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
325 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
326 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
327 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
329 elseif (CRM_Utils_Array
::value('soft_credit', $params)) {
330 $softParams = $params['soft_credit'];
332 if (!empty($softIDs)) {
333 foreach ( $softIDs as $softID) {
334 if (!in_array($softID, $params['soft_credit_ids'])) {
335 $deleteParams = array('id' => $softID);
336 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
341 foreach ($softParams as $softParam) {
342 $softParam['contribution_id'] = $contribution->id
;
343 $softParam['currency'] = $contribution->currency
;
344 $softParam['pcp_id'] = 'null';
345 $softParam['pcp_display_in_roll'] = 'null';
346 $softParam['pcp_roll_nickname'] = 'null';
347 $softParam['pcp_personal_note'] = 'NULL';
348 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
352 $transaction->commit();
354 // do not add to recent items for import, CRM-4399
355 if (!CRM_Utils_Array
::value('skipRecentView', $params)) {
356 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
357 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
359 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
360 $titleFields = array(
366 $retrieveRequired = 0;
367 foreach ($titleFields as $titleField) {
368 if(!isset($contribution->$titleField)){
369 $retrieveRequired = 1;
373 if($retrieveRequired == 1){
374 $contribution->find(TRUE);
376 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
377 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
379 $recentOther = array();
380 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
381 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
382 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
386 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
387 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
388 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
392 // add the recently created Contribution
393 CRM_Utils_Recent
::add($title,
397 $contribution->contact_id
,
403 return $contribution;
407 * Get the values for pseudoconstants for name->value and reverse.
409 * @param array $defaults (reference) the default values, some of which need to be resolved.
410 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
416 static function resolveDefaults(&$defaults, $reverse = FALSE) {
417 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
418 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
419 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
420 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
424 * This function is used to convert associative array names to values
427 * This function is used by both the web form layer and the api. Note that
428 * the api needs the name => value conversion, also the view layer typically
429 * requires value => name conversion
431 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
432 $id = $property . '_id';
434 $src = $reverse ?
$property : $id;
435 $dst = $reverse ?
$id : $property;
437 if (!array_key_exists($src, $defaults)) {
441 $look = $reverse ?
array_flip($lookup) : $lookup;
443 if (is_array($look)) {
444 if (!array_key_exists($defaults[$src], $look)) {
448 $defaults[$dst] = $look[$defaults[$src]];
453 * Takes a bunch of params that are needed to match certain criteria and
454 * retrieves the relevant objects. We'll tweak this function to be more
455 * full featured over a period of time. This is the inverse function of
456 * create. It also stores all the retrieved values in the default array
458 * @param array $params (reference ) an assoc array of name/value pairs
459 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
460 * in a hierarchical manner
461 * @param array $ids (reference) the array that holds all the db ids
463 * @return object CRM_Contribute_BAO_Contribution object
467 static function retrieve(&$params, &$defaults, &$ids) {
468 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
469 return $contribution;
473 * combine all the importable fields from the lower levels object
475 * The ordering is important, since currently we do not have a weight
476 * scheme. Adding weight is super important and should be done in the
477 * next week or so, before this can be called complete.
479 * @return array array of importable Fields
483 static function &importableFields($contactType = 'Individual', $status = TRUE) {
484 if (!self
::$_importableFields) {
485 if (!self
::$_importableFields) {
486 self
::$_importableFields = array();
490 $fields = array('' => array('title' => ts('- do not import -')));
493 $fields = array('' => array('title' => ts('- Contribution Fields -')));
496 $note = CRM_Core_DAO_Note
::import();
497 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
498 unset($tmpFields['option_value']);
499 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
500 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
502 // Using new Dedupe rule.
504 'contact_type' => $contactType,
505 'used' => 'Unsupervised',
507 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
508 $tmpContactField = array();
509 if (is_array($fieldsArray)) {
510 foreach ($fieldsArray as $value) {
511 //skip if there is no dupe rule
512 if ($value == 'none') {
515 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
520 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
521 $tmpContactField[trim($value)] = $contactFields[trim($value)];
523 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
526 $title = $tmpContactField[trim($value)]['title'];
528 $tmpContactField[trim($value)]['title'] = $title;
532 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
533 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
534 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
535 $fields = array_merge($fields, $tmpContactField);
536 $fields = array_merge($fields, $tmpFields);
537 $fields = array_merge($fields, $note);
538 $fields = array_merge($fields, $optionFields);
539 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
540 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
541 self
::$_importableFields = $fields;
543 return self
::$_importableFields;
546 static function &exportableFields() {
547 if (!self
::$_exportableFields) {
548 if (!self
::$_exportableFields) {
549 self
::$_exportableFields = array();
552 $impFields = CRM_Contribute_DAO_Contribution
::export();
553 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
554 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
555 $typeField = CRM_Financial_DAO_FinancialType
::export();
556 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
557 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
558 $contributionStatus = array(
559 'contribution_status' => array(
560 'title' => ts('Contribution Status'),
561 'name' => 'contribution_status',
562 'data_type' => CRM_Utils_Type
::T_STRING
565 $contributionNote = array(
566 'contribution_note' =>
568 'title' => ts('Contribution Note'),
569 'name' => 'contribution_note',
570 'data_type' => CRM_Utils_Type
::T_TEXT
574 $contributionRecurId = array(
575 'contribution_recur_id' =>
577 'title' => ts('Recurring Contributions ID'),
578 'name' => 'contribution_recur_id',
579 'where' => 'civicrm_contribution.contribution_recur_id',
580 'data_type' => CRM_Utils_Type
::T_INT
583 $extraFields = array(
584 'contribution_batch' => array(
585 'title' => ts('Batch Name')
589 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
590 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $financialAccount,
591 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
594 self
::$_exportableFields = $fields;
597 return self
::$_exportableFields;
600 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
604 $where[] = 'contribution_status_id = 1';
608 $where[] = 'contribution_status_id = 3';
613 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
616 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
619 $whereCond = implode(' AND ', $where);
622 SELECT sum( total_amount ) as total_amount,
623 count( civicrm_contribution.id ) as total_count,
625 FROM civicrm_contribution
626 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
628 AND ( is_test = 0 OR is_test IS NULL )
629 AND contact.is_deleted = 0
633 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
636 while ($dao->fetch()) {
637 $count +
= $dao->total_count
;
638 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
641 return array('amount' => implode(', ', $amount),
649 * Delete the indirect records associated with this contribution first
651 * @return $results no of deleted Contribution on success, false otherwise
655 static function deleteContribution($id) {
656 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
658 $transaction = new CRM_Core_Transaction();
661 //delete activity record
663 'source_record_id' => $id,
664 // activity type id for contribution
665 'activity_type_id' => 6,
668 CRM_Activity_BAO_Activity
::deleteActivity($params);
670 //delete billing address if exists for this contribution.
671 self
::deleteAddress($id);
673 //update pledge and pledge payment, CRM-3961
674 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
676 // remove entry from civicrm_price_set_entity, CRM-5095
677 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
678 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
680 // cleanup line items.
681 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
683 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
684 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
686 if ($participantId) {
687 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
690 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
694 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
695 $noteId = key($note);
697 CRM_Core_BAO_Note
::del($noteId, FALSE);
700 $dao = new CRM_Contribute_DAO_Contribution();
703 $results = $dao->delete();
705 $transaction->commit();
707 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
709 // delete the recently created Contribution
710 $contributionRecent = array(
712 'type' => 'Contribution',
714 CRM_Utils_Recent
::del($contributionRecent);
720 * Check if there is a contribution with the same trxn_id or invoice_id
722 * @param array $params (reference ) an assoc array of name/value pairs
723 * @param array $duplicates (reference ) store ids of duplicate contribs
725 * @return boolean true if duplicate, false otherwise
729 static function checkDuplicate($input, &$duplicates, $id = NULL) {
731 $id = CRM_Utils_Array
::value('id', $input);
733 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
734 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
740 $clause[] = "trxn_id = %1";
741 $input[1] = array($trxn_id, 'String');
745 $clause[] = "invoice_id = %2";
746 $input[2] = array($invoice_id, 'String');
749 if (empty($clause)) {
753 $clause = implode(' OR ', $clause);
755 $clause = "( $clause ) AND id != %3";
756 $input[3] = array($id, 'Integer');
759 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
760 $dao = CRM_Core_DAO
::executeQuery($query, $input);
762 while ($dao->fetch()) {
763 $duplicates[] = $dao->id
;
770 * takes an associative array and creates a contribution_product object
772 * the function extract all the params it needs to initialize the create a
773 * contribution_product object. the params array could contain additional unused name/value
776 * @param array $params (reference ) an assoc array of name/value pairs
778 * @return object CRM_Contribute_BAO_ContributionProduct object
782 static function addPremium(&$params) {
783 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
784 $contributionProduct->copyValues($params);
785 return $contributionProduct->save();
789 * Function to get list of contribution fields for profile
790 * For now we only allow custom contribution fields to be in
793 * @param boolean $addExtraFields true if special fields needs to be added
795 * @return return the list of contribution fields
799 static function getContributionFields($addExtraFields = TRUE) {
800 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
801 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
803 if ($addExtraFields) {
804 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
807 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
809 foreach ($contributionFields as $key => $var) {
810 if ($key == 'contribution_contact_id') {
813 elseif ($key == 'contribution_campaign_id') {
814 $var['title'] = ts('Campaign');
816 $fields[$key] = $var;
819 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
824 * Function to add extra fields specific to contribtion
828 static function getSpecialContributionFields() {
829 $extraFields = array(
830 'honor_contact_name' => array(
831 'name' => 'honor_contact_name',
832 'title' => 'Honor Contact Name',
833 'headerPattern' => '/^honor_contact_name$/i',
834 'where' => 'civicrm_contact_c.display_name',
836 'honor_contact_email' => array(
837 'name' => 'honor_contact_email',
838 'title' => 'Honor Contact Email',
839 'headerPattern' => '/^honor_contact_email$/i',
840 'where' => 'honor_email.email',
842 'honor_contact_id' => array(
843 'name' => 'honor_contact_id',
844 'title' => 'Honor Contact ID',
845 'headerPattern' => '/^honor_contact_id$/i',
846 'where' => 'civicrm_contribution.honor_contact_id',
848 'honor_type_label' => array(
849 'name' => 'honor_type_label',
850 'title' => 'Honor Type Label',
851 'headerPattern' => '/^honor_type_label$/i',
852 'where' => 'honor_type.label',
854 'soft_credit_name' => array(
855 'name' => 'soft_credit_name',
856 'title' => 'Soft Credit Name',
857 'headerPattern' => '/^soft_credit_name$/i',
858 'where' => 'civicrm_contact_d.display_name',
860 'soft_credit_email' => array(
861 'name' => 'soft_credit_email',
862 'title' => 'Soft Credit Email',
863 'headerPattern' => '/^soft_credit_email$/i',
864 'where' => 'soft_email.email',
866 'soft_credit_phone' => array(
867 'name' => 'soft_credit_phone',
868 'title' => 'Soft Credit Phone',
869 'headerPattern' => '/^soft_credit_phone$/i',
870 'where' => 'soft_phone.phone',
872 'soft_credit_contact_id' => array(
873 'name' => 'soft_credit_contact_id',
874 'title' => 'Soft Credit Contact ID',
875 'headerPattern' => '/^soft_credit_contact_id$/i',
876 'where' => 'civicrm_contribution_soft.contact_id',
883 static function getCurrentandGoalAmount($pageID) {
885 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
886 FROM civicrm_contribution_page p,
887 civicrm_contribution c
888 WHERE p.id = c.contribution_page_id
890 AND c.cancel_date is null
894 $config = CRM_Core_Config
::singleton();
895 $params = array(1 => array($pageID, 'Integer'));
896 $dao = CRM_Core_DAO
::executeQuery($query, $params);
899 return array($dao->goal
, $dao->total
);
902 return array(NULL, NULL);
907 * Function to create is honor of
909 * @param array $params associated array of fields (by reference)
910 * @param int $honorId honor Id
911 * @param array $honorParams any params that should be send to the create function
915 static function createHonorContact(&$params, $honorId = NULL, $honorParams = array()) {
916 $honorParams = array_merge(
918 'first_name' => $params['honor_first_name'],
919 'last_name' => $params['honor_last_name'],
920 'prefix_id' => $params['honor_prefix_id'],
921 'email-Primary' => $params['honor_email'],
926 $honorParams['email'] = $params['honor_email'];
928 $dedupeParams = CRM_Dedupe_Finder
::formatParams($honorParams, 'Individual');
929 $dedupeParams['check_permission'] = FALSE;
930 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
932 // if we find more than one contact, use the first one
933 $honorId = CRM_Utils_Array
::value(0, $ids);
936 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
938 CRM_Core_DAO
::$_nullArray,
945 * Function to get list of contribution In Honor of contact Ids
947 * @param int $honorId In Honor of Contact ID
949 * @return return the list of contribution fields
954 static function getHonorContacts($honorId) {
956 $honorDAO = new CRM_Contribute_DAO_Contribution();
957 $honorDAO->honor_contact_id
= $honorId;
960 $status = CRM_Contribute_PseudoConstant
::contributionStatus($honorDAO->contribution_status_id
);
961 $type = CRM_Contribute_PseudoConstant
::financialType();
963 while ($honorDAO->fetch()) {
964 $params[$honorDAO->id
]['honorId'] = $honorDAO->contact_id
;
965 $params[$honorDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $honorDAO->contact_id
, 'display_name');
966 $params[$honorDAO->id
]['type'] = $type[$honorDAO->financial_type_id
];
967 $params[$honorDAO->id
]['type_id'] = $honorDAO->financial_type_id
;
968 $params[$honorDAO->id
]['amount'] = CRM_Utils_Money
::format($honorDAO->total_amount
, $honorDAO->currency
);
969 $params[$honorDAO->id
]['source'] = $honorDAO->source
;
970 $params[$honorDAO->id
]['receive_date'] = $honorDAO->receive_date
;
971 $params[$honorDAO->id
]['contribution_status'] = CRM_Utils_Array
::value($honorDAO->contribution_status_id
, $status);
978 * function to get the sort name of a contact for a particular contribution
980 * @param int $id id of the contribution
982 * @return null|string sort name of the contact if found
986 static function sortName($id) {
987 $id = CRM_Utils_Type
::escape($id, 'Integer');
990 SELECT civicrm_contact.sort_name
991 FROM civicrm_contribution, civicrm_contact
992 WHERE civicrm_contribution.contact_id = civicrm_contact.id
993 AND civicrm_contribution.id = {$id}
995 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
998 static function annual($contactID) {
999 if (is_array($contactID)) {
1000 $contactIDs = implode(',', $contactID);
1003 $contactIDs = $contactID;
1006 $config = CRM_Core_Config
::singleton();
1007 $startDate = $endDate = NULL;
1009 $currentMonth = date('m');
1010 $currentDay = date('d');
1011 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1012 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1013 (int ) $config->fiscalYearStart
['d'] > $currentDay
1016 $year = date('Y') - 1;
1021 $nextYear = $year +
1;
1023 if ($config->fiscalYearStart
) {
1024 if ($config->fiscalYearStart
['M'] < 10) {
1025 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1027 if ($config->fiscalYearStart
['d'] < 10) {
1028 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1030 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1035 $startDate = "$year$monthDay";
1036 $endDate = "$nextYear$monthDay";
1039 SELECT count(*) as count,
1040 sum(total_amount) as amount,
1041 avg(total_amount) as average,
1043 FROM civicrm_contribution b
1044 WHERE b.contact_id IN ( $contactIDs )
1045 AND b.contribution_status_id = 1
1047 AND b.receive_date >= $startDate
1048 AND b.receive_date < $endDate
1051 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1053 $amount = $average = array();
1054 while ($dao->fetch()) {
1055 if ($dao->count
> 0 && $dao->amount
> 0) {
1056 $count +
= $dao->count
;
1057 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1058 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1064 implode(', ', $amount),
1065 implode(', ', $average),
1068 return array(0, 0, 0);
1072 * Check if there is a contribution with the params passed in.
1073 * Used for trxn_id,invoice_id and contribution_id
1075 * @param array $params an assoc array of name/value pairs
1077 * @return array contribution id if success else NULL
1081 static function checkDuplicateIds($params) {
1082 $dao = new CRM_Contribute_DAO_Contribution();
1086 foreach ($params as $k => $v) {
1088 $clause[] = "$k = '$v'";
1091 $clause = implode(' AND ', $clause);
1092 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1093 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1095 while ($dao->fetch()) {
1103 * Function to get the contribution details for component export
1105 * @param int $exportMode export mode
1106 * @param string $componentIds component ids
1108 * @return array associated array
1113 static function getContributionDetails($exportMode, $componentIds) {
1114 $paymentDetails = array();
1115 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1117 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1118 $componentSelect = " civicrm_participant_payment.participant_id id";
1119 $additionalClause = "
1120 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1121 AND civicrm_participant_payment.participant_id {$componentClause} )
1124 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1125 $componentSelect = " civicrm_membership_payment.membership_id id";
1126 $additionalClause = "
1127 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1128 AND civicrm_membership_payment.membership_id {$componentClause} )
1131 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1132 $componentSelect = " civicrm_pledge_payment.id id";
1133 $additionalClause = "
1134 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1135 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1139 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1140 trxn_id, {$componentSelect}
1141 FROM civicrm_contribution
1142 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1143 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1144 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1145 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1146 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1147 AND option_group_contribution_status.id = contribution_status.option_group_id )
1151 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1153 while ($dao->fetch()) {
1154 $paymentDetails[$dao->id
] = array(
1155 'total_amount' => $dao->total_amount
,
1156 'contribution_status' => $dao->status
,
1157 'receive_date' => $dao->receive_date
,
1158 'pay_instru' => $dao->payment_instrument
,
1159 'trxn_id' => $dao->trxn_id
,
1163 return $paymentDetails;
1167 * Function to create address associated with contribution record.
1168 * @param array $params an associated array
1169 * @param int $billingID $billingLocationTypeID
1171 * @return address id
1174 static function createAddress(&$params, $billingLocationTypeID) {
1175 $billingFields = array(
1178 'state_province_id',
1183 //build address array
1184 $addressParams = array();
1185 $addressParams['location_type_id'] = $billingLocationTypeID;
1186 $addressParams['is_billing'] = 1;
1188 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1189 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1190 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1191 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1193 foreach ($billingFields as $value) {
1194 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1197 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1199 return $address->id
;
1203 * Delete billing address record related contribution
1205 * @param int $contact_id contact id
1206 * @param int $contribution_id contributionId
1210 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1212 $contactJoin = NULL;
1214 if ($contributionId) {
1215 $clauses[] = "cc.id = {$contributionId}";
1219 $clauses[] = "cco.id = {$contactId}";
1220 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1223 if (empty($clauses)) {
1224 CRM_Core_Error
::fatal();
1227 $condition = implode(' OR ', $clauses);
1231 FROM civicrm_address ca
1232 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1236 $dao = CRM_Core_DAO
::executeQuery($query);
1238 while ($dao->fetch()) {
1239 $params = array('id' => $dao->id
);
1240 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1245 * This function check online pending contribution associated w/
1246 * Online Event Registration or Online Membership signup.
1248 * @param int $componentId participant/membership id.
1249 * @param string $componentName Event/Membership.
1251 * @return $contributionId pending contribution id.
1254 static function checkOnlinePendingContribution($componentId, $componentName) {
1255 $contributionId = NULL;
1256 if (!$componentId ||
1257 !in_array($componentName, array('Event', 'Membership'))
1259 return $contributionId;
1262 if ($componentName == 'Event') {
1263 $idName = 'participant_id';
1264 $componentTable = 'civicrm_participant';
1265 $paymentTable = 'civicrm_participant_payment';
1266 $source = ts('Online Event Registration');
1269 if ($componentName == 'Membership') {
1270 $idName = 'membership_id';
1271 $componentTable = 'civicrm_membership';
1272 $paymentTable = 'civicrm_membership_payment';
1273 $source = ts('Online Contribution');
1276 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1279 SELECT component.id as {$idName},
1280 componentPayment.contribution_id as contribution_id,
1281 contribution.source source,
1282 contribution.contribution_status_id as contribution_status_id,
1283 contribution.is_pay_later as is_pay_later
1284 FROM $componentTable component
1285 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1286 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1287 WHERE component.id = {$componentId}";
1289 $dao = CRM_Core_DAO
::executeQuery($query);
1291 while ($dao->fetch()) {
1292 if ($dao->contribution_id
&&
1293 $dao->is_pay_later
&&
1294 $dao->contribution_status_id
== $pendingStatusId &&
1295 strpos($dao->source
, $source) !== FALSE
1297 $contributionId = $dao->contribution_id
;
1302 return $contributionId;
1306 * This function update contribution as well as related objects.
1308 static function transitionComponents($params, $processContributionObject = FALSE) {
1309 // get minimum required values.
1310 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1311 $componentId = CRM_Utils_Array
::value('component_id', $params);
1312 $componentName = CRM_Utils_Array
::value('componentName', $params);
1313 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1314 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1316 // if we already processed contribution object pass previous status id.
1317 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1319 $updateResult = array();
1321 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1323 // we process only ( Completed, Cancelled, or Failed ) contributions.
1324 if (!$contributionId ||
1325 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1326 array_search('Cancelled', $contributionStatuses),
1327 array_search('Failed', $contributionStatuses),
1330 return $updateResult;
1333 if (!$componentName ||
!$componentId) {
1334 // get the related component details.
1335 $componentDetails = self
::getComponentDetails($contributionId);
1338 $componentDetails['contact_id'] = $contactId;
1339 $componentDetails['component'] = $componentName;
1341 if ($componentName == 'event') {
1342 $componentDetails['participant'] = $componentId;
1345 $componentDetails['membership'] = $componentId;
1349 if (CRM_Utils_Array
::value('contact_id', $componentDetails)) {
1350 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1356 // do check for required ids.
1357 if (!CRM_Utils_Array
::value('membership', $componentDetails) &&
1358 !CRM_Utils_Array
::value('participant', $componentDetails) &&
1359 !CRM_Utils_Array
::value('pledge_payment', $componentDetails) ||
1360 !CRM_Utils_Array
::value('contact_id', $componentDetails)
1362 return $updateResult;
1365 //now we are ready w/ required ids, start processing.
1367 $baseIPN = new CRM_Core_Payment_BaseIPN();
1369 $input = $ids = $objects = array();
1371 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1372 $ids['contribution'] = $contributionId;
1373 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1374 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1375 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1376 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1377 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1378 $ids['contributionRecur'] = NULL;
1379 $ids['contributionPage'] = NULL;
1381 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1382 CRM_Core_Error
::fatal();
1385 $memberships = &$objects['membership'];
1386 $participant = &$objects['participant'];
1387 $pledgePayment = &$objects['pledge_payment'];
1388 $contribution = &$objects['contribution'];
1390 if ($pledgePayment) {
1391 $pledgePaymentIDs = array();
1392 foreach ($pledgePayment as $key => $object) {
1393 $pledgePaymentIDs[] = $object->id
;
1395 $pledgeID = $pledgePayment[0]->pledge_id
;
1398 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1401 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1402 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1407 // we might want to process contribution object.
1408 $processContribution = FALSE;
1409 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1410 if (is_array($memberships)) {
1411 foreach ($memberships as $membership) {
1413 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1414 $membership->save();
1416 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1417 if ($processContributionObject) {
1418 $processContribution = TRUE;
1425 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1426 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1428 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1429 if ($processContributionObject) {
1430 $processContribution = TRUE;
1434 if ($pledgePayment) {
1435 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1437 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1438 if ($processContributionObject) {
1439 $processContribution = TRUE;
1443 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1444 if (is_array($memberships)) {
1445 foreach ($memberships as $membership) {
1447 $membership->status_id
= array_search('Expired', $membershipStatuses);
1448 $membership->save();
1450 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1451 if ($processContributionObject) {
1452 $processContribution = TRUE;
1458 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1459 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1461 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1462 if ($processContributionObject) {
1463 $processContribution = TRUE;
1467 if ($pledgePayment) {
1468 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1470 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1471 if ($processContributionObject) {
1472 $processContribution = TRUE;
1476 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1478 // only pending contribution related object processed.
1479 if ($previousContriStatusId &&
1480 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1482 // this is case when we already processed contribution object.
1483 return $updateResult;
1485 elseif (!$previousContriStatusId &&
1486 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1488 // this is case when we are going to process contribution object later.
1489 return $updateResult;
1492 if (is_array($memberships)) {
1493 foreach ($memberships as $membership) {
1498 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1499 $membership->membership_type_id
,
1500 $membership->is_test
, $membership->id
1503 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1504 // this picks up membership type changes during renewals
1506 SELECT membership_type_id
1507 FROM civicrm_membership_log
1508 WHERE membership_id=$membership->id
1511 $dao = new CRM_Core_DAO
;
1513 if ($dao->fetch()) {
1514 if (!empty($dao->membership_type_id
)) {
1515 $membership->membership_type_id
= $dao->membership_type_id
;
1516 $membership->save();
1519 // else fall back to using current membership type
1522 // Figure out number of terms
1524 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1525 foreach ($lineitems as $lineitem) {
1526 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1527 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1529 // in case membership_num_terms comes through as null or zero
1530 $numterms = $numterms >= 1 ?
$numterms : 1;
1535 if ($currentMembership) {
1536 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1537 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1538 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1541 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1544 //get the status for membership.
1545 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1547 $dates['join_date'],
1552 $formattedParams = array(
1553 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1554 array_search('Current', $membershipStatuses)
1556 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1557 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1558 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1561 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1563 $membership->copyValues($formattedParams);
1564 $membership->save();
1566 //updating the membership log
1567 $membershipLog = array();
1568 $membershipLog = $formattedParams;
1569 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1570 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1572 $membershipLog['start_date'] = $logStartDate;
1573 $membershipLog['membership_id'] = $membership->id
;
1574 $membershipLog['modified_id'] = $membership->contact_id
;
1575 $membershipLog['modified_date'] = date('Ymd');
1576 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1578 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1580 //update related Memberships.
1581 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1583 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1586 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1587 if ($processContributionObject) {
1588 $processContribution = TRUE;
1591 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1597 $updatedStatusId = array_search('Registered', $participantStatuses);
1598 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1600 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1601 if ($processContributionObject) {
1602 $processContribution = TRUE;
1606 if ($pledgePayment) {
1607 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1609 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1610 if ($processContributionObject) {
1611 $processContribution = TRUE;
1616 // process contribution object.
1617 if ($processContribution) {
1618 $contributionParams = array();
1620 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1621 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1622 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1624 foreach ($fields as $field) {
1625 if (!CRM_Utils_Array
::value($field, $params)) {
1628 $contributionParams[$field] = $params[$field];
1631 $ids = array('contribution' => $contributionId);
1632 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1635 return $updateResult;
1639 * This function returns all contribution related object ids.
1641 public static function getComponentDetails($contributionId) {
1642 $componentDetails = $pledgePayment = array();
1643 if (!$contributionId) {
1644 return $componentDetails;
1648 SELECT c.id as contribution_id,
1649 c.contact_id as contact_id,
1650 mp.membership_id as membership_id,
1651 m.membership_type_id as membership_type_id,
1652 pp.participant_id as participant_id,
1653 p.event_id as event_id,
1654 pgp.id as pledge_payment_id
1655 FROM civicrm_contribution c
1656 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1657 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1658 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1659 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1660 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1661 WHERE c.id = $contributionId";
1663 $dao = CRM_Core_DAO
::executeQuery($query);
1664 $componentDetails = array();
1666 while ($dao->fetch()) {
1667 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1668 $componentDetails['contact_id'] = $dao->contact_id
;
1669 if ($dao->event_id
) {
1670 $componentDetails['event'] = $dao->event_id
;
1672 if ($dao->participant_id
) {
1673 $componentDetails['participant'] = $dao->participant_id
;
1675 if ($dao->membership_id
) {
1676 if (!isset($componentDetails['membership'])) {
1677 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1679 $componentDetails['membership'][] = $dao->membership_id
;
1680 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1682 if ($dao->pledge_payment_id
) {
1683 $pledgePayment[] = $dao->pledge_payment_id
;
1687 if ($pledgePayment) {
1688 $componentDetails['pledge_payment'] = $pledgePayment;
1691 return $componentDetails;
1694 static function contributionCount($contactId, $includeSoftCredit = TRUE, $includeHonoree = TRUE) {
1699 $contactContributionsSQL = "
1700 SELECT contribution.id AS id
1701 FROM civicrm_contribution contribution
1702 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1704 $contactHonoreeContributionsSQL = "
1705 SELECT contribution.id
1706 FROM civicrm_contribution contribution
1707 WHERE contribution.is_test = 0 AND contribution.honor_contact_id = {$contactId} ";
1709 $contactSoftCreditContributionsSQL = "
1710 SELECT contribution.id
1711 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1712 ON ( contribution.id = softContribution.contribution_id )
1713 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1714 $query = "SELECT count( x.id ) count FROM ( ";
1715 $query .= $contactContributionsSQL;
1717 if ($includeSoftCredit) {
1718 $query .= " UNION ";
1719 $query .= $contactSoftCreditContributionsSQL;
1722 if ($includeHonoree) {
1723 $query .= " UNION ";
1724 $query .= $contactHonoreeContributionsSQL;
1729 return CRM_Core_DAO
::singleValueQuery($query);
1733 * Function to get individual id for onbehalf contribution
1735 * @param int $contributionId contribution id
1736 * @param int $contributorId contributor id
1738 * @return array $ids containing organization id and individual id
1741 static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1745 if (!$contributionId) {
1749 // fetch contributor id if null
1750 if (!$contributorId) {
1751 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1752 $contributionId, 'contact_id'
1756 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1757 $activityTypeId = array_search('Contribution', $activityTypeIds);
1759 if ($activityTypeId && $contributorId) {
1761 SELECT civicrm_activity_contact.contact_id
1762 FROM civicrm_activity_contact
1763 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1764 WHERE civicrm_activity.activity_type_id = %1
1765 AND civicrm_activity.source_record_id = %2
1766 AND civicrm_activity_contact.record_type_id = %3
1769 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1770 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1773 1 => array($activityTypeId, 'Integer'),
1774 2 => array($contributionId, 'Integer'),
1775 3 => array($sourceID, 'Integer'),
1778 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1780 // for on behalf contribution source is individual and contributor is organization
1781 if ($sourceContactId && $sourceContactId != $contributorId) {
1782 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1783 // get rel type id for employee of relation
1784 foreach ($relationshipTypeIds as $id => $typeVals) {
1785 if ($typeVals['name_a_b'] == 'Employee of') {
1786 $relationshipTypeId = $id;
1791 $rel = new CRM_Contact_DAO_Relationship();
1792 $rel->relationship_type_id
= $relationshipTypeId;
1793 $rel->contact_id_a
= $sourceContactId;
1794 $rel->contact_id_b
= $contributorId;
1795 if ($rel->find(TRUE)) {
1796 $ids['individual_id'] = $rel->contact_id_a
;
1797 $ids['organization_id'] = $rel->contact_id_b
;
1809 static function getContributionDates() {
1810 $config = CRM_Core_Config
::singleton();
1811 $currentMonth = date('m');
1812 $currentDay = date('d');
1813 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1814 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1815 (int ) $config->fiscalYearStart
['d'] > $currentDay
1818 $year = date('Y') - 1;
1823 $year = array('Y' => $year);
1824 $yearDate = $config->fiscalYearStart
;
1825 $yearDate = array_merge($year, $yearDate);
1826 $yearDate = CRM_Utils_Date
::format($yearDate);
1828 $monthDate = date('Ym') . '01';
1834 'yearDate' => $yearDate,
1835 'monthDate' => $monthDate,
1840 * Load objects relations to contribution object
1841 * Objects are stored in the $_relatedObjects property
1842 * In the first instance we are just moving functionality from BASEIpn -
1843 * see http://issues.civicrm.org/jira/browse/CRM-9996
1845 * @param array $input Input as delivered from Payment Processor
1846 * @param array $ids Ids as Loaded by Payment Processor
1847 * @param boolean $required Is Payment processor / contribution page required
1848 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1849 * Note that the unit test for the BaseIPN class tests this function
1851 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1853 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
1854 if(empty($ids['contact']) && isset($this->contact_id
)){
1855 $ids['contact'] = $this->contact_id
;
1858 if (empty($this->_component
)) {
1859 if (! empty($ids['event'])) {
1860 $this->_component
= 'event';
1863 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1866 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1867 $contributionType = new CRM_Financial_BAO_FinancialType();
1868 $contributionType->id
= $this->financial_type_id
;
1869 if (!$contributionType->find(TRUE)) {
1870 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1872 if (!empty($ids['contact'])) {
1873 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1874 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1875 $this->_relatedObjects
['contact']->find(TRUE);
1877 $this->_relatedObjects
['contributionType'] = $contributionType;
1879 if ($this->_component
== 'contribute') {
1880 // retrieve the other optional objects first so
1881 // stuff down the line can use this info and do things
1883 //in any case get the memberships associated with the contribution
1884 //because we now support multiple memberships w/ price set
1885 // see if there are any other memberships to be considered for same contribution.
1887 SELECT membership_id
1888 FROM civicrm_membership_payment
1889 WHERE contribution_id = %1 ";
1890 $params = array(1 => array($this->id
, 'Integer'));
1892 $dao = CRM_Core_DAO
::executeQuery($query, $params );
1893 while ($dao->fetch()) {
1894 if ($dao->membership_id
) {
1895 if (!is_array($ids['membership'])) {
1896 $ids['membership'] = array();
1898 $ids['membership'][] = $dao->membership_id
;
1902 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1903 foreach ($ids['membership'] as $id) {
1905 $membership = new CRM_Member_BAO_Membership();
1906 $membership->id
= $id;
1907 if (!$membership->find(TRUE)) {
1908 throw new Exception("Could not find membership record: $id");
1910 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
1911 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
1912 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
1913 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
1914 $membership->free();
1919 if (!empty($ids['pledge_payment'])) {
1921 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1922 if (empty($paymentID)) {
1925 $payment = new CRM_Pledge_BAO_PledgePayment();
1926 $payment->id
= $paymentID;
1927 if (!$payment->find(TRUE)) {
1928 throw new Exception("Could not find pledge payment record: " . $paymentID);
1930 $this->_relatedObjects
['pledge_payment'][] = $payment;
1934 if (!empty($ids['contributionRecur'])) {
1935 $recur = new CRM_Contribute_BAO_ContributionRecur();
1936 $recur->id
= $ids['contributionRecur'];
1937 if (!$recur->find(TRUE)) {
1938 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
1940 $this->_relatedObjects
['contributionRecur'] = &$recur;
1941 //get payment processor id from recur object.
1942 $paymentProcessorID = $recur->payment_processor_id
;
1944 //for normal contribution get the payment processor id.
1945 if (!$paymentProcessorID) {
1946 if ($this->contribution_page_id
) {
1947 // get the payment processor id from contribution page
1948 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
1949 $this->contribution_page_id
,
1953 //fail to load payment processor id.
1954 elseif (!CRM_Utils_Array
::value('pledge_payment', $ids)) {
1955 $loadObjectSuccess = TRUE;
1957 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
1959 return $loadObjectSuccess;
1964 // we are in event mode
1965 // make sure event exists and is valid
1966 $event = new CRM_Event_BAO_Event();
1967 $event->id
= $ids['event'];
1968 if ($ids['event'] &&
1971 throw new Exception("Could not find event: " . $ids['event']);
1974 $this->_relatedObjects
['event'] = &$event;
1976 $participant = new CRM_Event_BAO_Participant();
1977 $participant->id
= $ids['participant'];
1978 if ($ids['participant'] &&
1979 !$participant->find(TRUE)
1981 throw new Exception("Could not find participant: " . $ids['participant']);
1983 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
1985 $this->_relatedObjects
['participant'] = &$participant;
1987 if (!$paymentProcessorID) {
1988 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
1992 $loadObjectSuccess = TRUE;
1993 if ($paymentProcessorID) {
1994 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
1995 $this->is_test ?
'test' : 'live'
1997 $ids['paymentProcessor'] = $paymentProcessorID;
1998 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2000 elseif ($required) {
2001 $loadObjectSuccess = FALSE;
2002 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2005 return $loadObjectSuccess;
2009 * Create array of message information - ie. return html version, txt version, to field
2011 * @param array $input incoming information
2012 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2013 * just check presence of recur object but maintaining legacy approach
2015 * @param array $ids IDs of related objects
2016 * @param array $values any values that may have already been compiled by calling process
2017 * This is augmented by values 'gathered' by gatherMessageValues
2018 * @param bool $returnMessageText distinguishes between whether to send message or return
2019 * message text. We are working towards this function ALWAYS returning message text & calling
2020 * function doing emails / pdfs with it
2021 * @return array $messageArray - messages
2023 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2024 if (empty($this->_relatedObjects
)) {
2025 $this->loadRelatedObjects($input, $ids);
2027 if (empty($this->_component
)) {
2028 $this->_component
= CRM_Utils_Array
::value('component', $input);
2031 //not really sure what params might be passed in but lets merge em into values
2032 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2033 $template = CRM_Core_Smarty
::singleton();
2034 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2035 //what does recur 'mean here - to do with payment processor return functionality but
2036 // what is the importance
2037 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2038 $paymentObject = &CRM_Core_Payment
::singleton(
2039 $this->is_test ?
'test' : 'live',
2040 $this->_relatedObjects
['paymentProcessor']
2043 $entityID = $entity = NULL;
2044 if (isset($ids['contribution'])) {
2045 $entity = 'contribution';
2046 $entityID = $ids['contribution'];
2048 if (isset($ids['membership']) && $ids['membership']) {
2049 $entity = 'membership';
2050 $entityID = $ids['membership'];
2053 $url = $paymentObject->subscriptionURL($entityID, $entity);
2054 $template->assign('cancelSubscriptionUrl', $url);
2056 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2057 $template->assign('updateSubscriptionBillingUrl', $url);
2059 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2060 $template->assign('updateSubscriptionUrl', $url);
2062 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2063 //direct mode showing billing block, so use directIPN for temporary
2064 $template->assign('contributeMode', 'directIPN');
2067 // todo remove strtolower - check consistency
2068 if (strtolower($this->_component
) == 'event') {
2069 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2070 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2074 $values['contribution_id'] = $this->id
;
2075 if (CRM_Utils_Array
::value('related_contact', $ids)) {
2076 $values['related_contact'] = $ids['related_contact'];
2077 if (isset($ids['onbehalf_dupe_alert'])) {
2078 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2080 $entityBlock = array(
2081 'contact_id' => $ids['contact'],
2082 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2083 'Home', 'id', 'name'
2086 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2087 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2090 if ($this->is_test
) {
2093 if (!empty($this->_relatedObjects
['membership'])) {
2094 foreach ($this->_relatedObjects
['membership'] as $membership) {
2095 if ($membership->id
) {
2096 $values['membership_id'] = $membership->id
;
2098 // need to set the membership values here
2099 $template->assign('membership_assign', 1);
2100 $template->assign('membership_name',
2101 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2103 $template->assign('mem_start_date', $membership->start_date
);
2104 $template->assign('mem_join_date', $membership->join_date
);
2105 $template->assign('mem_end_date', $membership->end_date
);
2106 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2107 $template->assign('mem_status', $membership_status);
2108 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2109 $template->assign('is_pay_later', 1);
2112 // if separate payment there are two contributions recorded and the
2113 // admin will need to send a receipt for each of them separately.
2114 // we dont link the two in the db (but can potentially infer it if needed)
2115 $template->assign('is_separate_payment', 0);
2117 if ($recur && $paymentObject) {
2118 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2119 $template->assign('cancelSubscriptionUrl', $url);
2120 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2121 $template->assign('updateSubscriptionBillingUrl', $url);
2122 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2123 $template->assign('updateSubscriptionUrl', $url);
2126 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2129 // otherwise if its about sending emails, continue sending without return, as we
2130 // don't want to exit the loop.
2135 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2141 * Gather values for contribution mail - this function has been created
2142 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2143 * Values related to the contribution in question are gathered
2145 * @param array $input input into function (probably from payment processor)
2146 * @param array $ids the set of ids related to the inpurt
2148 * @return array $values
2150 * NB don't add direct calls to the function as we intend to change the signature
2152 function _gatherMessageValues($input, &$values, $ids = array()) {
2153 // set display address of contributor
2154 if ($this->address_id
) {
2155 $addressParams = array('id' => $this->address_id
);
2156 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2157 $addressDetails = array_values($addressDetails);
2158 $values['address'] = $addressDetails[0]['display'];
2160 if ($this->_component
== 'contribute') {
2161 if (isset($this->contribution_page_id
)) {
2162 CRM_Contribute_BAO_ContributionPage
::setValues(
2163 $this->contribution_page_id
,
2166 if ($this->contribution_page_id
) {
2167 // CRM-8254 - override default currency if applicable
2168 $config = CRM_Core_Config
::singleton();
2169 $config->defaultCurrency
= CRM_Utils_Array
::value(
2172 $config->defaultCurrency
2176 // no contribution page -probably back office
2178 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2179 $values['is_email_receipt'] = 1;
2180 $values['title'] = 'Contribution';
2182 // set lineItem for contribution
2184 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2185 if (!empty($lineItem)) {
2186 $itemId = key($lineItem);
2187 foreach ($lineItem as &$eachItem) {
2188 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2189 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2190 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2191 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2194 $values['lineItem'][0] = $lineItem;
2195 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2199 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2203 // if this is onbehalf of contribution then set related contact
2204 if (CRM_Utils_Array
::value('individual_id', $relatedContact)) {
2205 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2210 $eventParams = array(
2211 'id' => $this->_relatedObjects
['event']->id
,
2213 $values['event'] = array();
2215 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2217 //get location details
2218 $locationParams = array(
2219 'entity_id' => $this->_relatedObjects
['event']->id
,
2220 'entity_table' => 'civicrm_event',
2222 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2224 $ufJoinParams = array(
2225 'entity_table' => 'civicrm_event',
2226 'entity_id' => $ids['event'],
2227 'module' => 'CiviEvent',
2230 list($custom_pre_id,
2232 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2234 $values['custom_pre_id'] = $custom_pre_id;
2235 $values['custom_post_id'] = $custom_post_ids;
2237 // set lineItem for event contribution
2239 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2240 if (!empty($participantIds)) {
2241 foreach ($participantIds as $pIDs) {
2242 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2243 if (!CRM_Utils_System
::isNull($lineItem)) {
2244 $values['lineItem'][] = $lineItem;
2255 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2256 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2257 * Note we send directly from this function in some cases because it is only partly refactored
2258 * Don't call this function directly as the signature will change
2260 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2261 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2262 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2263 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2264 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2265 $template->assign('useForMember', true);
2267 //assign honor infomation to receiptmessage
2268 $honorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2272 if (!empty($honorID)) {
2274 $honorDefault = $honorIds = array();
2275 $honorIds['contribution'] = $this->id
;
2276 $idParams = array('id' => $honorID, 'contact_id' => $honorID);
2277 CRM_Contact_BAO_Contact
::retrieve($idParams, $honorDefault, $honorIds);
2278 $honorType = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'honor_type_id');
2280 $template->assign('honor_block_is_active', 1);
2281 if (CRM_Utils_Array
::value('prefix_id', $honorDefault)) {
2282 $prefix = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id');
2283 $template->assign('honor_prefix', $prefix[$honorDefault['prefix_id']]);
2285 $template->assign('honor_first_name', CRM_Utils_Array
::value('first_name', $honorDefault));
2286 $template->assign('honor_last_name', CRM_Utils_Array
::value('last_name', $honorDefault));
2287 $template->assign('honor_email', CRM_Utils_Array
::value('email', $honorDefault['email'][1]));
2288 $template->assign('honor_type', $honorType[$this->honor_type_id
]);
2291 $dao = new CRM_Contribute_DAO_ContributionProduct();
2292 $dao->contribution_id
= $this->id
;
2293 if ($dao->find(TRUE)) {
2294 $premiumId = $dao->product_id
;
2295 $template->assign('option', $dao->product_option
);
2297 $productDAO = new CRM_Contribute_DAO_Product();
2298 $productDAO->id
= $premiumId;
2299 $productDAO->find(TRUE);
2300 $template->assign('selectPremium', TRUE);
2301 $template->assign('product_name', $productDAO->name
);
2302 $template->assign('price', $productDAO->price
);
2303 $template->assign('sku', $productDAO->sku
);
2305 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2306 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2307 if(empty($amount) && isset($this->total_amount
)){
2308 $amount = $this->total_amount
;
2310 $template->assign('amount', $amount);
2311 // add the new contribution values
2312 if (strtolower($this->_component
) == 'contribute') {
2314 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2315 $softDAO->contribution_id
= $this->id
;
2316 if ($softDAO->find(TRUE)) {
2317 $template->assign('pcpBlock', TRUE);
2318 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2319 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2320 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2322 //assign the pcp page title for email subject
2323 $pcpDAO = new CRM_PCP_DAO_PCP();
2324 $pcpDAO->id
= $softDAO->pcp_id
;
2325 if ($pcpDAO->find(TRUE)) {
2326 $template->assign('title', $pcpDAO->title
);
2331 if ($this->financial_type_id
) {
2332 $values['financial_type_id'] = $this->financial_type_id
;
2336 $template->assign('trxn_id', $this->trxn_id
);
2337 $template->assign('receive_date',
2338 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2340 $template->assign('contributeMode', 'notify');
2341 $template->assign('action', $this->is_test ?
1024 : 1);
2342 $template->assign('receipt_text',
2343 CRM_Utils_Array
::value('receipt_text',
2347 $template->assign('is_monetary', 1);
2348 $template->assign('is_recur', (bool) $recur);
2349 $template->assign('currency', $this->currency
);
2350 $template->assign('address', CRM_Utils_Address
::format($input));
2351 if ($this->_component
== 'event') {
2352 $template->assign('title', $values['event']['title']);
2353 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2354 $viewRoles = array();
2355 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2356 $viewRoles[] = $participantRoles[$v];
2358 $values['event']['participant_role'] = implode(', ', $viewRoles);
2359 $template->assign('event', $values['event']);
2360 $template->assign('location', $values['location']);
2361 $template->assign('customPre', $values['custom_pre_id']);
2362 $template->assign('customPost', $values['custom_post_id']);
2365 if ($this->_relatedObjects
['participant']->is_test
) {
2369 $values['params'] = array();
2370 //to get email of primary participant.
2371 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2372 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2373 //build an array of cId/pId of participants
2374 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2375 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2376 //send receipt to additional participant if exists
2377 if (count($additionalIDs)) {
2378 $template->assign('isPrimary', 0);
2379 $template->assign('customProfile', NULL);
2380 //set additionalParticipant true
2381 $values['params']['additionalParticipant'] = TRUE;
2382 foreach ($additionalIDs as $pId => $cId) {
2384 //to change the status pending to completed
2385 $additional = new CRM_Event_DAO_Participant();
2386 $additional->id
= $pId;
2387 $additional->contact_id
= $cId;
2388 $additional->find(TRUE);
2389 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2390 $additional->status_id
= 1;
2391 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2392 //if additional participant dont have email
2394 if (!$additionalParticipantInfo) {
2395 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2397 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2398 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2399 $additional->save();
2400 $additional->free();
2401 $template->assign('amount', $amount);
2402 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2406 //build an array of custom profile and assigning it to template
2407 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2409 if (count($customProfile)) {
2410 $template->assign('customProfile', $customProfile);
2413 // for primary contact
2414 $values['params']['additionalParticipant'] = FALSE;
2415 $template->assign('isPrimary', 1);
2416 $template->assign('amount', $primaryAmount);
2417 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2418 if ($this->payment_instrument_id
) {
2419 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2420 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2422 // carry paylater, since we did not created billing,
2423 // so need to pull email from primary location, CRM-4395
2424 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2430 * Function to check whether payment processor supports
2431 * cancellation of contribution subscription
2433 * @param int $contributionId contribution id
2439 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2440 $cacheKeyString = "$contributionId";
2441 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2443 static $supportsCancel = array();
2445 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2446 $supportsCancel[$cacheKeyString] = FALSE;
2447 $isCancelled = FALSE;
2449 if ($isNotCancelled) {
2450 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2453 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2454 if (!empty($paymentObject)) {
2455 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2458 return $supportsCancel[$cacheKeyString];
2462 * Function to check whether subscription is already cancelled
2464 * @param int $contributionId contribution id
2466 * @return string $status contribution status
2470 static function isSubscriptionCancelled($contributionId) {
2472 SELECT cr.contribution_status_id
2473 FROM civicrm_contribution_recur cr
2474 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2475 WHERE con.id = %1 LIMIT 1";
2476 $params = array(1 => array($contributionId, 'Integer'));
2477 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2478 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2479 if ($status == 'Cancelled') {
2486 * Function to create all financial accounts entry
2488 * @param array $params contribution object, line item array and params for trxn
2494 static function recordFinancialAccounts(&$params) {
2495 $skipRecords = $update = FALSE;
2496 $additionalParticipantId = array();
2497 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2499 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2500 $entityId = $params['participant_id'];
2501 $entityTable = 'civicrm_participant';
2502 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2505 $entityId = $params['contribution']->id
;
2506 $entityTable = 'civicrm_contribution';
2509 $entityID[] = $entityId;
2510 if (!empty($additionalParticipantId)) {
2511 $entityID +
= $additionalParticipantId;
2513 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2514 if (!CRM_Utils_Array
::value('prevContribution', $params)) {
2521 // build line item array if its not set in $params
2522 if (!CRM_Utils_Array
::value('line_item', $params) ||
$additionalParticipantId) {
2523 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
2526 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2527 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2528 $skipRecords = TRUE;
2529 $pendingStatus = array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses));
2530 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2531 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2532 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2534 elseif (CRM_Utils_Array
::value('payment_processor', $params)) {
2535 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2537 elseif (CRM_Utils_Array
::value('payment_instrument_id', $params)) {
2538 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2541 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2542 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2543 $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);
2546 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2547 if (!isset($totalAmount) && CRM_Utils_Array
::value('prevContribution', $params)) {
2548 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2550 //build financial transaction params
2551 $trxnParams = array(
2552 'contribution_id' => $params['contribution']->id
,
2553 'to_financial_account_id' => $params['to_financial_account_id'],
2554 'trxn_date' => date('YmdHis'),
2555 'total_amount' => $totalAmount,
2556 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2557 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2558 'currency' => $params['contribution']->currency
,
2559 'trxn_id' => $params['contribution']->trxn_id
,
2560 'status_id' => $params['contribution']->contribution_status_id
,
2561 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2562 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2565 if (CRM_Utils_Array
::value('payment_processor', $params)) {
2566 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2568 $params['trxnParams'] = $trxnParams;
2570 if (CRM_Utils_Array
::value('prevContribution', $params)) {
2571 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2572 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2573 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2574 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2575 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2576 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2577 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2579 //if financial type is changed
2580 if (CRM_Utils_Array
::value('financial_type_id', $params) &&
2581 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2582 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2583 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2584 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2585 if ($oldFinancialAccount != $newFinancialAccount) {
2586 $params['total_amount'] = 0;
2587 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2588 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2589 $params['prevContribution']->financial_type_id
, $relationTypeId);
2592 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2593 if (CRM_Utils_Array
::value('financialTrxnId', $lastFinancialTrxnId)) {
2594 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2597 self
::updateFinancialAccounts($params, 'changeFinancialType');
2598 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2599 $params['financial_account_id'] = $newFinancialAccount;
2600 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2601 self
::updateFinancialAccounts($params);
2602 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2606 //Update contribution status
2607 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2608 if (CRM_Utils_Array
::value('contribution_status_id', $params) &&
2609 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2610 //Update Financial Records
2611 self
::updateFinancialAccounts($params, 'changedStatus');
2614 // change Payment Instrument for a Completed contribution
2615 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2616 // instrument is null and now new payment instrument is added along with the payment
2617 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2618 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2619 if (array_key_exists('payment_instrument_id', $params)) {
2620 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2621 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2622 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2623 //check if status is changed from Pending to Completed
2624 // do not update payment instrument changes for Pending to Completed
2625 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2626 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))) {
2627 // for all other statuses create new financial records
2628 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2629 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2630 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2633 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2634 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2635 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2636 // for any other payment instrument changes create new financial records
2637 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2638 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2639 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2641 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2642 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2643 // another special case when check number is changed, create new financial records
2644 // create financial trxn with negative amount
2645 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2646 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2647 // create financial trxn with positive amount
2648 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2649 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2650 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2654 //if Change contribution amount
2655 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2656 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2657 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2658 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2659 if (isset($totalAmount) &&
2660 $totalAmount != $params['prevContribution']->total_amount
) {
2661 //Update Financial Records
2662 $params['trxnParams']['from_financial_account_id'] = NULL;
2663 self
::updateFinancialAccounts($params, 'changedAmount');
2668 //records finanical trxn and entity financial trxn
2669 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2670 $params['entity_id'] = $financialTxn->id
;
2673 // record line items and finacial items
2674 if (!CRM_Utils_Array
::value('skipLineItem', $params)) {
2675 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2678 // create batch entry if batch_id is passed
2679 if (CRM_Utils_Array
::value('batch_id', $params)) {
2680 $entityParams = array(
2681 'batch_id' => $params['batch_id'],
2682 'entity_table' => 'civicrm_financial_trxn',
2683 'entity_id' => $financialTxn->id
,
2685 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2688 // when a fee is charged
2689 if (CRM_Utils_Array
::value('fee_amount', $params) && (!CRM_Utils_Array
::value('prevContribution', $params)
2690 ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2691 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2694 if (CRM_Utils_Array
::value('prevContribution', $params) && $entityTable == 'civicrm_participant'
2695 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2696 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2697 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2698 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2700 unset($params['line_item']);
2704 * Function to update all financial accounts entry
2706 * @param array $params contribution object, line item array and params for trxn
2708 * @param string $context update scenarios
2713 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2714 $itemAmount = $trxnID = NULL;
2715 //get all the statuses
2716 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2717 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2718 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2719 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2720 && $context == 'changePaymentInstrument') {
2723 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2724 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2726 if ($context == 'changedStatus') {
2727 //get all the statuses
2728 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2730 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2731 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2732 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2733 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2735 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2736 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)) {
2737 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2738 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2739 $params['trxnParams']['to_financial_account_id'] = NULL;
2740 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2742 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2743 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2744 $financialTypeID, $relationTypeId);
2746 $itemAmount = $params['trxnParams']['total_amount'];
2748 elseif ($context == 'changePaymentInstrument') {
2749 if ($params['trxnParams']['total_amount'] < 0) {
2750 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2751 if (CRM_Utils_Array
::value('financialTrxnId', $lastFinancialTrxnId)) {
2752 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2753 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2757 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2758 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2761 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2762 $params['entity_id'] = $trxn->id
;
2764 if ($context == 'changedStatus') {
2765 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2766 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2767 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2768 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2769 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2771 $entityParams = array(
2772 'entity_table' => 'civicrm_financial_item',
2773 'financial_trxn_id' => $trxn->id
,
2775 foreach ($params['line_item'] as $fieldId => $fields) {
2776 foreach ($fields as $fieldValueId => $fieldValues) {
2778 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2779 2 => array($fieldValues['id'], 'Integer'),
2781 CRM_Core_DAO
::executeQuery($query, $fparams);
2783 1 => array($fieldValues['id'], 'Integer'),
2785 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2786 while ($financialItem->fetch()) {
2787 $entityParams['entity_id'] = $financialItem->id
;
2788 $entityParams['amount'] = $financialItem->amount
;
2789 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2796 if ($context != 'changePaymentInstrument') {
2797 $itemParams['entity_table'] = 'civicrm_line_item';
2798 $trxnIds['id'] = $params['entity_id'];
2799 foreach ($params['line_item'] as $fieldId => $fields) {
2800 foreach ($fields as $fieldValueId => $fieldValues) {
2801 $prevParams['entity_id'] = $fieldValues['id'];
2802 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2804 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2805 if ($params['contribution']->receive_date
) {
2806 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2809 $financialAccount = $prevfinancialItem->financial_account_id
;
2810 if (CRM_Utils_Array
::value('financial_account_id', $params)) {
2811 $financialAccount = $params['financial_account_id'];
2814 $currency = $params['prevContribution']->currency
;
2815 if ($params['contribution']->currency
) {
2816 $currency = $params['contribution']->currency
;
2818 if (CRM_Utils_Array
::value('is_quick_config', $params)) {
2819 $amount = $itemAmount;
2821 $amount = $params['total_amount'];
2826 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2829 $amount = $diff * $fieldValues['line_total'];
2832 $itemParams = array(
2833 'transaction_date' => $receiveDate,
2834 'contact_id' => $params['prevContribution']->contact_id
,
2835 'currency' => $currency,
2836 'amount' => $amount,
2837 'description' => $prevfinancialItem->description
,
2838 'status_id' => $prevfinancialItem->status_id
,
2839 'financial_account_id' => $financialAccount,
2840 'entity_table' => 'civicrm_line_item',
2841 'entity_id' => $fieldValues['id']
2843 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
2850 * Function to check status validation on update of a contribution
2852 * @param array $values previous form values before submit
2854 * @param array $fields the input form values
2856 * @param array $errors list of errors
2861 static function checkStatusValidation($values, &$fields, &$errors) {
2862 if (CRM_Utils_System
::isNull($values) && CRM_Utils_Array
::value('id', $fields)) {
2863 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
2864 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
2868 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2869 $checkStatus = array(
2870 'Cancelled' => array('Completed', 'Refunded'),
2871 'Completed' => array('Cancelled', 'Refunded'),
2872 'Pending' => array('Cancelled', 'Completed', 'Failed'),
2873 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
2874 'Refunded' => array('Cancelled', 'Completed')
2877 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
2878 $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']]));
2883 * Function to delete contribution of contact
2887 * @param integer $contactId contact id
2892 static function deleteContactContribution($contactId) {
2893 $contribution = new CRM_Contribute_DAO_Contribution();
2894 $contribution->contact_id
= $contactId;
2895 $contribution->find();
2896 while ($contribution->fetch()) {
2897 self
::deleteContribution($contribution->id
);
2902 * Get options for a given contribution field.
2903 * @see CRM_Core_DAO::buildOptions
2905 * @param String $fieldName
2906 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
2907 * @param Array $props: whatever is known about this dao object
2909 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2910 $className = __CLASS__
;
2912 switch ($fieldName) {
2913 // This field is not part of this object but the api supports it
2914 case 'payment_processor':
2915 $className = 'CRM_Contribute_BAO_ContributionPage';
2916 // Filter results by contribution page
2917 if (!empty($props['contribution_page_id'])) {
2918 $page = civicrm_api('contribution_page', 'getsingle', array(
2920 'id' => ($props['contribution_page_id'])
2922 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
2923 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
2926 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
2930 * Function to validate financial type
2934 * @param integer $financialTypeId Financial Type id
2939 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
2940 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
2941 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
2943 if (!$financialAccount) {
2944 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);