5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.3 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2013 |
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
33 * @copyright CiviCRM LLC (c) 2004-2013
37 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
40 * static field for all the contribution information that we can potentially import
45 static $_importableFields = NULL;
48 * static field for all the contribution information that we can potentially export
53 static $_exportableFields = NULL;
56 * field for all the objects related to this contribution
57 * @var array of objects (e.g membership object, participant object)
59 public $_relatedObjects = array();
62 * field for the component - either 'event' (participant) or 'contribute'
63 * (any item related to a contribution page e.g. membership, pledge, contribution)
64 * This is used for composing messages because they have dependency on the
65 * contribution_page or event page - although over time we may eliminate that
67 * @var string component or event
69 public $_component = NULL;
74 function __construct() {
75 parent
::__construct();
79 * takes an associative array and creates a contribution object
81 * the function extract all the params it needs to initialize the create a
82 * contribution object. the params array could contain additional unused name/value
85 * @param array $params (reference ) an assoc array of name/value pairs
86 * @param array $ids the array that holds all the db ids
88 * @return object CRM_Contribute_BAO_Contribution object
92 static function add(&$params, &$ids) {
97 $duplicates = array();
98 if (self
::checkDuplicate($params, $duplicates,
99 CRM_Utils_Array
::value('contribution', $ids)
101 $error = CRM_Core_Error
::singleton();
102 $d = implode(', ', $duplicates);
103 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
106 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
111 // first clean up all the money fields
112 $moneyFields = array(
116 'non_deductible_amount',
119 //if priceset is used, no need to cleanup money
120 if (CRM_Utils_Array
::value('skipCleanMoney', $params)) {
121 unset($moneyFields[0]);
124 foreach ($moneyFields as $field) {
125 if (isset($params[$field])) {
126 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
130 if (CRM_Utils_Array
::value('payment_instrument_id', $params)) {
131 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
132 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
133 $params['check_number'] = 'null';
137 // contribution status is missing, choose Completed as default status
138 if (!CRM_Utils_Array
::value('contribution_status_id', $params)) {
139 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
142 if (CRM_Utils_Array
::value('contribution', $ids)) {
143 CRM_Utils_Hook
::pre('edit', 'Contribution', $ids['contribution'], $params);
146 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
149 $contribution = new CRM_Contribute_BAO_Contribution();
150 $contribution->copyValues($params);
152 $contribution->id
= CRM_Utils_Array
::value('contribution', $ids);
154 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
155 $config = CRM_Core_Config
::singleton();
156 $contribution->currency
= $config->defaultCurrency
;
159 if (CRM_Utils_Array
::value('contribution', $ids)) {
160 $contributionId['id'] = $ids['contribution'];
161 $params['prevContribution'] = self
::getValues($contributionId, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
164 $result = $contribution->save();
166 // Add financial_trxn details as part of fix for CRM-4724
167 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
168 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
170 //add Account details
171 $params['contribution'] = $contribution;
172 self
::recordFinancialAccounts($params, $ids);
174 // reset the group contact cache for this group
175 CRM_Contact_BAO_GroupContactCache
::remove();
177 if (CRM_Utils_Array
::value('contribution', $ids)) {
178 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
181 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
188 * Given the list of params in the params array, fetch the object
189 * and store the values in the values array
191 * @param array $params input parameters to find object
192 * @param array $values output values of the object
193 * @param array $ids the array that holds all the db ids
195 * @return CRM_Contribute_BAO_Contribution|null the found object or null
199 static function &getValues(&$params, &$values, &$ids) {
200 if (empty($params)) {
203 $contribution = new CRM_Contribute_BAO_Contribution();
205 $contribution->copyValues($params);
207 if ($contribution->find(TRUE)) {
208 $ids['contribution'] = $contribution->id
;
210 CRM_Core_DAO
::storeValues($contribution, $values);
212 return $contribution;
218 * takes an associative array and creates a contribution object
220 * @param array $params (reference ) an assoc array of name/value pairs
221 * @param array $ids the array that holds all the db ids
223 * @return object CRM_Contribute_BAO_Contribution object
227 static function &create(&$params, &$ids) {
228 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
229 foreach ($dateFields as $df) {
230 if (isset($params[$df])) {
231 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
235 $transaction = new CRM_Core_Transaction();
237 $contribution = self
::add($params, $ids);
239 if (is_a($contribution, 'CRM_Core_Error')) {
240 $transaction->rollback();
241 return $contribution;
244 $params['contribution_id'] = $contribution->id
;
246 if (CRM_Utils_Array
::value('custom', $params) &&
247 is_array($params['custom'])
249 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
252 $session = CRM_Core_Session
::singleton();
254 if (CRM_Utils_Array
::value('note', $params)) {
256 'entity_table' => 'civicrm_contribution',
257 'note' => $params['note'],
258 'entity_id' => $contribution->id
,
259 'contact_id' => $session->get('userID'),
260 'modified_date' => date('Ymd'),
262 if (!$noteParams['contact_id']) {
263 $noteParams['contact_id'] = $params['contact_id'];
265 CRM_Core_BAO_Note
::add($noteParams,
266 CRM_Utils_Array
::value('note', $ids)
270 // make entry in batch entity batch table
271 if (CRM_Utils_Array
::value('batch_id', $params)) {
272 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
273 $titleFields = array(
279 $retrieveRequired = 0;
280 foreach ($titleFields as $titleField) {
281 if(!isset($contribution->$titleField)){
282 $retrieveRequired = 1;
286 if ($retrieveRequired == 1) {
287 $contribution->find(true);
291 // check if activity record exist for this contribution, if
293 $activity = new CRM_Activity_DAO_Activity();
294 $activity->source_record_id
= $contribution->id
;
295 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
299 if (!$activity->find()) {
300 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
302 // Handle soft credit and / or link to personal campaign page
303 if (CRM_Utils_Array
::value('deleteSoftCredit', $params, TRUE)) {
304 // first delete soft credits if any
305 //CRM_Contribute_BAO_ContributionSoft::del($contribution->id);
307 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
308 $softParams = array();
309 $softParams['contribution_id'] = $contribution->id
;
310 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
311 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
312 $pcp['pcp_made_through_id'], 'contact_id'
314 $softParams['currency'] = $contribution->currency
;
315 $softParams['amount'] = $contribution->total_amount
;
316 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
317 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
318 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
319 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
321 elseif (CRM_Utils_Array
::value('soft_credit', $params)) {
322 $softParams = $params['soft_credit'];
323 foreach ($softParams as $softParam) {
324 $softParam['contribution_id'] = $contribution->id
;
325 $softParam['currency'] = $contribution->currency
;
326 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
330 $transaction->commit();
332 // do not add to recent items for import, CRM-4399
333 if (!CRM_Utils_Array
::value('skipRecentView', $params)) {
334 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
335 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
337 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
338 $titleFields = array(
344 $retrieveRequired = 0;
345 foreach ($titleFields as $titleField) {
346 if(!isset($contribution->$titleField)){
347 $retrieveRequired = 1;
351 if($retrieveRequired == 1){
352 $contribution->find(true);
354 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
355 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
357 $recentOther = array();
358 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
359 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
360 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
364 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
365 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
366 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
370 // add the recently created Contribution
371 CRM_Utils_Recent
::add($title,
375 $contribution->contact_id
,
381 return $contribution;
385 * Get the values for pseudoconstants for name->value and reverse.
387 * @param array $defaults (reference) the default values, some of which need to be resolved.
388 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
394 static function resolveDefaults(&$defaults, $reverse = FALSE) {
395 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
396 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
397 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
398 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
402 * This function is used to convert associative array names to values
405 * This function is used by both the web form layer and the api. Note that
406 * the api needs the name => value conversion, also the view layer typically
407 * requires value => name conversion
409 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
410 $id = $property . '_id';
412 $src = $reverse ?
$property : $id;
413 $dst = $reverse ?
$id : $property;
415 if (!array_key_exists($src, $defaults)) {
419 $look = $reverse ?
array_flip($lookup) : $lookup;
421 if (is_array($look)) {
422 if (!array_key_exists($defaults[$src], $look)) {
426 $defaults[$dst] = $look[$defaults[$src]];
431 * Takes a bunch of params that are needed to match certain criteria and
432 * retrieves the relevant objects. We'll tweak this function to be more
433 * full featured over a period of time. This is the inverse function of
434 * create. It also stores all the retrieved values in the default array
436 * @param array $params (reference ) an assoc array of name/value pairs
437 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
438 * in a hierarchical manner
439 * @param array $ids (reference) the array that holds all the db ids
441 * @return object CRM_Contribute_BAO_Contribution object
445 static function retrieve(&$params, &$defaults, &$ids) {
446 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
447 return $contribution;
451 * combine all the importable fields from the lower levels object
453 * The ordering is important, since currently we do not have a weight
454 * scheme. Adding weight is super important and should be done in the
455 * next week or so, before this can be called complete.
457 * @return array array of importable Fields
461 static function &importableFields($contacType = 'Individual', $status = TRUE) {
462 if (!self
::$_importableFields) {
463 if (!self
::$_importableFields) {
464 self
::$_importableFields = array();
468 $fields = array('' => array('title' => ts('- do not import -')));
471 $fields = array('' => array('title' => ts('- Contribution Fields -')));
474 $note = CRM_Core_DAO_Note
::import();
475 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
476 unset($tmpFields['option_value']);
477 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
478 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contacType, NULL);
480 // Using new Dedupe rule.
482 'contact_type' => $contacType,
483 'used' => 'Unsupervised',
485 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
486 $tmpConatctField = array();
487 if (is_array($fieldsArray)) {
488 foreach ($fieldsArray as $value) {
489 //skip if there is no dupe rule
490 if ($value == 'none') {
493 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
498 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
499 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
501 $title = $tmpConatctField[trim($value)]['title'] . ' ' . ts('(match to contact)');
504 $title = $tmpConatctField[trim($value)]['title'];
506 $tmpConatctField[trim($value)]['title'] = $title;
510 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
511 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
512 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
513 $fields = array_merge($fields, $tmpConatctField);
514 $fields = array_merge($fields, $tmpFields);
515 $fields = array_merge($fields, $note);
516 $fields = array_merge($fields, $optionFields);
517 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
518 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
519 self
::$_importableFields = $fields;
521 return self
::$_importableFields;
524 static function &exportableFields() {
525 if (!self
::$_exportableFields) {
526 if (!self
::$_exportableFields) {
527 self
::$_exportableFields = array();
530 $impFields = CRM_Contribute_DAO_Contribution
::export();
531 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
532 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
533 $typeField = CRM_Financial_DAO_FinancialType
::export();
534 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
535 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
536 $contributionStatus = array(
537 'contribution_status' => array(
538 'title' => ts('Contribution Status'),
539 'name' => 'contribution_status',
540 'data_type' => CRM_Utils_Type
::T_STRING
543 $contributionNote = array(
544 'contribution_note' =>
546 'title' => ts('Contribution Note'),
547 'name' => 'contribution_note',
548 'data_type' => CRM_Utils_Type
::T_TEXT
552 $contributionRecurId = array(
553 'contribution_recur_id' =>
555 'title' => ts('Recurring Contributions ID'),
556 'name' => 'contribution_recur_id',
557 'where' => 'civicrm_contribution.contribution_recur_id',
558 'data_type' => CRM_Utils_Type
::T_INT
561 $extraFields = array(
562 'contribution_campaign' =>
564 'title' => ts('Campaign Title')
566 'contribution_batch' =>
568 'title' => ts('Batch Name')
572 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
573 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $financialAccount,
574 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
577 self
::$_exportableFields = $fields;
580 return self
::$_exportableFields;
583 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
587 $where[] = 'contribution_status_id = 1';
591 $where[] = 'contribution_status_id = 3';
596 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
599 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
602 $whereCond = implode(' AND ', $where);
605 SELECT sum( total_amount ) as total_amount,
606 count( civicrm_contribution.id ) as total_count,
608 FROM civicrm_contribution
609 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
611 AND ( is_test = 0 OR is_test IS NULL )
612 AND contact.is_deleted = 0
616 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
619 while ($dao->fetch()) {
620 $count +
= $dao->total_count
;
621 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
624 return array('amount' => implode(', ', $amount),
632 * Delete the indirect records associated with this contribution first
634 * @return $results no of deleted Contribution on success, false otherwise
638 static function deleteContribution($id) {
639 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
641 $transaction = new CRM_Core_Transaction();
644 //delete activity record
646 'source_record_id' => $id,
647 // activity type id for contribution
648 'activity_type_id' => 6,
651 CRM_Activity_BAO_Activity
::deleteActivity($params);
653 //delete billing address if exists for this contribution.
654 self
::deleteAddress($id);
656 //update pledge and pledge payment, CRM-3961
657 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
659 // remove entry from civicrm_price_set_entity, CRM-5095
660 if (CRM_Price_BAO_Set
::getFor('civicrm_contribution', $id)) {
661 CRM_Price_BAO_Set
::removeFrom('civicrm_contribution', $id);
663 // cleanup line items.
664 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
666 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
667 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
669 if ($participantId) {
670 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
673 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
677 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
678 $noteId = key($note);
680 CRM_Core_BAO_Note
::del($noteId, FALSE);
683 $dao = new CRM_Contribute_DAO_Contribution();
686 $results = $dao->delete();
688 $transaction->commit();
690 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
692 // delete the recently created Contribution
693 $contributionRecent = array(
695 'type' => 'Contribution',
697 CRM_Utils_Recent
::del($contributionRecent);
703 * Check if there is a contribution with the same trxn_id or invoice_id
705 * @param array $params (reference ) an assoc array of name/value pairs
706 * @param array $duplicates (reference ) store ids of duplicate contribs
708 * @return boolean true if duplicate, false otherwise
712 static function checkDuplicate($input, &$duplicates, $id = NULL) {
714 $id = CRM_Utils_Array
::value('id', $input);
716 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
717 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
723 $clause[] = "trxn_id = %1";
724 $input[1] = array($trxn_id, 'String');
728 $clause[] = "invoice_id = %2";
729 $input[2] = array($invoice_id, 'String');
732 if (empty($clause)) {
736 $clause = implode(' OR ', $clause);
738 $clause = "( $clause ) AND id != %3";
739 $input[3] = array($id, 'Integer');
742 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
743 $dao = CRM_Core_DAO
::executeQuery($query, $input);
745 while ($dao->fetch()) {
746 $duplicates[] = $dao->id
;
753 * takes an associative array and creates a contribution_product object
755 * the function extract all the params it needs to initialize the create a
756 * contribution_product object. the params array could contain additional unused name/value
759 * @param array $params (reference ) an assoc array of name/value pairs
761 * @return object CRM_Contribute_BAO_ContributionProduct object
765 static function addPremium(&$params) {
766 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
767 $contributionProduct->copyValues($params);
768 return $contributionProduct->save();
772 * Function to get list of contribution fields for profile
773 * For now we only allow custom contribution fields to be in
776 * @param boolean $addExtraFields true if special fields needs to be added
778 * @return return the list of contribution fields
782 static function getContributionFields($addExtraFields = TRUE) {
783 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
784 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
786 if ($addExtraFields) {
787 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
790 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
792 foreach ($contributionFields as $key => $var) {
793 if ($key == 'contribution_contact_id') {
796 elseif ($key == 'contribution_campaign_id') {
797 $var['title'] = ts('Campaign');
799 $fields[$key] = $var;
802 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
807 * Function to add extra fields specific to contribtion
811 static function getSpecialContributionFields() {
812 $extraFields = array(
813 'honor_contact_name' => array(
814 'name' => 'honor_contact_name',
815 'title' => 'Honor Contact Name',
816 'headerPattern' => '/^honor_contact_name$/i',
817 'where' => 'civicrm_contact_c.display_name',
819 'honor_contact_email' => array(
820 'name' => 'honor_contact_email',
821 'title' => 'Honor Contact Email',
822 'headerPattern' => '/^honor_contact_email$/i',
823 'where' => 'honor_email.email',
825 'honor_contact_id' => array(
826 'name' => 'honor_contact_id',
827 'title' => 'Honor Contact ID',
828 'headerPattern' => '/^honor_contact_id$/i',
829 'where' => 'civicrm_contribution.honor_contact_id',
831 'honor_type_label' => array(
832 'name' => 'honor_type_label',
833 'title' => 'Honor Type Label',
834 'headerPattern' => '/^honor_type_label$/i',
835 'where' => 'honor_type.label',
837 'soft_credit_name' => array(
838 'name' => 'soft_credit_name',
839 'title' => 'Soft Credit Name',
840 'headerPattern' => '/^soft_credit_name$/i',
841 'where' => 'civicrm_contact_d.display_name',
843 'soft_credit_email' => array(
844 'name' => 'soft_credit_email',
845 'title' => 'Soft Credit Email',
846 'headerPattern' => '/^soft_credit_email$/i',
847 'where' => 'soft_email.email',
849 'soft_credit_phone' => array(
850 'name' => 'soft_credit_phone',
851 'title' => 'Soft Credit Phone',
852 'headerPattern' => '/^soft_credit_phone$/i',
853 'where' => 'soft_phone.phone',
855 'soft_credit_contact_id' => array(
856 'name' => 'soft_credit_contact_id',
857 'title' => 'Soft Credit Contact ID',
858 'headerPattern' => '/^soft_credit_contact_id$/i',
859 'where' => 'civicrm_contribution_soft.contact_id',
866 static function getCurrentandGoalAmount($pageID) {
868 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
869 FROM civicrm_contribution_page p,
870 civicrm_contribution c
871 WHERE p.id = c.contribution_page_id
873 AND c.cancel_date is null
877 $config = CRM_Core_Config
::singleton();
878 $params = array(1 => array($pageID, 'Integer'));
879 $dao = CRM_Core_DAO
::executeQuery($query, $params);
882 return array($dao->goal
, $dao->total
);
885 return array(NULL, NULL);
890 * Function to create is honor of
892 * @param array $params associated array of fields (by reference)
893 * @param int $honorId honor Id
894 * @param array $honorParams any params that should be send to the create function
898 static function createHonorContact(&$params, $honorId = NULL, $honorParams = array()) {
899 $honorParams = array_merge(
901 'first_name' => $params['honor_first_name'],
902 'last_name' => $params['honor_last_name'],
903 'prefix_id' => $params['honor_prefix_id'],
904 'email-Primary' => $params['honor_email'],
909 $honorParams['email'] = $params['honor_email'];
911 $dedupeParams = CRM_Dedupe_Finder
::formatParams($honorParams, 'Individual');
912 $dedupeParams['check_permission'] = FALSE;
913 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
915 // if we find more than one contact, use the first one
916 $honorId = CRM_Utils_Array
::value(0, $ids);
919 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
921 CRM_Core_DAO
::$_nullArray,
928 * Function to get list of contribution In Honor of contact Ids
930 * @param int $honorId In Honor of Contact ID
932 * @return return the list of contribution fields
937 static function getHonorContacts($honorId) {
939 $honorDAO = new CRM_Contribute_DAO_Contribution();
940 $honorDAO->honor_contact_id
= $honorId;
943 $status = CRM_Contribute_PseudoConstant
::contributionStatus($honorDAO->contribution_status_id
);
944 $type = CRM_Contribute_PseudoConstant
::financialType();
946 while ($honorDAO->fetch()) {
947 $params[$honorDAO->id
]['honorId'] = $honorDAO->contact_id
;
948 $params[$honorDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $honorDAO->contact_id
, 'display_name');
949 $params[$honorDAO->id
]['type'] = $type[$honorDAO->financial_type_id
];
950 $params[$honorDAO->id
]['type_id'] = $honorDAO->financial_type_id
;
951 $params[$honorDAO->id
]['amount'] = CRM_Utils_Money
::format($honorDAO->total_amount
, $honorDAO->currency
);
952 $params[$honorDAO->id
]['source'] = $honorDAO->source
;
953 $params[$honorDAO->id
]['receive_date'] = $honorDAO->receive_date
;
954 $params[$honorDAO->id
]['contribution_status'] = CRM_Utils_Array
::value($honorDAO->contribution_status_id
, $status);
961 * function to get the sort name of a contact for a particular contribution
963 * @param int $id id of the contribution
965 * @return null|string sort name of the contact if found
969 static function sortName($id) {
970 $id = CRM_Utils_Type
::escape($id, 'Integer');
973 SELECT civicrm_contact.sort_name
974 FROM civicrm_contribution, civicrm_contact
975 WHERE civicrm_contribution.contact_id = civicrm_contact.id
976 AND civicrm_contribution.id = {$id}
978 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
981 static function annual($contactID) {
982 if (is_array($contactID)) {
983 $contactIDs = implode(',', $contactID);
986 $contactIDs = $contactID;
989 $config = CRM_Core_Config
::singleton();
990 $startDate = $endDate = NULL;
992 $currentMonth = date('m');
993 $currentDay = date('d');
994 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
995 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
996 (int ) $config->fiscalYearStart
['d'] > $currentDay
999 $year = date('Y') - 1;
1004 $nextYear = $year +
1;
1006 if ($config->fiscalYearStart
) {
1007 if ($config->fiscalYearStart
['M'] < 10) {
1008 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1010 if ($config->fiscalYearStart
['d'] < 10) {
1011 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1013 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1018 $startDate = "$year$monthDay";
1019 $endDate = "$nextYear$monthDay";
1022 SELECT count(*) as count,
1023 sum(total_amount) as amount,
1024 avg(total_amount) as average,
1026 FROM civicrm_contribution b
1027 WHERE b.contact_id IN ( $contactIDs )
1028 AND b.contribution_status_id = 1
1030 AND b.receive_date >= $startDate
1031 AND b.receive_date < $endDate
1034 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1036 $amount = $average = array();
1037 while ($dao->fetch()) {
1038 if ($dao->count
> 0 && $dao->amount
> 0) {
1039 $count +
= $dao->count
;
1040 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1041 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1047 implode(', ', $amount),
1048 implode(', ', $average),
1051 return array(0, 0, 0);
1055 * Check if there is a contribution with the params passed in.
1056 * Used for trxn_id,invoice_id and contribution_id
1058 * @param array $params an assoc array of name/value pairs
1060 * @return array contribution id if success else NULL
1064 static function checkDuplicateIds($params) {
1065 $dao = new CRM_Contribute_DAO_Contribution();
1069 foreach ($params as $k => $v) {
1071 $clause[] = "$k = '$v'";
1074 $clause = implode(' AND ', $clause);
1075 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1076 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1078 while ($dao->fetch()) {
1086 * Function to get the contribution details for component export
1088 * @param int $exportMode export mode
1089 * @param string $componentIds component ids
1091 * @return array associated array
1096 static function getContributionDetails($exportMode, $componentIds) {
1097 $paymentDetails = array();
1098 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1100 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1101 $componentSelect = " civicrm_participant_payment.participant_id id";
1102 $additionalClause = "
1103 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1104 AND civicrm_participant_payment.participant_id {$componentClause} )
1107 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1108 $componentSelect = " civicrm_membership_payment.membership_id id";
1109 $additionalClause = "
1110 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1111 AND civicrm_membership_payment.membership_id {$componentClause} )
1114 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1115 $componentSelect = " civicrm_pledge_payment.id id";
1116 $additionalClause = "
1117 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1118 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1122 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1123 trxn_id, {$componentSelect}
1124 FROM civicrm_contribution
1125 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1126 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1127 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1128 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1129 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1130 AND option_group_contribution_status.id = contribution_status.option_group_id )
1134 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1136 while ($dao->fetch()) {
1137 $paymentDetails[$dao->id
] = array(
1138 'total_amount' => $dao->total_amount
,
1139 'contribution_status' => $dao->status
,
1140 'receive_date' => $dao->receive_date
,
1141 'pay_instru' => $dao->payment_instrument
,
1142 'trxn_id' => $dao->trxn_id
,
1146 return $paymentDetails;
1150 * Function to create address associated with contribution record.
1151 * @param array $params an associated array
1152 * @param int $billingID $billingLocationTypeID
1154 * @return address id
1157 static function createAddress(&$params, $billingLocationTypeID) {
1158 $billingFields = array(
1161 'state_province_id',
1166 //build address array
1167 $addressParams = array();
1168 $addressParams['location_type_id'] = $billingLocationTypeID;
1169 $addressParams['is_billing'] = 1;
1170 $addressParams['address_name'] = "{$params['billing_first_name']}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$params['billing_middle_name']}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$params['billing_last_name']}";
1172 foreach ($billingFields as $value) {
1173 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"];
1176 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1178 return $address->id
;
1182 * Delete billing address record related contribution
1184 * @param int $contact_id contact id
1185 * @param int $contribution_id contributionId
1189 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1191 $contactJoin = NULL;
1193 if ($contributionId) {
1194 $clauses[] = "cc.id = {$contributionId}";
1198 $clauses[] = "cco.id = {$contactId}";
1199 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1202 if (empty($clauses)) {
1203 CRM_Core_Error
::fatal();
1206 $condition = implode(' OR ', $clauses);
1210 FROM civicrm_address ca
1211 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1215 $dao = CRM_Core_DAO
::executeQuery($query);
1217 while ($dao->fetch()) {
1218 $params = array('id' => $dao->id
);
1219 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1224 * This function check online pending contribution associated w/
1225 * Online Event Registration or Online Membership signup.
1227 * @param int $componentId participant/membership id.
1228 * @param string $componentName Event/Membership.
1230 * @return $contributionId pending contribution id.
1233 static function checkOnlinePendingContribution($componentId, $componentName) {
1234 $contributionId = NULL;
1235 if (!$componentId ||
1236 !in_array($componentName, array('Event', 'Membership'))
1238 return $contributionId;
1241 if ($componentName == 'Event') {
1242 $idName = 'participant_id';
1243 $componentTable = 'civicrm_participant';
1244 $paymentTable = 'civicrm_participant_payment';
1245 $source = ts('Online Event Registration');
1248 if ($componentName == 'Membership') {
1249 $idName = 'membership_id';
1250 $componentTable = 'civicrm_membership';
1251 $paymentTable = 'civicrm_membership_payment';
1252 $source = ts('Online Contribution');
1255 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1258 SELECT component.id as {$idName},
1259 componentPayment.contribution_id as contribution_id,
1260 contribution.source source,
1261 contribution.contribution_status_id as contribution_status_id,
1262 contribution.is_pay_later as is_pay_later
1263 FROM $componentTable component
1264 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1265 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1266 WHERE component.id = {$componentId}";
1268 $dao = CRM_Core_DAO
::executeQuery($query);
1270 while ($dao->fetch()) {
1271 if ($dao->contribution_id
&&
1272 $dao->is_pay_later
&&
1273 $dao->contribution_status_id
== $pendingStatusId &&
1274 strpos($dao->source
, $source) !== FALSE
1276 $contributionId = $dao->contribution_id
;
1281 return $contributionId;
1285 * This function update contribution as well as related objects.
1287 function transitionComponents($params, $processContributionObject = FALSE) {
1288 // get minimum required values.
1289 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1290 $componentId = CRM_Utils_Array
::value('component_id', $params);
1291 $componentName = CRM_Utils_Array
::value('componentName', $params);
1292 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1293 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1295 // if we already processed contribution object pass previous status id.
1296 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1298 $updateResult = array();
1300 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1302 // we process only ( Completed, Cancelled, or Failed ) contributions.
1303 if (!$contributionId ||
1304 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1305 array_search('Cancelled', $contributionStatuses),
1306 array_search('Failed', $contributionStatuses),
1309 return $updateResult;
1312 if (!$componentName ||
!$componentId) {
1313 // get the related component details.
1314 $componentDetails = self
::getComponentDetails($contributionId);
1317 $componentDetails['contact_id'] = $contactId;
1318 $componentDetails['component'] = $componentName;
1320 if ($componentName == 'event') {
1321 $componentDetails['participant'] = $componentId;
1324 $componentDetails['membership'] = $componentId;
1328 if (CRM_Utils_Array
::value('contact_id', $componentDetails)) {
1329 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1335 // do check for required ids.
1336 if (!CRM_Utils_Array
::value('membership', $componentDetails) &&
1337 !CRM_Utils_Array
::value('participant', $componentDetails) &&
1338 !CRM_Utils_Array
::value('pledge_payment', $componentDetails) ||
1339 !CRM_Utils_Array
::value('contact_id', $componentDetails)
1341 return $updateResult;
1344 //now we are ready w/ required ids, start processing.
1346 $baseIPN = new CRM_Core_Payment_BaseIPN();
1348 $input = $ids = $objects = array();
1350 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1351 $ids['contribution'] = $contributionId;
1352 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1353 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1354 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1355 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1356 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1357 $ids['contributionRecur'] = NULL;
1358 $ids['contributionPage'] = NULL;
1360 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1361 CRM_Core_Error
::fatal();
1364 $memberships = &$objects['membership'];
1365 $participant = &$objects['participant'];
1366 $pledgePayment = &$objects['pledge_payment'];
1367 $contribution = &$objects['contribution'];
1369 if ($pledgePayment) {
1370 $pledgePaymentIDs = array();
1371 foreach ($pledgePayment as $key => $object) {
1372 $pledgePaymentIDs[] = $object->id
;
1374 $pledgeID = $pledgePayment[0]->pledge_id
;
1377 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1380 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1381 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1386 // we might want to process contribution object.
1387 $processContribution = FALSE;
1388 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1389 if (is_array($memberships)) {
1390 foreach ($memberships as $membership) {
1392 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1393 $membership->save();
1395 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1396 if ($processContributionObject) {
1397 $processContribution = TRUE;
1404 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1405 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1407 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1408 if ($processContributionObject) {
1409 $processContribution = TRUE;
1413 if ($pledgePayment) {
1414 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1416 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1417 if ($processContributionObject) {
1418 $processContribution = TRUE;
1422 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1423 if (is_array($memberships)) {
1424 foreach ($memberships as $membership) {
1426 $membership->status_id
= array_search('Expired', $membershipStatuses);
1427 $membership->save();
1429 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1430 if ($processContributionObject) {
1431 $processContribution = TRUE;
1437 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1438 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1440 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1441 if ($processContributionObject) {
1442 $processContribution = TRUE;
1446 if ($pledgePayment) {
1447 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1449 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1450 if ($processContributionObject) {
1451 $processContribution = TRUE;
1455 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1457 // only pending contribution related object processed.
1458 if ($previousContriStatusId &&
1459 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1461 // this is case when we already processed contribution object.
1462 return $updateResult;
1464 elseif (!$previousContriStatusId &&
1465 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1467 // this is case when we are going to process contribution object later.
1468 return $updateResult;
1471 if (is_array($memberships)) {
1472 foreach ($memberships as $membership) {
1477 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1478 $membership->membership_type_id
,
1479 $membership->is_test
, $membership->id
1482 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1483 // this picks up membership type changes during renewals
1485 SELECT membership_type_id
1486 FROM civicrm_membership_log
1487 WHERE membership_id=$membership->id
1490 $dao = new CRM_Core_DAO
;
1492 if ($dao->fetch()) {
1493 if (!empty($dao->membership_type_id
)) {
1494 $membership->membership_type_id
= $dao->membership_type_id
;
1495 $membership->save();
1498 // else fall back to using current membership type
1501 // Figure out number of terms
1503 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1504 foreach ($lineitems as $lineitem) {
1505 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1506 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1508 // in case membership_num_terms comes through as null or zero
1509 $numterms = $numterms >= 1 ?
$numterms : 1;
1514 if ($currentMembership) {
1515 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1516 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1517 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1520 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, null, null, null, $numterms);
1523 //get the status for membership.
1524 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1526 $dates['join_date'],
1531 $formatedParams = array(
1532 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1533 array_search('Current', $membershipStatuses)
1535 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1536 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1537 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1540 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formatedParams);
1542 $membership->copyValues($formatedParams);
1543 $membership->save();
1545 //updating the membership log
1546 $membershipLog = array();
1547 $membershipLog = $formatedParams;
1548 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1549 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formatedParams['start_date'];
1551 $membershipLog['start_date'] = $logStartDate;
1552 $membershipLog['membership_id'] = $membership->id
;
1553 $membershipLog['modified_id'] = $membership->contact_id
;
1554 $membershipLog['modified_date'] = date('Ymd');
1555 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1557 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1559 //update related Memberships.
1560 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formatedParams);
1562 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1565 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1566 if ($processContributionObject) {
1567 $processContribution = TRUE;
1570 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1576 $updatedStatusId = array_search('Registered', $participantStatuses);
1577 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1579 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1580 if ($processContributionObject) {
1581 $processContribution = TRUE;
1585 if ($pledgePayment) {
1586 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1588 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1589 if ($processContributionObject) {
1590 $processContribution = TRUE;
1595 // process contribution object.
1596 if ($processContribution) {
1597 $contributionParams = array();
1599 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1600 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1601 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1603 foreach ($fields as $field) {
1604 if (!CRM_Utils_Array
::value($field, $params)) {
1607 $contributionParams[$field] = $params[$field];
1610 $ids = array('contribution' => $contributionId);
1611 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1614 return $updateResult;
1618 * This function returns all contribution related object ids.
1620 function getComponentDetails($contributionId) {
1621 $componentDetails = $pledgePayment = array();
1622 if (!$contributionId) {
1623 return $componentDetails;
1627 SELECT c.id as contribution_id,
1628 c.contact_id as contact_id,
1629 mp.membership_id as membership_id,
1630 m.membership_type_id as membership_type_id,
1631 pp.participant_id as participant_id,
1632 p.event_id as event_id,
1633 pgp.id as pledge_payment_id
1634 FROM civicrm_contribution c
1635 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1636 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1637 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1638 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1639 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1640 WHERE c.id = $contributionId";
1642 $dao = CRM_Core_DAO
::executeQuery($query);
1643 $componentDetails = array();
1645 while ($dao->fetch()) {
1646 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1647 $componentDetails['contact_id'] = $dao->contact_id
;
1648 if ($dao->event_id
) {
1649 $componentDetails['event'] = $dao->event_id
;
1651 if ($dao->participant_id
) {
1652 $componentDetails['participant'] = $dao->participant_id
;
1654 if ($dao->membership_id
) {
1655 if (!isset($componentDetails['membership'])) {
1656 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1658 $componentDetails['membership'][] = $dao->membership_id
;
1659 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1661 if ($dao->pledge_payment_id
) {
1662 $pledgePayment[] = $dao->pledge_payment_id
;
1666 if ($pledgePayment) {
1667 $componentDetails['pledge_payment'] = $pledgePayment;
1670 return $componentDetails;
1673 static function contributionCount($contactId, $includeSoftCredit = TRUE, $includeHonoree = TRUE) {
1678 $fromClause = "civicrm_contribution contribution";
1679 $whereConditions = array("contribution.contact_id = {$contactId}");
1680 if ($includeSoftCredit) {
1681 $fromClause .= " LEFT JOIN civicrm_contribution_soft softContribution
1682 ON ( contribution.id = softContribution.contribution_id )";
1683 $whereConditions[] = " softContribution.contact_id = {$contactId}";
1685 if ($includeHonoree) {
1686 $whereConditions[] = " contribution.honor_contact_id = {$contactId}";
1688 $whereClause = " contribution.is_test = 0 AND ( " . implode(' OR ', $whereConditions) . " )";
1691 SELECT count( contribution.id ) count
1693 WHERE {$whereClause}";
1695 return CRM_Core_DAO
::singleValueQuery($query);
1699 * Function to get individual id for onbehalf contribution
1701 * @param int $contributionId contribution id
1702 * @param int $contributorId contributer id
1704 * @return array $ids containing organization id and individual id
1707 function getOnbehalfIds($contributionId, $contributorId = NULL) {
1711 if (!$contributionId) {
1715 // fetch contributor id if null
1716 if (!$contributorId) {
1717 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1718 $contributionId, 'contact_id'
1722 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1723 $activityTypeId = array_search('Contribution', $activityTypeIds);
1725 if ($activityTypeId && $contributorId) {
1727 SELECT civicrm_activity_contact.contact_id
1728 FROM civicrm_activity_contact
1729 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1730 WHERE civicrm_activity.activity_type_id = %1
1731 AND civicrm_activity.source_record_id = %2
1732 AND civicrm_activity_contact.record_type_id = %3
1735 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
1736 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1739 1 => array($activityTypeId, 'Integer'),
1740 2 => array($contributionId, 'Integer'),
1741 3 => array($sourceID, 'Integer'),
1744 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1746 // for on behalf contribution source is individual and contributor is organization
1747 if ($sourceContactId && $sourceContactId != $contributorId) {
1748 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1749 // get rel type id for employee of relation
1750 foreach ($relationshipTypeIds as $id => $typeVals) {
1751 if ($typeVals['name_a_b'] == 'Employee of') {
1752 $relationshipTypeId = $id;
1757 $rel = new CRM_Contact_DAO_Relationship();
1758 $rel->relationship_type_id
= $relationshipTypeId;
1759 $rel->contact_id_a
= $sourceContactId;
1760 $rel->contact_id_b
= $contributorId;
1761 if ($rel->find(TRUE)) {
1762 $ids['individual_id'] = $rel->contact_id_a
;
1763 $ids['organization_id'] = $rel->contact_id_b
;
1775 static function getContributionDates() {
1776 $config = CRM_Core_Config
::singleton();
1777 $currentMonth = date('m');
1778 $currentDay = date('d');
1779 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1780 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1781 (int ) $config->fiscalYearStart
['d'] > $currentDay
1784 $year = date('Y') - 1;
1789 $year = array('Y' => $year);
1790 $yearDate = $config->fiscalYearStart
;
1791 $yearDate = array_merge($year, $yearDate);
1792 $yearDate = CRM_Utils_Date
::format($yearDate);
1794 $monthDate = date('Ym') . '01';
1800 'yearDate' => $yearDate,
1801 'monthDate' => $monthDate,
1806 * Load objects relations to contribution object
1807 * Objects are stored in the $_relatedObjects property
1808 * In the first instance we are just moving functionality from BASEIpn -
1809 * see http://issues.civicrm.org/jira/browse/CRM-9996
1811 * @param array $input Input as delivered from Payment Processor
1812 * @param array $ids Ids as Loaded by Payment Processor
1813 * @param boolean $required Is Payment processor / contribution page required
1814 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1815 * Note that the unit test for the BaseIPN class tests this function
1817 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1819 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
1820 if(empty($ids['contact']) && isset($this->contact_id
)){
1821 $ids['contact'] = $this->contact_id
;
1824 if (empty($this->_component
)) {
1825 if (! empty($ids['event'])) {
1826 $this->_component
= 'event';
1829 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1832 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1833 $contributionType = new CRM_Financial_BAO_FinancialType();
1834 $contributionType->id
= $this->financial_type_id
;
1835 if (!$contributionType->find(TRUE)) {
1836 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1838 if (!empty($ids['contact'])) {
1839 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1840 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1841 $this->_relatedObjects
['contact']->find(TRUE);
1843 $this->_relatedObjects
['contributionType'] = $contributionType;
1845 if ($this->_component
== 'contribute') {
1846 // retrieve the other optional objects first so
1847 // stuff down the line can use this info and do things
1849 //in any case get the memberships associated with the contribution
1850 //because we now support multiple memberships w/ price set
1851 // see if there are any other memberships to be considered for same contribution.
1853 SELECT membership_id
1854 FROM civicrm_membership_payment
1855 WHERE contribution_id = %1 ";
1856 $params = array(1 => array($this->id
, 'Integer'));
1858 $dao = CRM_Core_DAO
::executeQuery($query, $params );
1859 while ($dao->fetch()) {
1860 if ($dao->membership_id
) {
1861 if (!is_array($ids['membership'])) {
1862 $ids['membership'] = array();
1864 $ids['membership'][] = $dao->membership_id
;
1868 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1869 foreach ($ids['membership'] as $id) {
1871 $membership = new CRM_Member_BAO_Membership();
1872 $membership->id
= $id;
1873 if (!$membership->find(TRUE)) {
1874 throw new Exception("Could not find membership record: $id");
1876 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
1877 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
1878 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
1879 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
1880 $membership->free();
1885 if (!empty($ids['pledge_payment'])) {
1887 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1888 if (empty($paymentID)) {
1891 $payment = new CRM_Pledge_BAO_PledgePayment();
1892 $payment->id
= $paymentID;
1893 if (!$payment->find(TRUE)) {
1894 throw new Exception("Could not find pledge payment record: " . $paymentID);
1896 $this->_relatedObjects
['pledge_payment'][] = $payment;
1900 if (!empty($ids['contributionRecur'])) {
1901 $recur = new CRM_Contribute_BAO_ContributionRecur();
1902 $recur->id
= $ids['contributionRecur'];
1903 if (!$recur->find(TRUE)) {
1904 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
1906 $this->_relatedObjects
['contributionRecur'] = &$recur;
1907 //get payment processor id from recur object.
1908 $paymentProcessorID = $recur->payment_processor_id
;
1910 //for normal contribution get the payment processor id.
1911 if (!$paymentProcessorID) {
1912 if ($this->contribution_page_id
) {
1913 // get the payment processor id from contribution page
1914 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
1915 $this->contribution_page_id
,
1919 //fail to load payment processor id.
1920 elseif (!CRM_Utils_Array
::value('pledge_payment', $ids)) {
1921 $loadObjectSuccess = TRUE;
1923 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
1925 return $loadObjectSuccess;
1930 // we are in event mode
1931 // make sure event exists and is valid
1932 $event = new CRM_Event_BAO_Event();
1933 $event->id
= $ids['event'];
1934 if ($ids['event'] &&
1937 throw new Exception("Could not find event: " . $ids['event']);
1940 $this->_relatedObjects
['event'] = &$event;
1942 $participant = new CRM_Event_BAO_Participant();
1943 $participant->id
= $ids['participant'];
1944 if ($ids['participant'] &&
1945 !$participant->find(TRUE)
1947 throw new Exception("Could not find participant: " . $ids['participant']);
1949 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
1951 $this->_relatedObjects
['participant'] = &$participant;
1953 if (!$paymentProcessorID) {
1954 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
1958 $loadObjectSuccess = TRUE;
1959 if ($paymentProcessorID) {
1960 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
1961 $this->is_test ?
'test' : 'live'
1963 $ids['paymentProcessor'] = $paymentProcessorID;
1964 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
1966 elseif ($required) {
1967 $loadObjectSuccess = FALSE;
1968 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
1971 return $loadObjectSuccess;
1975 * Create array of message information - ie. return html version, txt version, to field
1977 * @param array $input incoming information
1978 * - is_recur - should this be treated as recurring (not sure why you wouldn't
1979 * just check presence of recur object but maintaining legacy approach
1981 * @param array $ids IDs of related objects
1982 * @param array $values any values that may have already been compiled by calling process
1983 * This is augmented by values 'gathered' by gatherMessageValues
1984 * @param bool $returnMessageText distinguishes between whether to send message or return
1985 * message text. We are working towards this function ALWAYS returning message text & calling
1986 * function doing emails / pdfs with it
1987 * @return array $messageArray - messages
1989 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
1990 if (empty($this->_relatedObjects
)) {
1991 $this->loadRelatedObjects($input, $ids);
1993 if (empty($this->_component
)) {
1994 $this->_component
= CRM_Utils_Array
::value('component', $input);
1997 //not really sure what params might be passed in but lets merge em into values
1998 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
1999 $template = CRM_Core_Smarty
::singleton();
2000 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2001 //what does recur 'mean here - to do with payment processor return functionality but
2002 // what is the importance
2003 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2004 $paymentObject = &CRM_Core_Payment
::singleton(
2005 $this->is_test ?
'test' : 'live',
2006 $this->_relatedObjects
['paymentProcessor']
2009 $entityID = $entity = NULL;
2010 if (isset($ids['contribution'])) {
2011 $entity = 'contribution';
2012 $entityID = $ids['contribution'];
2014 if (isset($ids['membership']) && $ids['membership']) {
2015 $entity = 'membership';
2016 $entityID = $ids['membership'];
2019 $url = $paymentObject->subscriptionURL($entityID, $entity);
2020 $template->assign('cancelSubscriptionUrl', $url);
2022 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2023 $template->assign('updateSubscriptionBillingUrl', $url);
2025 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2026 $template->assign('updateSubscriptionUrl', $url);
2028 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2029 //direct mode showing billing block, so use directIPN for temporary
2030 $template->assign('contributeMode', 'directIPN');
2033 // todo remove strtolower - check consistency
2034 if (strtolower($this->_component
) == 'event') {
2035 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2036 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2040 $values['contribution_id'] = $this->id
;
2041 if (CRM_Utils_Array
::value('related_contact', $ids)) {
2042 $values['related_contact'] = $ids['related_contact'];
2043 if (isset($ids['onbehalf_dupe_alert'])) {
2044 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2046 $entityBlock = array(
2047 'contact_id' => $ids['contact'],
2048 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2049 'Home', 'id', 'name'
2052 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2053 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2056 if ($this->is_test
) {
2059 if (!empty($this->_relatedObjects
['membership'])) {
2060 foreach ($this->_relatedObjects
['membership'] as $membership) {
2061 if ($membership->id
) {
2062 $values['membership_id'] = $membership->id
;
2064 // need to set the membership values here
2065 $template->assign('membership_assign', 1);
2066 $template->assign('membership_name',
2067 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2069 $template->assign('mem_start_date', $membership->start_date
);
2070 $template->assign('mem_join_date', $membership->join_date
);
2071 $template->assign('mem_end_date', $membership->end_date
);
2072 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2073 $template->assign('mem_status', $membership_status);
2074 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2075 $template->assign('is_pay_later', 1);
2078 // if separate payment there are two contributions recorded and the
2079 // admin will need to send a receipt for each of them separately.
2080 // we dont link the two in the db (but can potentially infer it if needed)
2081 $template->assign('is_separate_payment', 0);
2083 if ($recur && $paymentObject) {
2084 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2085 $template->assign('cancelSubscriptionUrl', $url);
2086 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2087 $template->assign('updateSubscriptionBillingUrl', $url);
2088 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2089 $template->assign('updateSubscriptionUrl', $url);
2092 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2095 // otherwise if its about sending emails, continue sending without return, as we
2096 // don't want to exit the loop.
2101 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2107 * Gather values for contribution mail - this function has been created
2108 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2109 * Values related to the contribution in question are gathered
2111 * @param array $input input into function (probably from payment processor)
2112 * @param array $ids the set of ids related to the inpurt
2114 * @return array $values
2116 * NB don't add direct calls to the function as we intend to change the signature
2118 function _gatherMessageValues($input, &$values, $ids = array()) {
2119 // set display address of contributor
2120 if ($this->address_id
) {
2121 $addressParams = array('id' => $this->address_id
);
2122 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2123 $addressDetails = array_values($addressDetails);
2124 $values['address'] = $addressDetails[0]['display'];
2126 if ($this->_component
== 'contribute') {
2127 if (isset($this->contribution_page_id
)) {
2128 CRM_Contribute_BAO_ContributionPage
::setValues(
2129 $this->contribution_page_id
,
2132 if ($this->contribution_page_id
) {
2133 // CRM-8254 - override default currency if applicable
2134 $config = CRM_Core_Config
::singleton();
2135 $config->defaultCurrency
= CRM_Utils_Array
::value(
2138 $config->defaultCurrency
2142 // no contribution page -probably back office
2144 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2145 $values['is_email_receipt'] = 1;
2146 $values['title'] = 'Contribution';
2148 // set lineItem for contribution
2150 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2151 if (!empty($lineItem)) {
2152 $itemId = key($lineItem);
2153 foreach ($lineItem as &$eachItem) {
2154 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2155 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2156 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2157 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2160 $values['lineItem'][0] = $lineItem;
2161 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_Field', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2165 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2169 // if this is onbehalf of contribution then set related contact
2170 if (CRM_Utils_Array
::value('individual_id', $relatedContact)) {
2171 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2176 $eventParams = array(
2177 'id' => $this->_relatedObjects
['event']->id
,
2179 $values['event'] = array();
2181 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2183 //get location details
2184 $locationParams = array(
2185 'entity_id' => $this->_relatedObjects
['event']->id
,
2186 'entity_table' => 'civicrm_event',
2188 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2190 $ufJoinParams = array(
2191 'entity_table' => 'civicrm_event',
2192 'entity_id' => $ids['event'],
2193 'module' => 'CiviEvent',
2196 list($custom_pre_id,
2198 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2200 $values['custom_pre_id'] = $custom_pre_id;
2201 $values['custom_post_id'] = $custom_post_ids;
2203 // set lineItem for event contribution
2205 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2206 if (!empty($participantIds)) {
2207 foreach ($participantIds as $pIDs) {
2208 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2209 if (!CRM_Utils_System
::isNull($lineItem)) {
2210 $values['lineItem'][] = $lineItem;
2221 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2222 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2223 * Note we send directly from this function in some cases because it is only partly refactored
2224 * Don't call this function directly as the signature will change
2226 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2227 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2228 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2229 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2230 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2231 $template->assign('useForMember', true);
2233 //assign honor infomation to receiptmessage
2234 $honorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2238 if (!empty($honorID)) {
2240 $honorDefault = $honorIds = array();
2241 $honorIds['contribution'] = $this->id
;
2242 $idParams = array('id' => $honorID, 'contact_id' => $honorID);
2243 CRM_Contact_BAO_Contact
::retrieve($idParams, $honorDefault, $honorIds);
2244 $honorType = CRM_Core_PseudoConstant
::honor();
2246 $template->assign('honor_block_is_active', 1);
2247 if (CRM_Utils_Array
::value('prefix_id', $honorDefault)) {
2248 $prefix = CRM_Core_PseudoConstant
::individualPrefix();
2249 $template->assign('honor_prefix', $prefix[$honorDefault['prefix_id']]);
2251 $template->assign('honor_first_name', CRM_Utils_Array
::value('first_name', $honorDefault));
2252 $template->assign('honor_last_name', CRM_Utils_Array
::value('last_name', $honorDefault));
2253 $template->assign('honor_email', CRM_Utils_Array
::value('email', $honorDefault['email'][1]));
2254 $template->assign('honor_type', $honorType[$this->honor_type_id
]);
2257 $dao = new CRM_Contribute_DAO_ContributionProduct();
2258 $dao->contribution_id
= $this->id
;
2259 if ($dao->find(TRUE)) {
2260 $premiumId = $dao->product_id
;
2261 $template->assign('option', $dao->product_option
);
2263 $productDAO = new CRM_Contribute_DAO_Product();
2264 $productDAO->id
= $premiumId;
2265 $productDAO->find(TRUE);
2266 $template->assign('selectPremium', TRUE);
2267 $template->assign('product_name', $productDAO->name
);
2268 $template->assign('price', $productDAO->price
);
2269 $template->assign('sku', $productDAO->sku
);
2271 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2272 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2273 if(empty($amount) && isset($this->total_amount
)){
2274 $amount = $this->total_amount
;
2276 $template->assign('amount', $amount);
2277 // add the new contribution values
2278 if (strtolower($this->_component
) == 'contribute') {
2280 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2281 $softDAO->contribution_id
= $this->id
;
2282 if ($softDAO->find(TRUE)) {
2283 $template->assign('pcpBlock', TRUE);
2284 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2285 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2286 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2288 //assign the pcp page title for email subject
2289 $pcpDAO = new CRM_PCP_DAO_PCP();
2290 $pcpDAO->id
= $softDAO->pcp_id
;
2291 if ($pcpDAO->find(TRUE)) {
2292 $template->assign('title', $pcpDAO->title
);
2297 if ($this->financial_type_id
) {
2298 $values['financial_type_id'] = $this->financial_type_id
;
2302 $template->assign('trxn_id', $this->trxn_id
);
2303 $template->assign('receive_date',
2304 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2306 $template->assign('contributeMode', 'notify');
2307 $template->assign('action', $this->is_test ?
1024 : 1);
2308 $template->assign('receipt_text',
2309 CRM_Utils_Array
::value('receipt_text',
2313 $template->assign('is_monetary', 1);
2314 $template->assign('is_recur', (bool) $recur);
2315 $template->assign('currency', $this->currency
);
2316 $template->assign('address', CRM_Utils_Address
::format($input));
2317 if ($this->_component
== 'event') {
2318 $template->assign('title', $values['event']['title']);
2319 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2320 $viewRoles = array();
2321 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2322 $viewRoles[] = $participantRoles[$v];
2324 $values['event']['participant_role'] = implode(', ', $viewRoles);
2325 $template->assign('event', $values['event']);
2326 $template->assign('location', $values['location']);
2327 $template->assign('customPre', $values['custom_pre_id']);
2328 $template->assign('customPost', $values['custom_post_id']);
2331 if ($this->_relatedObjects
['participant']->is_test
) {
2335 $values['params'] = array();
2336 //to get email of primary participant.
2337 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2338 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2339 //build an array of cId/pId of participants
2340 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2341 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2342 //send receipt to additional participant if exists
2343 if (count($additionalIDs)) {
2344 $template->assign('isPrimary', 0);
2345 $template->assign('customProfile', NULL);
2346 //set additionalParticipant true
2347 $values['params']['additionalParticipant'] = TRUE;
2348 foreach ($additionalIDs as $pId => $cId) {
2350 //to change the status pending to completed
2351 $additional = new CRM_Event_DAO_Participant();
2352 $additional->id
= $pId;
2353 $additional->contact_id
= $cId;
2354 $additional->find(TRUE);
2355 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2356 $additional->status_id
= 1;
2357 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2358 //if additional participant dont have email
2360 if (!$additionalParticipantInfo) {
2361 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2363 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2364 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2365 $additional->save();
2366 $additional->free();
2367 $template->assign('amount', $amount);
2368 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2372 //build an array of custom profile and assigning it to template
2373 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2375 if (count($customProfile)) {
2376 $template->assign('customProfile', $customProfile);
2379 // for primary contact
2380 $values['params']['additionalParticipant'] = FALSE;
2381 $template->assign('isPrimary', 1);
2382 $template->assign('amount', $primaryAmount);
2383 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2384 if ($this->payment_instrument_id
) {
2385 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2386 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2388 // carry paylater, since we did not created billing,
2389 // so need to pull email from primary location, CRM-4395
2390 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2396 * Function to check whether payment processor supports
2397 * cancellation of contribution subscription
2399 * @param int $contributionId contribution id
2405 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2406 $cacheKeyString = "$contributionId";
2407 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2409 static $supportsCancel = array();
2411 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2412 $supportsCancel[$cacheKeyString] = FALSE;
2413 $isCancelled = FALSE;
2415 if ($isNotCancelled) {
2416 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2419 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2420 if (!empty($paymentObject)) {
2421 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2424 return $supportsCancel[$cacheKeyString];
2428 * Function to check whether subscription is already cancelled
2430 * @param int $contributionId contribution id
2432 * @return string $status contribution status
2436 static function isSubscriptionCancelled($contributionId) {
2438 SELECT cr.contribution_status_id
2439 FROM civicrm_contribution_recur cr
2440 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2441 WHERE con.id = %1 LIMIT 1";
2442 $params = array(1 => array($contributionId, 'Integer'));
2443 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2444 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2445 if ($status == 'Cancelled') {
2452 * Function to create all financial accounts entry
2454 * @param array $params contribution object, line item array and params for trxn
2456 * @param array $ids of contribution id
2461 static function recordFinancialAccounts(&$params, $ids) {
2462 $skipRecords = $update = FALSE;
2463 $additionalParticipantId = array();
2464 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2466 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2467 $entityId = $params['participant_id'];
2468 $entityTable = 'civicrm_participant';
2469 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2472 $entityId = $params['contribution']->id
;
2473 $entityTable = 'civicrm_contribution';
2475 $entityID[] = $entityId;
2476 if (!empty($additionalParticipantId)) {
2477 $entityID +
= $additionalParticipantId;
2479 if (!CRM_Utils_Array
::value('prevContribution', $params)) {
2482 // build line item array if its not set in $params
2483 if (!CRM_Utils_Array
::value('line_item', $params) ||
$additionalParticipantId) {
2484 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
2487 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2488 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2489 $skipRecords = TRUE;
2490 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses)) {
2491 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2492 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2494 elseif (CRM_Utils_Array
::value('payment_processor', $params)) {
2495 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2497 elseif (CRM_Utils_Array
::value('payment_instrument_id', $params)) {
2498 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2501 $params['to_financial_account_id'] = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1");
2504 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2505 if (!isset($totalAmount) && CRM_Utils_Array
::value('prevContribution', $params)) {
2506 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2508 //build financial transaction params
2509 $trxnParams = array(
2510 'contribution_id' => $params['contribution']->id
,
2511 'to_financial_account_id' => $params['to_financial_account_id'],
2512 'trxn_date' => date('YmdHis'),
2513 'total_amount' => $totalAmount,
2514 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2515 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2516 'currency' => $params['contribution']->currency
,
2517 'trxn_id' => $params['contribution']->trxn_id
,
2518 'status_id' => $params['contribution']->contribution_status_id
,
2519 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params),
2520 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2523 if (CRM_Utils_Array
::value('payment_processor', $params)) {
2524 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2526 $params['trxnParams'] = $trxnParams;
2528 if (CRM_Utils_Array
::value('prevContribution', $params)) {
2530 //if Change contribution amount
2531 if (array_key_exists('total_amount', $params) && isset($params['total_amount']) &&
2532 $params['total_amount'] != $params['prevContribution']->total_amount
) {
2533 //Update Financial Records
2534 self
::updateFinancialAccounts($params, 'changedAmount');
2537 //Update contribution status
2538 if (CRM_Utils_Array
::value('contribution_status_id', $params) &&
2539 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2540 //Update Financial Records
2541 self
::updateFinancialAccounts($params, 'changedStatus');
2544 // change Payment Instrument for a Completed contribution
2545 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2546 // instrument is null and now new payment instrument is added along with the payment
2547 if (array_key_exists('payment_instrument_id', $params)) {
2548 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2549 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2550 //check if status is changed from Pending to Completed
2551 // do not update payment instrument changes for Pending to Completed
2552 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2553 $params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses))) {
2554 // for all other statuses create new financial records
2555 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2558 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2559 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2560 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2561 // for any other payment instrument changes create new financial records
2562 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2564 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2565 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2566 // another special case when check number is changed, create new financial records
2567 // create financial trxn with negative amount
2568 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2569 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2570 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2571 // create financial trxn with positive amount
2572 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2573 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2574 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2578 //if financial type is changed
2579 if (CRM_Utils_Array
::value('financial_type_id', $params) &&
2580 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2581 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2582 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2583 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2584 if ($oldFinancialAccount != $newFinancialAccount) {
2585 $params['total_amount'] = 0;
2586 if ($params['contribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)) {
2587 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2588 $params['prevContribution']->financial_type_id
, $relationTypeId);
2590 self
::updateFinancialAccounts($params, 'changeFinancialType');
2591 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2592 $params['financial_account_id'] = $newFinancialAccount;
2593 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2594 self
::updateFinancialAccounts($params);
2601 //records finanical trxn and entity financial trxn
2602 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2603 $params['entity_id'] = $financialTxn->id
;
2606 // record line items and finacial items
2608 if (!CRM_Utils_Array
::value('skipLineItem', $params)) {
2609 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2612 // create batch entry if batch_id is passed
2613 if (CRM_Utils_Array
::value('batch_id', $params)) {
2614 $entityParams = array(
2615 'batch_id' => $params['batch_id'],
2616 'entity_table' => 'civicrm_financial_trxn',
2617 'entity_id' => $financialTxn->id
,
2619 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2622 // when a fee is charged
2623 if (CRM_Utils_Array
::value('fee_amount', $params) && (!CRM_Utils_Array
::value('prevContribution', $params)
2624 ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2625 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2628 if (CRM_Utils_Array
::value('prevContribution', $params) && $entityTable == 'civicrm_participant'
2629 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2630 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2631 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2632 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2634 unset($params['line_item']);
2638 * Function to update all financial accounts entry
2640 * @param array $params contribution object, line item array and params for trxn
2642 * @param string $context update scenarios
2647 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2648 $itemAmount = $trxnID = NULL;
2649 //get all the statuses
2650 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2651 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus) &&
2652 $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2653 && $context == 'changePaymentInstrument') {
2656 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2657 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2659 if ($context == 'changedStatus') {
2660 //get all the statuses
2661 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2663 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2664 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2665 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2667 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2669 elseif ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
2670 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2671 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2672 $params['trxnParams']['to_financial_account_id'] = NULL;
2673 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2675 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL,
2676 " AND v.name LIKE 'Accounts Receivable Account is' "));
2677 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2678 $financialTypeID, $relationTypeId);
2680 $itemAmount = $params['trxnParams']['total_amount'];
2682 elseif ($context == 'changePaymentInstrument') {
2683 if ($params['prevContribution']->payment_instrument_id
!= null
2684 && $params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2685 && $params['contribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
2686 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2687 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2689 elseif ($params['prevContribution']->payment_instrument_id
!= null) {
2690 $params['trxnParams']['from_financial_account_id'] =
2691 CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount(
2692 $params['prevContribution']->payment_instrument_id
);
2695 $params['trxnParams']['from_financial_account_id'] = CRM_Core_DAO
::singleValueQuery(
2696 "SELECT id FROM civicrm_financial_account WHERE is_default = 1");
2700 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2701 $params['entity_id'] = $trxn->id
;
2703 if ($context == 'changedStatus') {
2704 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) &&
2705 ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2706 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2707 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2709 $entityParams = array(
2710 'entity_table' => 'civicrm_financial_item',
2711 'financial_trxn_id' => $trxn->id
,
2713 foreach ($params['line_item'] as $fieldId => $fields) {
2714 foreach ($fields as $fieldValueId => $fieldValues) {
2716 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2717 2 => array($fieldValues['id'], 'Integer'),
2719 CRM_Core_DAO
::executeQuery($query, $fparams);
2721 1 => array($fieldValues['id'], 'Integer'),
2723 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2724 while ($financialItem->fetch()) {
2725 $entityParams['entity_id'] = $financialItem->id
;
2726 $entityParams['amount'] = $financialItem->amount
;
2727 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2734 if ($context != 'changePaymentInstrument') {
2735 $itemParams['entity_table'] = 'civicrm_line_item';
2736 $trxnIds['id'] = $params['entity_id'];
2737 foreach ($params['line_item'] as $fieldId => $fields) {
2738 foreach ($fields as $fieldValueId => $fieldValues) {
2739 $prevParams['entity_id'] = $fieldValues['id'];
2740 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2742 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2743 if ($params['contribution']->receive_date
) {
2744 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2747 $financialAccount = $prevfinancialItem->financial_account_id
;
2748 if (CRM_Utils_Array
::value('financial_account_id', $params)) {
2749 $financialAccount = $params['financial_account_id'];
2752 $currency = $params['prevContribution']->currency
;
2753 if ($params['contribution']->currency
) {
2754 $currency = $params['contribution']->currency
;
2756 if (CRM_Utils_Array
::value('is_quick_config', $params)) {
2757 $amount = $itemAmount;
2759 $amount = $params['total_amount'];
2764 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2767 $amount = $diff * $fieldValues['line_total'];
2770 $itemParams = array(
2771 'transaction_date' => $receiveDate,
2772 'contact_id' => $params['prevContribution']->contact_id
,
2773 'currency' => $currency,
2774 'amount' => $amount,
2775 'description' => $prevfinancialItem->description
,
2776 'status_id' => $prevfinancialItem->status_id
,
2777 'financial_account_id' => $financialAccount,
2778 'entity_table' => 'civicrm_line_item',
2779 'entity_id' => $fieldValues['id']
2781 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
2788 * Function to check status validation on update of a contribution
2790 * @param array $values previous form values before submit
2792 * @param array $fields the input form values
2794 * @param array $errors list of errors
2799 static function checkStatusValidation($values, &$fields, &$errors) {
2800 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2801 $checkStatus = array(
2802 'Cancelled' => array('Completed', 'Refunded'),
2803 'Completed' => array('Cancelled', 'Refunded'),
2804 'Pending' => array('Cancelled', 'Completed', 'Failed'),
2805 'Refunded' => array('Cancelled', 'Completed')
2808 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
2809 $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']]));
2814 * Function to delete contribution of contact
2818 * @param integer $contactId contact id
2823 static function deleteContactContribution($contactId) {
2824 $contribution = new CRM_Contribute_DAO_Contribution();
2825 $contribution->contact_id
= $contactId;
2826 $contribution->find();
2827 while ($contribution->fetch()) {
2828 self
::deleteContribution($contribution->id
);