3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
35 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
38 * static field for all the contribution information that we can potentially import
43 static $_importableFields = NULL;
46 * static field for all the contribution information that we can potentially export
51 static $_exportableFields = NULL;
54 * field for all the objects related to this contribution
55 * @var array of objects (e.g membership object, participant object)
57 public $_relatedObjects = array();
60 * field for the component - either 'event' (participant) or 'contribute'
61 * (any item related to a contribution page e.g. membership, pledge, contribution)
62 * This is used for composing messages because they have dependency on the
63 * contribution_page or event page - although over time we may eliminate that
65 * @var string component or event
67 public $_component = NULL;
72 function __construct() {
73 parent
::__construct();
77 * takes an associative array and creates a contribution object
79 * the function extract all the params it needs to initialize the create a
80 * contribution object. the params array could contain additional unused name/value
83 * @param array $params (reference ) an assoc array of name/value pairs
84 * @param array $ids the array that holds all the db ids
86 * @return object CRM_Contribute_BAO_Contribution object
90 static function add(&$params, $ids = array()) {
94 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
95 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
97 $duplicates = array();
98 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
99 $error = CRM_Core_Error
::singleton();
100 $d = implode(', ', $duplicates);
101 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
104 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
109 // first clean up all the money fields
110 $moneyFields = array(
114 'non_deductible_amount',
117 //if priceset is used, no need to cleanup money
118 if (CRM_Utils_Array
::value('skipCleanMoney', $params)) {
119 unset($moneyFields[0]);
122 foreach ($moneyFields as $field) {
123 if (isset($params[$field])) {
124 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
128 // CRM-13420, set payment instrument to default if payment_instrument_id is empty
129 if (!$contributionID && !CRM_Utils_Array
::value('payment_instrument_id', $params)) {
130 $params['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument',
131 FALSE, FALSE, FALSE, 'AND is_default = 1'));
134 if (CRM_Utils_Array
::value('payment_instrument_id', $params)) {
135 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
136 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
137 $params['check_number'] = 'null';
141 // contribution status is missing, choose Completed as default status
142 // do this for create mode only
143 if (!CRM_Utils_Array
::value('contribution', $ids) && !CRM_Utils_Array
::value('contribution_status_id', $params)) {
144 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
147 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, $ids);
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_campaign' =>
586 'title' => ts('Campaign Title')
588 'contribution_batch' =>
590 'title' => ts('Batch Name')
594 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
595 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $financialAccount,
596 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
599 self
::$_exportableFields = $fields;
602 return self
::$_exportableFields;
605 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
609 $where[] = 'contribution_status_id = 1';
613 $where[] = 'contribution_status_id = 3';
618 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
621 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
624 $whereCond = implode(' AND ', $where);
627 SELECT sum( total_amount ) as total_amount,
628 count( civicrm_contribution.id ) as total_count,
630 FROM civicrm_contribution
631 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
633 AND ( is_test = 0 OR is_test IS NULL )
634 AND contact.is_deleted = 0
638 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
641 while ($dao->fetch()) {
642 $count +
= $dao->total_count
;
643 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
646 return array('amount' => implode(', ', $amount),
654 * Delete the indirect records associated with this contribution first
656 * @return $results no of deleted Contribution on success, false otherwise
660 static function deleteContribution($id) {
661 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
663 $transaction = new CRM_Core_Transaction();
666 //delete activity record
668 'source_record_id' => $id,
669 // activity type id for contribution
670 'activity_type_id' => 6,
673 CRM_Activity_BAO_Activity
::deleteActivity($params);
675 //delete billing address if exists for this contribution.
676 self
::deleteAddress($id);
678 //update pledge and pledge payment, CRM-3961
679 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
681 // remove entry from civicrm_price_set_entity, CRM-5095
682 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
683 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
685 // cleanup line items.
686 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
688 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
689 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
691 if ($participantId) {
692 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
695 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
699 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
700 $noteId = key($note);
702 CRM_Core_BAO_Note
::del($noteId, FALSE);
705 $dao = new CRM_Contribute_DAO_Contribution();
708 $results = $dao->delete();
710 $transaction->commit();
712 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
714 // delete the recently created Contribution
715 $contributionRecent = array(
717 'type' => 'Contribution',
719 CRM_Utils_Recent
::del($contributionRecent);
725 * Check if there is a contribution with the same trxn_id or invoice_id
727 * @param array $params (reference ) an assoc array of name/value pairs
728 * @param array $duplicates (reference ) store ids of duplicate contribs
730 * @return boolean true if duplicate, false otherwise
734 static function checkDuplicate($input, &$duplicates, $id = NULL) {
736 $id = CRM_Utils_Array
::value('id', $input);
738 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
739 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
745 $clause[] = "trxn_id = %1";
746 $input[1] = array($trxn_id, 'String');
750 $clause[] = "invoice_id = %2";
751 $input[2] = array($invoice_id, 'String');
754 if (empty($clause)) {
758 $clause = implode(' OR ', $clause);
760 $clause = "( $clause ) AND id != %3";
761 $input[3] = array($id, 'Integer');
764 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
765 $dao = CRM_Core_DAO
::executeQuery($query, $input);
767 while ($dao->fetch()) {
768 $duplicates[] = $dao->id
;
775 * takes an associative array and creates a contribution_product object
777 * the function extract all the params it needs to initialize the create a
778 * contribution_product object. the params array could contain additional unused name/value
781 * @param array $params (reference ) an assoc array of name/value pairs
783 * @return object CRM_Contribute_BAO_ContributionProduct object
787 static function addPremium(&$params) {
788 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
789 $contributionProduct->copyValues($params);
790 return $contributionProduct->save();
794 * Function to get list of contribution fields for profile
795 * For now we only allow custom contribution fields to be in
798 * @param boolean $addExtraFields true if special fields needs to be added
800 * @return return the list of contribution fields
804 static function getContributionFields($addExtraFields = TRUE) {
805 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
806 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
808 if ($addExtraFields) {
809 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
812 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
814 foreach ($contributionFields as $key => $var) {
815 if ($key == 'contribution_contact_id') {
818 elseif ($key == 'contribution_campaign_id') {
819 $var['title'] = ts('Campaign');
821 $fields[$key] = $var;
824 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
829 * Function to add extra fields specific to contribtion
833 static function getSpecialContributionFields() {
834 $extraFields = array(
835 'honor_contact_name' => array(
836 'name' => 'honor_contact_name',
837 'title' => 'Honor Contact Name',
838 'headerPattern' => '/^honor_contact_name$/i',
839 'where' => 'civicrm_contact_c.display_name',
841 'honor_contact_email' => array(
842 'name' => 'honor_contact_email',
843 'title' => 'Honor Contact Email',
844 'headerPattern' => '/^honor_contact_email$/i',
845 'where' => 'honor_email.email',
847 'honor_contact_id' => array(
848 'name' => 'honor_contact_id',
849 'title' => 'Honor Contact ID',
850 'headerPattern' => '/^honor_contact_id$/i',
851 'where' => 'civicrm_contribution.honor_contact_id',
853 'honor_type_label' => array(
854 'name' => 'honor_type_label',
855 'title' => 'Honor Type Label',
856 'headerPattern' => '/^honor_type_label$/i',
857 'where' => 'honor_type.label',
859 'soft_credit_name' => array(
860 'name' => 'soft_credit_name',
861 'title' => 'Soft Credit Name',
862 'headerPattern' => '/^soft_credit_name$/i',
863 'where' => 'civicrm_contact_d.display_name',
865 'soft_credit_email' => array(
866 'name' => 'soft_credit_email',
867 'title' => 'Soft Credit Email',
868 'headerPattern' => '/^soft_credit_email$/i',
869 'where' => 'soft_email.email',
871 'soft_credit_phone' => array(
872 'name' => 'soft_credit_phone',
873 'title' => 'Soft Credit Phone',
874 'headerPattern' => '/^soft_credit_phone$/i',
875 'where' => 'soft_phone.phone',
877 'soft_credit_contact_id' => array(
878 'name' => 'soft_credit_contact_id',
879 'title' => 'Soft Credit Contact ID',
880 'headerPattern' => '/^soft_credit_contact_id$/i',
881 'where' => 'civicrm_contribution_soft.contact_id',
888 static function getCurrentandGoalAmount($pageID) {
890 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
891 FROM civicrm_contribution_page p,
892 civicrm_contribution c
893 WHERE p.id = c.contribution_page_id
895 AND c.cancel_date is null
899 $config = CRM_Core_Config
::singleton();
900 $params = array(1 => array($pageID, 'Integer'));
901 $dao = CRM_Core_DAO
::executeQuery($query, $params);
904 return array($dao->goal
, $dao->total
);
907 return array(NULL, NULL);
912 * Function to create is honor of
914 * @param array $params associated array of fields (by reference)
915 * @param int $honorId honor Id
916 * @param array $honorParams any params that should be send to the create function
920 static function createHonorContact(&$params, $honorId = NULL, $honorParams = array()) {
921 $honorParams = array_merge(
923 'first_name' => $params['honor_first_name'],
924 'last_name' => $params['honor_last_name'],
925 'prefix_id' => $params['honor_prefix_id'],
926 'email-Primary' => $params['honor_email'],
931 $honorParams['email'] = $params['honor_email'];
933 $dedupeParams = CRM_Dedupe_Finder
::formatParams($honorParams, 'Individual');
934 $dedupeParams['check_permission'] = FALSE;
935 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
937 // if we find more than one contact, use the first one
938 $honorId = CRM_Utils_Array
::value(0, $ids);
941 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
943 CRM_Core_DAO
::$_nullArray,
950 * Function to get list of contribution In Honor of contact Ids
952 * @param int $honorId In Honor of Contact ID
954 * @return return the list of contribution fields
959 static function getHonorContacts($honorId) {
961 $honorDAO = new CRM_Contribute_DAO_Contribution();
962 $honorDAO->honor_contact_id
= $honorId;
965 $status = CRM_Contribute_PseudoConstant
::contributionStatus($honorDAO->contribution_status_id
);
966 $type = CRM_Contribute_PseudoConstant
::financialType();
968 while ($honorDAO->fetch()) {
969 $params[$honorDAO->id
]['honorId'] = $honorDAO->contact_id
;
970 $params[$honorDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $honorDAO->contact_id
, 'display_name');
971 $params[$honorDAO->id
]['type'] = $type[$honorDAO->financial_type_id
];
972 $params[$honorDAO->id
]['type_id'] = $honorDAO->financial_type_id
;
973 $params[$honorDAO->id
]['amount'] = CRM_Utils_Money
::format($honorDAO->total_amount
, $honorDAO->currency
);
974 $params[$honorDAO->id
]['source'] = $honorDAO->source
;
975 $params[$honorDAO->id
]['receive_date'] = $honorDAO->receive_date
;
976 $params[$honorDAO->id
]['contribution_status'] = CRM_Utils_Array
::value($honorDAO->contribution_status_id
, $status);
983 * function to get the sort name of a contact for a particular contribution
985 * @param int $id id of the contribution
987 * @return null|string sort name of the contact if found
991 static function sortName($id) {
992 $id = CRM_Utils_Type
::escape($id, 'Integer');
995 SELECT civicrm_contact.sort_name
996 FROM civicrm_contribution, civicrm_contact
997 WHERE civicrm_contribution.contact_id = civicrm_contact.id
998 AND civicrm_contribution.id = {$id}
1000 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1003 static function annual($contactID) {
1004 if (is_array($contactID)) {
1005 $contactIDs = implode(',', $contactID);
1008 $contactIDs = $contactID;
1011 $config = CRM_Core_Config
::singleton();
1012 $startDate = $endDate = NULL;
1014 $currentMonth = date('m');
1015 $currentDay = date('d');
1016 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1017 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1018 (int ) $config->fiscalYearStart
['d'] > $currentDay
1021 $year = date('Y') - 1;
1026 $nextYear = $year +
1;
1028 if ($config->fiscalYearStart
) {
1029 if ($config->fiscalYearStart
['M'] < 10) {
1030 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1032 if ($config->fiscalYearStart
['d'] < 10) {
1033 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1035 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1040 $startDate = "$year$monthDay";
1041 $endDate = "$nextYear$monthDay";
1044 SELECT count(*) as count,
1045 sum(total_amount) as amount,
1046 avg(total_amount) as average,
1048 FROM civicrm_contribution b
1049 WHERE b.contact_id IN ( $contactIDs )
1050 AND b.contribution_status_id = 1
1052 AND b.receive_date >= $startDate
1053 AND b.receive_date < $endDate
1056 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1058 $amount = $average = array();
1059 while ($dao->fetch()) {
1060 if ($dao->count
> 0 && $dao->amount
> 0) {
1061 $count +
= $dao->count
;
1062 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1063 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1069 implode(', ', $amount),
1070 implode(', ', $average),
1073 return array(0, 0, 0);
1077 * Check if there is a contribution with the params passed in.
1078 * Used for trxn_id,invoice_id and contribution_id
1080 * @param array $params an assoc array of name/value pairs
1082 * @return array contribution id if success else NULL
1086 static function checkDuplicateIds($params) {
1087 $dao = new CRM_Contribute_DAO_Contribution();
1091 foreach ($params as $k => $v) {
1093 $clause[] = "$k = '$v'";
1096 $clause = implode(' AND ', $clause);
1097 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1098 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1100 while ($dao->fetch()) {
1108 * Function to get the contribution details for component export
1110 * @param int $exportMode export mode
1111 * @param string $componentIds component ids
1113 * @return array associated array
1118 static function getContributionDetails($exportMode, $componentIds) {
1119 $paymentDetails = array();
1120 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1122 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1123 $componentSelect = " civicrm_participant_payment.participant_id id";
1124 $additionalClause = "
1125 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1126 AND civicrm_participant_payment.participant_id {$componentClause} )
1129 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1130 $componentSelect = " civicrm_membership_payment.membership_id id";
1131 $additionalClause = "
1132 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1133 AND civicrm_membership_payment.membership_id {$componentClause} )
1136 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1137 $componentSelect = " civicrm_pledge_payment.id id";
1138 $additionalClause = "
1139 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1140 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1144 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1145 trxn_id, {$componentSelect}
1146 FROM civicrm_contribution
1147 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1148 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1149 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1150 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1151 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1152 AND option_group_contribution_status.id = contribution_status.option_group_id )
1156 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1158 while ($dao->fetch()) {
1159 $paymentDetails[$dao->id
] = array(
1160 'total_amount' => $dao->total_amount
,
1161 'contribution_status' => $dao->status
,
1162 'receive_date' => $dao->receive_date
,
1163 'pay_instru' => $dao->payment_instrument
,
1164 'trxn_id' => $dao->trxn_id
,
1168 return $paymentDetails;
1172 * Function to create address associated with contribution record.
1173 * @param array $params an associated array
1174 * @param int $billingID $billingLocationTypeID
1176 * @return address id
1179 static function createAddress(&$params, $billingLocationTypeID) {
1180 $billingFields = array(
1183 'state_province_id',
1188 //build address array
1189 $addressParams = array();
1190 $addressParams['location_type_id'] = $billingLocationTypeID;
1191 $addressParams['is_billing'] = 1;
1193 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1194 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1195 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1196 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1198 foreach ($billingFields as $value) {
1199 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1202 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1204 return $address->id
;
1208 * Delete billing address record related contribution
1210 * @param int $contact_id contact id
1211 * @param int $contribution_id contributionId
1215 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1217 $contactJoin = NULL;
1219 if ($contributionId) {
1220 $clauses[] = "cc.id = {$contributionId}";
1224 $clauses[] = "cco.id = {$contactId}";
1225 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1228 if (empty($clauses)) {
1229 CRM_Core_Error
::fatal();
1232 $condition = implode(' OR ', $clauses);
1236 FROM civicrm_address ca
1237 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1241 $dao = CRM_Core_DAO
::executeQuery($query);
1243 while ($dao->fetch()) {
1244 $params = array('id' => $dao->id
);
1245 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1250 * This function check online pending contribution associated w/
1251 * Online Event Registration or Online Membership signup.
1253 * @param int $componentId participant/membership id.
1254 * @param string $componentName Event/Membership.
1256 * @return $contributionId pending contribution id.
1259 static function checkOnlinePendingContribution($componentId, $componentName) {
1260 $contributionId = NULL;
1261 if (!$componentId ||
1262 !in_array($componentName, array('Event', 'Membership'))
1264 return $contributionId;
1267 if ($componentName == 'Event') {
1268 $idName = 'participant_id';
1269 $componentTable = 'civicrm_participant';
1270 $paymentTable = 'civicrm_participant_payment';
1271 $source = ts('Online Event Registration');
1274 if ($componentName == 'Membership') {
1275 $idName = 'membership_id';
1276 $componentTable = 'civicrm_membership';
1277 $paymentTable = 'civicrm_membership_payment';
1278 $source = ts('Online Contribution');
1281 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1284 SELECT component.id as {$idName},
1285 componentPayment.contribution_id as contribution_id,
1286 contribution.source source,
1287 contribution.contribution_status_id as contribution_status_id,
1288 contribution.is_pay_later as is_pay_later
1289 FROM $componentTable component
1290 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1291 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1292 WHERE component.id = {$componentId}";
1294 $dao = CRM_Core_DAO
::executeQuery($query);
1296 while ($dao->fetch()) {
1297 if ($dao->contribution_id
&&
1298 $dao->is_pay_later
&&
1299 $dao->contribution_status_id
== $pendingStatusId &&
1300 strpos($dao->source
, $source) !== FALSE
1302 $contributionId = $dao->contribution_id
;
1307 return $contributionId;
1311 * This function update contribution as well as related objects.
1313 static function transitionComponents($params, $processContributionObject = FALSE) {
1314 // get minimum required values.
1315 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1316 $componentId = CRM_Utils_Array
::value('component_id', $params);
1317 $componentName = CRM_Utils_Array
::value('componentName', $params);
1318 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1319 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1321 // if we already processed contribution object pass previous status id.
1322 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1324 $updateResult = array();
1326 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1328 // we process only ( Completed, Cancelled, or Failed ) contributions.
1329 if (!$contributionId ||
1330 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1331 array_search('Cancelled', $contributionStatuses),
1332 array_search('Failed', $contributionStatuses),
1335 return $updateResult;
1338 if (!$componentName ||
!$componentId) {
1339 // get the related component details.
1340 $componentDetails = self
::getComponentDetails($contributionId);
1343 $componentDetails['contact_id'] = $contactId;
1344 $componentDetails['component'] = $componentName;
1346 if ($componentName == 'event') {
1347 $componentDetails['participant'] = $componentId;
1350 $componentDetails['membership'] = $componentId;
1354 if (CRM_Utils_Array
::value('contact_id', $componentDetails)) {
1355 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1361 // do check for required ids.
1362 if (!CRM_Utils_Array
::value('membership', $componentDetails) &&
1363 !CRM_Utils_Array
::value('participant', $componentDetails) &&
1364 !CRM_Utils_Array
::value('pledge_payment', $componentDetails) ||
1365 !CRM_Utils_Array
::value('contact_id', $componentDetails)
1367 return $updateResult;
1370 //now we are ready w/ required ids, start processing.
1372 $baseIPN = new CRM_Core_Payment_BaseIPN();
1374 $input = $ids = $objects = array();
1376 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1377 $ids['contribution'] = $contributionId;
1378 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1379 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1380 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1381 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1382 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1383 $ids['contributionRecur'] = NULL;
1384 $ids['contributionPage'] = NULL;
1386 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1387 CRM_Core_Error
::fatal();
1390 $memberships = &$objects['membership'];
1391 $participant = &$objects['participant'];
1392 $pledgePayment = &$objects['pledge_payment'];
1393 $contribution = &$objects['contribution'];
1395 if ($pledgePayment) {
1396 $pledgePaymentIDs = array();
1397 foreach ($pledgePayment as $key => $object) {
1398 $pledgePaymentIDs[] = $object->id
;
1400 $pledgeID = $pledgePayment[0]->pledge_id
;
1403 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1406 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1407 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1412 // we might want to process contribution object.
1413 $processContribution = FALSE;
1414 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1415 if (is_array($memberships)) {
1416 foreach ($memberships as $membership) {
1418 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1419 $membership->save();
1421 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1422 if ($processContributionObject) {
1423 $processContribution = TRUE;
1430 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1431 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1433 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1434 if ($processContributionObject) {
1435 $processContribution = TRUE;
1439 if ($pledgePayment) {
1440 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1442 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1443 if ($processContributionObject) {
1444 $processContribution = TRUE;
1448 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1449 if (is_array($memberships)) {
1450 foreach ($memberships as $membership) {
1452 $membership->status_id
= array_search('Expired', $membershipStatuses);
1453 $membership->save();
1455 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1456 if ($processContributionObject) {
1457 $processContribution = TRUE;
1463 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1464 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1466 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1467 if ($processContributionObject) {
1468 $processContribution = TRUE;
1472 if ($pledgePayment) {
1473 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1475 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1476 if ($processContributionObject) {
1477 $processContribution = TRUE;
1481 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1483 // only pending contribution related object processed.
1484 if ($previousContriStatusId &&
1485 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1487 // this is case when we already processed contribution object.
1488 return $updateResult;
1490 elseif (!$previousContriStatusId &&
1491 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1493 // this is case when we are going to process contribution object later.
1494 return $updateResult;
1497 if (is_array($memberships)) {
1498 foreach ($memberships as $membership) {
1503 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1504 $membership->membership_type_id
,
1505 $membership->is_test
, $membership->id
1508 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1509 // this picks up membership type changes during renewals
1511 SELECT membership_type_id
1512 FROM civicrm_membership_log
1513 WHERE membership_id=$membership->id
1516 $dao = new CRM_Core_DAO
;
1518 if ($dao->fetch()) {
1519 if (!empty($dao->membership_type_id
)) {
1520 $membership->membership_type_id
= $dao->membership_type_id
;
1521 $membership->save();
1524 // else fall back to using current membership type
1527 // Figure out number of terms
1529 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1530 foreach ($lineitems as $lineitem) {
1531 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1532 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1534 // in case membership_num_terms comes through as null or zero
1535 $numterms = $numterms >= 1 ?
$numterms : 1;
1540 if ($currentMembership) {
1541 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1542 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1543 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1546 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1549 //get the status for membership.
1550 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1552 $dates['join_date'],
1557 $formattedParams = array(
1558 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1559 array_search('Current', $membershipStatuses)
1561 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1562 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1563 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1566 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1568 $membership->copyValues($formattedParams);
1569 $membership->save();
1571 //updating the membership log
1572 $membershipLog = array();
1573 $membershipLog = $formattedParams;
1574 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1575 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1577 $membershipLog['start_date'] = $logStartDate;
1578 $membershipLog['membership_id'] = $membership->id
;
1579 $membershipLog['modified_id'] = $membership->contact_id
;
1580 $membershipLog['modified_date'] = date('Ymd');
1581 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1583 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1585 //update related Memberships.
1586 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1588 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1591 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1592 if ($processContributionObject) {
1593 $processContribution = TRUE;
1596 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1602 $updatedStatusId = array_search('Registered', $participantStatuses);
1603 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1605 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1606 if ($processContributionObject) {
1607 $processContribution = TRUE;
1611 if ($pledgePayment) {
1612 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1614 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1615 if ($processContributionObject) {
1616 $processContribution = TRUE;
1621 // process contribution object.
1622 if ($processContribution) {
1623 $contributionParams = array();
1625 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1626 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1627 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1629 foreach ($fields as $field) {
1630 if (!CRM_Utils_Array
::value($field, $params)) {
1633 $contributionParams[$field] = $params[$field];
1636 $ids = array('contribution' => $contributionId);
1637 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1640 return $updateResult;
1644 * This function returns all contribution related object ids.
1646 public static function getComponentDetails($contributionId) {
1647 $componentDetails = $pledgePayment = array();
1648 if (!$contributionId) {
1649 return $componentDetails;
1653 SELECT c.id as contribution_id,
1654 c.contact_id as contact_id,
1655 mp.membership_id as membership_id,
1656 m.membership_type_id as membership_type_id,
1657 pp.participant_id as participant_id,
1658 p.event_id as event_id,
1659 pgp.id as pledge_payment_id
1660 FROM civicrm_contribution c
1661 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1662 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1663 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1664 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1665 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1666 WHERE c.id = $contributionId";
1668 $dao = CRM_Core_DAO
::executeQuery($query);
1669 $componentDetails = array();
1671 while ($dao->fetch()) {
1672 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1673 $componentDetails['contact_id'] = $dao->contact_id
;
1674 if ($dao->event_id
) {
1675 $componentDetails['event'] = $dao->event_id
;
1677 if ($dao->participant_id
) {
1678 $componentDetails['participant'] = $dao->participant_id
;
1680 if ($dao->membership_id
) {
1681 if (!isset($componentDetails['membership'])) {
1682 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1684 $componentDetails['membership'][] = $dao->membership_id
;
1685 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1687 if ($dao->pledge_payment_id
) {
1688 $pledgePayment[] = $dao->pledge_payment_id
;
1692 if ($pledgePayment) {
1693 $componentDetails['pledge_payment'] = $pledgePayment;
1696 return $componentDetails;
1699 static function contributionCount($contactId, $includeSoftCredit = TRUE, $includeHonoree = TRUE) {
1704 $contactContributionsSQL = "
1705 SELECT contribution.id AS id
1706 FROM civicrm_contribution contribution
1707 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1709 $contactHonoreeContributionsSQL = "
1710 SELECT contribution.id
1711 FROM civicrm_contribution contribution
1712 WHERE contribution.is_test = 0 AND contribution.honor_contact_id = {$contactId} ";
1714 $contactSoftCreditContributionsSQL = "
1715 SELECT contribution.id
1716 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1717 ON ( contribution.id = softContribution.contribution_id )
1718 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1719 $query = "SELECT count( x.id ) count FROM ( ";
1720 $query .= $contactContributionsSQL;
1722 if ($includeSoftCredit) {
1723 $query .= " UNION ";
1724 $query .= $contactSoftCreditContributionsSQL;
1727 if ($includeHonoree) {
1728 $query .= " UNION ";
1729 $query .= $contactHonoreeContributionsSQL;
1734 return CRM_Core_DAO
::singleValueQuery($query);
1738 * Function to get individual id for onbehalf contribution
1740 * @param int $contributionId contribution id
1741 * @param int $contributorId contributor id
1743 * @return array $ids containing organization id and individual id
1746 static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1750 if (!$contributionId) {
1754 // fetch contributor id if null
1755 if (!$contributorId) {
1756 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1757 $contributionId, 'contact_id'
1761 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1762 $activityTypeId = array_search('Contribution', $activityTypeIds);
1764 if ($activityTypeId && $contributorId) {
1766 SELECT civicrm_activity_contact.contact_id
1767 FROM civicrm_activity_contact
1768 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1769 WHERE civicrm_activity.activity_type_id = %1
1770 AND civicrm_activity.source_record_id = %2
1771 AND civicrm_activity_contact.record_type_id = %3
1774 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1775 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1778 1 => array($activityTypeId, 'Integer'),
1779 2 => array($contributionId, 'Integer'),
1780 3 => array($sourceID, 'Integer'),
1783 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1785 // for on behalf contribution source is individual and contributor is organization
1786 if ($sourceContactId && $sourceContactId != $contributorId) {
1787 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1788 // get rel type id for employee of relation
1789 foreach ($relationshipTypeIds as $id => $typeVals) {
1790 if ($typeVals['name_a_b'] == 'Employee of') {
1791 $relationshipTypeId = $id;
1796 $rel = new CRM_Contact_DAO_Relationship();
1797 $rel->relationship_type_id
= $relationshipTypeId;
1798 $rel->contact_id_a
= $sourceContactId;
1799 $rel->contact_id_b
= $contributorId;
1800 if ($rel->find(TRUE)) {
1801 $ids['individual_id'] = $rel->contact_id_a
;
1802 $ids['organization_id'] = $rel->contact_id_b
;
1814 static function getContributionDates() {
1815 $config = CRM_Core_Config
::singleton();
1816 $currentMonth = date('m');
1817 $currentDay = date('d');
1818 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1819 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1820 (int ) $config->fiscalYearStart
['d'] > $currentDay
1823 $year = date('Y') - 1;
1828 $year = array('Y' => $year);
1829 $yearDate = $config->fiscalYearStart
;
1830 $yearDate = array_merge($year, $yearDate);
1831 $yearDate = CRM_Utils_Date
::format($yearDate);
1833 $monthDate = date('Ym') . '01';
1839 'yearDate' => $yearDate,
1840 'monthDate' => $monthDate,
1845 * Load objects relations to contribution object
1846 * Objects are stored in the $_relatedObjects property
1847 * In the first instance we are just moving functionality from BASEIpn -
1848 * see http://issues.civicrm.org/jira/browse/CRM-9996
1850 * @param array $input Input as delivered from Payment Processor
1851 * @param array $ids Ids as Loaded by Payment Processor
1852 * @param boolean $required Is Payment processor / contribution page required
1853 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1854 * Note that the unit test for the BaseIPN class tests this function
1856 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1858 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
1859 if(empty($ids['contact']) && isset($this->contact_id
)){
1860 $ids['contact'] = $this->contact_id
;
1863 if (empty($this->_component
)) {
1864 if (! empty($ids['event'])) {
1865 $this->_component
= 'event';
1868 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1871 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1872 $contributionType = new CRM_Financial_BAO_FinancialType();
1873 $contributionType->id
= $this->financial_type_id
;
1874 if (!$contributionType->find(TRUE)) {
1875 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1877 if (!empty($ids['contact'])) {
1878 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1879 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1880 $this->_relatedObjects
['contact']->find(TRUE);
1882 $this->_relatedObjects
['contributionType'] = $contributionType;
1884 if ($this->_component
== 'contribute') {
1885 // retrieve the other optional objects first so
1886 // stuff down the line can use this info and do things
1888 //in any case get the memberships associated with the contribution
1889 //because we now support multiple memberships w/ price set
1890 // see if there are any other memberships to be considered for same contribution.
1892 SELECT membership_id
1893 FROM civicrm_membership_payment
1894 WHERE contribution_id = %1 ";
1895 $params = array(1 => array($this->id
, 'Integer'));
1897 $dao = CRM_Core_DAO
::executeQuery($query, $params );
1898 while ($dao->fetch()) {
1899 if ($dao->membership_id
) {
1900 if (!is_array($ids['membership'])) {
1901 $ids['membership'] = array();
1903 $ids['membership'][] = $dao->membership_id
;
1907 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1908 foreach ($ids['membership'] as $id) {
1910 $membership = new CRM_Member_BAO_Membership();
1911 $membership->id
= $id;
1912 if (!$membership->find(TRUE)) {
1913 throw new Exception("Could not find membership record: $id");
1915 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
1916 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
1917 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
1918 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
1919 $membership->free();
1924 if (!empty($ids['pledge_payment'])) {
1926 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1927 if (empty($paymentID)) {
1930 $payment = new CRM_Pledge_BAO_PledgePayment();
1931 $payment->id
= $paymentID;
1932 if (!$payment->find(TRUE)) {
1933 throw new Exception("Could not find pledge payment record: " . $paymentID);
1935 $this->_relatedObjects
['pledge_payment'][] = $payment;
1939 if (!empty($ids['contributionRecur'])) {
1940 $recur = new CRM_Contribute_BAO_ContributionRecur();
1941 $recur->id
= $ids['contributionRecur'];
1942 if (!$recur->find(TRUE)) {
1943 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
1945 $this->_relatedObjects
['contributionRecur'] = &$recur;
1946 //get payment processor id from recur object.
1947 $paymentProcessorID = $recur->payment_processor_id
;
1949 //for normal contribution get the payment processor id.
1950 if (!$paymentProcessorID) {
1951 if ($this->contribution_page_id
) {
1952 // get the payment processor id from contribution page
1953 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
1954 $this->contribution_page_id
,
1958 //fail to load payment processor id.
1959 elseif (!CRM_Utils_Array
::value('pledge_payment', $ids)) {
1960 $loadObjectSuccess = TRUE;
1962 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
1964 return $loadObjectSuccess;
1969 // we are in event mode
1970 // make sure event exists and is valid
1971 $event = new CRM_Event_BAO_Event();
1972 $event->id
= $ids['event'];
1973 if ($ids['event'] &&
1976 throw new Exception("Could not find event: " . $ids['event']);
1979 $this->_relatedObjects
['event'] = &$event;
1981 $participant = new CRM_Event_BAO_Participant();
1982 $participant->id
= $ids['participant'];
1983 if ($ids['participant'] &&
1984 !$participant->find(TRUE)
1986 throw new Exception("Could not find participant: " . $ids['participant']);
1988 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
1990 $this->_relatedObjects
['participant'] = &$participant;
1992 if (!$paymentProcessorID) {
1993 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
1997 $loadObjectSuccess = TRUE;
1998 if ($paymentProcessorID) {
1999 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2000 $this->is_test ?
'test' : 'live'
2002 $ids['paymentProcessor'] = $paymentProcessorID;
2003 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2005 elseif ($required) {
2006 $loadObjectSuccess = FALSE;
2007 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2010 return $loadObjectSuccess;
2014 * Create array of message information - ie. return html version, txt version, to field
2016 * @param array $input incoming information
2017 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2018 * just check presence of recur object but maintaining legacy approach
2020 * @param array $ids IDs of related objects
2021 * @param array $values any values that may have already been compiled by calling process
2022 * This is augmented by values 'gathered' by gatherMessageValues
2023 * @param bool $returnMessageText distinguishes between whether to send message or return
2024 * message text. We are working towards this function ALWAYS returning message text & calling
2025 * function doing emails / pdfs with it
2026 * @return array $messageArray - messages
2028 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2029 if (empty($this->_relatedObjects
)) {
2030 $this->loadRelatedObjects($input, $ids);
2032 if (empty($this->_component
)) {
2033 $this->_component
= CRM_Utils_Array
::value('component', $input);
2036 //not really sure what params might be passed in but lets merge em into values
2037 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2038 $template = CRM_Core_Smarty
::singleton();
2039 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2040 //what does recur 'mean here - to do with payment processor return functionality but
2041 // what is the importance
2042 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2043 $paymentObject = &CRM_Core_Payment
::singleton(
2044 $this->is_test ?
'test' : 'live',
2045 $this->_relatedObjects
['paymentProcessor']
2048 $entityID = $entity = NULL;
2049 if (isset($ids['contribution'])) {
2050 $entity = 'contribution';
2051 $entityID = $ids['contribution'];
2053 if (isset($ids['membership']) && $ids['membership']) {
2054 $entity = 'membership';
2055 $entityID = $ids['membership'];
2058 $url = $paymentObject->subscriptionURL($entityID, $entity);
2059 $template->assign('cancelSubscriptionUrl', $url);
2061 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2062 $template->assign('updateSubscriptionBillingUrl', $url);
2064 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2065 $template->assign('updateSubscriptionUrl', $url);
2067 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2068 //direct mode showing billing block, so use directIPN for temporary
2069 $template->assign('contributeMode', 'directIPN');
2072 // todo remove strtolower - check consistency
2073 if (strtolower($this->_component
) == 'event') {
2074 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2075 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2079 $values['contribution_id'] = $this->id
;
2080 if (CRM_Utils_Array
::value('related_contact', $ids)) {
2081 $values['related_contact'] = $ids['related_contact'];
2082 if (isset($ids['onbehalf_dupe_alert'])) {
2083 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2085 $entityBlock = array(
2086 'contact_id' => $ids['contact'],
2087 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2088 'Home', 'id', 'name'
2091 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2092 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2095 if ($this->is_test
) {
2098 if (!empty($this->_relatedObjects
['membership'])) {
2099 foreach ($this->_relatedObjects
['membership'] as $membership) {
2100 if ($membership->id
) {
2101 $values['membership_id'] = $membership->id
;
2103 // need to set the membership values here
2104 $template->assign('membership_assign', 1);
2105 $template->assign('membership_name',
2106 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2108 $template->assign('mem_start_date', $membership->start_date
);
2109 $template->assign('mem_join_date', $membership->join_date
);
2110 $template->assign('mem_end_date', $membership->end_date
);
2111 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2112 $template->assign('mem_status', $membership_status);
2113 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2114 $template->assign('is_pay_later', 1);
2117 // if separate payment there are two contributions recorded and the
2118 // admin will need to send a receipt for each of them separately.
2119 // we dont link the two in the db (but can potentially infer it if needed)
2120 $template->assign('is_separate_payment', 0);
2122 if ($recur && $paymentObject) {
2123 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2124 $template->assign('cancelSubscriptionUrl', $url);
2125 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2126 $template->assign('updateSubscriptionBillingUrl', $url);
2127 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2128 $template->assign('updateSubscriptionUrl', $url);
2131 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2134 // otherwise if its about sending emails, continue sending without return, as we
2135 // don't want to exit the loop.
2140 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2146 * Gather values for contribution mail - this function has been created
2147 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2148 * Values related to the contribution in question are gathered
2150 * @param array $input input into function (probably from payment processor)
2151 * @param array $ids the set of ids related to the inpurt
2153 * @return array $values
2155 * NB don't add direct calls to the function as we intend to change the signature
2157 function _gatherMessageValues($input, &$values, $ids = array()) {
2158 // set display address of contributor
2159 if ($this->address_id
) {
2160 $addressParams = array('id' => $this->address_id
);
2161 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2162 $addressDetails = array_values($addressDetails);
2163 $values['address'] = $addressDetails[0]['display'];
2165 if ($this->_component
== 'contribute') {
2166 if (isset($this->contribution_page_id
)) {
2167 CRM_Contribute_BAO_ContributionPage
::setValues(
2168 $this->contribution_page_id
,
2171 if ($this->contribution_page_id
) {
2172 // CRM-8254 - override default currency if applicable
2173 $config = CRM_Core_Config
::singleton();
2174 $config->defaultCurrency
= CRM_Utils_Array
::value(
2177 $config->defaultCurrency
2181 // no contribution page -probably back office
2183 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2184 $values['is_email_receipt'] = 1;
2185 $values['title'] = 'Contribution';
2187 // set lineItem for contribution
2189 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2190 if (!empty($lineItem)) {
2191 $itemId = key($lineItem);
2192 foreach ($lineItem as &$eachItem) {
2193 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2194 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2195 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2196 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2199 $values['lineItem'][0] = $lineItem;
2200 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2204 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2208 // if this is onbehalf of contribution then set related contact
2209 if (CRM_Utils_Array
::value('individual_id', $relatedContact)) {
2210 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2215 $eventParams = array(
2216 'id' => $this->_relatedObjects
['event']->id
,
2218 $values['event'] = array();
2220 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2222 //get location details
2223 $locationParams = array(
2224 'entity_id' => $this->_relatedObjects
['event']->id
,
2225 'entity_table' => 'civicrm_event',
2227 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2229 $ufJoinParams = array(
2230 'entity_table' => 'civicrm_event',
2231 'entity_id' => $ids['event'],
2232 'module' => 'CiviEvent',
2235 list($custom_pre_id,
2237 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2239 $values['custom_pre_id'] = $custom_pre_id;
2240 $values['custom_post_id'] = $custom_post_ids;
2242 // set lineItem for event contribution
2244 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2245 if (!empty($participantIds)) {
2246 foreach ($participantIds as $pIDs) {
2247 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2248 if (!CRM_Utils_System
::isNull($lineItem)) {
2249 $values['lineItem'][] = $lineItem;
2260 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2261 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2262 * Note we send directly from this function in some cases because it is only partly refactored
2263 * Don't call this function directly as the signature will change
2265 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2266 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2267 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2268 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2269 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2270 $template->assign('useForMember', true);
2272 //assign honor infomation to receiptmessage
2273 $honorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2277 if (!empty($honorID)) {
2279 $honorDefault = $honorIds = array();
2280 $honorIds['contribution'] = $this->id
;
2281 $idParams = array('id' => $honorID, 'contact_id' => $honorID);
2282 CRM_Contact_BAO_Contact
::retrieve($idParams, $honorDefault, $honorIds);
2283 $honorType = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'honor_type_id');
2285 $template->assign('honor_block_is_active', 1);
2286 if (CRM_Utils_Array
::value('prefix_id', $honorDefault)) {
2287 $prefix = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id');
2288 $template->assign('honor_prefix', $prefix[$honorDefault['prefix_id']]);
2290 $template->assign('honor_first_name', CRM_Utils_Array
::value('first_name', $honorDefault));
2291 $template->assign('honor_last_name', CRM_Utils_Array
::value('last_name', $honorDefault));
2292 $template->assign('honor_email', CRM_Utils_Array
::value('email', $honorDefault['email'][1]));
2293 $template->assign('honor_type', $honorType[$this->honor_type_id
]);
2296 $dao = new CRM_Contribute_DAO_ContributionProduct();
2297 $dao->contribution_id
= $this->id
;
2298 if ($dao->find(TRUE)) {
2299 $premiumId = $dao->product_id
;
2300 $template->assign('option', $dao->product_option
);
2302 $productDAO = new CRM_Contribute_DAO_Product();
2303 $productDAO->id
= $premiumId;
2304 $productDAO->find(TRUE);
2305 $template->assign('selectPremium', TRUE);
2306 $template->assign('product_name', $productDAO->name
);
2307 $template->assign('price', $productDAO->price
);
2308 $template->assign('sku', $productDAO->sku
);
2310 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2311 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2312 if(empty($amount) && isset($this->total_amount
)){
2313 $amount = $this->total_amount
;
2315 $template->assign('amount', $amount);
2316 // add the new contribution values
2317 if (strtolower($this->_component
) == 'contribute') {
2319 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2320 $softDAO->contribution_id
= $this->id
;
2321 if ($softDAO->find(TRUE)) {
2322 $template->assign('pcpBlock', TRUE);
2323 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2324 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2325 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2327 //assign the pcp page title for email subject
2328 $pcpDAO = new CRM_PCP_DAO_PCP();
2329 $pcpDAO->id
= $softDAO->pcp_id
;
2330 if ($pcpDAO->find(TRUE)) {
2331 $template->assign('title', $pcpDAO->title
);
2336 if ($this->financial_type_id
) {
2337 $values['financial_type_id'] = $this->financial_type_id
;
2341 $template->assign('trxn_id', $this->trxn_id
);
2342 $template->assign('receive_date',
2343 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2345 $template->assign('contributeMode', 'notify');
2346 $template->assign('action', $this->is_test ?
1024 : 1);
2347 $template->assign('receipt_text',
2348 CRM_Utils_Array
::value('receipt_text',
2352 $template->assign('is_monetary', 1);
2353 $template->assign('is_recur', (bool) $recur);
2354 $template->assign('currency', $this->currency
);
2355 $template->assign('address', CRM_Utils_Address
::format($input));
2356 if ($this->_component
== 'event') {
2357 $template->assign('title', $values['event']['title']);
2358 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2359 $viewRoles = array();
2360 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2361 $viewRoles[] = $participantRoles[$v];
2363 $values['event']['participant_role'] = implode(', ', $viewRoles);
2364 $template->assign('event', $values['event']);
2365 $template->assign('location', $values['location']);
2366 $template->assign('customPre', $values['custom_pre_id']);
2367 $template->assign('customPost', $values['custom_post_id']);
2370 if ($this->_relatedObjects
['participant']->is_test
) {
2374 $values['params'] = array();
2375 //to get email of primary participant.
2376 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2377 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2378 //build an array of cId/pId of participants
2379 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2380 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2381 //send receipt to additional participant if exists
2382 if (count($additionalIDs)) {
2383 $template->assign('isPrimary', 0);
2384 $template->assign('customProfile', NULL);
2385 //set additionalParticipant true
2386 $values['params']['additionalParticipant'] = TRUE;
2387 foreach ($additionalIDs as $pId => $cId) {
2389 //to change the status pending to completed
2390 $additional = new CRM_Event_DAO_Participant();
2391 $additional->id
= $pId;
2392 $additional->contact_id
= $cId;
2393 $additional->find(TRUE);
2394 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2395 $additional->status_id
= 1;
2396 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2397 //if additional participant dont have email
2399 if (!$additionalParticipantInfo) {
2400 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2402 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2403 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2404 $additional->save();
2405 $additional->free();
2406 $template->assign('amount', $amount);
2407 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2411 //build an array of custom profile and assigning it to template
2412 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2414 if (count($customProfile)) {
2415 $template->assign('customProfile', $customProfile);
2418 // for primary contact
2419 $values['params']['additionalParticipant'] = FALSE;
2420 $template->assign('isPrimary', 1);
2421 $template->assign('amount', $primaryAmount);
2422 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2423 if ($this->payment_instrument_id
) {
2424 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2425 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2427 // carry paylater, since we did not created billing,
2428 // so need to pull email from primary location, CRM-4395
2429 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2435 * Function to check whether payment processor supports
2436 * cancellation of contribution subscription
2438 * @param int $contributionId contribution id
2444 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2445 $cacheKeyString = "$contributionId";
2446 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2448 static $supportsCancel = array();
2450 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2451 $supportsCancel[$cacheKeyString] = FALSE;
2452 $isCancelled = FALSE;
2454 if ($isNotCancelled) {
2455 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2458 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2459 if (!empty($paymentObject)) {
2460 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2463 return $supportsCancel[$cacheKeyString];
2467 * Function to check whether subscription is already cancelled
2469 * @param int $contributionId contribution id
2471 * @return string $status contribution status
2475 static function isSubscriptionCancelled($contributionId) {
2477 SELECT cr.contribution_status_id
2478 FROM civicrm_contribution_recur cr
2479 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2480 WHERE con.id = %1 LIMIT 1";
2481 $params = array(1 => array($contributionId, 'Integer'));
2482 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2483 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2484 if ($status == 'Cancelled') {
2491 * Function to create all financial accounts entry
2493 * @param array $params contribution object, line item array and params for trxn
2499 static function recordFinancialAccounts(&$params) {
2500 $skipRecords = $update = FALSE;
2501 $additionalParticipantId = array();
2502 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2504 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2505 $entityId = $params['participant_id'];
2506 $entityTable = 'civicrm_participant';
2507 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2510 $entityId = $params['contribution']->id
;
2511 $entityTable = 'civicrm_contribution';
2514 $entityID[] = $entityId;
2515 if (!empty($additionalParticipantId)) {
2516 $entityID +
= $additionalParticipantId;
2518 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2519 if (!CRM_Utils_Array
::value('prevContribution', $params)) {
2526 // build line item array if its not set in $params
2527 if (!CRM_Utils_Array
::value('line_item', $params) ||
$additionalParticipantId) {
2528 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
2531 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2532 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2533 $skipRecords = TRUE;
2534 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses)) {
2535 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2536 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2538 elseif (CRM_Utils_Array
::value('payment_processor', $params)) {
2539 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2541 elseif (CRM_Utils_Array
::value('payment_instrument_id', $params)) {
2542 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2545 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2546 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2547 $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);
2550 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2551 if (!isset($totalAmount) && CRM_Utils_Array
::value('prevContribution', $params)) {
2552 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2554 //build financial transaction params
2555 $trxnParams = array(
2556 'contribution_id' => $params['contribution']->id
,
2557 'to_financial_account_id' => $params['to_financial_account_id'],
2558 'trxn_date' => date('YmdHis'),
2559 'total_amount' => $totalAmount,
2560 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2561 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2562 'currency' => $params['contribution']->currency
,
2563 'trxn_id' => $params['contribution']->trxn_id
,
2564 'status_id' => $params['contribution']->contribution_status_id
,
2565 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2566 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2569 if (CRM_Utils_Array
::value('payment_processor', $params)) {
2570 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2572 $params['trxnParams'] = $trxnParams;
2574 if (CRM_Utils_Array
::value('prevContribution', $params)) {
2575 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2576 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2577 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2578 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2579 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2580 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2581 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2583 //if financial type is changed
2584 if (CRM_Utils_Array
::value('financial_type_id', $params) &&
2585 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2586 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2587 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2588 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2589 if ($oldFinancialAccount != $newFinancialAccount) {
2590 $params['total_amount'] = 0;
2591 if ($params['contribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)) {
2592 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2593 $params['prevContribution']->financial_type_id
, $relationTypeId);
2596 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2597 if (CRM_Utils_Array
::value('financialTrxnId', $lastFinancialTrxnId)) {
2598 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2601 self
::updateFinancialAccounts($params, 'changeFinancialType');
2602 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2603 $params['financial_account_id'] = $newFinancialAccount;
2604 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2605 self
::updateFinancialAccounts($params);
2606 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2610 //Update contribution status
2611 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2612 if (CRM_Utils_Array
::value('contribution_status_id', $params) &&
2613 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2614 //Update Financial Records
2615 self
::updateFinancialAccounts($params, 'changedStatus');
2618 // change Payment Instrument for a Completed contribution
2619 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2620 // instrument is null and now new payment instrument is added along with the payment
2621 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2622 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2623 if (array_key_exists('payment_instrument_id', $params)) {
2624 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2625 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2626 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2627 //check if status is changed from Pending to Completed
2628 // do not update payment instrument changes for Pending to Completed
2629 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2630 $params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses))) {
2631 // for all other statuses create new financial records
2632 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2633 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2634 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2637 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2638 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2639 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2640 // for any other payment instrument changes create new financial records
2641 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2642 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2643 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2645 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2646 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2647 // another special case when check number is changed, create new financial records
2648 // create financial trxn with negative amount
2649 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2650 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2651 // create financial trxn with positive amount
2652 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2653 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2654 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2658 //if Change contribution amount
2659 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2660 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2661 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2662 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2663 if (isset($totalAmount) &&
2664 $totalAmount != $params['prevContribution']->total_amount
) {
2665 //Update Financial Records
2666 $params['trxnParams']['from_financial_account_id'] = NULL;
2667 self
::updateFinancialAccounts($params, 'changedAmount');
2672 //records finanical trxn and entity financial trxn
2673 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2674 $params['entity_id'] = $financialTxn->id
;
2677 // record line items and finacial items
2678 if (!CRM_Utils_Array
::value('skipLineItem', $params)) {
2679 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2682 // create batch entry if batch_id is passed
2683 if (CRM_Utils_Array
::value('batch_id', $params)) {
2684 $entityParams = array(
2685 'batch_id' => $params['batch_id'],
2686 'entity_table' => 'civicrm_financial_trxn',
2687 'entity_id' => $financialTxn->id
,
2689 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2692 // when a fee is charged
2693 if (CRM_Utils_Array
::value('fee_amount', $params) && (!CRM_Utils_Array
::value('prevContribution', $params)
2694 ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2695 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2698 if (CRM_Utils_Array
::value('prevContribution', $params) && $entityTable == 'civicrm_participant'
2699 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2700 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2701 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2702 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2704 unset($params['line_item']);
2708 * Function to update all financial accounts entry
2710 * @param array $params contribution object, line item array and params for trxn
2712 * @param string $context update scenarios
2717 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2718 $itemAmount = $trxnID = NULL;
2719 //get all the statuses
2720 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2721 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus) &&
2722 $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2723 && $context == 'changePaymentInstrument') {
2726 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2727 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2729 if ($context == 'changedStatus') {
2730 //get all the statuses
2731 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2733 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2734 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2735 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2737 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2739 elseif ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2740 && $params['prevContribution']->is_pay_later
) {
2741 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2742 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2743 $params['trxnParams']['to_financial_account_id'] = NULL;
2744 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2746 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2747 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2748 $financialTypeID, $relationTypeId);
2750 $itemAmount = $params['trxnParams']['total_amount'];
2752 elseif ($context == 'changePaymentInstrument') {
2753 if ($params['trxnParams']['total_amount'] < 0) {
2754 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2755 if (CRM_Utils_Array
::value('financialTrxnId', $lastFinancialTrxnId)) {
2756 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2757 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2761 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2762 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2765 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2766 $params['entity_id'] = $trxn->id
;
2768 if ($context == 'changedStatus') {
2769 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) &&
2770 ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2771 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2772 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2774 $entityParams = array(
2775 'entity_table' => 'civicrm_financial_item',
2776 'financial_trxn_id' => $trxn->id
,
2778 foreach ($params['line_item'] as $fieldId => $fields) {
2779 foreach ($fields as $fieldValueId => $fieldValues) {
2781 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2782 2 => array($fieldValues['id'], 'Integer'),
2784 CRM_Core_DAO
::executeQuery($query, $fparams);
2786 1 => array($fieldValues['id'], 'Integer'),
2788 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2789 while ($financialItem->fetch()) {
2790 $entityParams['entity_id'] = $financialItem->id
;
2791 $entityParams['amount'] = $financialItem->amount
;
2792 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2799 if ($context != 'changePaymentInstrument') {
2800 $itemParams['entity_table'] = 'civicrm_line_item';
2801 $trxnIds['id'] = $params['entity_id'];
2802 foreach ($params['line_item'] as $fieldId => $fields) {
2803 foreach ($fields as $fieldValueId => $fieldValues) {
2804 $prevParams['entity_id'] = $fieldValues['id'];
2805 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2807 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2808 if ($params['contribution']->receive_date
) {
2809 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2812 $financialAccount = $prevfinancialItem->financial_account_id
;
2813 if (CRM_Utils_Array
::value('financial_account_id', $params)) {
2814 $financialAccount = $params['financial_account_id'];
2817 $currency = $params['prevContribution']->currency
;
2818 if ($params['contribution']->currency
) {
2819 $currency = $params['contribution']->currency
;
2821 if (CRM_Utils_Array
::value('is_quick_config', $params)) {
2822 $amount = $itemAmount;
2824 $amount = $params['total_amount'];
2829 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2832 $amount = $diff * $fieldValues['line_total'];
2835 $itemParams = array(
2836 'transaction_date' => $receiveDate,
2837 'contact_id' => $params['prevContribution']->contact_id
,
2838 'currency' => $currency,
2839 'amount' => $amount,
2840 'description' => $prevfinancialItem->description
,
2841 'status_id' => $prevfinancialItem->status_id
,
2842 'financial_account_id' => $financialAccount,
2843 'entity_table' => 'civicrm_line_item',
2844 'entity_id' => $fieldValues['id']
2846 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
2853 * Function to check status validation on update of a contribution
2855 * @param array $values previous form values before submit
2857 * @param array $fields the input form values
2859 * @param array $errors list of errors
2864 static function checkStatusValidation($values, &$fields, &$errors) {
2865 if (CRM_Utils_System
::isNull($values) && CRM_Utils_Array
::value('id', $fields)) {
2866 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
2867 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
2871 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2872 $checkStatus = array(
2873 'Cancelled' => array('Completed', 'Refunded'),
2874 'Completed' => array('Cancelled', 'Refunded'),
2875 'Pending' => array('Cancelled', 'Completed', 'Failed'),
2876 'Refunded' => array('Cancelled', 'Completed')
2879 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
2880 $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']]));
2885 * Function to delete contribution of contact
2889 * @param integer $contactId contact id
2894 static function deleteContactContribution($contactId) {
2895 $contribution = new CRM_Contribute_DAO_Contribution();
2896 $contribution->contact_id
= $contactId;
2897 $contribution->find();
2898 while ($contribution->fetch()) {
2899 self
::deleteContribution($contribution->id
);
2904 * Get options for a given contribution field.
2905 * @see CRM_Core_DAO::buildOptions
2907 * @param String $fieldName
2908 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
2909 * @param Array $props: whatever is known about this dao object
2911 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2912 $className = __CLASS__
;
2914 switch ($fieldName) {
2915 // This field is not part of this object but the api supports it
2916 case 'payment_processor':
2917 $className = 'CRM_Contribute_BAO_ContributionPage';
2918 // Filter results by contribution page
2919 if (!empty($props['contribution_page_id'])) {
2920 $page = civicrm_api('contribution_page', 'getsingle', array(
2922 'id' => ($props['contribution_page_id'])
2924 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
2925 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
2928 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
2932 * Function to validate financial type
2936 * @param integer $financialTypeId Financial Type id
2941 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
2942 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
2943 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
2945 if (!$financialAccount) {
2946 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);