Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2013-12-09-17-00-10
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35 class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
36
37 /**
38 * static field for all the contribution information that we can potentially import
39 *
40 * @var array
41 * @static
42 */
43 static $_importableFields = NULL;
44
45 /**
46 * static field for all the contribution information that we can potentially export
47 *
48 * @var array
49 * @static
50 */
51 static $_exportableFields = NULL;
52
53 /**
54 * field for all the objects related to this contribution
55 * @var array of objects (e.g membership object, participant object)
56 */
57 public $_relatedObjects = array();
58
59 /**
60 * field for the component - either 'event' (participant) or 'contribute'
61 * (any item related to a contribution page e.g. membership, pledge, contribution)
62 * This is used for composing messages because they have dependency on the
63 * contribution_page or event page - although over time we may eliminate that
64 *
65 * @var string component or event
66 */
67 public $_component = NULL;
68
69 /*
70 * construct method
71 */
72 function __construct() {
73 parent::__construct();
74 }
75
76 /**
77 * takes an associative array and creates a contribution object
78 *
79 * the function extract all the params it needs to initialize the create a
80 * contribution object. the params array could contain additional unused name/value
81 * pairs
82 *
83 * @param array $params (reference ) an assoc array of name/value pairs
84 * @param array $ids the array that holds all the db ids
85 *
86 * @return object CRM_Contribute_BAO_Contribution object
87 * @access public
88 * @static
89 */
90 static function add(&$params, $ids = array()) {
91 if (empty($params)) {
92 return;
93 }
94 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
95 $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params));
96
97 $duplicates = array();
98 if (self::checkDuplicate($params, $duplicates, $contributionID)) {
99 $error = CRM_Core_Error::singleton();
100 $d = implode(', ', $duplicates);
101 $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION,
102 'Fatal',
103 array($d),
104 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
105 );
106 return $error;
107 }
108
109 // first clean up all the money fields
110 $moneyFields = array(
111 'total_amount',
112 'net_amount',
113 'fee_amount',
114 'non_deductible_amount',
115 );
116
117 //if priceset is used, no need to cleanup money
118 if (CRM_Utils_Array::value('skipCleanMoney', $params)) {
119 unset($moneyFields[0]);
120 }
121
122 foreach ($moneyFields as $field) {
123 if (isset($params[$field])) {
124 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
125 }
126 }
127
128 // CRM-13420, set payment instrument to default if payment_instrument_id is empty
129 if (!$contributionID && !CRM_Utils_Array::value('payment_instrument_id', $params)) {
130 $params['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument',
131 FALSE, FALSE, FALSE, 'AND is_default = 1'));
132 }
133
134 if (CRM_Utils_Array::value('payment_instrument_id', $params)) {
135 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
136 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
137 $params['check_number'] = 'null';
138 }
139 }
140
141 // contribution status is missing, choose Completed as default status
142 // do this for create mode only
143 if (!CRM_Utils_Array::value('contribution', $ids) && !CRM_Utils_Array::value('contribution_status_id', $params)) {
144 $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
145 }
146
147 if ($contributionID) {
148 CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params);
149 }
150 else {
151 CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params);
152 }
153
154 $contribution = new CRM_Contribute_BAO_Contribution();
155 $contribution->copyValues($params);
156
157 $contribution->id = $contributionID;
158
159 if (!CRM_Utils_Rule::currencyCode($contribution->currency)) {
160 $config = CRM_Core_Config::singleton();
161 $contribution->currency = $config->defaultCurrency;
162 }
163
164 if ($contributionID) {
165 $params['prevContribution'] = self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
166 }
167
168 $result = $contribution->save();
169
170 // Add financial_trxn details as part of fix for CRM-4724
171 $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params);
172 $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params);
173
174 //add Account details
175 $params['contribution'] = $contribution;
176 self::recordFinancialAccounts($params, $ids);
177
178 // reset the group contact cache for this group
179 CRM_Contact_BAO_GroupContactCache::remove();
180
181 if ($contributionID) {
182 CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution);
183 }
184 else {
185 CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution);
186 }
187
188 return $result;
189 }
190
191 /**
192 * Given the list of params in the params array, fetch the object
193 * and store the values in the values array
194 *
195 * @param array $params input parameters to find object
196 * @param array $values output values of the object
197 * @param array $ids the array that holds all the db ids
198 *
199 * @return CRM_Contribute_BAO_Contribution|null the found object or null
200 * @access public
201 * @static
202 */
203 static function &getValues($params, &$values, &$ids) {
204 if (empty($params)) {
205 return NULL;
206 }
207 $contribution = new CRM_Contribute_BAO_Contribution();
208
209 $contribution->copyValues($params);
210
211 if ($contribution->find(TRUE)) {
212 $ids['contribution'] = $contribution->id;
213
214 CRM_Core_DAO::storeValues($contribution, $values);
215
216 return $contribution;
217 }
218 return NULL;
219 }
220
221 /**
222 * takes an associative array and creates a contribution object
223 *
224 * @param array $params (reference ) an assoc array of name/value pairs
225 * @param array $ids the array that holds all the db ids
226 *
227 * @return object CRM_Contribute_BAO_Contribution object
228 * @access public
229 * @static
230 */
231 static function &create(&$params, $ids = array()) {
232 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
233 foreach ($dateFields as $df) {
234 if (isset($params[$df])) {
235 $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
236 }
237 }
238
239 $transaction = new CRM_Core_Transaction();
240
241 $contribution = self::add($params, $ids);
242
243 if (is_a($contribution, 'CRM_Core_Error')) {
244 $transaction->rollback();
245 return $contribution;
246 }
247
248 $params['contribution_id'] = $contribution->id;
249
250 if (CRM_Utils_Array::value('custom', $params) &&
251 is_array($params['custom'])
252 ) {
253 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
254 }
255
256 $session = CRM_Core_Session::singleton();
257
258 if (CRM_Utils_Array::value('note', $params)) {
259 $noteParams = array(
260 'entity_table' => 'civicrm_contribution',
261 'note' => $params['note'],
262 'entity_id' => $contribution->id,
263 'contact_id' => $session->get('userID'),
264 'modified_date' => date('Ymd'),
265 );
266 if (!$noteParams['contact_id']) {
267 $noteParams['contact_id'] = $params['contact_id'];
268 }
269 CRM_Core_BAO_Note::add($noteParams);
270 }
271
272 // make entry in batch entity batch table
273 if (CRM_Utils_Array::value('batch_id', $params)) {
274 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
275 $titleFields = array(
276 'contact_id',
277 'total_amount',
278 'currency',
279 'financial_type_id',
280 );
281 $retrieveRequired = 0;
282 foreach ($titleFields as $titleField) {
283 if(!isset($contribution->$titleField)){
284 $retrieveRequired = 1;
285 break;
286 }
287 }
288 if ($retrieveRequired == 1) {
289 $contribution->find(TRUE);
290 }
291 }
292
293 // check if activity record exist for this contribution, if
294 // not add activity
295 $activity = new CRM_Activity_DAO_Activity();
296 $activity->source_record_id = $contribution->id;
297 $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
298 'Contribution',
299 'name'
300 );
301 if (!$activity->find(TRUE)) {
302 CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
303 }
304 else {
305 // CRM-13237 : if activity record found, update it with campaign id of contribution
306 CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
307 }
308
309 // Handle soft credit and / or link to personal campaign page
310 list($type, $softIDs) = CRM_Contribute_BAO_ContributionSoft::getSoftCreditType($contribution->id);
311 if ($pcp = CRM_Utils_Array::value('pcp', $params)) {
312 if (!empty($type) && $type == 'soft') {
313 $deleteParams = array('contribution_id' => $contribution->id);
314 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
315 }
316 $softParams = array();
317 $softParams['contribution_id'] = $contribution->id;
318 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
319 $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
320 $pcp['pcp_made_through_id'], 'contact_id'
321 );
322 $softParams['currency'] = $contribution->currency;
323 $softParams['amount'] = $contribution->total_amount;
324 $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
325 $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
326 $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
327 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
328 CRM_Contribute_BAO_ContributionSoft::add($softParams);
329 }
330 elseif (CRM_Utils_Array::value('soft_credit', $params)) {
331 $softParams = $params['soft_credit'];
332
333 if (!empty($softIDs)) {
334 foreach ( $softIDs as $softID) {
335 if (!in_array($softID, $params['soft_credit_ids'])) {
336 $deleteParams = array('id' => $softID);
337 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
338 }
339 }
340 }
341
342 foreach ($softParams as $softParam) {
343 $softParam['contribution_id'] = $contribution->id;
344 $softParam['currency'] = $contribution->currency;
345 $softParam['pcp_id'] = 'null';
346 $softParam['pcp_display_in_roll'] = 'null';
347 $softParam['pcp_roll_nickname'] = 'null';
348 $softParam['pcp_personal_note'] = 'NULL';
349 CRM_Contribute_BAO_ContributionSoft::add($softParam);
350 }
351 }
352
353 $transaction->commit();
354
355 // do not add to recent items for import, CRM-4399
356 if (!CRM_Utils_Array::value('skipRecentView', $params)) {
357 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
358 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
359 );
360 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
361 $titleFields = array(
362 'contact_id',
363 'total_amount',
364 'currency',
365 'financial_type_id',
366 );
367 $retrieveRequired = 0;
368 foreach ($titleFields as $titleField) {
369 if(!isset($contribution->$titleField)){
370 $retrieveRequired = 1;
371 break;
372 }
373 }
374 if($retrieveRequired == 1){
375 $contribution->find(TRUE);
376 }
377 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
378 $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
379
380 $recentOther = array();
381 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
382 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
383 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
384 );
385 }
386
387 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
388 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
389 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
390 );
391 }
392
393 // add the recently created Contribution
394 CRM_Utils_Recent::add($title,
395 $url,
396 $contribution->id,
397 'Contribution',
398 $contribution->contact_id,
399 NULL,
400 $recentOther
401 );
402 }
403
404 return $contribution;
405 }
406
407 /**
408 * Get the values for pseudoconstants for name->value and reverse.
409 *
410 * @param array $defaults (reference) the default values, some of which need to be resolved.
411 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
412 *
413 * @return void
414 * @access public
415 * @static
416 */
417 static function resolveDefaults(&$defaults, $reverse = FALSE) {
418 self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse);
419 self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse);
420 self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(), $reverse);
421 self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse);
422 }
423
424 /**
425 * This function is used to convert associative array names to values
426 * and vice-versa.
427 *
428 * This function is used by both the web form layer and the api. Note that
429 * the api needs the name => value conversion, also the view layer typically
430 * requires value => name conversion
431 */
432 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
433 $id = $property . '_id';
434
435 $src = $reverse ? $property : $id;
436 $dst = $reverse ? $id : $property;
437
438 if (!array_key_exists($src, $defaults)) {
439 return FALSE;
440 }
441
442 $look = $reverse ? array_flip($lookup) : $lookup;
443
444 if (is_array($look)) {
445 if (!array_key_exists($defaults[$src], $look)) {
446 return FALSE;
447 }
448 }
449 $defaults[$dst] = $look[$defaults[$src]];
450 return TRUE;
451 }
452
453 /**
454 * Takes a bunch of params that are needed to match certain criteria and
455 * retrieves the relevant objects. We'll tweak this function to be more
456 * full featured over a period of time. This is the inverse function of
457 * create. It also stores all the retrieved values in the default array
458 *
459 * @param array $params (reference ) an assoc array of name/value pairs
460 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
461 * in a hierarchical manner
462 * @param array $ids (reference) the array that holds all the db ids
463 *
464 * @return object CRM_Contribute_BAO_Contribution object
465 * @access public
466 * @static
467 */
468 static function retrieve(&$params, &$defaults, &$ids) {
469 $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
470 return $contribution;
471 }
472
473 /**
474 * combine all the importable fields from the lower levels object
475 *
476 * The ordering is important, since currently we do not have a weight
477 * scheme. Adding weight is super important and should be done in the
478 * next week or so, before this can be called complete.
479 *
480 * @return array array of importable Fields
481 * @access public
482 * @static
483 */
484 static function &importableFields($contactType = 'Individual', $status = TRUE) {
485 if (!self::$_importableFields) {
486 if (!self::$_importableFields) {
487 self::$_importableFields = array();
488 }
489
490 if (!$status) {
491 $fields = array('' => array('title' => ts('- do not import -')));
492 }
493 else {
494 $fields = array('' => array('title' => ts('- Contribution Fields -')));
495 }
496
497 $note = CRM_Core_DAO_Note::import();
498 $tmpFields = CRM_Contribute_DAO_Contribution::import();
499 unset($tmpFields['option_value']);
500 $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
501 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
502
503 // Using new Dedupe rule.
504 $ruleParams = array(
505 'contact_type' => $contactType,
506 'used' => 'Unsupervised',
507 );
508 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
509 $tmpContactField = array();
510 if (is_array($fieldsArray)) {
511 foreach ($fieldsArray as $value) {
512 //skip if there is no dupe rule
513 if ($value == 'none') {
514 continue;
515 }
516 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
517 $value,
518 'id',
519 'column_name'
520 );
521 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
522 $tmpContactField[trim($value)] = $contactFields[trim($value)];
523 if (!$status) {
524 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
525 }
526 else {
527 $title = $tmpContactField[trim($value)]['title'];
528 }
529 $tmpContactField[trim($value)]['title'] = $title;
530 }
531 }
532
533 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
534 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
535 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
536 $fields = array_merge($fields, $tmpContactField);
537 $fields = array_merge($fields, $tmpFields);
538 $fields = array_merge($fields, $note);
539 $fields = array_merge($fields, $optionFields);
540 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
541 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
542 self::$_importableFields = $fields;
543 }
544 return self::$_importableFields;
545 }
546
547 static function &exportableFields() {
548 if (!self::$_exportableFields) {
549 if (!self::$_exportableFields) {
550 self::$_exportableFields = array();
551 }
552
553 $impFields = CRM_Contribute_DAO_Contribution::export();
554 $expFieldProduct = CRM_Contribute_DAO_Product::export();
555 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct::export();
556 $typeField = CRM_Financial_DAO_FinancialType::export();
557 $financialAccount = CRM_Financial_DAO_FinancialAccount::export();
558 $optionField = CRM_Core_OptionValue::getFields($mode = 'contribute');
559 $contributionStatus = array(
560 'contribution_status' => array(
561 'title' => ts('Contribution Status'),
562 'name' => 'contribution_status',
563 'data_type' => CRM_Utils_Type::T_STRING
564 ));
565
566 $contributionNote = array(
567 'contribution_note' =>
568 array(
569 'title' => ts('Contribution Note'),
570 'name' => 'contribution_note',
571 'data_type' => CRM_Utils_Type::T_TEXT
572 )
573 );
574
575 $contributionRecurId = array(
576 'contribution_recur_id' =>
577 array(
578 'title' => ts('Recurring Contributions ID'),
579 'name' => 'contribution_recur_id',
580 'where' => 'civicrm_contribution.contribution_recur_id',
581 'data_type' => CRM_Utils_Type::T_INT
582 ));
583
584 $extraFields = array(
585 'contribution_campaign' =>
586 array(
587 'title' => ts('Campaign Title')
588 ),
589 'contribution_batch' =>
590 array(
591 'title' => ts('Batch Name')
592 )
593 );
594
595 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
596 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $financialAccount,
597 CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')
598 );
599
600 self::$_exportableFields = $fields;
601 }
602
603 return self::$_exportableFields;
604 }
605
606 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
607 $where = array();
608 switch ($status) {
609 case 'Valid':
610 $where[] = 'contribution_status_id = 1';
611 break;
612
613 case 'Cancelled':
614 $where[] = 'contribution_status_id = 3';
615 break;
616 }
617
618 if ($startDate) {
619 $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
620 }
621 if ($endDate) {
622 $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
623 }
624
625 $whereCond = implode(' AND ', $where);
626
627 $query = "
628 SELECT sum( total_amount ) as total_amount,
629 count( civicrm_contribution.id ) as total_count,
630 currency
631 FROM civicrm_contribution
632 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
633 WHERE $whereCond
634 AND ( is_test = 0 OR is_test IS NULL )
635 AND contact.is_deleted = 0
636 GROUP BY currency
637 ";
638
639 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
640 $amount = array();
641 $count = 0;
642 while ($dao->fetch()) {
643 $count += $dao->total_count;
644 $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
645 }
646 if ($count) {
647 return array('amount' => implode(', ', $amount),
648 'count' => $count,
649 );
650 }
651 return NULL;
652 }
653
654 /**
655 * Delete the indirect records associated with this contribution first
656 *
657 * @return $results no of deleted Contribution on success, false otherwise
658 * @access public
659 * @static
660 */
661 static function deleteContribution($id) {
662 CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray);
663
664 $transaction = new CRM_Core_Transaction();
665
666 $results = NULL;
667 //delete activity record
668 $params = array(
669 'source_record_id' => $id,
670 // activity type id for contribution
671 'activity_type_id' => 6,
672 );
673
674 CRM_Activity_BAO_Activity::deleteActivity($params);
675
676 //delete billing address if exists for this contribution.
677 self::deleteAddress($id);
678
679 //update pledge and pledge payment, CRM-3961
680 CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
681
682 // remove entry from civicrm_price_set_entity, CRM-5095
683 if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
684 CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
685 }
686 // cleanup line items.
687 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
688
689 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
690 CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id);
691
692 if ($participantId) {
693 CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant');
694 }
695 else {
696 CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution');
697 }
698
699 //delete note.
700 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution');
701 $noteId = key($note);
702 if ($noteId) {
703 CRM_Core_BAO_Note::del($noteId, FALSE);
704 }
705
706 $dao = new CRM_Contribute_DAO_Contribution();
707 $dao->id = $id;
708
709 $results = $dao->delete();
710
711 $transaction->commit();
712
713 CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao);
714
715 // delete the recently created Contribution
716 $contributionRecent = array(
717 'id' => $id,
718 'type' => 'Contribution',
719 );
720 CRM_Utils_Recent::del($contributionRecent);
721
722 return $results;
723 }
724
725 /**
726 * Check if there is a contribution with the same trxn_id or invoice_id
727 *
728 * @param array $params (reference ) an assoc array of name/value pairs
729 * @param array $duplicates (reference ) store ids of duplicate contribs
730 *
731 * @return boolean true if duplicate, false otherwise
732 * @access public
733 * static
734 */
735 static function checkDuplicate($input, &$duplicates, $id = NULL) {
736 if (!$id) {
737 $id = CRM_Utils_Array::value('id', $input);
738 }
739 $trxn_id = CRM_Utils_Array::value('trxn_id', $input);
740 $invoice_id = CRM_Utils_Array::value('invoice_id', $input);
741
742 $clause = array();
743 $input = array();
744
745 if ($trxn_id) {
746 $clause[] = "trxn_id = %1";
747 $input[1] = array($trxn_id, 'String');
748 }
749
750 if ($invoice_id) {
751 $clause[] = "invoice_id = %2";
752 $input[2] = array($invoice_id, 'String');
753 }
754
755 if (empty($clause)) {
756 return FALSE;
757 }
758
759 $clause = implode(' OR ', $clause);
760 if ($id) {
761 $clause = "( $clause ) AND id != %3";
762 $input[3] = array($id, 'Integer');
763 }
764
765 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
766 $dao = CRM_Core_DAO::executeQuery($query, $input);
767 $result = FALSE;
768 while ($dao->fetch()) {
769 $duplicates[] = $dao->id;
770 $result = TRUE;
771 }
772 return $result;
773 }
774
775 /**
776 * takes an associative array and creates a contribution_product object
777 *
778 * the function extract all the params it needs to initialize the create a
779 * contribution_product object. the params array could contain additional unused name/value
780 * pairs
781 *
782 * @param array $params (reference ) an assoc array of name/value pairs
783 *
784 * @return object CRM_Contribute_BAO_ContributionProduct object
785 * @access public
786 * @static
787 */
788 static function addPremium(&$params) {
789 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
790 $contributionProduct->copyValues($params);
791 return $contributionProduct->save();
792 }
793
794 /**
795 * Function to get list of contribution fields for profile
796 * For now we only allow custom contribution fields to be in
797 * profile
798 *
799 * @param boolean $addExtraFields true if special fields needs to be added
800 *
801 * @return return the list of contribution fields
802 * @static
803 * @access public
804 */
805 static function getContributionFields($addExtraFields = TRUE) {
806 $contributionFields = CRM_Contribute_DAO_Contribution::export();
807 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
808
809 if ($addExtraFields) {
810 $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields());
811 }
812
813 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export());
814
815 foreach ($contributionFields as $key => $var) {
816 if ($key == 'contribution_contact_id') {
817 continue;
818 }
819 elseif ($key == 'contribution_campaign_id') {
820 $var['title'] = ts('Campaign');
821 }
822 $fields[$key] = $var;
823 }
824
825 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
826 return $fields;
827 }
828
829 /**
830 * Function to add extra fields specific to contribtion
831 *
832 * @static
833 */
834 static function getSpecialContributionFields() {
835 $extraFields = array(
836 'honor_contact_name' => array(
837 'name' => 'honor_contact_name',
838 'title' => 'Honor Contact Name',
839 'headerPattern' => '/^honor_contact_name$/i',
840 'where' => 'civicrm_contact_c.display_name',
841 ),
842 'honor_contact_email' => array(
843 'name' => 'honor_contact_email',
844 'title' => 'Honor Contact Email',
845 'headerPattern' => '/^honor_contact_email$/i',
846 'where' => 'honor_email.email',
847 ),
848 'honor_contact_id' => array(
849 'name' => 'honor_contact_id',
850 'title' => 'Honor Contact ID',
851 'headerPattern' => '/^honor_contact_id$/i',
852 'where' => 'civicrm_contribution.honor_contact_id',
853 ),
854 'honor_type_label' => array(
855 'name' => 'honor_type_label',
856 'title' => 'Honor Type Label',
857 'headerPattern' => '/^honor_type_label$/i',
858 'where' => 'honor_type.label',
859 ),
860 'soft_credit_name' => array(
861 'name' => 'soft_credit_name',
862 'title' => 'Soft Credit Name',
863 'headerPattern' => '/^soft_credit_name$/i',
864 'where' => 'civicrm_contact_d.display_name',
865 ),
866 'soft_credit_email' => array(
867 'name' => 'soft_credit_email',
868 'title' => 'Soft Credit Email',
869 'headerPattern' => '/^soft_credit_email$/i',
870 'where' => 'soft_email.email',
871 ),
872 'soft_credit_phone' => array(
873 'name' => 'soft_credit_phone',
874 'title' => 'Soft Credit Phone',
875 'headerPattern' => '/^soft_credit_phone$/i',
876 'where' => 'soft_phone.phone',
877 ),
878 'soft_credit_contact_id' => array(
879 'name' => 'soft_credit_contact_id',
880 'title' => 'Soft Credit Contact ID',
881 'headerPattern' => '/^soft_credit_contact_id$/i',
882 'where' => 'civicrm_contribution_soft.contact_id',
883 ),
884 );
885
886 return $extraFields;
887 }
888
889 static function getCurrentandGoalAmount($pageID) {
890 $query = "
891 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
892 FROM civicrm_contribution_page p,
893 civicrm_contribution c
894 WHERE p.id = c.contribution_page_id
895 AND p.id = %1
896 AND c.cancel_date is null
897 GROUP BY p.id
898 ";
899
900 $config = CRM_Core_Config::singleton();
901 $params = array(1 => array($pageID, 'Integer'));
902 $dao = CRM_Core_DAO::executeQuery($query, $params);
903
904 if ($dao->fetch()) {
905 return array($dao->goal, $dao->total);
906 }
907 else {
908 return array(NULL, NULL);
909 }
910 }
911
912 /**
913 * Function to create is honor of
914 *
915 * @param array $params associated array of fields (by reference)
916 * @param int $honorId honor Id
917 * @param array $honorParams any params that should be send to the create function
918 *
919 * @return contact id
920 */
921 static function createHonorContact(&$params, $honorId = NULL, $honorParams = array()) {
922 $honorParams = array_merge(
923 array(
924 'first_name' => $params['honor_first_name'],
925 'last_name' => $params['honor_last_name'],
926 'prefix_id' => $params['honor_prefix_id'],
927 'email-Primary' => $params['honor_email'],
928 ),
929 $honorParams
930 );
931 if (!$honorId) {
932 $honorParams['email'] = $params['honor_email'];
933
934 $dedupeParams = CRM_Dedupe_Finder::formatParams($honorParams, 'Individual');
935 $dedupeParams['check_permission'] = FALSE;
936 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
937
938 // if we find more than one contact, use the first one
939 $honorId = CRM_Utils_Array::value(0, $ids);
940 }
941
942 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
943 $honorParams,
944 CRM_Core_DAO::$_nullArray,
945 $honorId
946 );
947 return $contactID;
948 }
949
950 /**
951 * Function to get list of contribution In Honor of contact Ids
952 *
953 * @param int $honorId In Honor of Contact ID
954 *
955 * @return return the list of contribution fields
956 *
957 * @access public
958 * @static
959 */
960 static function getHonorContacts($honorId) {
961 $params = array();
962 $honorDAO = new CRM_Contribute_DAO_Contribution();
963 $honorDAO->honor_contact_id = $honorId;
964 $honorDAO->find();
965
966 $status = CRM_Contribute_PseudoConstant::contributionStatus($honorDAO->contribution_status_id);
967 $type = CRM_Contribute_PseudoConstant::financialType();
968
969 while ($honorDAO->fetch()) {
970 $params[$honorDAO->id]['honorId'] = $honorDAO->contact_id;
971 $params[$honorDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $honorDAO->contact_id, 'display_name');
972 $params[$honorDAO->id]['type'] = $type[$honorDAO->financial_type_id];
973 $params[$honorDAO->id]['type_id'] = $honorDAO->financial_type_id;
974 $params[$honorDAO->id]['amount'] = CRM_Utils_Money::format($honorDAO->total_amount, $honorDAO->currency);
975 $params[$honorDAO->id]['source'] = $honorDAO->source;
976 $params[$honorDAO->id]['receive_date'] = $honorDAO->receive_date;
977 $params[$honorDAO->id]['contribution_status'] = CRM_Utils_Array::value($honorDAO->contribution_status_id, $status);
978 }
979
980 return $params;
981 }
982
983 /**
984 * function to get the sort name of a contact for a particular contribution
985 *
986 * @param int $id id of the contribution
987 *
988 * @return null|string sort name of the contact if found
989 * @static
990 * @access public
991 */
992 static function sortName($id) {
993 $id = CRM_Utils_Type::escape($id, 'Integer');
994
995 $query = "
996 SELECT civicrm_contact.sort_name
997 FROM civicrm_contribution, civicrm_contact
998 WHERE civicrm_contribution.contact_id = civicrm_contact.id
999 AND civicrm_contribution.id = {$id}
1000 ";
1001 return CRM_Core_DAO::singleValueQuery($query, CRM_Core_DAO::$_nullArray);
1002 }
1003
1004 static function annual($contactID) {
1005 if (is_array($contactID)) {
1006 $contactIDs = implode(',', $contactID);
1007 }
1008 else {
1009 $contactIDs = $contactID;
1010 }
1011
1012 $config = CRM_Core_Config::singleton();
1013 $startDate = $endDate = NULL;
1014
1015 $currentMonth = date('m');
1016 $currentDay = date('d');
1017 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1018 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1019 (int ) $config->fiscalYearStart['d'] > $currentDay
1020 )
1021 ) {
1022 $year = date('Y') - 1;
1023 }
1024 else {
1025 $year = date('Y');
1026 }
1027 $nextYear = $year + 1;
1028
1029 if ($config->fiscalYearStart) {
1030 if ($config->fiscalYearStart['M'] < 10) {
1031 $config->fiscalYearStart['M'] = '0' . $config->fiscalYearStart['M'];
1032 }
1033 if ($config->fiscalYearStart['d'] < 10) {
1034 $config->fiscalYearStart['d'] = '0' . $config->fiscalYearStart['d'];
1035 }
1036 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
1037 }
1038 else {
1039 $monthDay = '0101';
1040 }
1041 $startDate = "$year$monthDay";
1042 $endDate = "$nextYear$monthDay";
1043
1044 $query = "
1045 SELECT count(*) as count,
1046 sum(total_amount) as amount,
1047 avg(total_amount) as average,
1048 currency
1049 FROM civicrm_contribution b
1050 WHERE b.contact_id IN ( $contactIDs )
1051 AND b.contribution_status_id = 1
1052 AND b.is_test = 0
1053 AND b.receive_date >= $startDate
1054 AND b.receive_date < $endDate
1055 GROUP BY currency
1056 ";
1057 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1058 $count = 0;
1059 $amount = $average = array();
1060 while ($dao->fetch()) {
1061 if ($dao->count > 0 && $dao->amount > 0) {
1062 $count += $dao->count;
1063 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency);
1064 $average[] = CRM_Utils_Money::format($dao->average, $dao->currency);
1065 }
1066 }
1067 if ($count > 0) {
1068 return array(
1069 $count,
1070 implode(',&nbsp;', $amount),
1071 implode(',&nbsp;', $average),
1072 );
1073 }
1074 return array(0, 0, 0);
1075 }
1076
1077 /**
1078 * Check if there is a contribution with the params passed in.
1079 * Used for trxn_id,invoice_id and contribution_id
1080 *
1081 * @param array $params an assoc array of name/value pairs
1082 *
1083 * @return array contribution id if success else NULL
1084 * @access public
1085 * static
1086 */
1087 static function checkDuplicateIds($params) {
1088 $dao = new CRM_Contribute_DAO_Contribution();
1089
1090 $clause = array();
1091 $input = array();
1092 foreach ($params as $k => $v) {
1093 if ($v) {
1094 $clause[] = "$k = '$v'";
1095 }
1096 }
1097 $clause = implode(' AND ', $clause);
1098 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1099 $dao = CRM_Core_DAO::executeQuery($query, $input);
1100
1101 while ($dao->fetch()) {
1102 $result = $dao->id;
1103 return $result;
1104 }
1105 return NULL;
1106 }
1107
1108 /**
1109 * Function to get the contribution details for component export
1110 *
1111 * @param int $exportMode export mode
1112 * @param string $componentIds component ids
1113 *
1114 * @return array associated array
1115 *
1116 * @static
1117 * @access public
1118 */
1119 static function getContributionDetails($exportMode, $componentIds) {
1120 $paymentDetails = array();
1121 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1122
1123 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1124 $componentSelect = " civicrm_participant_payment.participant_id id";
1125 $additionalClause = "
1126 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1127 AND civicrm_participant_payment.participant_id {$componentClause} )
1128 ";
1129 }
1130 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1131 $componentSelect = " civicrm_membership_payment.membership_id id";
1132 $additionalClause = "
1133 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1134 AND civicrm_membership_payment.membership_id {$componentClause} )
1135 ";
1136 }
1137 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1138 $componentSelect = " civicrm_pledge_payment.id id";
1139 $additionalClause = "
1140 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1141 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1142 ";
1143 }
1144
1145 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1146 trxn_id, {$componentSelect}
1147 FROM civicrm_contribution
1148 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1149 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1150 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1151 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1152 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1153 AND option_group_contribution_status.id = contribution_status.option_group_id )
1154 {$additionalClause}
1155 ";
1156
1157 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1158
1159 while ($dao->fetch()) {
1160 $paymentDetails[$dao->id] = array(
1161 'total_amount' => $dao->total_amount,
1162 'contribution_status' => $dao->status,
1163 'receive_date' => $dao->receive_date,
1164 'pay_instru' => $dao->payment_instrument,
1165 'trxn_id' => $dao->trxn_id,
1166 );
1167 }
1168
1169 return $paymentDetails;
1170 }
1171
1172 /**
1173 * Function to create address associated with contribution record.
1174 * @param array $params an associated array
1175 * @param int $billingID $billingLocationTypeID
1176 *
1177 * @return address id
1178 * @static
1179 */
1180 static function createAddress(&$params, $billingLocationTypeID) {
1181 $billingFields = array(
1182 'street_address',
1183 'city',
1184 'state_province_id',
1185 'postal_code',
1186 'country_id',
1187 );
1188
1189 //build address array
1190 $addressParams = array();
1191 $addressParams['location_type_id'] = $billingLocationTypeID;
1192 $addressParams['is_billing'] = 1;
1193
1194 $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params);
1195 $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params);
1196 $billingLastName = CRM_Utils_Array::value('billing_last_name', $params);
1197 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}";
1198
1199 foreach ($billingFields as $value) {
1200 $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params);
1201 }
1202
1203 $address = CRM_Core_BAO_Address::add($addressParams, FALSE);
1204
1205 return $address->id;
1206 }
1207
1208 /**
1209 * Delete billing address record related contribution
1210 *
1211 * @param int $contact_id contact id
1212 * @param int $contribution_id contributionId
1213 * @access public
1214 * @static
1215 */
1216 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1217 $clauses = array();
1218 $contactJoin = NULL;
1219
1220 if ($contributionId) {
1221 $clauses[] = "cc.id = {$contributionId}";
1222 }
1223
1224 if ($contactId) {
1225 $clauses[] = "cco.id = {$contactId}";
1226 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1227 }
1228
1229 if (empty($clauses)) {
1230 CRM_Core_Error::fatal();
1231 }
1232
1233 $condition = implode(' OR ', $clauses);
1234
1235 $query = "
1236 SELECT ca.id
1237 FROM civicrm_address ca
1238 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1239 $contactJoin
1240 WHERE $condition
1241 ";
1242 $dao = CRM_Core_DAO::executeQuery($query);
1243
1244 while ($dao->fetch()) {
1245 $params = array('id' => $dao->id);
1246 CRM_Core_BAO_Block::blockDelete('Address', $params);
1247 }
1248 }
1249
1250 /**
1251 * This function check online pending contribution associated w/
1252 * Online Event Registration or Online Membership signup.
1253 *
1254 * @param int $componentId participant/membership id.
1255 * @param string $componentName Event/Membership.
1256 *
1257 * @return $contributionId pending contribution id.
1258 * @static
1259 */
1260 static function checkOnlinePendingContribution($componentId, $componentName) {
1261 $contributionId = NULL;
1262 if (!$componentId ||
1263 !in_array($componentName, array('Event', 'Membership'))
1264 ) {
1265 return $contributionId;
1266 }
1267
1268 if ($componentName == 'Event') {
1269 $idName = 'participant_id';
1270 $componentTable = 'civicrm_participant';
1271 $paymentTable = 'civicrm_participant_payment';
1272 $source = ts('Online Event Registration');
1273 }
1274
1275 if ($componentName == 'Membership') {
1276 $idName = 'membership_id';
1277 $componentTable = 'civicrm_membership';
1278 $paymentTable = 'civicrm_membership_payment';
1279 $source = ts('Online Contribution');
1280 }
1281
1282 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
1283
1284 $query = "
1285 SELECT component.id as {$idName},
1286 componentPayment.contribution_id as contribution_id,
1287 contribution.source source,
1288 contribution.contribution_status_id as contribution_status_id,
1289 contribution.is_pay_later as is_pay_later
1290 FROM $componentTable component
1291 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1292 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1293 WHERE component.id = {$componentId}";
1294
1295 $dao = CRM_Core_DAO::executeQuery($query);
1296
1297 while ($dao->fetch()) {
1298 if ($dao->contribution_id &&
1299 $dao->is_pay_later &&
1300 $dao->contribution_status_id == $pendingStatusId &&
1301 strpos($dao->source, $source) !== FALSE
1302 ) {
1303 $contributionId = $dao->contribution_id;
1304 $dao->free();
1305 }
1306 }
1307
1308 return $contributionId;
1309 }
1310
1311 /**
1312 * This function update contribution as well as related objects.
1313 */
1314 static function transitionComponents($params, $processContributionObject = FALSE) {
1315 // get minimum required values.
1316 $contactId = CRM_Utils_Array::value('contact_id', $params);
1317 $componentId = CRM_Utils_Array::value('component_id', $params);
1318 $componentName = CRM_Utils_Array::value('componentName', $params);
1319 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
1320 $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
1321
1322 // if we already processed contribution object pass previous status id.
1323 $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
1324
1325 $updateResult = array();
1326
1327 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1328
1329 // we process only ( Completed, Cancelled, or Failed ) contributions.
1330 if (!$contributionId ||
1331 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1332 array_search('Cancelled', $contributionStatuses),
1333 array_search('Failed', $contributionStatuses),
1334 ))
1335 ) {
1336 return $updateResult;
1337 }
1338
1339 if (!$componentName || !$componentId) {
1340 // get the related component details.
1341 $componentDetails = self::getComponentDetails($contributionId);
1342 }
1343 else {
1344 $componentDetails['contact_id'] = $contactId;
1345 $componentDetails['component'] = $componentName;
1346
1347 if ($componentName == 'event') {
1348 $componentDetails['participant'] = $componentId;
1349 }
1350 else {
1351 $componentDetails['membership'] = $componentId;
1352 }
1353 }
1354
1355 if (CRM_Utils_Array::value('contact_id', $componentDetails)) {
1356 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1357 $contributionId,
1358 'contact_id'
1359 );
1360 }
1361
1362 // do check for required ids.
1363 if (!CRM_Utils_Array::value('membership', $componentDetails) &&
1364 !CRM_Utils_Array::value('participant', $componentDetails) &&
1365 !CRM_Utils_Array::value('pledge_payment', $componentDetails) ||
1366 !CRM_Utils_Array::value('contact_id', $componentDetails)
1367 ) {
1368 return $updateResult;
1369 }
1370
1371 //now we are ready w/ required ids, start processing.
1372
1373 $baseIPN = new CRM_Core_Payment_BaseIPN();
1374
1375 $input = $ids = $objects = array();
1376
1377 $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
1378 $ids['contribution'] = $contributionId;
1379 $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
1380 $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
1381 $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
1382 $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
1383 $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
1384 $ids['contributionRecur'] = NULL;
1385 $ids['contributionPage'] = NULL;
1386
1387 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1388 CRM_Core_Error::fatal();
1389 }
1390
1391 $memberships = &$objects['membership'];
1392 $participant = &$objects['participant'];
1393 $pledgePayment = &$objects['pledge_payment'];
1394 $contribution = &$objects['contribution'];
1395
1396 if ($pledgePayment) {
1397 $pledgePaymentIDs = array();
1398 foreach ($pledgePayment as $key => $object) {
1399 $pledgePaymentIDs[] = $object->id;
1400 }
1401 $pledgeID = $pledgePayment[0]->pledge_id;
1402 }
1403
1404 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
1405
1406 if ($participant) {
1407 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1408 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1409 $participant->id,
1410 'status_id'
1411 );
1412 }
1413 // we might want to process contribution object.
1414 $processContribution = FALSE;
1415 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1416 if (is_array($memberships)) {
1417 foreach ($memberships as $membership) {
1418 if ($membership) {
1419 $membership->status_id = array_search('Cancelled', $membershipStatuses);
1420 $membership->save();
1421
1422 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1423 if ($processContributionObject) {
1424 $processContribution = TRUE;
1425 }
1426 }
1427 }
1428 }
1429
1430 if ($participant) {
1431 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1432 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1433
1434 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1435 if ($processContributionObject) {
1436 $processContribution = TRUE;
1437 }
1438 }
1439
1440 if ($pledgePayment) {
1441 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1442
1443 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1444 if ($processContributionObject) {
1445 $processContribution = TRUE;
1446 }
1447 }
1448 }
1449 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1450 if (is_array($memberships)) {
1451 foreach ($memberships as $membership) {
1452 if ($membership) {
1453 $membership->status_id = array_search('Expired', $membershipStatuses);
1454 $membership->save();
1455
1456 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1457 if ($processContributionObject) {
1458 $processContribution = TRUE;
1459 }
1460 }
1461 }
1462 }
1463 if ($participant) {
1464 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1465 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1466
1467 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1468 if ($processContributionObject) {
1469 $processContribution = TRUE;
1470 }
1471 }
1472
1473 if ($pledgePayment) {
1474 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1475
1476 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1477 if ($processContributionObject) {
1478 $processContribution = TRUE;
1479 }
1480 }
1481 }
1482 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1483
1484 // only pending contribution related object processed.
1485 if ($previousContriStatusId &&
1486 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1487 ) {
1488 // this is case when we already processed contribution object.
1489 return $updateResult;
1490 }
1491 elseif (!$previousContriStatusId &&
1492 $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)
1493 ) {
1494 // this is case when we are going to process contribution object later.
1495 return $updateResult;
1496 }
1497
1498 if (is_array($memberships)) {
1499 foreach ($memberships as $membership) {
1500 if ($membership) {
1501 $format = '%Y%m%d';
1502
1503 //CRM-4523
1504 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
1505 $membership->membership_type_id,
1506 $membership->is_test, $membership->id
1507 );
1508
1509 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1510 // this picks up membership type changes during renewals
1511 $sql = "
1512 SELECT membership_type_id
1513 FROM civicrm_membership_log
1514 WHERE membership_id=$membership->id
1515 ORDER BY id DESC
1516 LIMIT 1;";
1517 $dao = new CRM_Core_DAO;
1518 $dao->query($sql);
1519 if ($dao->fetch()) {
1520 if (!empty($dao->membership_type_id)) {
1521 $membership->membership_type_id = $dao->membership_type_id;
1522 $membership->save();
1523 }
1524 }
1525 // else fall back to using current membership type
1526 $dao->free();
1527
1528 // Figure out number of terms
1529 $numterms = 1;
1530 $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution');
1531 foreach ($lineitems as $lineitem) {
1532 if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
1533 $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
1534
1535 // in case membership_num_terms comes through as null or zero
1536 $numterms = $numterms >= 1 ? $numterms : 1;
1537 break;
1538 }
1539 }
1540
1541 if ($currentMembership) {
1542 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1543 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
1544 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1545 }
1546 else {
1547 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $numterms);
1548 }
1549
1550 //get the status for membership.
1551 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
1552 $dates['end_date'],
1553 $dates['join_date'],
1554 'today',
1555 TRUE
1556 );
1557
1558 $formattedParams = array(
1559 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
1560 array_search('Current', $membershipStatuses)
1561 ),
1562 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
1563 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
1564 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
1565 );
1566
1567 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
1568
1569 $membership->copyValues($formattedParams);
1570 $membership->save();
1571
1572 //updating the membership log
1573 $membershipLog = array();
1574 $membershipLog = $formattedParams;
1575 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
1576 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
1577
1578 $membershipLog['start_date'] = $logStartDate;
1579 $membershipLog['membership_id'] = $membership->id;
1580 $membershipLog['modified_id'] = $membership->contact_id;
1581 $membershipLog['modified_date'] = date('Ymd');
1582 $membershipLog['membership_type_id'] = $membership->membership_type_id;
1583
1584 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1585
1586 //update related Memberships.
1587 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
1588
1589 $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
1590 '%B %E%f, %Y'
1591 );
1592 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1593 if ($processContributionObject) {
1594 $processContribution = TRUE;
1595 }
1596
1597 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
1598 }
1599 }
1600 }
1601
1602 if ($participant) {
1603 $updatedStatusId = array_search('Registered', $participantStatuses);
1604 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1605
1606 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1607 if ($processContributionObject) {
1608 $processContribution = TRUE;
1609 }
1610 }
1611
1612 if ($pledgePayment) {
1613 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1614
1615 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1616 if ($processContributionObject) {
1617 $processContribution = TRUE;
1618 }
1619 }
1620 }
1621
1622 // process contribution object.
1623 if ($processContribution) {
1624 $contributionParams = array();
1625 $fields = array(
1626 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1627 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1628 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1629 );
1630 foreach ($fields as $field) {
1631 if (!CRM_Utils_Array::value($field, $params)) {
1632 continue;
1633 }
1634 $contributionParams[$field] = $params[$field];
1635 }
1636
1637 $ids = array('contribution' => $contributionId);
1638 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1639 }
1640
1641 return $updateResult;
1642 }
1643
1644 /**
1645 * This function returns all contribution related object ids.
1646 */
1647 public static function getComponentDetails($contributionId) {
1648 $componentDetails = $pledgePayment = array();
1649 if (!$contributionId) {
1650 return $componentDetails;
1651 }
1652
1653 $query = "
1654 SELECT c.id as contribution_id,
1655 c.contact_id as contact_id,
1656 mp.membership_id as membership_id,
1657 m.membership_type_id as membership_type_id,
1658 pp.participant_id as participant_id,
1659 p.event_id as event_id,
1660 pgp.id as pledge_payment_id
1661 FROM civicrm_contribution c
1662 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1663 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1664 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1665 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1666 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1667 WHERE c.id = $contributionId";
1668
1669 $dao = CRM_Core_DAO::executeQuery($query);
1670 $componentDetails = array();
1671
1672 while ($dao->fetch()) {
1673 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
1674 $componentDetails['contact_id'] = $dao->contact_id;
1675 if ($dao->event_id) {
1676 $componentDetails['event'] = $dao->event_id;
1677 }
1678 if ($dao->participant_id) {
1679 $componentDetails['participant'] = $dao->participant_id;
1680 }
1681 if ($dao->membership_id) {
1682 if (!isset($componentDetails['membership'])) {
1683 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1684 }
1685 $componentDetails['membership'][] = $dao->membership_id;
1686 $componentDetails['membership_type'][] = $dao->membership_type_id;
1687 }
1688 if ($dao->pledge_payment_id) {
1689 $pledgePayment[] = $dao->pledge_payment_id;
1690 }
1691 }
1692
1693 if ($pledgePayment) {
1694 $componentDetails['pledge_payment'] = $pledgePayment;
1695 }
1696
1697 return $componentDetails;
1698 }
1699
1700 static function contributionCount($contactId, $includeSoftCredit = TRUE, $includeHonoree = TRUE) {
1701 if (!$contactId) {
1702 return 0;
1703 }
1704
1705 $contactContributionsSQL = "
1706 SELECT contribution.id AS id
1707 FROM civicrm_contribution contribution
1708 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1709
1710 $contactHonoreeContributionsSQL = "
1711 SELECT contribution.id
1712 FROM civicrm_contribution contribution
1713 WHERE contribution.is_test = 0 AND contribution.honor_contact_id = {$contactId} ";
1714
1715 $contactSoftCreditContributionsSQL = "
1716 SELECT contribution.id
1717 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1718 ON ( contribution.id = softContribution.contribution_id )
1719 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1720 $query = "SELECT count( x.id ) count FROM ( ";
1721 $query .= $contactContributionsSQL;
1722
1723 if ($includeSoftCredit) {
1724 $query .= " UNION ";
1725 $query .= $contactSoftCreditContributionsSQL;
1726 }
1727
1728 if ($includeHonoree) {
1729 $query .= " UNION ";
1730 $query .= $contactHonoreeContributionsSQL;
1731 }
1732
1733 $query .= ") x";
1734
1735 return CRM_Core_DAO::singleValueQuery($query);
1736 }
1737
1738 /**
1739 * Function to get individual id for onbehalf contribution
1740 *
1741 * @param int $contributionId contribution id
1742 * @param int $contributorId contributor id
1743 *
1744 * @return array $ids containing organization id and individual id
1745 * @access public
1746 */
1747 static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1748
1749 $ids = array();
1750
1751 if (!$contributionId) {
1752 return $ids;
1753 }
1754
1755 // fetch contributor id if null
1756 if (!$contributorId) {
1757 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1758 $contributionId, 'contact_id'
1759 );
1760 }
1761
1762 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
1763 $activityTypeId = array_search('Contribution', $activityTypeIds);
1764
1765 if ($activityTypeId && $contributorId) {
1766 $activityQuery = "
1767 SELECT civicrm_activity_contact.contact_id
1768 FROM civicrm_activity_contact
1769 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1770 WHERE civicrm_activity.activity_type_id = %1
1771 AND civicrm_activity.source_record_id = %2
1772 AND civicrm_activity_contact.record_type_id = %3
1773 ";
1774
1775 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1776 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1777
1778 $params = array(
1779 1 => array($activityTypeId, 'Integer'),
1780 2 => array($contributionId, 'Integer'),
1781 3 => array($sourceID, 'Integer'),
1782 );
1783
1784 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
1785
1786 // for on behalf contribution source is individual and contributor is organization
1787 if ($sourceContactId && $sourceContactId != $contributorId) {
1788 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
1789 // get rel type id for employee of relation
1790 foreach ($relationshipTypeIds as $id => $typeVals) {
1791 if ($typeVals['name_a_b'] == 'Employee of') {
1792 $relationshipTypeId = $id;
1793 break;
1794 }
1795 }
1796
1797 $rel = new CRM_Contact_DAO_Relationship();
1798 $rel->relationship_type_id = $relationshipTypeId;
1799 $rel->contact_id_a = $sourceContactId;
1800 $rel->contact_id_b = $contributorId;
1801 if ($rel->find(TRUE)) {
1802 $ids['individual_id'] = $rel->contact_id_a;
1803 $ids['organization_id'] = $rel->contact_id_b;
1804 }
1805 }
1806 }
1807
1808 return $ids;
1809 }
1810
1811 /**
1812 * @return array
1813 * @static
1814 */
1815 static function getContributionDates() {
1816 $config = CRM_Core_Config::singleton();
1817 $currentMonth = date('m');
1818 $currentDay = date('d');
1819 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1820 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1821 (int ) $config->fiscalYearStart['d'] > $currentDay
1822 )
1823 ) {
1824 $year = date('Y') - 1;
1825 }
1826 else {
1827 $year = date('Y');
1828 }
1829 $year = array('Y' => $year);
1830 $yearDate = $config->fiscalYearStart;
1831 $yearDate = array_merge($year, $yearDate);
1832 $yearDate = CRM_Utils_Date::format($yearDate);
1833
1834 $monthDate = date('Ym') . '01';
1835
1836 $now = date('Ymd');
1837
1838 return array(
1839 'now' => $now,
1840 'yearDate' => $yearDate,
1841 'monthDate' => $monthDate,
1842 );
1843 }
1844
1845 /*
1846 * Load objects relations to contribution object
1847 * Objects are stored in the $_relatedObjects property
1848 * In the first instance we are just moving functionality from BASEIpn -
1849 * see http://issues.civicrm.org/jira/browse/CRM-9996
1850 *
1851 * @param array $input Input as delivered from Payment Processor
1852 * @param array $ids Ids as Loaded by Payment Processor
1853 * @param boolean $required Is Payment processor / contribution page required
1854 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1855 * Note that the unit test for the BaseIPN class tests this function
1856 */
1857 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1858 if($loadAll){
1859 $ids = array_merge($this->getComponentDetails($this->id),$ids);
1860 if(empty($ids['contact']) && isset($this->contact_id)){
1861 $ids['contact'] = $this->contact_id;
1862 }
1863 }
1864 if (empty($this->_component)) {
1865 if (! empty($ids['event'])) {
1866 $this->_component = 'event';
1867 }
1868 else {
1869 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
1870 }
1871 }
1872 $paymentProcessorID = CRM_Utils_Array::value('paymentProcessor', $ids);
1873 $contributionType = new CRM_Financial_BAO_FinancialType();
1874 $contributionType->id = $this->financial_type_id;
1875 if (!$contributionType->find(TRUE)) {
1876 throw new Exception("Could not find financial type record: " . $this->financial_type_id);
1877 }
1878 if (!empty($ids['contact'])) {
1879 $this->_relatedObjects['contact'] = new CRM_Contact_BAO_Contact();
1880 $this->_relatedObjects['contact']->id = $ids['contact'];
1881 $this->_relatedObjects['contact']->find(TRUE);
1882 }
1883 $this->_relatedObjects['contributionType'] = $contributionType;
1884
1885 if ($this->_component == 'contribute') {
1886 // retrieve the other optional objects first so
1887 // stuff down the line can use this info and do things
1888 // CRM-6056
1889 //in any case get the memberships associated with the contribution
1890 //because we now support multiple memberships w/ price set
1891 // see if there are any other memberships to be considered for same contribution.
1892 $query = "
1893 SELECT membership_id
1894 FROM civicrm_membership_payment
1895 WHERE contribution_id = %1 ";
1896 $params = array(1 => array($this->id, 'Integer'));
1897
1898 $dao = CRM_Core_DAO::executeQuery($query, $params );
1899 while ($dao->fetch()) {
1900 if ($dao->membership_id) {
1901 if (!is_array($ids['membership'])) {
1902 $ids['membership'] = array();
1903 }
1904 $ids['membership'][] = $dao->membership_id;
1905 }
1906 }
1907
1908 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1909 foreach ($ids['membership'] as $id) {
1910 if (!empty($id)) {
1911 $membership = new CRM_Member_BAO_Membership();
1912 $membership->id = $id;
1913 if (!$membership->find(TRUE)) {
1914 throw new Exception("Could not find membership record: $id");
1915 }
1916 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
1917 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
1918 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
1919 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
1920 $membership->free();
1921 }
1922 }
1923 }
1924
1925 if (!empty($ids['pledge_payment'])) {
1926
1927 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1928 if (empty($paymentID)) {
1929 continue;
1930 }
1931 $payment = new CRM_Pledge_BAO_PledgePayment();
1932 $payment->id = $paymentID;
1933 if (!$payment->find(TRUE)) {
1934 throw new Exception("Could not find pledge payment record: " . $paymentID);
1935 }
1936 $this->_relatedObjects['pledge_payment'][] = $payment;
1937 }
1938 }
1939
1940 if (!empty($ids['contributionRecur'])) {
1941 $recur = new CRM_Contribute_BAO_ContributionRecur();
1942 $recur->id = $ids['contributionRecur'];
1943 if (!$recur->find(TRUE)) {
1944 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
1945 }
1946 $this->_relatedObjects['contributionRecur'] = &$recur;
1947 //get payment processor id from recur object.
1948 $paymentProcessorID = $recur->payment_processor_id;
1949 }
1950 //for normal contribution get the payment processor id.
1951 if (!$paymentProcessorID) {
1952 if ($this->contribution_page_id) {
1953 // get the payment processor id from contribution page
1954 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
1955 $this->contribution_page_id,
1956 'payment_processor'
1957 );
1958 }
1959 //fail to load payment processor id.
1960 elseif (!CRM_Utils_Array::value('pledge_payment', $ids)) {
1961 $loadObjectSuccess = TRUE;
1962 if ($required) {
1963 throw new Exception("Could not find contribution page for contribution record: " . $this->id);
1964 }
1965 return $loadObjectSuccess;
1966 }
1967 }
1968 }
1969 else {
1970 // we are in event mode
1971 // make sure event exists and is valid
1972 $event = new CRM_Event_BAO_Event();
1973 $event->id = $ids['event'];
1974 if ($ids['event'] &&
1975 !$event->find(TRUE)
1976 ) {
1977 throw new Exception("Could not find event: " . $ids['event']);
1978 }
1979
1980 $this->_relatedObjects['event'] = &$event;
1981
1982 $participant = new CRM_Event_BAO_Participant();
1983 $participant->id = $ids['participant'];
1984 if ($ids['participant'] &&
1985 !$participant->find(TRUE)
1986 ) {
1987 throw new Exception("Could not find participant: " . $ids['participant']);
1988 }
1989 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
1990
1991 $this->_relatedObjects['participant'] = &$participant;
1992
1993 if (!$paymentProcessorID) {
1994 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
1995 }
1996 }
1997
1998 $loadObjectSuccess = TRUE;
1999 if ($paymentProcessorID) {
2000 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2001 $this->is_test ? 'test' : 'live'
2002 );
2003 $ids['paymentProcessor'] = $paymentProcessorID;
2004 $this->_relatedObjects['paymentProcessor'] = &$paymentProcessor;
2005 }
2006 elseif ($required) {
2007 $loadObjectSuccess = FALSE;
2008 throw new Exception("Could not find payment processor for contribution record: " . $this->id);
2009 }
2010
2011 return $loadObjectSuccess;
2012 }
2013
2014 /*
2015 * Create array of message information - ie. return html version, txt version, to field
2016 *
2017 * @param array $input incoming information
2018 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2019 * just check presence of recur object but maintaining legacy approach
2020 * to be careful)
2021 * @param array $ids IDs of related objects
2022 * @param array $values any values that may have already been compiled by calling process
2023 * This is augmented by values 'gathered' by gatherMessageValues
2024 * @param bool $returnMessageText distinguishes between whether to send message or return
2025 * message text. We are working towards this function ALWAYS returning message text & calling
2026 * function doing emails / pdfs with it
2027 * @return array $messageArray - messages
2028 */
2029 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2030 if (empty($this->_relatedObjects)) {
2031 $this->loadRelatedObjects($input, $ids);
2032 }
2033 if (empty($this->_component)) {
2034 $this->_component = CRM_Utils_Array::value('component', $input);
2035 }
2036
2037 //not really sure what params might be passed in but lets merge em into values
2038 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2039 $template = CRM_Core_Smarty::singleton();
2040 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2041 //what does recur 'mean here - to do with payment processor return functionality but
2042 // what is the importance
2043 if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) {
2044 $paymentObject = &CRM_Core_Payment::singleton(
2045 $this->is_test ? 'test' : 'live',
2046 $this->_relatedObjects['paymentProcessor']
2047 );
2048
2049 $entityID = $entity = NULL;
2050 if (isset($ids['contribution'])) {
2051 $entity = 'contribution';
2052 $entityID = $ids['contribution'];
2053 }
2054 if (isset($ids['membership']) && $ids['membership']) {
2055 $entity = 'membership';
2056 $entityID = $ids['membership'];
2057 }
2058
2059 $url = $paymentObject->subscriptionURL($entityID, $entity);
2060 $template->assign('cancelSubscriptionUrl', $url);
2061
2062 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2063 $template->assign('updateSubscriptionBillingUrl', $url);
2064
2065 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2066 $template->assign('updateSubscriptionUrl', $url);
2067
2068 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2069 //direct mode showing billing block, so use directIPN for temporary
2070 $template->assign('contributeMode', 'directIPN');
2071 }
2072 }
2073 // todo remove strtolower - check consistency
2074 if (strtolower($this->_component) == 'event') {
2075 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2076 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2077 );
2078 }
2079 else {
2080 $values['contribution_id'] = $this->id;
2081 if (CRM_Utils_Array::value('related_contact', $ids)) {
2082 $values['related_contact'] = $ids['related_contact'];
2083 if (isset($ids['onbehalf_dupe_alert'])) {
2084 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2085 }
2086 $entityBlock = array(
2087 'contact_id' => $ids['contact'],
2088 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2089 'Home', 'id', 'name'
2090 ),
2091 );
2092 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2093 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2094 }
2095 $isTest = FALSE;
2096 if ($this->is_test) {
2097 $isTest = TRUE;
2098 }
2099 if (!empty($this->_relatedObjects['membership'])) {
2100 foreach ($this->_relatedObjects['membership'] as $membership) {
2101 if ($membership->id) {
2102 $values['membership_id'] = $membership->id;
2103
2104 // need to set the membership values here
2105 $template->assign('membership_assign', 1);
2106 $template->assign('membership_name',
2107 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2108 );
2109 $template->assign('mem_start_date', $membership->start_date);
2110 $template->assign('mem_join_date', $membership->join_date);
2111 $template->assign('mem_end_date', $membership->end_date);
2112 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2113 $template->assign('mem_status', $membership_status);
2114 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
2115 $template->assign('is_pay_later', 1);
2116 }
2117
2118 // if separate payment there are two contributions recorded and the
2119 // admin will need to send a receipt for each of them separately.
2120 // we dont link the two in the db (but can potentially infer it if needed)
2121 $template->assign('is_separate_payment', 0);
2122
2123 if ($recur && $paymentObject) {
2124 $url = $paymentObject->subscriptionURL($membership->id, 'membership');
2125 $template->assign('cancelSubscriptionUrl', $url);
2126 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
2127 $template->assign('updateSubscriptionBillingUrl', $url);
2128 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2129 $template->assign('updateSubscriptionUrl', $url);
2130 }
2131
2132 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2133
2134 return $result;
2135 // otherwise if its about sending emails, continue sending without return, as we
2136 // don't want to exit the loop.
2137 }
2138 }
2139 }
2140 else {
2141 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2142 }
2143 }
2144 }
2145
2146 /*
2147 * Gather values for contribution mail - this function has been created
2148 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2149 * Values related to the contribution in question are gathered
2150 *
2151 * @param array $input input into function (probably from payment processor)
2152 * @param array $ids the set of ids related to the inpurt
2153 *
2154 * @return array $values
2155 *
2156 * NB don't add direct calls to the function as we intend to change the signature
2157 */
2158 function _gatherMessageValues($input, &$values, $ids = array()) {
2159 // set display address of contributor
2160 if ($this->address_id) {
2161 $addressParams = array('id' => $this->address_id);
2162 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
2163 $addressDetails = array_values($addressDetails);
2164 $values['address'] = $addressDetails[0]['display'];
2165 }
2166 if ($this->_component == 'contribute') {
2167 if (isset($this->contribution_page_id)) {
2168 CRM_Contribute_BAO_ContributionPage::setValues(
2169 $this->contribution_page_id,
2170 $values
2171 );
2172 if ($this->contribution_page_id) {
2173 // CRM-8254 - override default currency if applicable
2174 $config = CRM_Core_Config::singleton();
2175 $config->defaultCurrency = CRM_Utils_Array::value(
2176 'currency',
2177 $values,
2178 $config->defaultCurrency
2179 );
2180 }
2181 }
2182 // no contribution page -probably back office
2183 else {
2184 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2185 $values['is_email_receipt'] = 1;
2186 $values['title'] = 'Contribution';
2187 }
2188 // set lineItem for contribution
2189 if ($this->id) {
2190 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
2191 if (!empty($lineItem)) {
2192 $itemId = key($lineItem);
2193 foreach ($lineItem as &$eachItem) {
2194 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership']) ) {
2195 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
2196 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
2197 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
2198 }
2199 }
2200 $values['lineItem'][0] = $lineItem;
2201 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2202 }
2203 }
2204
2205 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
2206 $this->id,
2207 $this->contact_id
2208 );
2209 // if this is onbehalf of contribution then set related contact
2210 if (CRM_Utils_Array::value('individual_id', $relatedContact)) {
2211 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2212 }
2213 }
2214 else {
2215 // event
2216 $eventParams = array(
2217 'id' => $this->_relatedObjects['event']->id,
2218 );
2219 $values['event'] = array();
2220
2221 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2222
2223 //get location details
2224 $locationParams = array(
2225 'entity_id' => $this->_relatedObjects['event']->id,
2226 'entity_table' => 'civicrm_event',
2227 );
2228 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2229
2230 $ufJoinParams = array(
2231 'entity_table' => 'civicrm_event',
2232 'entity_id' => $ids['event'],
2233 'module' => 'CiviEvent',
2234 );
2235
2236 list($custom_pre_id,
2237 $custom_post_ids
2238 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2239
2240 $values['custom_pre_id'] = $custom_pre_id;
2241 $values['custom_post_id'] = $custom_post_ids;
2242
2243 // set lineItem for event contribution
2244 if ($this->id) {
2245 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
2246 if (!empty($participantIds)) {
2247 foreach ($participantIds as $pIDs) {
2248 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
2249 if (!CRM_Utils_System::isNull($lineItem)) {
2250 $values['lineItem'][] = $lineItem;
2251 }
2252 }
2253 }
2254 }
2255 }
2256
2257 return $values;
2258 }
2259
2260 /**
2261 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2262 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2263 * Note we send directly from this function in some cases because it is only partly refactored
2264 * Don't call this function directly as the signature will change
2265 */
2266 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2267 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
2268 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
2269 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
2270 if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) {
2271 $template->assign('useForMember', true);
2272 }
2273 //assign honor infomation to receiptmessage
2274 $honorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2275 $this->id,
2276 'honor_contact_id'
2277 );
2278 if (!empty($honorID)) {
2279
2280 $honorDefault = $honorIds = array();
2281 $honorIds['contribution'] = $this->id;
2282 $idParams = array('id' => $honorID, 'contact_id' => $honorID);
2283 CRM_Contact_BAO_Contact::retrieve($idParams, $honorDefault, $honorIds);
2284 $honorType = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'honor_type_id');
2285
2286 $template->assign('honor_block_is_active', 1);
2287 if (CRM_Utils_Array::value('prefix_id', $honorDefault)) {
2288 $prefix = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id');
2289 $template->assign('honor_prefix', $prefix[$honorDefault['prefix_id']]);
2290 }
2291 $template->assign('honor_first_name', CRM_Utils_Array::value('first_name', $honorDefault));
2292 $template->assign('honor_last_name', CRM_Utils_Array::value('last_name', $honorDefault));
2293 $template->assign('honor_email', CRM_Utils_Array::value('email', $honorDefault['email'][1]));
2294 $template->assign('honor_type', $honorType[$this->honor_type_id]);
2295 }
2296
2297 $dao = new CRM_Contribute_DAO_ContributionProduct();
2298 $dao->contribution_id = $this->id;
2299 if ($dao->find(TRUE)) {
2300 $premiumId = $dao->product_id;
2301 $template->assign('option', $dao->product_option);
2302
2303 $productDAO = new CRM_Contribute_DAO_Product();
2304 $productDAO->id = $premiumId;
2305 $productDAO->find(TRUE);
2306 $template->assign('selectPremium', TRUE);
2307 $template->assign('product_name', $productDAO->name);
2308 $template->assign('price', $productDAO->price);
2309 $template->assign('sku', $productDAO->sku);
2310 }
2311 $template->assign('title', CRM_Utils_Array::value('title',$values));
2312 $amount = CRM_Utils_Array::value('total_amount', $input,(CRM_Utils_Array::value('amount', $input)),null);
2313 if(empty($amount) && isset($this->total_amount)){
2314 $amount = $this->total_amount;
2315 }
2316 $template->assign('amount', $amount);
2317 // add the new contribution values
2318 if (strtolower($this->_component) == 'contribute') {
2319 //PCP Info
2320 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2321 $softDAO->contribution_id = $this->id;
2322 if ($softDAO->find(TRUE)) {
2323 $template->assign('pcpBlock', TRUE);
2324 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
2325 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
2326 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
2327
2328 //assign the pcp page title for email subject
2329 $pcpDAO = new CRM_PCP_DAO_PCP();
2330 $pcpDAO->id = $softDAO->pcp_id;
2331 if ($pcpDAO->find(TRUE)) {
2332 $template->assign('title', $pcpDAO->title);
2333 }
2334 }
2335 }
2336
2337 if ($this->financial_type_id) {
2338 $values['financial_type_id'] = $this->financial_type_id;
2339 }
2340
2341
2342 $template->assign('trxn_id', $this->trxn_id);
2343 $template->assign('receive_date',
2344 CRM_Utils_Date::mysqlToIso($this->receive_date)
2345 );
2346 $template->assign('contributeMode', 'notify');
2347 $template->assign('action', $this->is_test ? 1024 : 1);
2348 $template->assign('receipt_text',
2349 CRM_Utils_Array::value('receipt_text',
2350 $values
2351 )
2352 );
2353 $template->assign('is_monetary', 1);
2354 $template->assign('is_recur', (bool) $recur);
2355 $template->assign('currency', $this->currency);
2356 $template->assign('address', CRM_Utils_Address::format($input));
2357 if ($this->_component == 'event') {
2358 $template->assign('title', $values['event']['title']);
2359 $participantRoles = CRM_Event_PseudoConstant::participantRole();
2360 $viewRoles = array();
2361 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
2362 $viewRoles[] = $participantRoles[$v];
2363 }
2364 $values['event']['participant_role'] = implode(', ', $viewRoles);
2365 $template->assign('event', $values['event']);
2366 $template->assign('location', $values['location']);
2367 $template->assign('customPre', $values['custom_pre_id']);
2368 $template->assign('customPost', $values['custom_post_id']);
2369
2370 $isTest = FALSE;
2371 if ($this->_relatedObjects['participant']->is_test) {
2372 $isTest = TRUE;
2373 }
2374
2375 $values['params'] = array();
2376 //to get email of primary participant.
2377 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
2378 $primaryAmount[] = array('label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects['participant']->fee_amount);
2379 //build an array of cId/pId of participants
2380 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
2381 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
2382 //send receipt to additional participant if exists
2383 if (count($additionalIDs)) {
2384 $template->assign('isPrimary', 0);
2385 $template->assign('customProfile', NULL);
2386 //set additionalParticipant true
2387 $values['params']['additionalParticipant'] = TRUE;
2388 foreach ($additionalIDs as $pId => $cId) {
2389 $amount = array();
2390 //to change the status pending to completed
2391 $additional = new CRM_Event_DAO_Participant();
2392 $additional->id = $pId;
2393 $additional->contact_id = $cId;
2394 $additional->find(TRUE);
2395 $additional->register_date = $this->_relatedObjects['participant']->register_date;
2396 $additional->status_id = 1;
2397 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
2398 //if additional participant dont have email
2399 //use display name.
2400 if (!$additionalParticipantInfo) {
2401 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
2402 }
2403 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
2404 $primaryAmount[] = array('label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount);
2405 $additional->save();
2406 $additional->free();
2407 $template->assign('amount', $amount);
2408 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2409 }
2410 }
2411
2412 //build an array of custom profile and assigning it to template
2413 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
2414
2415 if (count($customProfile)) {
2416 $template->assign('customProfile', $customProfile);
2417 }
2418
2419 // for primary contact
2420 $values['params']['additionalParticipant'] = FALSE;
2421 $template->assign('isPrimary', 1);
2422 $template->assign('amount', $primaryAmount);
2423 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
2424 if ($this->payment_instrument_id) {
2425 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
2426 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
2427 }
2428 // carry paylater, since we did not created billing,
2429 // so need to pull email from primary location, CRM-4395
2430 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
2431 }
2432 return $template;
2433 }
2434
2435 /**
2436 * Function to check whether payment processor supports
2437 * cancellation of contribution subscription
2438 *
2439 * @param int $contributionId contribution id
2440 *
2441 * @return boolean
2442 * @access public
2443 * @static
2444 */
2445 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2446 $cacheKeyString = "$contributionId";
2447 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2448
2449 static $supportsCancel = array();
2450
2451 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2452 $supportsCancel[$cacheKeyString] = FALSE;
2453 $isCancelled = FALSE;
2454
2455 if ($isNotCancelled) {
2456 $isCancelled = self::isSubscriptionCancelled($contributionId);
2457 }
2458
2459 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
2460 if (!empty($paymentObject)) {
2461 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2462 }
2463 }
2464 return $supportsCancel[$cacheKeyString];
2465 }
2466
2467 /**
2468 * Function to check whether subscription is already cancelled
2469 *
2470 * @param int $contributionId contribution id
2471 *
2472 * @return string $status contribution status
2473 * @access public
2474 * @static
2475 */
2476 static function isSubscriptionCancelled($contributionId) {
2477 $sql = "
2478 SELECT cr.contribution_status_id
2479 FROM civicrm_contribution_recur cr
2480 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2481 WHERE con.id = %1 LIMIT 1";
2482 $params = array(1 => array($contributionId, 'Integer'));
2483 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
2484 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId);
2485 if ($status == 'Cancelled') {
2486 return TRUE;
2487 }
2488 return FALSE;
2489 }
2490
2491 /**
2492 * Function to create all financial accounts entry
2493 *
2494 * @param array $params contribution object, line item array and params for trxn
2495 *
2496 *
2497 * @access public
2498 * @static
2499 */
2500 static function recordFinancialAccounts(&$params) {
2501 $skipRecords = $update = FALSE;
2502 $additionalParticipantId = array();
2503 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2504
2505 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
2506 $entityId = $params['participant_id'];
2507 $entityTable = 'civicrm_participant';
2508 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
2509 }
2510 else {
2511 $entityId = $params['contribution']->id;
2512 $entityTable = 'civicrm_contribution';
2513 }
2514
2515 $entityID[] = $entityId;
2516 if (!empty($additionalParticipantId)) {
2517 $entityID += $additionalParticipantId;
2518 }
2519 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2520 if (!CRM_Utils_Array::value('prevContribution', $params)) {
2521 $entityID = NULL;
2522 }
2523 else {
2524 $update = TRUE;
2525 }
2526
2527 // build line item array if its not set in $params
2528 if (!CRM_Utils_Array::value('line_item', $params) || $additionalParticipantId) {
2529 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
2530 }
2531
2532 if (CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2533 !(CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later)) {
2534 $skipRecords = TRUE;
2535 if (CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses)) {
2536 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2537 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2538 }
2539 elseif (CRM_Utils_Array::value('payment_processor', $params)) {
2540 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2541 }
2542 elseif (CRM_Utils_Array::value('payment_instrument_id', $params)) {
2543 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
2544 }
2545 else {
2546 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2547 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2548 $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
2549 }
2550
2551 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
2552 if (!isset($totalAmount) && CRM_Utils_Array::value('prevContribution', $params)) {
2553 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
2554 }
2555 //build financial transaction params
2556 $trxnParams = array(
2557 'contribution_id' => $params['contribution']->id,
2558 'to_financial_account_id' => $params['to_financial_account_id'],
2559 'trxn_date' => date('YmdHis'),
2560 'total_amount' => $totalAmount,
2561 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
2562 'net_amount' => CRM_Utils_Array::value('net_amount', $params),
2563 'currency' => $params['contribution']->currency,
2564 'trxn_id' => $params['contribution']->trxn_id,
2565 'status_id' => $params['contribution']->contribution_status_id,
2566 'payment_instrument_id' => $params['contribution']->payment_instrument_id,
2567 'check_number' => CRM_Utils_Array::value('check_number', $params),
2568 );
2569
2570 if (CRM_Utils_Array::value('payment_processor', $params)) {
2571 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2572 }
2573 $params['trxnParams'] = $trxnParams;
2574
2575 if (CRM_Utils_Array::value('prevContribution', $params)) {
2576 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
2577 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
2578 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
2579 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
2580 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
2581 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
2582 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2583
2584 //if financial type is changed
2585 if (CRM_Utils_Array::value('financial_type_id', $params) &&
2586 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id) {
2587 $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2588 $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId);
2589 $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId);
2590 if ($oldFinancialAccount != $newFinancialAccount) {
2591 $params['total_amount'] = 0;
2592 if ($params['contribution']->contribution_status_id == array_search('Pending', $contributionStatuses)) {
2593 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2594 $params['prevContribution']->financial_type_id, $relationTypeId);
2595 }
2596 else {
2597 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
2598 if (CRM_Utils_Array::value('financialTrxnId', $lastFinancialTrxnId)) {
2599 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2600 }
2601 }
2602 self::updateFinancialAccounts($params, 'changeFinancialType');
2603 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2604 $params['financial_account_id'] = $newFinancialAccount;
2605 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2606 self::updateFinancialAccounts($params);
2607 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2608 }
2609 }
2610
2611 //Update contribution status
2612 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
2613 if (CRM_Utils_Array::value('contribution_status_id', $params) &&
2614 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id) {
2615 //Update Financial Records
2616 self::updateFinancialAccounts($params, 'changedStatus');
2617 }
2618
2619 // change Payment Instrument for a Completed contribution
2620 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2621 // instrument is null and now new payment instrument is added along with the payment
2622 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2623 $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params);
2624 if (array_key_exists('payment_instrument_id', $params)) {
2625 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2626 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
2627 !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)) {
2628 //check if status is changed from Pending to Completed
2629 // do not update payment instrument changes for Pending to Completed
2630 if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) &&
2631 $params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses))) {
2632 // for all other statuses create new financial records
2633 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2634 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2635 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2636 }
2637 }
2638 else if ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) ||
2639 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
2640 $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id) {
2641 // for any other payment instrument changes create new financial records
2642 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2643 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2644 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2645 }
2646 else if (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
2647 $params['contribution']->check_number != $params['prevContribution']->check_number) {
2648 // another special case when check number is changed, create new financial records
2649 // create financial trxn with negative amount
2650 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2651 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2652 // create financial trxn with positive amount
2653 $params['trxnParams']['check_number'] = $params['contribution']->check_number;
2654 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2655 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2656 }
2657 }
2658
2659 //if Change contribution amount
2660 $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2661 $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
2662 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2663 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
2664 if (isset($totalAmount) &&
2665 $totalAmount != $params['prevContribution']->total_amount) {
2666 //Update Financial Records
2667 $params['trxnParams']['from_financial_account_id'] = NULL;
2668 self::updateFinancialAccounts($params, 'changedAmount');
2669 }
2670 }
2671
2672 if (!$update) {
2673 //records finanical trxn and entity financial trxn
2674 $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
2675 $params['entity_id'] = $financialTxn->id;
2676 }
2677 }
2678 // record line items and finacial items
2679 if (!CRM_Utils_Array::value('skipLineItem', $params)) {
2680 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
2681 }
2682
2683 // create batch entry if batch_id is passed
2684 if (CRM_Utils_Array::value('batch_id', $params)) {
2685 $entityParams = array(
2686 'batch_id' => $params['batch_id'],
2687 'entity_table' => 'civicrm_financial_trxn',
2688 'entity_id' => $financialTxn->id,
2689 );
2690 CRM_Batch_BAO_Batch::addBatchEntity($entityParams);
2691 }
2692
2693 // when a fee is charged
2694 if (CRM_Utils_Array::value('fee_amount', $params) && (!CRM_Utils_Array::value('prevContribution', $params)
2695 || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
2696 CRM_Core_BAO_FinancialTrxn::recordFees($params);
2697 }
2698
2699 if (CRM_Utils_Array::value('prevContribution', $params) && $entityTable == 'civicrm_participant'
2700 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id) {
2701 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2702 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
2703 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
2704 }
2705 unset($params['line_item']);
2706 }
2707
2708 /**
2709 * Function to update all financial accounts entry
2710 *
2711 * @param array $params contribution object, line item array and params for trxn
2712 *
2713 * @param string $context update scenarios
2714 *
2715 * @access public
2716 * @static
2717 */
2718 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2719 $itemAmount = $trxnID = NULL;
2720 //get all the statuses
2721 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2722 if ($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus) &&
2723 $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2724 && $context == 'changePaymentInstrument') {
2725 return;
2726 }
2727 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
2728 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount;
2729 }
2730 if ($context == 'changedStatus') {
2731 //get all the statuses
2732 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2733
2734 if ($params['prevContribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2735 && ($params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
2736 || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus))) {
2737
2738 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2739 }
2740 elseif ($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2741 && $params['prevContribution']->is_pay_later) {
2742 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
2743 if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
2744 $params['trxnParams']['to_financial_account_id'] = NULL;
2745 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2746 }
2747 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2748 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2749 $financialTypeID, $relationTypeId);
2750 }
2751 $itemAmount = $params['trxnParams']['total_amount'];
2752 }
2753 elseif ($context == 'changePaymentInstrument') {
2754 if ($params['trxnParams']['total_amount'] < 0) {
2755 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
2756 if (CRM_Utils_Array::value('financialTrxnId', $lastFinancialTrxnId)) {
2757 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2758 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
2759 }
2760 }
2761 else {
2762 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2763 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2764 }
2765 }
2766 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
2767 $params['entity_id'] = $trxn->id;
2768
2769 if ($context == 'changedStatus') {
2770 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)) &&
2771 ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))) {
2772 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2773 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2774
2775 $entityParams = array(
2776 'entity_table' => 'civicrm_financial_item',
2777 'financial_trxn_id' => $trxn->id,
2778 );
2779 foreach ($params['line_item'] as $fieldId => $fields) {
2780 foreach ($fields as $fieldValueId => $fieldValues) {
2781 $fparams = array(
2782 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2783 2 => array($fieldValues['id'], 'Integer'),
2784 );
2785 CRM_Core_DAO::executeQuery($query, $fparams);
2786 $fparams = array(
2787 1 => array($fieldValues['id'], 'Integer'),
2788 );
2789 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
2790 while ($financialItem->fetch()) {
2791 $entityParams['entity_id'] = $financialItem->id;
2792 $entityParams['amount'] = $financialItem->amount;
2793 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
2794 }
2795 }
2796 }
2797 return;
2798 }
2799 }
2800 if ($context != 'changePaymentInstrument') {
2801 $itemParams['entity_table'] = 'civicrm_line_item';
2802 $trxnIds['id'] = $params['entity_id'];
2803 foreach ($params['line_item'] as $fieldId => $fields) {
2804 foreach ($fields as $fieldValueId => $fieldValues) {
2805 $prevParams['entity_id'] = $fieldValues['id'];
2806 $prevfinancialItem = CRM_Financial_BAO_FinancialItem::retrieve($prevParams, CRM_Core_DAO::$_nullArray);
2807
2808 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
2809 if ($params['contribution']->receive_date) {
2810 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
2811 }
2812
2813 $financialAccount = $prevfinancialItem->financial_account_id;
2814 if (CRM_Utils_Array::value('financial_account_id', $params)) {
2815 $financialAccount = $params['financial_account_id'];
2816 }
2817
2818 $currency = $params['prevContribution']->currency;
2819 if ($params['contribution']->currency) {
2820 $currency = $params['contribution']->currency;
2821 }
2822 if (CRM_Utils_Array::value('is_quick_config', $params)) {
2823 $amount = $itemAmount;
2824 if (!$amount) {
2825 $amount = $params['total_amount'];
2826 }
2827 }
2828 else {
2829 $diff = 1;
2830 if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
2831 $diff = -1;
2832 }
2833 $amount = $diff * $fieldValues['line_total'];
2834 }
2835
2836 $itemParams = array(
2837 'transaction_date' => $receiveDate,
2838 'contact_id' => $params['prevContribution']->contact_id,
2839 'currency' => $currency,
2840 'amount' => $amount,
2841 'description' => $prevfinancialItem->description,
2842 'status_id' => $prevfinancialItem->status_id,
2843 'financial_account_id' => $financialAccount,
2844 'entity_table' => 'civicrm_line_item',
2845 'entity_id' => $fieldValues['id']
2846 );
2847 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
2848 }
2849 }
2850 }
2851 }
2852
2853 /**
2854 * Function to check status validation on update of a contribution
2855 *
2856 * @param array $values previous form values before submit
2857 *
2858 * @param array $fields the input form values
2859 *
2860 * @param array $errors list of errors
2861 *
2862 * @access public
2863 * @static
2864 */
2865 static function checkStatusValidation($values, &$fields, &$errors) {
2866 if (CRM_Utils_System::isNull($values) && CRM_Utils_Array::value('id', $fields)) {
2867 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
2868 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
2869 return FALSE;
2870 }
2871 }
2872 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2873 $checkStatus = array(
2874 'Cancelled' => array('Completed', 'Refunded'),
2875 'Completed' => array('Cancelled', 'Refunded'),
2876 'Pending' => array('Cancelled', 'Completed', 'Failed'),
2877 'Refunded' => array('Cancelled', 'Completed')
2878 );
2879
2880 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
2881 $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']]));
2882 }
2883 }
2884
2885 /**
2886 * Function to delete contribution of contact
2887 *
2888 * CRM-12155
2889 *
2890 * @param integer $contactId contact id
2891 *
2892 * @access public
2893 * @static
2894 */
2895 static function deleteContactContribution($contactId) {
2896 $contribution = new CRM_Contribute_DAO_Contribution();
2897 $contribution->contact_id = $contactId;
2898 $contribution->find();
2899 while ($contribution->fetch()) {
2900 self::deleteContribution($contribution->id);
2901 }
2902 }
2903
2904 /**
2905 * Get options for a given contribution field.
2906 * @see CRM_Core_DAO::buildOptions
2907 *
2908 * @param String $fieldName
2909 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
2910 * @param Array $props: whatever is known about this dao object
2911 */
2912 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2913 $className = __CLASS__;
2914 $params = array();
2915 switch ($fieldName) {
2916 // This field is not part of this object but the api supports it
2917 case 'payment_processor':
2918 $className = 'CRM_Contribute_BAO_ContributionPage';
2919 // Filter results by contribution page
2920 if (!empty($props['contribution_page_id'])) {
2921 $page = civicrm_api('contribution_page', 'getsingle', array(
2922 'version' => 3,
2923 'id' => ($props['contribution_page_id'])
2924 ));
2925 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
2926 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
2927 }
2928 }
2929 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
2930 }
2931
2932 /**
2933 * Function to validate financial type
2934 *
2935 * CRM-13231
2936 *
2937 * @param integer $financialTypeId Financial Type id
2938 *
2939 * @access public
2940 * @static
2941 */
2942 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
2943 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
2944 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
2945
2946 if (!$financialAccount) {
2947 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
2948 }
2949 return FALSE;
2950 }
2951 }
2952
2953